@whotracksme/reporting 7.12.2 → 8.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/communication/test/helpers/in-memory-database.js +45 -0
- package/package.json +2 -2
- package/reporting/src/hash-detector-v2/index.js +164 -0
- package/reporting/src/hash-detector-v2/prob.js +599 -0
- package/reporting/src/hash-detector-v2.js +18 -0
- package/reporting/src/observable.js +43 -0
- package/reporting/src/pages.js +11 -12
- package/reporting/src/paused-domains-reporter.js +50 -0
- package/reporting/src/persisted-counters.js +158 -0
- package/reporting/src/popularity-estimator.js +625 -0
- package/reporting/src/popularity-vote-handler.js +219 -0
- package/reporting/src/popularity-vote-sanitizer.js +384 -0
- package/reporting/src/random.js +90 -1
- package/reporting/src/reporting.js +98 -13
- package/reporting/src/utils.js +41 -1
- package/reporting/test/activity-estimator.spec.js +3 -2
- package/reporting/test/alive-check.spec.js +2 -2
- package/reporting/test/country-provider.spec.js +2 -2
- package/reporting/test/index.js +6 -0
- package/reporting/test/job-scheduler.spec.js +2 -2
- package/reporting/test/observable.spec.js +72 -0
- package/reporting/test/page-aggregator.spec.js +3 -0
- package/reporting/test/patterns-updater.spec.js +2 -2
- package/reporting/test/persisted-counters.spec.js +132 -0
- package/reporting/test/popularity-estimator.spec.js +710 -0
- package/reporting/test/popularity-vote-handler.spec.js +420 -0
- package/reporting/test/popularity-vote-sanitizer.spec.js +635 -0
- package/reporting/test/random.spec.js +157 -0
- package/reporting/test/reporting.spec.js +202 -180
- package/reporting/test/utils.spec.js +42 -0
|
@@ -0,0 +1,625 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WhoTracks.Me
|
|
3
|
+
* https://whotracks.me/
|
|
4
|
+
*
|
|
5
|
+
* Copyright 2017-present Ghostery GmbH. All rights reserved.
|
|
6
|
+
*
|
|
7
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
8
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
9
|
+
* file, You can obtain one at http://mozilla.org/MPL/2.0
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import * as tldts from 'tldts-experimental';
|
|
13
|
+
|
|
14
|
+
import logger from './logger';
|
|
15
|
+
import SeqExecutor from './seq-executor';
|
|
16
|
+
import PersistedCounters from './persisted-counters';
|
|
17
|
+
import { randomSafeIntBetween } from './random';
|
|
18
|
+
import { requireParam, requireUTC, requireString, requireInt } from './utils';
|
|
19
|
+
import SelfCheck from './self-check';
|
|
20
|
+
|
|
21
|
+
const SECOND = 1000;
|
|
22
|
+
const MINUTE = 60 * SECOND;
|
|
23
|
+
const HOUR = 60 * MINUTE;
|
|
24
|
+
const DAY = 24 * HOUR;
|
|
25
|
+
const WEEK = 7 * DAY;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Increase this only if you want all state (the persisted counters
|
|
29
|
+
* and the rotation config) to be cleared.
|
|
30
|
+
*/
|
|
31
|
+
const DB_VERSION = 1;
|
|
32
|
+
|
|
33
|
+
function intervalTypeToMillseconds(intervalType) {
|
|
34
|
+
switch (intervalType) {
|
|
35
|
+
case '1d':
|
|
36
|
+
return DAY;
|
|
37
|
+
case '1w':
|
|
38
|
+
return WEEK;
|
|
39
|
+
case '4w':
|
|
40
|
+
return 4 * WEEK;
|
|
41
|
+
default:
|
|
42
|
+
throw new Error(`Unexpected interval type: <<${intervalType}>>`);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function chooseNumSamplesPerInterval(intervalType) {
|
|
47
|
+
switch (intervalType) {
|
|
48
|
+
case '1d':
|
|
49
|
+
return 3;
|
|
50
|
+
case '1w':
|
|
51
|
+
return 3;
|
|
52
|
+
case '4w':
|
|
53
|
+
return 3;
|
|
54
|
+
default:
|
|
55
|
+
throw new Error(`Unexpected interval type: <<${intervalType}>>`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function isLegalVoteCount({ numVotes, intervalType }) {
|
|
60
|
+
requireInt(numVotes);
|
|
61
|
+
return numVotes >= 0 && numVotes <= chooseNumSamplesPerInterval(intervalType);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export default class PopularityEstimator {
|
|
65
|
+
constructor({ storage, storageKey, connectDatabase, jobScheduler }) {
|
|
66
|
+
this.active = false;
|
|
67
|
+
this.storage = requireParam(storage);
|
|
68
|
+
this.storageKey = requireString(storageKey);
|
|
69
|
+
this.jobScheduler = requireParam(jobScheduler);
|
|
70
|
+
|
|
71
|
+
// Sets up the following structure:
|
|
72
|
+
// - level 1: urlProjection (how to map the URL to a key)
|
|
73
|
+
// - level 2: countType (what event to count)
|
|
74
|
+
// - level 3: interval (what time interval to aggregate)
|
|
75
|
+
//
|
|
76
|
+
// this._popularityBy = {
|
|
77
|
+
// domain: {
|
|
78
|
+
// visits: {
|
|
79
|
+
// '1d': new PersistedCounter(..),
|
|
80
|
+
// '1w': ..
|
|
81
|
+
// '4w': ..
|
|
82
|
+
// }
|
|
83
|
+
// },
|
|
84
|
+
// hostname: {
|
|
85
|
+
// visits: {
|
|
86
|
+
// '1d': ..
|
|
87
|
+
// '1w': ..
|
|
88
|
+
// '4w': ..
|
|
89
|
+
// }
|
|
90
|
+
// },
|
|
91
|
+
// hostnamePath: {
|
|
92
|
+
// visits: {
|
|
93
|
+
// ..
|
|
94
|
+
// }
|
|
95
|
+
// }
|
|
96
|
+
// }
|
|
97
|
+
this._popularityBy = {};
|
|
98
|
+
this._allCounters = [];
|
|
99
|
+
for (const urlProjection of ['domain', 'hostname', 'hostnamePath']) {
|
|
100
|
+
this._popularityBy[urlProjection] = { visits: {} };
|
|
101
|
+
for (const interval of ['1d', '1w', '4w']) {
|
|
102
|
+
const name = `${urlProjection}::visits::${interval}`;
|
|
103
|
+
const db = connectDatabase(`popularity_estimator::${name}`, {
|
|
104
|
+
version: DB_VERSION,
|
|
105
|
+
});
|
|
106
|
+
const counter = new PersistedCounters({ name, db });
|
|
107
|
+
this._popularityBy[urlProjection].visits[interval] = counter;
|
|
108
|
+
this._allCounters.push(counter);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// to throttle page visit updates (e.g. history updates can spam)
|
|
113
|
+
this._visitCooldown = {
|
|
114
|
+
hostname: '',
|
|
115
|
+
expireAt: 0, // UTC timestamp
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
this._nextRotationCheck = 0; // UTC timestamp
|
|
119
|
+
this._criticalSection = new SeqExecutor();
|
|
120
|
+
this._rotationConfig = null;
|
|
121
|
+
this._rotationConfigPendingWrite = null;
|
|
122
|
+
this._rotationFailuresInARow = 0;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// convenience function to iterate over "_popularityBy" (see constructor)
|
|
126
|
+
_forEachCounter(cb) {
|
|
127
|
+
for (const [urlProjection, level2] of Object.entries(this._popularityBy)) {
|
|
128
|
+
for (const [countType, level3] of Object.entries(level2)) {
|
|
129
|
+
for (const [intervalType, persistedCounter] of Object.entries(level3)) {
|
|
130
|
+
cb(urlProjection, countType, intervalType, persistedCounter);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async init() {
|
|
137
|
+
this.active = true;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
unload() {
|
|
141
|
+
this.active = false;
|
|
142
|
+
this.flush().catch(logger.error);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Forces an immediate synchronization of all pending data to disk.
|
|
146
|
+
//
|
|
147
|
+
// Context: Persistence usually happens automatically in the background.
|
|
148
|
+
// However, explicitly calling this method is useful for scenarios
|
|
149
|
+
// requiring strong consistency guarantees, such as testing.
|
|
150
|
+
//
|
|
151
|
+
// Once awaited, this function guarantees that all writes have completed.
|
|
152
|
+
async flush() {
|
|
153
|
+
await Promise.all([
|
|
154
|
+
// 1. Immediate Flush
|
|
155
|
+
// Trigger flush operations for all counters without delay.
|
|
156
|
+
this._flushCounters(),
|
|
157
|
+
|
|
158
|
+
// 2. Deferred Flush
|
|
159
|
+
// Runs in parallel with the immediate flush but handles a specific edge case:
|
|
160
|
+
// pending "onPageEvent" operations may not have triggered writes yet.
|
|
161
|
+
// To ensure "flush" is intuitive, we wait for all critical sections
|
|
162
|
+
// (event processing) to complete before flushing again.
|
|
163
|
+
this._criticalSection
|
|
164
|
+
.run(async () => {})
|
|
165
|
+
.then(() => this._flushCounters()),
|
|
166
|
+
]);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
async _flushCounters() {
|
|
170
|
+
await Promise.all(
|
|
171
|
+
this._allCounters.map((counter) =>
|
|
172
|
+
counter.flush().catch((e) => {
|
|
173
|
+
logger.error(`Failed to flush counter: ${counter}`, e);
|
|
174
|
+
}),
|
|
175
|
+
),
|
|
176
|
+
);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
onPageEvent(event) {
|
|
180
|
+
if (!this.active) {
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
if (event.type === 'safe-page-navigation') {
|
|
185
|
+
const { hostname, pathname } = new URL(event.url);
|
|
186
|
+
const { domain, isIp } = tldts.parse(hostname, {
|
|
187
|
+
extractHostname: false,
|
|
188
|
+
mixedInputs: false,
|
|
189
|
+
validateHostname: false,
|
|
190
|
+
});
|
|
191
|
+
if (isIp) {
|
|
192
|
+
logger.info(
|
|
193
|
+
'[popularity] ignoring visit, because hostname is IP address:',
|
|
194
|
+
event.url,
|
|
195
|
+
);
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
if (!domain) {
|
|
199
|
+
logger.warn('Invalid domain detected in visited URL:', event.url);
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// Some sites (e.g. Google maps) spam history navigations. To avoid
|
|
204
|
+
// inflating the "visited" counts, ignore updates for a few seconds.
|
|
205
|
+
const now = Date.now();
|
|
206
|
+
try {
|
|
207
|
+
if (
|
|
208
|
+
event.isHistoryNavigation &&
|
|
209
|
+
now < this._visitCooldown.expireAt &&
|
|
210
|
+
this._visitCooldown.hostname === hostname
|
|
211
|
+
) {
|
|
212
|
+
logger.debug(
|
|
213
|
+
'[popularity] skip visit (cooldown not reached)',
|
|
214
|
+
event.url,
|
|
215
|
+
);
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
} finally {
|
|
219
|
+
this._visitCooldown = { hostname, expireAt: now + 20 * SECOND };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
this._criticalSection
|
|
223
|
+
.run(async () => {
|
|
224
|
+
await this._runRotationChecks(now);
|
|
225
|
+
if (this._rotationFailuresInARow !== 0) {
|
|
226
|
+
logger.warn(
|
|
227
|
+
'Skipping visits, because the last rotation failed:',
|
|
228
|
+
event,
|
|
229
|
+
);
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const hostnamePath = hostname + pathname;
|
|
234
|
+
for (const [interval, samplingSize] of [
|
|
235
|
+
['1d', 1],
|
|
236
|
+
['1w', 10],
|
|
237
|
+
['4w', 100],
|
|
238
|
+
]) {
|
|
239
|
+
if (randomSafeIntBetween(1, samplingSize) === 1) {
|
|
240
|
+
this._popularityBy.domain.visits[interval].count(domain);
|
|
241
|
+
this._popularityBy.hostname.visits[interval].count(hostname);
|
|
242
|
+
this._popularityBy.hostnamePath.visits[interval].count(
|
|
243
|
+
hostnamePath,
|
|
244
|
+
);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
})
|
|
248
|
+
.catch((e) => {
|
|
249
|
+
logger.error('Unexpected error', e);
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
async _runRotationChecks(now) {
|
|
255
|
+
if (requireUTC(now) >= this._nextRotationCheck) {
|
|
256
|
+
try {
|
|
257
|
+
this._rotationConfig ||= await this._loadRotationConfig(now);
|
|
258
|
+
await this._expireRotationCooldowns(now);
|
|
259
|
+
await this._processCompletedRotations(now);
|
|
260
|
+
this._scheduleNextRotationCheck();
|
|
261
|
+
this._rotationFailuresInARow = 0;
|
|
262
|
+
} catch (e) {
|
|
263
|
+
// Should normally not happen, because it should be doing only disk IO
|
|
264
|
+
// operations (not network request, which have a higher chance to fail).
|
|
265
|
+
logger.error('Error while rotating', e);
|
|
266
|
+
|
|
267
|
+
// Keep a bit of cooldown before retrying, because the IO operation
|
|
268
|
+
// may be expensive (e.g. table scans over the whole database).
|
|
269
|
+
// Note: The heuristic here is not very effective, since the termination
|
|
270
|
+
// of service worker will reset it. Thus, it will repeat the check on
|
|
271
|
+
// each service worker restart; but perhaps that is okay. Also, when
|
|
272
|
+
// we are in this situation, there are not many options. It is likely
|
|
273
|
+
// that IO is not reliable at the moment (e.g. out of disk).
|
|
274
|
+
this._rotationFailuresInARow += 1;
|
|
275
|
+
this._nextRotationCheck = now + this._rotationFailuresInARow * SECOND;
|
|
276
|
+
|
|
277
|
+
if (this._rotationFailuresInARow >= 3) {
|
|
278
|
+
try {
|
|
279
|
+
logger.error(
|
|
280
|
+
'Too many rotation errors in a row. Purging state in an attempt to recover',
|
|
281
|
+
);
|
|
282
|
+
await this.purgeAllState();
|
|
283
|
+
logger.info(
|
|
284
|
+
'Successfully purged the state. Rotations will be retried on the next visit.',
|
|
285
|
+
);
|
|
286
|
+
this._nextRotationCheck = now;
|
|
287
|
+
} catch (e) {
|
|
288
|
+
// give up until the next service worker restart
|
|
289
|
+
logger.error(
|
|
290
|
+
'Failed to purge the state. Perhaps the browser profile is broken?',
|
|
291
|
+
e,
|
|
292
|
+
);
|
|
293
|
+
this._nextRotationCheck = Number.MAX_SAFE_INTEGER;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
async _loadRotationConfig(now) {
|
|
301
|
+
requireUTC(now);
|
|
302
|
+
|
|
303
|
+
let config = await this.storage.get(this.storageKey);
|
|
304
|
+
if (!config) {
|
|
305
|
+
logger.info(
|
|
306
|
+
'No rotation config exists found yet.',
|
|
307
|
+
'This should only happen on the first time the extension is started.',
|
|
308
|
+
);
|
|
309
|
+
} else if (config.dbVersion !== DB_VERSION) {
|
|
310
|
+
logger.warn(
|
|
311
|
+
`dbVersion mismatch: expected ${DB_VERSION}, but got ${config.dbVersion}. `,
|
|
312
|
+
'Discarding it and replacing it by a fresh rotation configuration.',
|
|
313
|
+
);
|
|
314
|
+
await this.purgeAllState().catch((e) =>
|
|
315
|
+
logger.warn('Failed to purge the state. Continuing...', e),
|
|
316
|
+
);
|
|
317
|
+
config = null;
|
|
318
|
+
} else if (config.lastUpdatedAt > now + 2 * DAY) {
|
|
319
|
+
logger.error(
|
|
320
|
+
'Reverse clock jump detected: lastUpdatedAt',
|
|
321
|
+
`(${new Date(config.lastUpdatedAt)})`,
|
|
322
|
+
`is significantly ahead of the current time (${new Date(now)}).`,
|
|
323
|
+
'Trying to reset the state and continuing...',
|
|
324
|
+
);
|
|
325
|
+
await this.purgeAllState().catch((e) =>
|
|
326
|
+
logger.warn('Failed to purge the state. Continuing...', e),
|
|
327
|
+
);
|
|
328
|
+
config = null;
|
|
329
|
+
} else {
|
|
330
|
+
logger.debug('Successfully loaded rotation config:', config);
|
|
331
|
+
return config;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
if (!config) {
|
|
335
|
+
config = this._createInitialRotationConfig(now);
|
|
336
|
+
this._rotationConfig = config;
|
|
337
|
+
this._markRotationConfigDirty(now);
|
|
338
|
+
logger.info('Created initial rotation config:', config);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
return config;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
_markRotationConfigDirty(now) {
|
|
345
|
+
if (!this._rotationConfig) {
|
|
346
|
+
throw new Error(
|
|
347
|
+
'Illegal state: rotationConfig must have been loaded before being marked as dirty',
|
|
348
|
+
);
|
|
349
|
+
}
|
|
350
|
+
this._rotationConfig.lastUpdatedAt = requireUTC(now);
|
|
351
|
+
|
|
352
|
+
if (this._rotationConfigPendingWrite === null) {
|
|
353
|
+
this._rotationConfigPendingWrite = setTimeout(() => {
|
|
354
|
+
this._rotationConfigPendingWrite = null;
|
|
355
|
+
(async () => {
|
|
356
|
+
try {
|
|
357
|
+
await this.storage.set(this.storageKey, this._rotationConfig);
|
|
358
|
+
logger.debug('Rotation config successfully persisted');
|
|
359
|
+
} catch (e) {
|
|
360
|
+
logger.error('Failed to persist rotation config', e);
|
|
361
|
+
}
|
|
362
|
+
})();
|
|
363
|
+
}, 0);
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
_createInitialRotationConfig(now) {
|
|
368
|
+
requireUTC(now);
|
|
369
|
+
|
|
370
|
+
const cooldowns = {};
|
|
371
|
+
this._forEachCounter((urlProjection, countType, intervalType) => {
|
|
372
|
+
const defaultRotationPeriod = intervalTypeToMillseconds(intervalType);
|
|
373
|
+
const expireAt = randomSafeIntBetween(now, now + defaultRotationPeriod);
|
|
374
|
+
cooldowns[urlProjection] ||= {};
|
|
375
|
+
cooldowns[urlProjection][countType] ||= {};
|
|
376
|
+
cooldowns[urlProjection][countType][intervalType] = expireAt;
|
|
377
|
+
|
|
378
|
+
logger.info('Scheduled cooldown:', {
|
|
379
|
+
urlProjection,
|
|
380
|
+
countType,
|
|
381
|
+
intervalType,
|
|
382
|
+
endsAt: new Date(expireAt),
|
|
383
|
+
});
|
|
384
|
+
});
|
|
385
|
+
|
|
386
|
+
return {
|
|
387
|
+
dbVersion: DB_VERSION,
|
|
388
|
+
lastUpdatedAt: now,
|
|
389
|
+
cooldowns,
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
async _expireRotationCooldowns(now) {
|
|
394
|
+
requireUTC(now);
|
|
395
|
+
|
|
396
|
+
const { cooldowns } = this._rotationConfig;
|
|
397
|
+
if (!cooldowns) {
|
|
398
|
+
return; // all cooldowns have already expired
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
let stillActive = 0;
|
|
402
|
+
const pendingIO = [];
|
|
403
|
+
|
|
404
|
+
this._forEachCounter(
|
|
405
|
+
(urlProjection, countType, intervalType, persistedCounter) => {
|
|
406
|
+
const expireAt = cooldowns[urlProjection]?.[countType]?.[intervalType];
|
|
407
|
+
if (expireAt !== undefined) {
|
|
408
|
+
if (now >= expireAt) {
|
|
409
|
+
logger.info(
|
|
410
|
+
'Rotation cooldown expired. Ensuring that counters are empty:',
|
|
411
|
+
{
|
|
412
|
+
urlProjection,
|
|
413
|
+
countType,
|
|
414
|
+
intervalType,
|
|
415
|
+
},
|
|
416
|
+
);
|
|
417
|
+
delete cooldowns[urlProjection][countType][intervalType];
|
|
418
|
+
pendingIO.push(persistedCounter.clear());
|
|
419
|
+
|
|
420
|
+
// Start initial rotation period:
|
|
421
|
+
const defaultRotationPeriod =
|
|
422
|
+
intervalTypeToMillseconds(intervalType);
|
|
423
|
+
const endsAt = now + defaultRotationPeriod;
|
|
424
|
+
|
|
425
|
+
this._rotationConfig.rotations ||= {};
|
|
426
|
+
this._rotationConfig.rotations[urlProjection] ||= {};
|
|
427
|
+
this._rotationConfig.rotations[urlProjection][countType] ||= {};
|
|
428
|
+
this._rotationConfig.rotations[urlProjection][countType][
|
|
429
|
+
intervalType
|
|
430
|
+
] = endsAt;
|
|
431
|
+
this._markRotationConfigDirty(now);
|
|
432
|
+
|
|
433
|
+
logger.info('Scheduled initial rotation:', {
|
|
434
|
+
urlProjection,
|
|
435
|
+
countType,
|
|
436
|
+
intervalType,
|
|
437
|
+
endsAt,
|
|
438
|
+
});
|
|
439
|
+
} else {
|
|
440
|
+
stillActive += 1;
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
},
|
|
444
|
+
);
|
|
445
|
+
if (pendingIO.length > 0) {
|
|
446
|
+
await Promise.all(pendingIO);
|
|
447
|
+
logger.debug('Successfully cleared counter.');
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
if (stillActive === 0) {
|
|
451
|
+
logger.info('All rotation cooldowns have expired.');
|
|
452
|
+
delete this._rotationConfig.cooldowns;
|
|
453
|
+
this._markRotationConfigDirty(now);
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
async _processCompletedRotations(now) {
|
|
458
|
+
requireUTC(now);
|
|
459
|
+
|
|
460
|
+
const { rotations } = this._rotationConfig;
|
|
461
|
+
if (!rotations) {
|
|
462
|
+
return; // rotations have not started yet
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
const pendingRotations = [];
|
|
466
|
+
this._forEachCounter(
|
|
467
|
+
(urlProjection, countType, intervalType, persistedCounter) => {
|
|
468
|
+
const expireAt = rotations[urlProjection]?.[countType]?.[intervalType];
|
|
469
|
+
if (expireAt !== undefined && now >= expireAt) {
|
|
470
|
+
// We know the end of the last period ("expireAt"). To determine the
|
|
471
|
+
// end of the new period, we first need to find its start. This start
|
|
472
|
+
// could be right after the old period, or if too much time has elapsed,
|
|
473
|
+
// we may have skipped several periods. In such cases, we need to account
|
|
474
|
+
// for the missed periods to maintain accurate time intervals.
|
|
475
|
+
const elapsedSinceEndOfLastPeriod = now - expireAt;
|
|
476
|
+
const defaultRotationPeriod = intervalTypeToMillseconds(intervalType);
|
|
477
|
+
const periodsMissed = Math.floor(
|
|
478
|
+
elapsedSinceEndOfLastPeriod / defaultRotationPeriod,
|
|
479
|
+
);
|
|
480
|
+
const periodStart = expireAt + periodsMissed * defaultRotationPeriod;
|
|
481
|
+
// Now that we know the begin of the current period, we can define
|
|
482
|
+
// the new end. The simplest approach is to advance it by the default
|
|
483
|
+
// period (e.g., 1d, 1w, 4w). This ensures we avoid unintended bias.
|
|
484
|
+
//
|
|
485
|
+
// However, introducing randomness is beneficial for two reasons:
|
|
486
|
+
// 1) It reduces the likelihood of the population being unintentionally
|
|
487
|
+
// synced by external events. (Though the initial cooldown protects
|
|
488
|
+
// protection against that, it only affects the first rotation.)
|
|
489
|
+
// 2) It makes it harder to predict when a client will rotate, making
|
|
490
|
+
// statistical attacks more difficult. (Although concrete attacks
|
|
491
|
+
// are hard to envision, adding noise should generally improve
|
|
492
|
+
// overall robustness against possible attacks.)
|
|
493
|
+
const minPeriod = Math.round(0.9 * defaultRotationPeriod);
|
|
494
|
+
const maxPeriod = Math.round(1.1 * defaultRotationPeriod);
|
|
495
|
+
const newExpireAt =
|
|
496
|
+
periodStart + randomSafeIntBetween(minPeriod, maxPeriod);
|
|
497
|
+
|
|
498
|
+
rotations[urlProjection][countType][intervalType] = newExpireAt;
|
|
499
|
+
this._markRotationConfigDirty(now);
|
|
500
|
+
|
|
501
|
+
logger.info('Rotation period ended and a new one started:', {
|
|
502
|
+
urlProjection,
|
|
503
|
+
countType,
|
|
504
|
+
intervalType,
|
|
505
|
+
periodsMissed,
|
|
506
|
+
newPeriod: {
|
|
507
|
+
startsAt: periodStart,
|
|
508
|
+
expiresAt: newExpireAt,
|
|
509
|
+
},
|
|
510
|
+
});
|
|
511
|
+
|
|
512
|
+
pendingRotations.push(
|
|
513
|
+
(async () => {
|
|
514
|
+
// 1) draw samples from the now expired period
|
|
515
|
+
const numSamples = chooseNumSamplesPerInterval(intervalType);
|
|
516
|
+
const groupedSamples = await persistedCounter.sample(numSamples, {
|
|
517
|
+
group: true, // helps to avoid unnecessary, duplicated quorum calls
|
|
518
|
+
});
|
|
519
|
+
|
|
520
|
+
// 2) reset counters (destructive action to enter the new period)
|
|
521
|
+
await persistedCounter.clear();
|
|
522
|
+
|
|
523
|
+
// 3) prepare jobs (but delay registration until all operations
|
|
524
|
+
// succeeded, which indicates that the system is healthy)
|
|
525
|
+
return groupedSamples.map(([value, count]) => ({
|
|
526
|
+
type: 'popularity-estimator:prepare-voting:v1',
|
|
527
|
+
args: {
|
|
528
|
+
urlProjection,
|
|
529
|
+
countType,
|
|
530
|
+
intervalType,
|
|
531
|
+
sample: {
|
|
532
|
+
value,
|
|
533
|
+
count,
|
|
534
|
+
},
|
|
535
|
+
},
|
|
536
|
+
config: {
|
|
537
|
+
min: 0,
|
|
538
|
+
max: 2 * MINUTE,
|
|
539
|
+
},
|
|
540
|
+
}));
|
|
541
|
+
})(),
|
|
542
|
+
);
|
|
543
|
+
}
|
|
544
|
+
},
|
|
545
|
+
);
|
|
546
|
+
|
|
547
|
+
if (pendingRotations.length > 0) {
|
|
548
|
+
const jobBatchesPerRotation = await Promise.all(pendingRotations);
|
|
549
|
+
const allJobs = jobBatchesPerRotation.flat();
|
|
550
|
+
try {
|
|
551
|
+
await this.jobScheduler.registerJobs(allJobs);
|
|
552
|
+
} catch (e) {
|
|
553
|
+
logger.error('Failed to register jobs. These were lost:', allJobs);
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
async purgeAllState() {
|
|
559
|
+
const results = await Promise.allSettled([
|
|
560
|
+
this.storage.remove(this.storageKey),
|
|
561
|
+
...this._allCounters.map((counter) => counter.clear()),
|
|
562
|
+
]);
|
|
563
|
+
const errors = results.filter((result) => result.status === 'rejected');
|
|
564
|
+
if (errors.length === 0) {
|
|
565
|
+
logger.info(
|
|
566
|
+
'Successfully cleared all state (including rotation config and counters)',
|
|
567
|
+
);
|
|
568
|
+
} else {
|
|
569
|
+
errors.forEach(({ reason }) =>
|
|
570
|
+
logger.error('Error while clearing the state:', reason),
|
|
571
|
+
);
|
|
572
|
+
throw new Error('Failed to clear state', { cause: errors[0].reason });
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
_scheduleNextRotationCheck() {
|
|
577
|
+
let nextCheckAt = Number.MAX_SAFE_INTEGER;
|
|
578
|
+
const check = (expireAt) => {
|
|
579
|
+
if (expireAt !== undefined && expireAt < nextCheckAt) {
|
|
580
|
+
nextCheckAt = expireAt;
|
|
581
|
+
}
|
|
582
|
+
};
|
|
583
|
+
const { cooldowns = {}, rotations = {} } = this._rotationConfig;
|
|
584
|
+
this._forEachCounter((urlProjection, countType, intervalType) => {
|
|
585
|
+
check(cooldowns[urlProjection]?.[countType]?.[intervalType]);
|
|
586
|
+
check(rotations[urlProjection]?.[countType]?.[intervalType]);
|
|
587
|
+
});
|
|
588
|
+
if (nextCheckAt === Number.MAX_SAFE_INTEGER) {
|
|
589
|
+
throw new Error(
|
|
590
|
+
'Illegal state: there must be at least one cooldown or rotation',
|
|
591
|
+
);
|
|
592
|
+
}
|
|
593
|
+
logger.debug('Schedule next rotation at', nextCheckAt);
|
|
594
|
+
this._nextRotationCheck = nextCheckAt;
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
async selfChecks(check = new SelfCheck()) {
|
|
598
|
+
if (this._rotationConfig) {
|
|
599
|
+
const { cooldowns, rotations } = this._rotationConfig;
|
|
600
|
+
if (!cooldowns && !rotations) {
|
|
601
|
+
check.fail(
|
|
602
|
+
'Lack of cooldowns and rotations means the system cannot make progress',
|
|
603
|
+
);
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
if (this._rotationFailuresInARow > 0) {
|
|
607
|
+
const failuresInARow = this._rotationFailuresInARow;
|
|
608
|
+
check.warn(
|
|
609
|
+
'Last rotation failed. All visit will be currently discarded.',
|
|
610
|
+
{
|
|
611
|
+
failuresInARow,
|
|
612
|
+
},
|
|
613
|
+
);
|
|
614
|
+
}
|
|
615
|
+
if (this._rotationConfigPendingWrite !== null) {
|
|
616
|
+
check.warn('Rotation config modified but not synced to disk yet.');
|
|
617
|
+
}
|
|
618
|
+
return check;
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
// visible for testing
|
|
622
|
+
async runRotationChecks(now = Date.now()) {
|
|
623
|
+
return this._criticalSection.run(async () => this._runRotationChecks(now));
|
|
624
|
+
}
|
|
625
|
+
}
|