1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
|
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'chrome://resources/cr_elements/cr_input/cr_input.js';
import 'chrome://resources/cr_elements/icons.m.js';
import 'chrome://resources/polymer/v3_0/iron-icon/iron-icon.js';
import {CrInputElement} from 'chrome://resources/cr_elements/cr_input/cr_input.js';
import {assertNotReached} from 'chrome://resources/js/assert_ts.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {getTemplate} from './database_tab.html.js';
import {boolToString, durationToString, getOrCreateSiteDataProvider, secondsToString} from './discards.js';
import {SiteDataDatabaseSize, SiteDataEntry, SiteDataFeature, SiteDataProviderRemote} from './site_data.mojom-webui.js';
import {SortedTableMixin} from './sorted_table_mixin.js';
/**
* Compares two db rows by their origin.
* @param a The first value being compared.
* @param b The second value being compared.
* @return A negative number if a < b, 0 if a === b, and a positive
* number if a > b.
*/
function compareRowsByOrigin(a: SiteDataEntry, b: SiteDataEntry): number {
return a.origin.localeCompare(b.origin);
}
/**
* Compares two db rows by their dirty bit.
* @param a The first value being compared.
* @param b The second value being compared.
* @return A negative number if a < b, 0 if a === b, and a positive
* number if a > b.
*/
function compareRowsByIsDirty(a: SiteDataEntry, b: SiteDataEntry): number {
return (a.isDirty ? 1 : 0) - (b.isDirty ? 1 : 0);
}
/**
* Compares two db rows by their last load time.
* @param a The first value being compared.
* @param b The second value being compared.
* @return A negative number if a < b, 0 if a === b, and a positive
* number if a > b.
*/
function compareRowsByLastLoaded(a: SiteDataEntry, b: SiteDataEntry): number {
return a.value!.lastLoaded - b.value!.lastLoaded;
}
/**
* Compares two db rows by their CPU usage.
* @param a The first value being compared.
* @param b The second value being compared.
* @return A negative number if a < b, 0 if a === b, and a positive
* number if a > b.
*/
function compareRowsByCpuUsage(a: SiteDataEntry, b: SiteDataEntry): number {
const keyA =
a.value!.loadTimeEstimates ? a.value!.loadTimeEstimates.avgCpuUsageUs : 0;
const keyB =
b.value!.loadTimeEstimates ? b.value!.loadTimeEstimates.avgCpuUsageUs : 0;
return keyA - keyB;
}
/**
* Compares two db rows by their memory usage.
* @param a The first value being compared.
* @param b The second value being compared.
* @return A negative number if a < b, 0 if a === b, and a positive
* number if a > b.
*/
function compareRowsByMemoryUsage(a: SiteDataEntry, b: SiteDataEntry): number {
const keyA = a.value!.loadTimeEstimates ?
a.value!.loadTimeEstimates.avgFootprintKb :
0;
const keyB = b.value!.loadTimeEstimates ?
b.value!.loadTimeEstimates.avgFootprintKb :
0;
return keyA - keyB;
}
/**
* Compares two db rows by their load duration.
* @param a The first value being compared.
* @param b The second value being compared.
* @return A negative number if a < b, 0 if a === b, and a positive
* number if a > b.
*/
function compareRowsByLoadDuration(a: SiteDataEntry, b: SiteDataEntry): number {
const keyA = a.value!.loadTimeEstimates ?
a.value!.loadTimeEstimates.avgLoadDurationUs :
0;
const keyB = b.value!.loadTimeEstimates ?
b.value!.loadTimeEstimates.avgLoadDurationUs :
0;
return keyA - keyB;
}
/**
* @param sortKey The sort key to get a function for.
* @return {function(SiteDataEntry, SiteDataEntry): number}
* A comparison function that compares two tab infos, returns
* negative number if a < b, 0 if a === b, and a positive
* number if a > b.
*/
function getSortFunctionForKey(sortKey: string): (
a: SiteDataEntry, b: SiteDataEntry) => number {
switch (sortKey) {
case 'origin':
return compareRowsByOrigin;
case 'dirty':
return compareRowsByIsDirty;
case 'lastLoaded':
return compareRowsByLastLoaded;
case 'cpuUsage':
return compareRowsByCpuUsage;
case 'memoryUsage':
return compareRowsByMemoryUsage;
case 'loadDuration':
return compareRowsByLoadDuration;
default:
assertNotReached('Unknown sortKey: ' + sortKey);
}
}
/**
* @param time A time in microseconds.
* @return A friendly, human readable string representing the input
* time with units.
*/
function microsecondsToString(time: number): string {
if (time < 1000) {
return time.toString() + ' µs';
}
time /= 1000;
if (time < 1000) {
return time.toFixed(2) + ' ms';
}
time /= 1000;
return time.toFixed(2) + ' s';
}
/**
* @param value A memory amount in kilobytes.
* @return A friendly, human readable string representing the input
* time with units.
*/
function kilobytesToString(value: number): string {
if (value < 1000) {
return value.toString() + ' KB';
}
value /= 1000;
if (value < 1000) {
return value.toFixed(1) + ' MB';
}
value /= 1000;
return value.toFixed(1) + ' GB';
}
/**
* @param item The item to retrieve a load time estimate for.
* @param propertyName Name of the load time estimate to retrieve.
* @return The requested load time estimate or 'N/A' if unavailable.
*/
function formatLoadTimeEstimate(
item: SiteDataEntry, propertyName: string): string {
if (!item.value || !item.value.loadTimeEstimates) {
return 'N/A';
}
const value =
(item.value.loadTimeEstimates as unknown as
{[key: string]: number})[propertyName];
if (propertyName.endsWith('Us')) {
return microsecondsToString(value);
} else if (propertyName.endsWith('Kb')) {
return kilobytesToString(value);
}
return value.toString();
}
interface DatabaseTabElement {
$: {
addOriginInput: CrInputElement,
};
}
const DatabaseTabElementBase = SortedTableMixin(PolymerElement);
class DatabaseTabElement extends DatabaseTabElementBase {
static get is() {
return 'database-tab';
}
static get template() {
return getTemplate();
}
static get properties() {
return {
/**
* List of database rows.
*/
rows_: Array,
/**
* The database size response.
*/
size_: {
type: Object,
value: {numRows: -1, onDiskSizeKb: -1},
},
/**
* An origin that can be added to requestedOrigins_ by onAddOriginClick_.
*/
newOrigin_: String,
};
}
private rows_: SiteDataEntry[]|null;
private size_: SiteDataDatabaseSize;
private newOrigin_: string;
private updateTableTimer_: number = 0;
private updateSizesTimer_: number = 0;
private requestedOrigins_: {[key: string]: boolean} = {};
private siteDataProvider_: SiteDataProviderRemote|null = null;
override connectedCallback() {
this.setSortKey('origin');
this.requestedOrigins_ = {};
this.siteDataProvider_ = getOrCreateSiteDataProvider();
// Specifies the update interval of the table, in ms.
const UPDATE_INTERVAL_MS = 1000;
// Update immediately.
this.updateDbRows_();
this.updateDbSizes_();
// Set an interval timer to update the database periodically.
this.updateTableTimer_ =
setInterval(this.updateDbRows_.bind(this), UPDATE_INTERVAL_MS);
// Set another interval timer to update the database sizes, but much less
// frequently, as this requires iterating the entire database.
this.updateSizesTimer_ =
setInterval(this.updateDbSizes_.bind(this), UPDATE_INTERVAL_MS * 30);
}
override disconnectedCallback() {
// Clear the update timers to avoid memory leaks.
clearInterval(this.updateTableTimer_);
this.updateTableTimer_ = 0;
clearInterval(this.updateSizesTimer_);
this.updateSizesTimer_ = 0;
}
/**
* Issues a request for the data and renders on response.
*/
private updateDbRows_() {
this.siteDataProvider_!
.getSiteDataArray(Object.keys(this.requestedOrigins_))
.then(response => {
// Bail if the SiteData database is turned off.
if (!response.result) {
return;
}
// Add any new origins to the (monotonically increasing)
// set of requested origins.
const dbRows = response.result.dbRows;
for (const dbRow of dbRows) {
this.requestedOrigins_[dbRow.origin] = true;
}
this.rows_ = dbRows;
});
}
/**
* Adds the current new origin to requested origins and starts an update.
*/
private addNewOrigin_() {
this.requestedOrigins_[this.newOrigin_] = true;
this.newOrigin_ = '';
this.updateDbRows_();
}
/**
* An on-click handler that adds the current new origin to requested
* origins.
*/
private onAddOriginClick_() {
this.addNewOrigin_();
// Set the focus back to the input field for convenience.
this.$.addOriginInput.focus();
}
/**
* A key-down handler that adds the current new origin to requested origins.
*/
private onOriginKeydown_(e: KeyboardEvent) {
if (e.key === 'Enter' && this.isValidOrigin_(this.newOrigin_)) {
this.addNewOrigin_();
e.stopPropagation();
}
}
/** Issues a request for the database sizes and renders on response. */
private updateDbSizes_() {
this.siteDataProvider_!.getSiteDataDatabaseSize().then(response => {
// Bail if the SiteData database is turned off.
if (!response.dbSize) {
return;
}
this.size_ = response.dbSize;
});
}
/**
* Returns a sort function to compare tab infos based on the provided sort
* key and a boolean reverse flag.
* @param sortKey The sort key for the returned function.
* @param sortReverse True if sorting is reversed.
* @return A comparison function that compares two tab infos, returns
* negative number if a < b, 0 if a === b, and a positive
* number if a > b.
*/
private computeSortFunction_(sortKey: string, sortReverse: boolean):
(a: SiteDataEntry, b: SiteDataEntry) => number {
// Polymer 2 may invoke multi-property observers before all properties
// are defined.
if (!sortKey) {
return (_a, _b) => 0;
}
const sortFunction = getSortFunctionForKey(sortKey);
return (a, b) => {
const comp = sortFunction(a, b);
return sortReverse ? -comp : comp;
};
}
/**
* @param origin A potentially valid origin string.
* @return Whether the origin is valid.
*/
private isValidOrigin_(origin: string): boolean {
const re = /(https?|ftp):\/\/[a-z+.]/;
return re.test(origin);
}
/**
* @param origin A potentially valid origin string.
* @return Whether the origin is valid or empty.
*/
private isEmptyOrValidOrigin_(origin: string): boolean {
return !origin || this.isValidOrigin_(origin);
}
/**
* @param value The value to convert.
* @return A display string representing value.
*/
private boolToString_(value: boolean): string {
return boolToString(value);
}
/**
* @param time Time in seconds since epoch.
* @return A user-friendly string explaining how long ago time
* occurred.
*/
private lastUseToString_(time: number): string {
const nowSecondsFromEpoch = Math.round(Date.now() / 1000);
return durationToString(nowSecondsFromEpoch - time);
}
/**
* @param feature The feature in question.
* @return A human-readable string representing the feature.
*/
private featureToString_(feature: SiteDataFeature|null): string {
if (!feature) {
return 'N/A';
}
if (feature.useTimestamp) {
const nowSecondsFromEpoch = Math.round(Date.now() / 1000);
return 'Used ' +
durationToString(
Number(BigInt(nowSecondsFromEpoch) - feature.useTimestamp));
}
if (feature.observationDuration) {
return secondsToString(Number(feature.observationDuration));
}
return 'N/A';
}
/**
* @param item The item to retrieve a load time estimate for.
* @param propertyName Name of the load time estimate to retrieve.
* @return The requested load time estimate or 'N/A' if
* unavailable.
*/
private getLoadTimeEstimate_(item: SiteDataEntry, propertyName: string):
string {
return formatLoadTimeEstimate(item, propertyName);
}
/**
* @param value A value in units of kilobytes, or -1 indicating not
* available.
* @return A human readable string representing value.
*/
private kilobytesToString_(value: number): string {
return value === -1 ? 'N/A' : kilobytesToString(value);
}
/**
* @param value A numeric value or -1, indicating not available.
* @return A human readable string representing value.
*/
private optionalIntegerToString_(value: number): string {
return value === -1 ? 'N/A' : value.toString();
}
}
customElements.define(DatabaseTabElement.is, DatabaseTabElement);
|