@whotracksme/reporting 7.4.0 β†’ 7.4.1

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 CHANGED
@@ -1,3 +1,15 @@
1
+ # v7.4.1 (Tue Jul 29 2025)
2
+
3
+ #### πŸ› Bug Fix
4
+
5
+ - Job scheduling: tweaked scheduling and misconfiguration detection [#163](https://github.com/whotracksme/webextension-packages/pull/163) ([@philipp-classen](https://github.com/philipp-classen))
6
+
7
+ #### Authors: 1
8
+
9
+ - Philipp Claßen ([@philipp-classen](https://github.com/philipp-classen))
10
+
11
+ ---
12
+
1
13
  # v7.4.0 (Tue Jul 01 2025)
2
14
 
3
15
  #### πŸš€ Enhancement
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@whotracksme/reporting",
3
- "version": "7.4.0",
3
+ "version": "7.4.1",
4
4
  "type": "module",
5
5
  "description": "",
6
6
  "scripts": {
@@ -17,8 +17,8 @@
17
17
  "@rollup/plugin-commonjs": "^23.0.0",
18
18
  "@rollup/plugin-json": "^5.0.0",
19
19
  "@rollup/plugin-node-resolve": "^13.3.0",
20
- "chai": "^4.3.6",
21
- "chai-as-promised": "^7.1.1",
20
+ "chai": "^5.2.0",
21
+ "chai-as-promised": "^8.0.1",
22
22
  "fake-indexeddb": "^6.0.0",
23
23
  "fast-check": "^3.3.0",
24
24
  "karma": "^6.4.1",
@@ -28,13 +28,13 @@
28
28
  "karma-mocha-reporter": "^2.2.5",
29
29
  "karma-rollup-preprocessor": "^7.0.8",
30
30
  "karma-sinon": "^1.0.5",
31
- "mocha": "^10.7.3",
31
+ "mocha": "^11.7.1",
32
32
  "rollup": "^2.79.1",
33
33
  "rollup-plugin-copy": "^3.5.0",
34
34
  "rollup-plugin-polyfill-node": "^0.8.0",
35
35
  "rollup-plugin-sourcemaps": "^0.6.3",
36
- "sinon": "^15.2.0",
37
- "sinon-chai": "^3.7.0",
36
+ "sinon": "^21.0.0",
37
+ "sinon-chai": "^4.0.0",
38
38
  "sinon-chrome": "^3.0.1",
39
39
  "web-ext": "^8.2.0"
40
40
  },
@@ -49,7 +49,7 @@ export default class AttrackMessageHandler {
49
49
  priority: -1000,
50
50
  cooldownInMs: 1 * SECOND,
51
51
  maxJobsTotal: 500,
52
- maxTTL: 14 * DAY,
52
+ ttlInMs: 14 * DAY,
53
53
  },
54
54
  );
55
55
  }
@@ -47,6 +47,12 @@ class PermanentError extends ExtendableError {
47
47
  */
48
48
  export class BadJobError extends PermanentError {}
49
49
 
50
+ /**
51
+ * For job handlers that are ill-formed (e.g. have missing or invalid fields
52
+ * in their configuration).
53
+ */
54
+ export class BadJobHandlerError extends PermanentError {}
55
+
50
56
  /**
51
57
  * If trying to override HTTP headers, but the platform does not support it.
52
58
  */
@@ -11,7 +11,7 @@
11
11
 
12
12
  import logger from './logger';
13
13
  import { randomBetween } from './random';
14
- import { BadJobError } from './errors';
14
+ import { BadJobError, BadJobHandlerError } from './errors';
15
15
  import SeqExecutor from './seq-executor';
16
16
  import { equalityCanBeProven } from './utils';
17
17
  import SelfCheck from './self-check';
@@ -55,21 +55,38 @@ class JobTester {
55
55
  return jobEntries.splice(0, pos);
56
56
  }
57
57
 
58
- // Note: smaller is of higher priority
58
+ /**
59
+ * Computes the priority of a job. Smaller is of higher priority.
60
+ *
61
+ * When ordering jobs by their priority, the order should remain stable over time.
62
+ * Formally, if "p(t,j)" is the priority function for job "j" at a given time "t",
63
+ * the following property should hold:
64
+ *
65
+ * For all jobs j1,j2 and for all times t1, t2 with t2 > t1:
66
+ * ```
67
+ * p(t1,j1) <= p(t1,j2) ==> p(t2,j1) <= p(t2,j2)
68
+ * ```
69
+ *
70
+ * Note: it automatically holds if p does not rely on the time. In other
71
+ * words, this is a sufficient, but not necessary condition:
72
+ * ```
73
+ * For all times t1, t2 and for all jobs j: p(t1,j) == p(t2,j)
74
+ * ```
75
+ */
59
76
  computePriority(jobEntry) {
60
- // TODO: this could be improved (though prefer old jobs is not a bad strategy)
61
- return jobEntry._meta.createdAt;
77
+ // This will order jobs primarily by the time when they become ready.
78
+ // It also guarantees that jobs that are ready will be sorted before
79
+ // jobs that are still blocked.
80
+ //
81
+ // To break ties between multiple jobs that are ready, it will run the
82
+ // oldest jobs first; thus, eliminating the possiblity of starvation.
83
+ //
84
+ // Note: preserves ordering, since the time is not used.
85
+ return Math.max(jobEntry._meta.createdAt, jobEntry._meta.readyAt);
62
86
  }
63
87
 
64
88
  compareJobsByPriority(jobEntry1, jobEntry2) {
65
- if (this.isJobReady(jobEntry1)) {
66
- return -1;
67
- } else if (this.isJobReady(jobEntry2)) {
68
- return 1;
69
- }
70
- const prio1 = this.computePriority(jobEntry1);
71
- const prio2 = this.computePriority(jobEntry2);
72
- return prio1 - prio2;
89
+ return this.computePriority(jobEntry1) - this.computePriority(jobEntry2);
73
90
  }
74
91
 
75
92
  sortJobs(jobEntries) {
@@ -166,6 +183,7 @@ export default class JobScheduler {
166
183
  // TODO: maybe add a flag to control if failed jobs should be put in the dlq
167
184
  // (and only added back if there was was a successful execution of that type before)
168
185
  };
186
+ this._ensureValidHandlerConfig(this.defaultConfig);
169
187
  this.handlerConfigs = {};
170
188
 
171
189
  // Note: this data structure is intended to be in a format that can be
@@ -189,6 +207,9 @@ export default class JobScheduler {
189
207
  }
190
208
 
191
209
  registerHandler(type, handler, config = {}) {
210
+ const fullConfig = { ...this.defaultConfig, ...config };
211
+ this._ensureValidHandlerConfig(fullConfig);
212
+
192
213
  if (this.active) {
193
214
  logger.warn(
194
215
  'Job handler for type',
@@ -202,12 +223,12 @@ export default class JobScheduler {
202
223
  logger.warn('Redefining handler for type:', type);
203
224
  }
204
225
  this.handlers[type] = handler;
205
- this.handlerConfigs[type] = { ...this.defaultConfig, ...config };
226
+ this.handlerConfigs[type] = fullConfig;
206
227
  logger.debug(
207
228
  'Registered job handler for',
208
229
  type,
209
230
  'with config:',
210
- this.handlerConfigs[type],
231
+ fullConfig,
211
232
  );
212
233
  this._resetPrecomputed();
213
234
  }
@@ -846,6 +867,52 @@ export default class JobScheduler {
846
867
  }
847
868
  }
848
869
 
870
+ // Validates the config that is passed when registering job handlers.
871
+ _ensureValidHandlerConfig(config) {
872
+ if (!config) {
873
+ throw new BadJobHandlerError('Missing config');
874
+ }
875
+ let numCheckedKeys = 0;
876
+ const expectInt = (key, extraCheck) => {
877
+ if (!Number.isInteger(config[key])) {
878
+ throw new BadJobHandlerError(
879
+ `Expected field "${key}" to be an integer, but got: ${config[key]}`,
880
+ );
881
+ }
882
+ if (extraCheck && !extraCheck(config[key])) {
883
+ throw new BadJobHandlerError(
884
+ `Illegal value found in field "${key}": <<${config[key]}>>`,
885
+ );
886
+ }
887
+ numCheckedKeys += 1;
888
+ };
889
+ const expectBool = (key) => {
890
+ if (config[key] !== true && config[key] !== false) {
891
+ throw new BadJobHandlerError(
892
+ `Expected field "${key}" to be bool, but got: ${config[key]}`,
893
+ );
894
+ }
895
+ numCheckedKeys += 1;
896
+ };
897
+ const nonNegative = (x) => x >= 0;
898
+
899
+ expectInt('priority');
900
+ expectInt('ttlInMs', nonNegative);
901
+ expectInt('maxJobsTotal', nonNegative);
902
+ expectInt('cooldownInMs', nonNegative);
903
+ expectInt('maxAutoRetriesAfterError', nonNegative);
904
+ expectBool('autoRetryAfterError');
905
+
906
+ if (numCheckedKeys !== Object.keys(config).length) {
907
+ const unexpectedKeys = Object.keys(config).filter(
908
+ (key) => !Object.hasOwn(this.defaultConfig, key),
909
+ );
910
+ throw new BadJobHandlerError(
911
+ `Invalid config: found unexpected keys: [${unexpectedKeys.join(', ')}]`,
912
+ );
913
+ }
914
+ }
915
+
849
916
  async selfChecks(check = new SelfCheck()) {
850
917
  const restoredJobs = JSON.parse(JSON.stringify(this.jobQueues));
851
918
  if (!equalityCanBeProven(this.jobQueues, restoredJobs)) {
@@ -25,11 +25,11 @@ const YEAR = 365 * DAY;
25
25
  function mockStorage(storageKey) {
26
26
  return {
27
27
  async get(key) {
28
- expect(key).to.equal(storageKey);
28
+ expect(key).to.eql(storageKey);
29
29
  return this._content;
30
30
  },
31
31
  async set(key, obj) {
32
- expect(key).to.equal(storageKey);
32
+ expect(key).to.eql(storageKey);
33
33
  this._content = obj;
34
34
  },
35
35
  };
@@ -296,7 +296,7 @@ describe('#JobScheduler', function () {
296
296
  await passesSelfChecks();
297
297
  });
298
298
 
299
- it('should allow to processPendingJobs when the queue, but jobs are registered', async function () {
299
+ it('should allow to processPendingJobs when the queue is empty, but jobs are registered', async function () {
300
300
  uut.registerHandler('dummy', () => expect.fail('should never be called'));
301
301
  await uut.init();
302
302
  await uut.processPendingJobs();
@@ -450,7 +450,7 @@ describe('#JobScheduler', function () {
450
450
  await uut.registerJob(job1);
451
451
  await uut.processPendingJobs();
452
452
  expectJobIsDone(job1);
453
- expect(uut.stats.jobRegistered).to.equal(1);
453
+ expect(uut.stats.jobRegistered).to.eql(1);
454
454
  expect(uut.stats.jobSucceeded).to.eql(1);
455
455
 
456
456
  // job2 -> undefined (does not spawn)
@@ -458,7 +458,7 @@ describe('#JobScheduler', function () {
458
458
  await uut.registerJob(job2);
459
459
  await uut.processPendingJobs();
460
460
  expectJobIsDone(job2);
461
- expect(uut.stats.jobRegistered).to.equal(2);
461
+ expect(uut.stats.jobRegistered).to.eql(2);
462
462
  expect(uut.stats.jobSucceeded).to.eql(2);
463
463
 
464
464
  // job3 -> [] (does not spawn)
@@ -466,7 +466,7 @@ describe('#JobScheduler', function () {
466
466
  await uut.registerJob(job3);
467
467
  await uut.processPendingJobs();
468
468
  expectJobIsDone(job3);
469
- expect(uut.stats.jobRegistered).to.equal(3);
469
+ expect(uut.stats.jobRegistered).to.eql(3);
470
470
  expect(uut.stats.jobSucceeded).to.eql(3);
471
471
 
472
472
  // job4 -> job5
@@ -479,11 +479,76 @@ describe('#JobScheduler', function () {
479
479
  await uut.processPendingJobs();
480
480
  expectJobIsDone(job4);
481
481
  expectJobIsDone(job5);
482
- expectJobIsDone(job6);
482
+
483
483
  expectJobIsDone(job7);
484
- expect(uut.stats.jobRegistered).to.equal(7);
484
+ expect(uut.stats.jobRegistered).to.eql(7);
485
485
  expect(uut.stats.jobSucceeded).to.eql(7);
486
486
  });
487
+
488
+ it('should not let one long-lived job block newly added short-lived jobs forever', async function () {
489
+ this.timeout(20 * SECOND);
490
+
491
+ const type = 'testjob';
492
+ uut.registerHandler(type, () => {});
493
+ await uut.init();
494
+
495
+ const start = Date.now();
496
+ const longLivedJob = {
497
+ type,
498
+ args: {
499
+ name: 'long-lived',
500
+ createdAt: Date.now(),
501
+ },
502
+ config: {
503
+ readyAt: start + DAY,
504
+ ttlInMs: 2 * DAY,
505
+ },
506
+ };
507
+ await uut.registerJob(longLivedJob);
508
+ expect(uut.stats.jobRegistered).to.eql(1);
509
+ expect(uut.stats.jobSucceeded).to.eql(0);
510
+
511
+ let shortLiveJobsCount = 0;
512
+ const mkShortLivedJob = () => {
513
+ return {
514
+ type,
515
+ args: {
516
+ name: ++shortLiveJobsCount,
517
+ createdAt: Date.now(),
518
+ },
519
+ config: {
520
+ readyIn: { min: 10 * SECOND },
521
+ ttlInMs: 2 * HOUR,
522
+ },
523
+ };
524
+ };
525
+ await passesSelfChecks();
526
+
527
+ while (Date.now() < longLivedJob.config.readyAt) {
528
+ expect(uut.stats.jobSucceeded).to.be.below(uut.stats.jobRegistered);
529
+ await uut.processPendingJobs();
530
+ expect(uut.stats.jobSucceeded).to.be.at.most(uut.stats.jobRegistered);
531
+
532
+ await uut.registerJob(mkShortLivedJob());
533
+ expect(uut.stats.jobRejected).to.eql(0);
534
+ expect(uut.stats.jobExpired).to.eql(0);
535
+ expect(uut.stats.jobFailed).to.eql(0);
536
+ expect(uut.stats.jobRegistered).to.eql(1 + shortLiveJobsCount);
537
+ expect(uut.stats.jobSucceeded).to.be.below(uut.stats.jobRegistered);
538
+
539
+ await clock.tickAsync(10 * MINUTE);
540
+ await passesSelfChecks();
541
+ }
542
+
543
+ await uut.processPendingJobs();
544
+ await clock.runAllAsync();
545
+
546
+ expect(uut.stats.jobExpired).to.eql(0);
547
+ expect(uut.stats.jobSucceeded).to.eql(uut.stats.jobRegistered);
548
+ expect(uut.stats.jobRejected).to.eql(0);
549
+ expect(uut.stats.jobFailed).to.eql(0);
550
+ await passesSelfChecks();
551
+ });
487
552
  });
488
553
 
489
554
  describe('after an extension restart', function () {
@@ -562,6 +627,8 @@ describe('#JobScheduler', function () {
562
627
  maxJobTypes = 20,
563
628
  minReadyIn = 0,
564
629
  maxReadyIn = 1 * MONTH,
630
+ minExpireIn = 1 * SECOND,
631
+ maxExpireIn = 1 * MONTH,
565
632
  minTTL = 1 * SECOND,
566
633
  maxTTL = 12 * MONTH,
567
634
  maxJobsPerType = 10000,
@@ -569,31 +636,57 @@ describe('#JobScheduler', function () {
569
636
  maxAutoRetriesAfterError = 100,
570
637
  maxClockJump = 6 * MONTH, // also simulates if a machines goes to sleep
571
638
  } = {}) {
639
+ // these fields are reserved for the config passed to the jobHandler
640
+ const commonJobConfigFields = () => ({
641
+ priority: fc.integer(),
642
+ ttlInMs: fc.integer({ min: minTTL, max: maxTTL }),
643
+ maxJobsTotal: fc.integer({ min: 1, max: maxJobsPerType }),
644
+ cooldownInMs: fc.nat(maxCooldown),
645
+ autoRetryAfterError: fc.boolean(),
646
+ maxAutoRetriesAfterError: fc.nat(maxAutoRetriesAfterError),
647
+ });
648
+ const individualJobConfigFields = () => ({
649
+ readyIn: fc.record(
650
+ {
651
+ min: fc.nat(minReadyIn),
652
+ max: fc.option(fc.integer({ min: minReadyIn, max: maxReadyIn })),
653
+ },
654
+ {
655
+ requiredKeys: ['min'],
656
+ },
657
+ ),
658
+ expireIn: fc.record(
659
+ {
660
+ min: fc.nat(minExpireIn),
661
+ max: fc.option(fc.integer({ min: minExpireIn, max: maxExpireIn })),
662
+ },
663
+ {
664
+ requiredKeys: ['min'],
665
+ },
666
+ ),
667
+ });
668
+
572
669
  const numToJobType = (x) => `testjob${x}`;
573
670
  const arbitraryJobType = () => fc.nat(maxJobTypes - 1).map(numToJobType);
574
671
  const arbitraryJobArgs = () => fc.array(fc.nat());
575
- const arbitraryJobConfig = () => {
576
- return fc.record({
577
- priority: fc.option(fc.integer()),
578
- ttlInMs: fc.option(fc.integer({ min: minTTL, max: maxTTL })),
579
- readyIn: fc.option(
580
- fc.record({
581
- min: fc.nat(minReadyIn),
582
- max: fc.option(fc.integer({ min: minReadyIn, max: maxReadyIn })),
583
- }),
584
- ),
585
- maxJobsTotal: fc.option(fc.nat(fc.nat(1, maxJobsPerType))),
586
- cooldownInMs: fc.option(fc.nat(maxCooldown)),
587
- autoRetryAfterError: fc.option(fc.boolean()),
588
- maxAutoRetriesAfterError: fc.option(fc.nat(maxAutoRetriesAfterError)),
589
- });
590
- };
672
+ const arbitraryJobConfig = () =>
673
+ fc.record(commonJobConfigFields(), { requiredKeys: [] });
591
674
  const arbitraryJob = () => {
592
675
  return fc
593
676
  .tuple(
594
677
  arbitraryJobType(),
595
678
  fc.option(arbitraryJobArgs()),
596
- fc.option(arbitraryJobConfig()),
679
+ fc.option(
680
+ fc.record(
681
+ {
682
+ ...commonJobConfigFields(),
683
+ ...individualJobConfigFields(),
684
+ },
685
+ {
686
+ requiredKeys: [],
687
+ },
688
+ ),
689
+ ),
597
690
  )
598
691
  .map(([type, args, config]) => ({
599
692
  type,