@whotracksme/reporting 5.1.28 → 5.1.30

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.
Files changed (59) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/package.json +1 -1
  3. package/reporting/example/index.js +2 -12
  4. package/reporting/example/manifests/chromium.json +1 -0
  5. package/reporting/snapshots/0001/events.log.br +0 -0
  6. package/reporting/snapshots/0001/snapshot.json +4173 -0
  7. package/reporting/snapshots/0002/events.log.br +0 -0
  8. package/reporting/snapshots/0002/snapshot.json +2539 -0
  9. package/reporting/snapshots/0003/events.log.br +0 -0
  10. package/reporting/snapshots/0003/snapshot.json +855 -0
  11. package/reporting/snapshots/0004/events.log.br +0 -0
  12. package/reporting/snapshots/0004/snapshot.json +802 -0
  13. package/reporting/src/hash-detector.js +1 -1
  14. package/reporting/src/index.js +1 -2
  15. package/reporting/src/request/config.js +9 -4
  16. package/reporting/src/request/{hash.js → hash/index.js} +3 -3
  17. package/reporting/src/request/index.js +447 -496
  18. package/reporting/src/{webrequest-pipeline → request}/page-store.js +65 -75
  19. package/reporting/src/request/qs-whitelist2.js +0 -2
  20. package/reporting/src/request/steps/cookie-context.js +6 -5
  21. package/reporting/src/request/steps/oauth-detector.js +3 -24
  22. package/reporting/src/request/steps/page-logger.js +3 -4
  23. package/reporting/src/request/steps/token-checker/token-domain.js +1 -1
  24. package/reporting/src/request/steps/token-examiner.js +3 -4
  25. package/reporting/src/request/steps/token-telemetry/cached-entry-pipeline.js +55 -75
  26. package/reporting/src/request/steps/token-telemetry/index.js +86 -115
  27. package/reporting/src/request/steps/token-telemetry/key-pipeline.js +3 -2
  28. package/reporting/src/request/steps/token-telemetry/token-pipeline.js +3 -2
  29. package/reporting/src/request/utils/temp-set.js +2 -4
  30. package/reporting/src/request/{time.js → utils/time.js} +0 -5
  31. package/reporting/src/request/utils/tlds.js +1 -11
  32. package/reporting/src/request/{utils.js → utils/utils.js} +9 -0
  33. package/reporting/src/{webrequest-pipeline/webrequest-context.js → request/utils/webrequest.js} +84 -4
  34. package/reporting/src/utils/url.js +0 -25
  35. package/reporting/test/helpers/scenarios.js +76 -17
  36. package/reporting/test/index.js +3 -8
  37. package/reporting/test/request/database.test.js +96 -0
  38. package/reporting/test/request/{hash.spec.js → hash/index.spec.js} +2 -2
  39. package/reporting/test/request/index.spec.js +24 -46
  40. package/reporting/test/{request-reporter.test.js → request/index.test.js} +102 -46
  41. package/reporting/test/{webrequest-pipeline → request}/page-store.test.js +1 -1
  42. package/reporting/test/request/steps/oauth-detector.spec.js +15 -25
  43. package/reporting/test/request/{utils.spec.js → utils/utils.spec.js} +2 -2
  44. package/reporting/test/setup.unit.js +1 -0
  45. package/reporting/test/utils/url.spec.js +1 -26
  46. package/reporting/src/request/page-telemetry.js +0 -42
  47. package/reporting/src/request/steps/subdomain-check.js +0 -34
  48. package/reporting/src/request/utils/subject.js +0 -37
  49. package/reporting/src/request-reporter.js +0 -111
  50. package/reporting/src/utils/pacemaker.js +0 -279
  51. package/reporting/src/webrequest-pipeline/cname-uncloak.js +0 -110
  52. package/reporting/src/webrequest-pipeline/index.js +0 -286
  53. package/reporting/src/webrequest-pipeline/logger.js +0 -14
  54. package/reporting/src/webrequest-pipeline/pipeline.js +0 -249
  55. package/reporting/src/webrequest-pipeline/utils/webrequest.js +0 -119
  56. package/reporting/test/utils/pacemaker.spec.js +0 -222
  57. package/reporting/test/webrequest-pipeline/index.test.js +0 -160
  58. package/reporting/test/webrequest-pipeline/pipeline.spec.js +0 -251
  59. /package/reporting/src/request/{resources → hash}/prob.js +0 -0
@@ -74,15 +74,11 @@ describe('request/steps/oauth-detector', function () {
74
74
  await detectorInstance.init();
75
75
  });
76
76
 
77
- afterEach(function () {
78
- detectorInstance.unload();
79
- });
80
-
81
77
  it('registers clicks on tabs', (done) => {
82
78
  const tab = 5;
83
79
  const url = 'https://cliqz.com';
84
80
  const sender = mockSender(tab, url);
85
- detectorInstance.recordClick(null, '', '', sender);
81
+ detectorInstance.recordClick(sender);
86
82
  delayedTest(
87
83
  () => {
88
84
  chai
@@ -102,8 +98,8 @@ describe('request/steps/oauth-detector', function () {
102
98
  const tab = 5;
103
99
  const url1 = 'https://cliqz.com';
104
100
  const url2 = 'https://ghostery.com';
105
- detectorInstance.recordClick(null, '', '', mockSender(tab, url1));
106
- detectorInstance.recordClick(null, '', '', mockSender(tab, url2));
101
+ detectorInstance.recordClick(mockSender(tab, url1));
102
+ detectorInstance.recordClick(mockSender(tab, url2));
107
103
  delayedTest(
108
104
  () => {
109
105
  chai
@@ -124,8 +120,8 @@ describe('request/steps/oauth-detector', function () {
124
120
  const tab2 = 6;
125
121
  const url1 = 'https://cliqz.com';
126
122
  const url2 = 'https://ghostery.com';
127
- detectorInstance.recordClick(null, '', '', mockSender(tab1, url1));
128
- detectorInstance.recordClick(null, '', '', mockSender(tab2, url2));
123
+ detectorInstance.recordClick(mockSender(tab1, url1));
124
+ detectorInstance.recordClick(mockSender(tab2, url2));
129
125
  delayedTest(
130
126
  () => {
131
127
  chai
@@ -146,7 +142,7 @@ describe('request/steps/oauth-detector', function () {
146
142
  const tab = 5;
147
143
  const url = 'https://cliqz.com';
148
144
  const sender = mockSender(tab, url);
149
- detectorInstance.recordClick(null, '', '', sender);
145
+ detectorInstance.recordClick(sender);
150
146
  delayedTest(
151
147
  () => {
152
148
  chai
@@ -165,10 +161,9 @@ describe('request/steps/oauth-detector', function () {
165
161
  const tab2 = 6;
166
162
  const url1 = 'https://cliqz.com';
167
163
  const url2 = 'https://ghostery.com';
168
- detectorInstance.recordClick(null, '', '', mockSender(tab1, url1));
164
+ detectorInstance.recordClick(mockSender(tab1, url1));
169
165
  setTimeout(
170
- () =>
171
- detectorInstance.recordClick(null, '', '', mockSender(tab2, url2)),
166
+ () => detectorInstance.recordClick(mockSender(tab2, url2)),
172
167
  10,
173
168
  );
174
169
  delayedTest(
@@ -191,11 +186,10 @@ describe('request/steps/oauth-detector', function () {
191
186
  const tab2 = 6;
192
187
  const url1 = 'https://cliqz.com';
193
188
  const url2 = 'https://ghostery.com';
194
- detectorInstance.recordClick(null, '', '', mockSender(tab1, url1));
195
- detectorInstance.recordClick(null, '', '', mockSender(tab2, url2));
189
+ detectorInstance.recordClick(mockSender(tab1, url1));
190
+ detectorInstance.recordClick(mockSender(tab2, url2));
196
191
  setTimeout(
197
- () =>
198
- detectorInstance.recordClick(null, '', '', mockSender(tab1, url1)),
192
+ () => detectorInstance.recordClick(mockSender(tab1, url1)),
199
193
  10,
200
194
  );
201
195
  delayedTest(
@@ -236,10 +230,6 @@ describe('request/steps/oauth-detector', function () {
236
230
  await detectorInstance.init();
237
231
  });
238
232
 
239
- afterEach(function () {
240
- detectorInstance.unload();
241
- });
242
-
243
233
  it('returns true when there has been no activity and the URL contains "/oauth"', () => {
244
234
  const state = mockState(
245
235
  5,
@@ -261,7 +251,7 @@ describe('request/steps/oauth-detector', function () {
261
251
  it('returns true when there is only a click', (done) => {
262
252
  const tab = 5;
263
253
  const tabUrl = 'https://cliqz.com/';
264
- detectorInstance.recordClick(null, '', '', mockSender(tab, tabUrl));
254
+ detectorInstance.recordClick(mockSender(tab, tabUrl));
265
255
  const state = mockState(tab, 'https://auth.ghostery.com/oauth', tabUrl);
266
256
  delayedTest(
267
257
  () => {
@@ -275,7 +265,7 @@ describe('request/steps/oauth-detector', function () {
275
265
  it('returns false with click and page', (done) => {
276
266
  const tab = 5;
277
267
  const tabUrl = 'https://cliqz.com/';
278
- detectorInstance.recordClick(null, '', '', mockSender(tab, tabUrl));
268
+ detectorInstance.recordClick(mockSender(tab, tabUrl));
279
269
  const fullPageState = mockState(
280
270
  tab + 1,
281
271
  'https://auth.ghostery.com/',
@@ -296,7 +286,7 @@ describe('request/steps/oauth-detector', function () {
296
286
  it('returns true if page domain does not match', (done) => {
297
287
  const tab = 5;
298
288
  const tabUrl = 'https://cliqz.com/';
299
- detectorInstance.recordClick(null, '', '', mockSender(tab, tabUrl));
289
+ detectorInstance.recordClick(mockSender(tab, tabUrl));
300
290
  const fullPageState = mockState(
301
291
  tab + 1,
302
292
  'https://www.ghostery.com/',
@@ -318,7 +308,7 @@ describe('request/steps/oauth-detector', function () {
318
308
  const tab = 5;
319
309
  const tabUrl = 'https://cliqz.com/';
320
310
  const tabUrl2 = 'https://www.cliqz.com/';
321
- detectorInstance.recordClick(null, '', '', mockSender(tab, tabUrl));
311
+ detectorInstance.recordClick(mockSender(tab, tabUrl));
322
312
  const fullPageState = mockState(
323
313
  tab + 1,
324
314
  'https://www.ghostery.com/',
@@ -11,9 +11,9 @@
11
11
 
12
12
  import * as chai from 'chai';
13
13
 
14
- import { truncateDomain } from '../../src/request/utils';
14
+ import { truncateDomain } from '../../../src/request/utils/utils';
15
15
 
16
- describe('request/utils', function () {
16
+ describe('request/utils/utils', function () {
17
17
  describe('truncateDomain', function () {
18
18
  it('does not change domain which is already tld+1', () => {
19
19
  chai
@@ -9,6 +9,7 @@
9
9
  * file, You can obtain one at http://mozilla.org/MPL/2.0
10
10
  */
11
11
 
12
+ import 'fake-indexeddb/auto';
12
13
  import * as chai from 'chai';
13
14
  import sinonChai from 'sinon-chai';
14
15
  import chaiAsPromised from 'chai-as-promised';
@@ -11,7 +11,7 @@
11
11
 
12
12
  import * as chai from 'chai';
13
13
 
14
- import { getName, parse } from '../../src/utils/url';
14
+ import { parse } from '../../src/utils/url';
15
15
 
16
16
  const plainUrls = [
17
17
  {
@@ -521,31 +521,6 @@ function fillInSpec(spec) {
521
521
  }
522
522
 
523
523
  describe('utils/url', function () {
524
- describe('#getName', () => {
525
- it('return "null" for invalid URL', () => {
526
- chai.expect(getName(parse('foo'))).to.equal(null);
527
- });
528
-
529
- it('return "IP" if URL is ipv4', () => {
530
- chai.expect(getName(parse('https://1.1.1.1/'))).to.equal('IP');
531
- });
532
-
533
- // Currently not handled by '@cliqz/url-parser' but will be fixed soon.
534
- it.skip('return "IP" if URL is ipv6', () => {
535
- chai.expect(getName(parse('https://[::1]/'))).to.equal('IP');
536
- });
537
-
538
- it('handle localhost', () => {
539
- chai
540
- .expect(getName(parse('http://localhost/path')))
541
- .to.equal('localhost');
542
- });
543
-
544
- it('return domain without suffix', () => {
545
- chai.expect(getName(parse('https://sub.foo.co.uk'))).to.equal('foo');
546
- });
547
- });
548
-
549
524
  describe('#parse', () => {
550
525
  function testSpecArray(name, spec) {
551
526
  describe(name, function () {
@@ -1,42 +0,0 @@
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 { truncatedHash } from '../md5.js';
13
- import { parse } from '../utils/url.js';
14
-
15
- function truncatePath(path) {
16
- // extract the first part of the page path
17
- const [prefix] = path.substring(1).split('/');
18
- return `/${prefix}`;
19
- }
20
-
21
- export default function buildPageLoadObject(page) {
22
- const urlParts = parse(page.url);
23
- const tps = { ...page.requestStats };
24
- return {
25
- hostname: truncatedHash(urlParts.hostname),
26
- path: truncatedHash(truncatePath(urlParts.path)),
27
- scheme: urlParts.scheme,
28
- c: 1,
29
- t: Math.round(page.destroyed - page.created),
30
- active: page.activeTime,
31
- counter: page.counter,
32
- ra: 0,
33
- tps,
34
- placeHolder: false,
35
- redirects: [],
36
- redirectsPlaceHolder: [],
37
- triggeringTree: {},
38
- tsv: '',
39
- tsv_id: false,
40
- frames: {},
41
- };
42
- }
@@ -1,34 +0,0 @@
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
- export default class SubdomainCheck {
13
- constructor(config) {
14
- this.config = config;
15
- }
16
-
17
- checkBadSubdomain(state, response) {
18
- const subdomainRewriteRules = this.config.subdomainRewriteRules || {};
19
- const requestHost = state.urlParts.hostname;
20
- const rules = Object.keys(subdomainRewriteRules);
21
- for (let i = 0; i < rules.length; i += 1) {
22
- const rule = rules[i];
23
- if (requestHost.endsWith(rule)) {
24
- const newUrl = state.url.replace(
25
- requestHost,
26
- subdomainRewriteRules[rule],
27
- );
28
- response.redirectTo(newUrl);
29
- return false;
30
- }
31
- }
32
- return true;
33
- }
34
- }
@@ -1,37 +0,0 @@
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 logger from '../../logger.js';
13
-
14
- export default class Subject {
15
- constructor() {
16
- this.listeners = new Set();
17
- }
18
-
19
- subscribe(callback) {
20
- this.listeners.add(callback);
21
- return {
22
- unsubscribe: () => {
23
- this.listeners.delete(callback);
24
- },
25
- };
26
- }
27
-
28
- pub(message) {
29
- this.listeners.forEach((listener) => {
30
- try {
31
- listener(message);
32
- } catch (e) {
33
- logger.error('Subject failed to notify listener', e);
34
- }
35
- });
36
- }
37
- }
@@ -1,111 +0,0 @@
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 RequestMonitor from './request/index.js';
13
- import Config from './request/config.js';
14
- import Database from './request/database.js';
15
-
16
- export default class RequestReporter {
17
- constructor(
18
- settings,
19
- {
20
- communication,
21
- countryProvider,
22
- trustedClock,
23
- webRequestPipeline,
24
- onTrackerInteraction,
25
- getBrowserInfo,
26
- isRequestAllowed,
27
- },
28
- ) {
29
- this.settings = settings;
30
- this.communication = communication;
31
- this.countryProvider = countryProvider;
32
- this.trustedClock = trustedClock;
33
- this.webRequestPipeline = webRequestPipeline;
34
- this.onTrackerInteraction = onTrackerInteraction;
35
- this.getBrowserInfo = getBrowserInfo;
36
- this.isRequestAllowed = isRequestAllowed;
37
- }
38
-
39
- async init() {
40
- this.db = new Database();
41
- await this.db.init();
42
-
43
- this.config = new Config(this.settings, {
44
- db: this.db,
45
- trustedClock: this.trustedClock,
46
- });
47
- this.requestMonitor = new RequestMonitor(this.settings, {
48
- db: this.db,
49
- webRequestPipeline: this.webRequestPipeline,
50
- trustedClock: this.trustedClock,
51
- countryProvider: this.countryProvider,
52
- communication: this.communication,
53
- onTrackerInteraction: this.onTrackerInteraction,
54
- getBrowserInfo: this.getBrowserInfo,
55
- isRequestAllowed: this.isRequestAllowed,
56
- });
57
-
58
- await this.config.init();
59
- await this.requestMonitor.init(this.config);
60
- }
61
-
62
- unload() {
63
- if (this.requestMonitor) {
64
- this.requestMonitor.unload();
65
- this.requestMonitor = null;
66
- }
67
- this.webRequestPipeline.unload();
68
- }
69
-
70
- addPipelineStep(stage, opts) {
71
- if (
72
- !this.requestMonitor.pipelines ||
73
- !this.requestMonitor.pipelines[stage]
74
- ) {
75
- return Promise.reject(
76
- new Error(`Could not add pipeline step: ${stage}, ${opts.name}`),
77
- );
78
- }
79
-
80
- return this.requestMonitor.pipelines[stage].addPipelineStep(opts);
81
- }
82
-
83
- removePipelineStep(stage, name) {
84
- if (
85
- this.requestMonitor &&
86
- this.requestMonitor.pipelines &&
87
- this.requestMonitor.pipelines[stage]
88
- ) {
89
- this.requestMonitor.pipelines[stage].removePipelineStep(name);
90
- }
91
- }
92
-
93
- recordClick(event, context, href, sender) {
94
- this.requestMonitor.pipelineSteps.cookieContext.setContextFromEvent(
95
- event,
96
- context,
97
- href,
98
- sender,
99
- );
100
- this.requestMonitor.pipelineSteps.oAuthDetector.recordClick(
101
- event,
102
- context,
103
- href,
104
- sender,
105
- );
106
- }
107
-
108
- clearCache() {
109
- this.requestMonitor.clearCache();
110
- }
111
- }
@@ -1,279 +0,0 @@
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 { Logger } from '../logger.js';
13
-
14
- // Pacemaker is a service which allows to schedule tasks (either as intervals or
15
- // timeouts) while doing its best to not wake-up the browser too often. To this
16
- // end, it offers a few common intervals (e.g.: every minute, every hour,
17
- // etc.) and makes sure that all the tasks are triggered at the same time. It
18
- // also tries to adapt its own frequency depending on registered tasks to
19
- // trigger as rarely as possible while respecting the contract. As a
20
- // consequence, if there is no task registered, the pacemaker will do nothing.
21
- //
22
- // It is possible to schedule tasks at any time, but this is not recommended. To
23
- // make sure the efficiency is maximal, you should pick a pre-defined method
24
- // like `everyFewMinutes` (instead of `register`) and choose the maximum time
25
- // which fits your use-case.
26
- //
27
- // Here are a few examples:
28
- //
29
- // 1. You need to update a config fetched from CDN and it does not change more
30
- // than once an hour, then it's recommended to use `pacemaker.everyHour()`.
31
- //
32
- // 2. You need to run a check on the state of your module every few seconds (and
33
- // it does not matter exactly how many seconds as long as it's less or equal to
34
- // 10), then you should use `pacemaker.everyFewSeconds()`.
35
-
36
- const logger = Logger.get('pacemaker', { level: 'log' });
37
-
38
- // Common durations
39
- const ONE_SECOND = 1000;
40
- const ONE_MINUTE = 60 * ONE_SECOND;
41
- const ONE_HOUR = 60 * ONE_MINUTE;
42
- // const ONE_DAY = 24 * ONE_HOUR;
43
-
44
- class Task {
45
- constructor({ fn, timeout, once, startImmediately, args }) {
46
- if (!fn.name || fn.name === 'fn') {
47
- throw new Error('Pacemaker can register named callbacks only');
48
- }
49
- this.name = fn.name || '<anon>';
50
- this.fn = fn;
51
- this.timeout = timeout;
52
- this.once = once;
53
- this.args = args;
54
-
55
- // Setting `last` to `0` means that whenever the next tick happens, this
56
- // task will be triggerd, no matter how big the `timeout` is.
57
- this.last = startImmediately ? -timeout : Date.now();
58
- this.startImmediately = startImmediately;
59
-
60
- this.verboseLogging = false;
61
- }
62
-
63
- run(now) {
64
- if (this.verboseLogging) {
65
- logger.debug('run task:', this.name);
66
- }
67
- const t0 = Date.now();
68
- try {
69
- this.fn(...this.args);
70
- this.last = now;
71
- if (this.verboseLogging) {
72
- logger.debug('task', this.name, 'took', Date.now() - t0, 'ms');
73
- }
74
- } catch (e) {
75
- logger.error('error executing task', this.name, e);
76
- }
77
- }
78
- }
79
-
80
- export class Pacemaker {
81
- constructor() {
82
- this.freq = null;
83
- this.timer = null;
84
- this.tasks = new Set();
85
- }
86
-
87
- stop() {
88
- clearTimeout(this.timer);
89
- this.timer = null;
90
- this.freq = null;
91
- this.tasks = new Set();
92
- }
93
-
94
- /**
95
- * When tasks are added or removed, make sure that the pacemaker interval is
96
- * running at a frequency which corresponds to the frequency of the most
97
- * frequent task. If that is not the case already, then the existing interval
98
- * is stopped and a new one is started with the correct frequency.
99
- *
100
- * If there is currently no registered task, then stop the interval completely.
101
- */
102
- _adjustFrequency({ added = [], removed = [] } = {}) {
103
- if (this.verboseLogging) {
104
- logger.debug('_adjustFrequency', { added, removed });
105
- }
106
-
107
- if (this.tasks.size === 0) {
108
- logger.log('no task in pacemaker, stop interval');
109
- this.stop();
110
- return;
111
- }
112
-
113
- if (this.freq !== null) {
114
- // Knowing which tasks were removed and which were added we can check if we
115
- // actually need to adjust the interval. If a task with interval lower than
116
- // the current pacemaker interval is added then we need to adjust.
117
- let minIntervalAdded = Number.MAX_SAFE_INTEGER;
118
- if (added.length !== 0) {
119
- for (const { timeout } of added) {
120
- if (timeout < minIntervalAdded) {
121
- minIntervalAdded = timeout;
122
- }
123
- }
124
- }
125
-
126
- // If a task with interval equal to the current interval of the pacemaker
127
- // then we might need to adjust (if this was the only task with this
128
- // interval).
129
- let minIntervalRemoved = Number.MAX_SAFE_INTEGER;
130
- if (removed.length !== 0) {
131
- for (const { timeout } of removed) {
132
- if (timeout < minIntervalRemoved) {
133
- minIntervalRemoved = timeout;
134
- }
135
- }
136
- }
137
-
138
- // If none of the conditions is met then the current interval is un-changed.
139
- if (minIntervalAdded >= this.freq && minIntervalRemoved > this.freq) {
140
- return;
141
- }
142
- }
143
-
144
- // Get minimum frequency of remaining tasks and use it as base interval
145
- let minFreq = Number.MAX_SAFE_INTEGER;
146
- for (const { timeout } of this.tasks) {
147
- if (timeout < minFreq) {
148
- minFreq = timeout;
149
- }
150
- }
151
- logger.debug('current minimum timeout:', minFreq);
152
-
153
- // Frequency needs to be adjusted
154
- if (this.freq === null || this.freq !== minFreq) {
155
- logger.log('interval timeout change detected', this.freq, '->', minFreq);
156
-
157
- // Reset timeout
158
- clearTimeout(this.timer);
159
- this.freq = minFreq;
160
-
161
- // In case some instant task was added, we run a first tick to make sure
162
- // instant timeouts or intervals are executed straight away. Otherwise, we
163
- // just set a timeout to trigger a _tick in `this.freq` milliseconds.
164
- const hasInstantTask = added.some(
165
- ({ startImmediately }) => startImmediately,
166
- );
167
- this._scheduleNextTick(hasInstantTask ? 0 : this.freq);
168
- }
169
- }
170
-
171
- /**
172
- * Schedule next tick
173
- */
174
- _scheduleNextTick(timeout) {
175
- clearTimeout(this.timer);
176
- this.timer = setTimeout(() => this._tick(), timeout);
177
- }
178
-
179
- /**
180
- * Make sure that tasks which should run... run.
181
- */
182
- _tick() {
183
- const now = Date.now();
184
- if (this.verboseLogging) {
185
- logger.debug('_tick', now);
186
- }
187
-
188
- // Check all tasks
189
- const removedTasks = [];
190
- for (const task of this.tasks) {
191
- if (now >= task.last + task.timeout) {
192
- task.run(now);
193
-
194
- // delete setTimeout tasks after they run
195
- if (task.once === true) {
196
- this.tasks.delete(task);
197
- removedTasks.push(task);
198
- }
199
- }
200
- }
201
- if (this.verboseLogging) {
202
- logger.debug('duration sync', Date.now() - now);
203
- }
204
-
205
- // Register timout for next _tick
206
- this._scheduleNextTick(this.freq);
207
-
208
- // Check if frequency needs to be adjusted
209
- if (removedTasks.length !== 0) {
210
- this._adjustFrequency({ removed: removedTasks });
211
- }
212
- }
213
-
214
- /**
215
- * Register a function to be run by the pacemaker. By default it will run
216
- * periodically like in a setInterval. It's possible to make the function
217
- * start immediately, or only once like a setTimeout.
218
- */
219
- register(fn, { timeout, once = false, startImmediately = false, args = [] }) {
220
- if (fn === undefined) {
221
- throw new Error('fn cannot be undefined');
222
- }
223
-
224
- if (timeout === undefined) {
225
- throw new Error('timeout cannot be undefined');
226
- }
227
-
228
- const task = new Task({
229
- fn,
230
- timeout,
231
- once,
232
- startImmediately,
233
- args,
234
- });
235
-
236
- logger.debug('new task', task);
237
- this.tasks.add(task);
238
- this._adjustFrequency({ added: [task] });
239
-
240
- return {
241
- stop: () => {
242
- this.tasks.delete(task);
243
- this._adjustFrequency({ removed: [task] });
244
- },
245
- };
246
- }
247
-
248
- everySecond(fn) {
249
- return this.register(fn, { timeout: ONE_SECOND });
250
- }
251
-
252
- everyFewSeconds(fn) {
253
- return this.register(fn, { timeout: 10 * ONE_SECOND });
254
- }
255
-
256
- everyMinute(fn) {
257
- return this.register(fn, { timeout: ONE_MINUTE });
258
- }
259
-
260
- everyFewMinutes(fn) {
261
- return this.register(fn, { timeout: 10 * ONE_MINUTE });
262
- }
263
-
264
- everyHour(fn) {
265
- return this.register(fn, { timeout: ONE_HOUR });
266
- }
267
-
268
- setTimeout(fn, timeout, ...args) {
269
- return this.register(fn, { timeout, once: true, args });
270
- }
271
-
272
- clearTimeout(timeout) {
273
- if (timeout && timeout.stop) {
274
- timeout.stop();
275
- }
276
- }
277
- }
278
-
279
- export default new Pacemaker();