@whotracksme/reporting 7.4.0 → 7.5.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 CHANGED
@@ -1,3 +1,27 @@
1
+ # v7.5.0 (Tue Jul 29 2025)
2
+
3
+ #### 🚀 Enhancement
4
+
5
+ - Error recovery [#164](https://github.com/whotracksme/webextension-packages/pull/164) ([@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
+
13
+ # v7.4.1 (Tue Jul 29 2025)
14
+
15
+ #### 🐛 Bug Fix
16
+
17
+ - Job scheduling: tweaked scheduling and misconfiguration detection [#163](https://github.com/whotracksme/webextension-packages/pull/163) ([@philipp-classen](https://github.com/philipp-classen))
18
+
19
+ #### Authors: 1
20
+
21
+ - Philipp Claßen ([@philipp-classen](https://github.com/philipp-classen))
22
+
23
+ ---
24
+
1
25
  # v7.4.0 (Tue Jul 01 2025)
2
26
 
3
27
  #### 🚀 Enhancement
@@ -12,7 +12,7 @@
12
12
  import { encodeWithPadding } from './padding.js';
13
13
  import { fromBase64, toBase64, fromUTF8, toUTF8 } from './encoding.js';
14
14
  import { inflate } from './zlib.js';
15
- import { ProtocolError } from './errors.js';
15
+ import { ProtocolError, TransportError } from './errors.js';
16
16
 
17
17
  const ANONYMOUS_COMMUNICATION_PROTOCOL_VERSION = 1;
18
18
  const ANONYMOUS_COMMUNICATION_ECDH_P256_AES_128_GCM = 0xea;
@@ -99,18 +99,37 @@ export default class ProxiedHttp {
99
99
  'Key-Date': serverPublicKeyDate,
100
100
  };
101
101
 
102
- const response = await fetch(this._chooseRandomProxyUrl(), {
103
- method: 'POST',
104
- headers,
105
- credentials: 'omit',
106
- cache: 'no-store',
107
- redirect: 'manual',
108
- body: ciphertext,
109
- });
102
+ const proxyUrl = this._chooseRandomProxyUrl();
103
+ let response;
104
+ try {
105
+ response = await fetch(proxyUrl, {
106
+ method: 'POST',
107
+ headers,
108
+ credentials: 'omit',
109
+ cache: 'no-store',
110
+ redirect: 'manual',
111
+ body: ciphertext,
112
+ });
113
+ } catch (e) {
114
+ throw new TransportError(`Failed to send data to '${proxyUrl}'`, {
115
+ cause: e,
116
+ });
117
+ }
110
118
  if (!response.ok) {
119
+ if (response.status === 429 || response.status >= 500) {
120
+ throw new TransportError(
121
+ `Failed to send data (${response.statusText})`,
122
+ );
123
+ }
111
124
  throw new Error(`Failed to send data (${response.statusText})`);
112
125
  }
113
- let data = new Uint8Array(await response.arrayBuffer());
126
+
127
+ let data;
128
+ try {
129
+ data = new Uint8Array(await response.arrayBuffer());
130
+ } catch (e) {
131
+ throw new TransportError('Failed to process response data', { cause: e });
132
+ }
114
133
 
115
134
  const serverIV = response.headers.get('Encryption-IV');
116
135
  if (serverIV) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@whotracksme/reporting",
3
- "version": "7.4.0",
3
+ "version": "7.5.0",
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';
@@ -25,7 +25,7 @@ import SelfCheck from './self-check';
25
25
  * dropped! To avoid that, you can define an optional migration
26
26
  * (see _tryDataMigration).
27
27
  */
28
- const DB_VERSION = 1;
28
+ const DB_VERSION = 2;
29
29
 
30
30
  const SECOND = 1000;
31
31
  const MINUTE = 60 * SECOND;
@@ -47,7 +47,11 @@ class JobTester {
47
47
  return this.now >= jobEntry._meta.expireAt;
48
48
  }
49
49
 
50
- expireJobs(jobEntries) {
50
+ // Note: this will not guarantee that all expired jobs get removed.
51
+ // It will only look at the jobs at the begin of the queue. Typically,
52
+ // that should be enough to eventually reap them. If you need stronger
53
+ // guarantees, you will have to do a full scan.
54
+ tryExpireJobs(jobEntries) {
51
55
  let pos = 0;
52
56
  while (pos < jobEntries.length && this.isJobExpired(jobEntries[pos])) {
53
57
  pos += 1;
@@ -55,21 +59,38 @@ class JobTester {
55
59
  return jobEntries.splice(0, pos);
56
60
  }
57
61
 
58
- // Note: smaller is of higher priority
62
+ /**
63
+ * Computes the priority of a job. Smaller is of higher priority.
64
+ *
65
+ * When ordering jobs by their priority, the order should remain stable over time.
66
+ * Formally, if "p(t,j)" is the priority function for job "j" at a given time "t",
67
+ * the following property should hold:
68
+ *
69
+ * For all jobs j1,j2 and for all times t1, t2 with t2 > t1:
70
+ * ```
71
+ * p(t1,j1) <= p(t1,j2) ==> p(t2,j1) <= p(t2,j2)
72
+ * ```
73
+ *
74
+ * Note: it automatically holds if p does not rely on the time. In other
75
+ * words, this is a sufficient, but not necessary condition:
76
+ * ```
77
+ * For all times t1, t2 and for all jobs j: p(t1,j) == p(t2,j)
78
+ * ```
79
+ */
59
80
  computePriority(jobEntry) {
60
- // TODO: this could be improved (though prefer old jobs is not a bad strategy)
61
- return jobEntry._meta.createdAt;
81
+ // This will order jobs primarily by the time when they become ready.
82
+ // It also guarantees that jobs that are ready will be sorted before
83
+ // jobs that are still blocked.
84
+ //
85
+ // To break ties between multiple jobs that are ready, it will run the
86
+ // oldest jobs first; thus, eliminating the possiblity of starvation.
87
+ //
88
+ // Note: preserves ordering, since the time is not used.
89
+ return Math.max(jobEntry._meta.createdAt, jobEntry._meta.readyAt);
62
90
  }
63
91
 
64
92
  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;
93
+ return this.computePriority(jobEntry1) - this.computePriority(jobEntry2);
73
94
  }
74
95
 
75
96
  sortJobs(jobEntries) {
@@ -122,17 +143,20 @@ class JobTester {
122
143
  * to clean up the queues fast enough. The second assumption is that
123
144
  * executing jobs when the service worker is already running should be
124
145
  * more resource friendly than waking up the user's device.
125
- * (TODO: Revisit this statement in the future. It would not be difficult
126
- * to add if needed: set an alert and call "processPendingJobs".)
127
146
  */
128
147
  export default class JobScheduler {
129
- static STATES = ['running', 'ready', 'waiting', 'dlq'];
148
+ static STATES = [
149
+ 'running', // jobs are that currently being executed
150
+ 'ready', // jobs are ready to be executed (ignoring optional cooldowns)
151
+ 'waiting', // jobs that are no ready to start
152
+ 'retryable', // jobs that failed with an ephemeral error
153
+ ];
130
154
 
131
155
  static EVENTS = [
132
156
  'jobRegistered',
133
157
  'jobStarted',
134
158
  'jobSucceeded',
135
- 'jobFailed', // TODO: what is the semantic? (permanently failed or retried?)
159
+ 'jobFailed',
136
160
  'jobExpired',
137
161
  'jobRejected',
138
162
  'syncedToDisk',
@@ -161,11 +185,9 @@ export default class JobScheduler {
161
185
  cooldownInMs: 0,
162
186
 
163
187
  // error handling:
164
- autoRetryAfterError: true,
165
- maxAutoRetriesAfterError: 3,
166
- // TODO: maybe add a flag to control if failed jobs should be put in the dlq
167
- // (and only added back if there was was a successful execution of that type before)
188
+ maxAutoRetriesAfterError: 2, // (give up after three attempts in total)
168
189
  };
190
+ this._ensureValidHandlerConfig(this.defaultConfig);
169
191
  this.handlerConfigs = {};
170
192
 
171
193
  // Note: this data structure is intended to be in a format that can be
@@ -189,6 +211,9 @@ export default class JobScheduler {
189
211
  }
190
212
 
191
213
  registerHandler(type, handler, config = {}) {
214
+ const fullConfig = { ...this.defaultConfig, ...config };
215
+ this._ensureValidHandlerConfig(fullConfig);
216
+
192
217
  if (this.active) {
193
218
  logger.warn(
194
219
  'Job handler for type',
@@ -202,12 +227,12 @@ export default class JobScheduler {
202
227
  logger.warn('Redefining handler for type:', type);
203
228
  }
204
229
  this.handlers[type] = handler;
205
- this.handlerConfigs[type] = { ...this.defaultConfig, ...config };
230
+ this.handlerConfigs[type] = fullConfig;
206
231
  logger.debug(
207
232
  'Registered job handler for',
208
233
  type,
209
234
  'with config:',
210
- this.handlerConfigs[type],
235
+ fullConfig,
211
236
  );
212
237
  this._resetPrecomputed();
213
238
  }
@@ -279,6 +304,7 @@ export default class JobScheduler {
279
304
  }
280
305
 
281
306
  async registerJobs(jobs, { now = Date.now(), autoTrigger = true } = {}) {
307
+ await this.ready();
282
308
  jobs.forEach((job) => this._registerJob(job, now));
283
309
  if (autoTrigger) {
284
310
  this._scheduleProcessPendingJobs();
@@ -357,13 +383,9 @@ export default class JobScheduler {
357
383
  },
358
384
  };
359
385
 
360
- if (this.getTotalJobs() >= this.globalJobLimit) {
361
- this.notifyObservers('jobRejected', 'global job limit reached', jobEntry);
362
- return;
363
- }
364
- const localLimit = this.handlerConfigs[type]?.maxJobsTotal;
365
- if (localLimit && this.getTotalJobsOfType(type) >= localLimit) {
366
- this.notifyObservers('jobRejected', 'local job limit reached', jobEntry);
386
+ const { ok, reason } = this._checkJobLimits(type, now);
387
+ if (!ok) {
388
+ this.notifyObservers('jobRejected', jobEntry, reason);
367
389
  return;
368
390
  }
369
391
 
@@ -376,15 +398,65 @@ export default class JobScheduler {
376
398
  }
377
399
  }
378
400
 
401
+ _checkJobLimits(jobType, now = Date.now()) {
402
+ const reject = (reason) => ({ ok: false, reason });
403
+ const ok = () => ({ ok: true });
404
+
405
+ const localLimit = this.handlerConfigs[jobType]?.maxJobsTotal;
406
+ if (localLimit && this.getTotalJobsOfType(jobType) >= localLimit) {
407
+ // Before giving up, make a best-effort attempt to expire local jobs.
408
+ // Not guaranteed to find something, since it will only look at the
409
+ // start of the queue; yet it is likely that expired jobs are
410
+ // in front.
411
+ const {
412
+ ready = [],
413
+ waiting = [],
414
+ retryable = [],
415
+ } = this.jobQueues[jobType];
416
+
417
+ const jobTester = new JobTester(now);
418
+ if (
419
+ this._tryExpireJobsInQueue(waiting, jobTester).numExpired === 0 &&
420
+ this._tryExpireJobsInQueue(ready, jobTester).numExpired === 0 &&
421
+ this._tryExpireJobsInQueue(retryable, jobTester).numExpired === 0
422
+ ) {
423
+ const deletedJob = retryable.shift();
424
+ if (deletedJob) {
425
+ logger.warn('Dropping oldest failed job to free space for new job:', {
426
+ deletedJob,
427
+ });
428
+ this._markAsDirty();
429
+ return ok(); // early exit since we now freed room for one job
430
+ } else {
431
+ return reject('local job limit reached');
432
+ }
433
+ }
434
+ }
435
+
436
+ // Currently, there are no attempts to clean up other queues.
437
+ // That is intentional.
438
+ //
439
+ // The rationale is that the global job limit should be conservative
440
+ // enough that a single queue cannot fill it. But when getting
441
+ // near the global limits, it is likely that there are already
442
+ // so many jobs in the system that slowing down by rejecting
443
+ // jobs looks like a good idea anyways; it might drop more jobs
444
+ // than necessary, but should reduce load on the system.
445
+ if (this.getTotalJobs() >= this.globalJobLimit) {
446
+ return reject('global job limit reached');
447
+ }
448
+
449
+ return ok();
450
+ }
451
+
379
452
  _pushToQueue({ jobEntry, state, now = Date.now() }) {
380
453
  this._ensureValidState(state);
381
454
  const { type } = jobEntry.job;
382
- if (!this.jobQueues[type]) {
383
- this.jobQueues[type] = Object.fromEntries(
384
- JobScheduler.STATES.map((x) => [x, []]),
385
- );
386
- }
387
- this.jobQueues[type][state] = this.jobQueues[type][state] || [];
455
+ this.jobQueues[type] ||= Object.fromEntries(
456
+ JobScheduler.STATES.map((x) => [x, []]),
457
+ );
458
+ this.jobQueues[type][state] ||= [];
459
+
388
460
  const len = this.jobQueues[type][state].length;
389
461
  if (len > 0 && state === 'waiting') {
390
462
  const lastJob = this.jobQueues[type][state][len - 1];
@@ -396,6 +468,39 @@ export default class JobScheduler {
396
468
  this._markAsDirty();
397
469
  }
398
470
 
471
+ _tryPushToRetryableQueue(jobEntry, now = Date.now()) {
472
+ const { job, _meta } = jobEntry;
473
+
474
+ let attemptsLeft;
475
+ if (Number.isInteger(_meta.attemptsLeft)) {
476
+ attemptsLeft = _meta.attemptsLeft - 1;
477
+ } else {
478
+ attemptsLeft =
479
+ job.config?.maxAutoRetriesAfterError ??
480
+ this.handlerConfigs[job.type]?.maxAutoRetriesAfterError ??
481
+ this.defaultConfig.maxAutoRetriesAfterError;
482
+ }
483
+ if (attemptsLeft <= 0) {
484
+ return false;
485
+ }
486
+
487
+ const retryJob = {
488
+ job,
489
+ _meta: {
490
+ ..._meta,
491
+
492
+ // Little detail: setting it to "now" will guarantee that it is at
493
+ // the end of the queue (in contrast to 0). By design, all jobs in
494
+ // the retry job are always ready (otherwise they would not have
495
+ // been executed before).
496
+ readyAt: now,
497
+ attemptsLeft,
498
+ },
499
+ };
500
+ this._pushToQueue({ jobEntry: retryJob, state: 'retryable', now });
501
+ return true;
502
+ }
503
+
399
504
  _removeFromRunningQueue(jobEntry, now = Date.now()) {
400
505
  const { type } = jobEntry.job;
401
506
  if (this.jobQueues[type].running.pop()) {
@@ -431,32 +536,58 @@ export default class JobScheduler {
431
536
  }
432
537
  this._pushToQueue({ jobEntry, state: 'running', now });
433
538
  let newJobs;
539
+ let success = false;
434
540
  try {
435
541
  this.notifyObservers('jobStarted', jobEntry);
436
- newJobs = await this._runJob(jobEntry.job);
542
+ newJobs = (await this._runJob(jobEntry.job)) || [];
543
+ success = true;
437
544
  this.notifyObservers('jobSucceeded', jobEntry);
438
545
  } catch (e) {
546
+ let pendingRetry = false;
439
547
  if (e.isPermanentError) {
440
- logger.warn('Job failed:', jobEntry.job, e.message);
548
+ logger.error('Job failed:', jobEntry.job, e.message);
441
549
  } else if (e.isRecoverableError) {
442
- // TODO: implement retry
443
- logger.warn('Job failed (skip retry):', jobEntry.job, e);
550
+ if (this._tryPushToRetryableQueue(jobEntry, now)) {
551
+ pendingRetry = true;
552
+ logger.warn('Job failed (pushed for retry):', jobEntry.job, e);
553
+ } else {
554
+ logger.error('Job failed (no more retries):', jobEntry.job, e);
555
+ }
444
556
  } else {
445
557
  logger.error('Job failed (unexpected error):', jobEntry.job, e);
446
558
  }
447
- this.notifyObservers('jobFailed', jobEntry, e);
559
+ this.notifyObservers('jobFailed', jobEntry, {
560
+ pendingRetry,
561
+ exception: e,
562
+ });
448
563
  } finally {
449
564
  now = Date.now();
450
565
  this._removeFromRunningQueue(jobEntry, now);
451
566
  }
452
567
 
453
- if (newJobs && newJobs.length > 0) {
454
- logger.debug('Job', jobEntry.job, 'spawned', newJobs);
455
- for (const job of newJobs) {
456
- try {
457
- this._registerJob(job, now);
458
- } catch (e) {
459
- logger.error('Failed to register spawned job:', job, e);
568
+ if (success) {
569
+ if (newJobs.length > 0) {
570
+ logger.debug('Job', jobEntry.job, 'spawned', newJobs);
571
+ for (const job of newJobs) {
572
+ try {
573
+ this._registerJob(job, now);
574
+ } catch (e) {
575
+ logger.error('Failed to register spawned job:', job, e);
576
+ }
577
+ }
578
+ }
579
+
580
+ const { type } = jobEntry.job;
581
+ const { retryable = [] } = this.jobQueues[type];
582
+ if (retryable.length > 0) {
583
+ this._tryExpireJobsInQueue(retryable, new JobTester(now));
584
+ if (retryable.length > 0) {
585
+ const jobEntry = this.jobQueues[type].retryable.shift();
586
+ logger.debug(
587
+ 'Reinserting previously failed job into the ready queue:',
588
+ jobEntry.job,
589
+ );
590
+ this._pushToQueue({ jobEntry, state: 'ready', now });
460
591
  }
461
592
  }
462
593
  }
@@ -484,16 +615,16 @@ export default class JobScheduler {
484
615
  }
485
616
  }
486
617
 
487
- _expireJobsInAllQueue(jobTester) {
488
- for (const queue of Object.values(this.jobQueue)) {
489
- this._expireJobsInQueue(queue, jobTester);
490
- }
491
- }
492
-
493
- _expireJobsInQueue(queue, jobTester) {
494
- for (const jobEntry of jobTester.expireJobs(queue)) {
495
- this.notifyObservers('jobExpired', jobEntry);
618
+ _tryExpireJobsInQueue(queue, jobTester) {
619
+ const expiredJobs = jobTester.tryExpireJobs(queue);
620
+ const numExpired = expiredJobs.length;
621
+ if (numExpired > 0) {
622
+ this._markAsDirty();
623
+ for (const jobEntry of expiredJobs) {
624
+ this.notifyObservers('jobExpired', jobEntry);
625
+ }
496
626
  }
627
+ return { numExpired, expiredJobs };
497
628
  }
498
629
 
499
630
  _findNextJobToRun(now = Date.now()) {
@@ -510,13 +641,13 @@ export default class JobScheduler {
510
641
  this.cooldowns[type] = null;
511
642
  }
512
643
  const { ready = [], waiting = [] } = this.jobQueues[type] || {};
513
- this._expireJobsInQueue(ready, jobTester);
644
+ this._tryExpireJobsInQueue(ready, jobTester);
514
645
  const nextJob = ready.shift();
515
646
  if (nextJob) {
516
647
  types.unshift(types.pop()); // to improve fairness
517
648
  return nextJob;
518
649
  }
519
- this._expireJobsInQueue(waiting, jobTester);
650
+ this._tryExpireJobsInQueue(waiting, jobTester);
520
651
  if (waiting.length > 0) {
521
652
  queuesToRescan.push(type);
522
653
  }
@@ -528,8 +659,7 @@ export default class JobScheduler {
528
659
  for (const type of queuesToRescan) {
529
660
  const { waiting = [] } = this.jobQueues[type];
530
661
  if (waiting.length > 0) {
531
- this._sortWaitingQueue(type, jobTester);
532
- this._expireJobsInQueue(waiting, jobTester);
662
+ this._sortWaitingQueue(type, jobTester, { removeExpiredJobs: true });
533
663
  let pos = 0;
534
664
  while (pos < waiting.length && jobTester.isJobReady(waiting[pos])) {
535
665
  pos += 1;
@@ -608,6 +738,8 @@ export default class JobScheduler {
608
738
  if (persistedState?.jobQueues) {
609
739
  const now = Date.now();
610
740
  const jobTester = new JobTester(now);
741
+ const isJobCreationTimeOK = ({ _meta }) => _meta.createdAt < now + DAY;
742
+
611
743
  for (const [type, queues] of Object.entries(persistedState.jobQueues)) {
612
744
  try {
613
745
  if (!queues) {
@@ -618,7 +750,29 @@ export default class JobScheduler {
618
750
  if (!Array.isArray(jobEntries)) {
619
751
  throw new Error(`Bad job queue in state=${state}`);
620
752
  }
621
- jobEntries.forEach((x) => this._ensureValidJobEntry(x));
753
+
754
+ const corruptedJobs = [];
755
+ jobEntries.forEach((jobEntry) => {
756
+ this._ensureValidJobEntry(jobEntry);
757
+
758
+ if (!isJobCreationTimeOK(jobEntry)) {
759
+ // Note: this is an ultra-rare edge case where the system clock
760
+ // was in the future while registering the job. Purging them
761
+ // may be necessary, since these jobs may otherwise be blocked
762
+ // for years - eating up slots and eventually preventing new
763
+ // jobs from being registered.
764
+ corruptedJobs.push(jobEntry);
765
+ }
766
+ });
767
+
768
+ if (corruptedJobs.length > 0) {
769
+ logger.warn(
770
+ 'Detected clock jump. Purging affected jobs:',
771
+ corruptedJobs,
772
+ );
773
+ queues[state] = [...jobEntries].filter(isJobCreationTimeOK);
774
+ this._markAsDirty();
775
+ }
622
776
  }
623
777
  if (queues.running && queues.running.length > 0) {
624
778
  // TODO: potentially add the running job into the queue again (it is repeatible)
@@ -627,12 +781,25 @@ export default class JobScheduler {
627
781
  queues.running,
628
782
  );
629
783
  queues.running = [];
784
+ this._markAsDirty();
630
785
  }
786
+
787
+ let alive = 0;
631
788
  for (const state of JobScheduler.STATES) {
632
789
  if (queues[state]) {
633
- this._expireJobsInQueue(queues[state], jobTester);
790
+ this._tryExpireJobsInQueue(queues[state], jobTester);
791
+ alive += queues[state].length;
634
792
  }
635
793
  }
794
+ if (alive === 0 && !this.handlers[type]) {
795
+ logger.info(
796
+ 'Cleaning up empty queue of type:',
797
+ type,
798
+ '(likely dead, since no handler was found)',
799
+ );
800
+ delete persistedState.jobQueues[type];
801
+ this._markAsDirty();
802
+ }
636
803
  } catch (e) {
637
804
  logger.warn(
638
805
  `Detected corrupted queue for type=<${type}>. Delete and continue...`,
@@ -640,6 +807,7 @@ export default class JobScheduler {
640
807
  e,
641
808
  );
642
809
  delete persistedState.jobQueues[type];
810
+ this._markAsDirty();
643
811
  }
644
812
  }
645
813
  this.jobQueues = persistedState.jobQueues;
@@ -693,6 +861,25 @@ export default class JobScheduler {
693
861
  * that, you can migrate jobs (either all or only selected types).
694
862
  */
695
863
  _tryDataMigration(persistedState) {
864
+ // -- begin of 1 ==> 2 (2025-07) ---
865
+ const log = (...args) => logger.info('[migrate: 1=>2]', ...args);
866
+ if (persistedState.dbVersion === 1) {
867
+ log('Migrating jobs...');
868
+ for (const queue of Object.values(persistedState.jobQueues)) {
869
+ if (queue.dlq) {
870
+ log('"dlq" renamed as "retryable"');
871
+ queue.retryable = queue.dlq;
872
+ delete queue.dlq;
873
+ }
874
+ }
875
+ persistedState.dbVersion = 2;
876
+ log('Migrating jobs...DONE');
877
+ }
878
+ if (persistedState.dbVersion === 2) {
879
+ return persistedState;
880
+ }
881
+ // -- end of 1 ==> 2 migration ---
882
+
696
883
  logger.warn(
697
884
  'DB_VERSION changed. Discarding the old state:',
698
885
  persistedState,
@@ -751,9 +938,16 @@ export default class JobScheduler {
751
938
  }
752
939
  }
753
940
 
754
- _sortWaitingQueue(type, jobTester) {
941
+ _sortWaitingQueue(type, jobTester, { removeExpiredJobs = false } = {}) {
942
+ if (removeExpiredJobs) {
943
+ this._tryExpireJobsInQueue(this.jobQueues[type].waiting, jobTester);
944
+ }
945
+
755
946
  if (!this._precomputed().waitingQueueSortedFlags[type]) {
756
947
  jobTester.sortJobs(this.jobQueues[type].waiting);
948
+ if (removeExpiredJobs) {
949
+ this._tryExpireJobsInQueue(this.jobQueues[type].waiting, jobTester);
950
+ }
757
951
  this._precomputed().waitingQueueSortedFlags[type] = true;
758
952
  }
759
953
  }
@@ -783,11 +977,11 @@ export default class JobScheduler {
783
977
  return count;
784
978
  }
785
979
 
786
- getTotalJobsInDlq() {
980
+ getTotalJobsWaitingForRetry() {
787
981
  let count = 0;
788
982
  for (const queue of Object.values(this.jobQueues)) {
789
- if (queue.dlq) {
790
- count += queue.dlq.length;
983
+ if (queue.retryable) {
984
+ count += queue.retryable.length;
791
985
  }
792
986
  }
793
987
  return count;
@@ -846,6 +1040,43 @@ export default class JobScheduler {
846
1040
  }
847
1041
  }
848
1042
 
1043
+ // Validates the config that is passed when registering job handlers.
1044
+ _ensureValidHandlerConfig(config) {
1045
+ if (!config) {
1046
+ throw new BadJobHandlerError('Missing config');
1047
+ }
1048
+ let numCheckedKeys = 0;
1049
+ const expectInt = (key, extraCheck) => {
1050
+ if (!Number.isInteger(config[key])) {
1051
+ throw new BadJobHandlerError(
1052
+ `Expected field "${key}" to be an integer, but got: ${config[key]}`,
1053
+ );
1054
+ }
1055
+ if (extraCheck && !extraCheck(config[key])) {
1056
+ throw new BadJobHandlerError(
1057
+ `Illegal value found in field "${key}": <<${config[key]}>>`,
1058
+ );
1059
+ }
1060
+ numCheckedKeys += 1;
1061
+ };
1062
+ const nonNegative = (x) => x >= 0;
1063
+
1064
+ expectInt('priority');
1065
+ expectInt('ttlInMs', nonNegative);
1066
+ expectInt('maxJobsTotal', nonNegative);
1067
+ expectInt('cooldownInMs', nonNegative);
1068
+ expectInt('maxAutoRetriesAfterError', nonNegative);
1069
+
1070
+ if (numCheckedKeys !== Object.keys(config).length) {
1071
+ const unexpectedKeys = Object.keys(config).filter(
1072
+ (key) => !Object.hasOwn(this.defaultConfig, key),
1073
+ );
1074
+ throw new BadJobHandlerError(
1075
+ `Invalid config: found unexpected keys: [${unexpectedKeys.join(', ')}]`,
1076
+ );
1077
+ }
1078
+ }
1079
+
849
1080
  async selfChecks(check = new SelfCheck()) {
850
1081
  const restoredJobs = JSON.parse(JSON.stringify(this.jobQueues));
851
1082
  if (!equalityCanBeProven(this.jobQueues, restoredJobs)) {
@@ -66,8 +66,14 @@ export async function runClockUntilJobQueueIsEmpty(
66
66
  }
67
67
  }
68
68
 
69
+ // To ensure that initialization is completed. Otherwise, job
70
+ // registrations may still be hanging.
71
+ await clock.runAllAsync();
72
+
69
73
  let iter = 0;
70
- while (jobScheduler.getTotalJobs() > jobScheduler.getTotalJobsInDlq()) {
74
+ while (
75
+ jobScheduler.getTotalJobs() > jobScheduler.getTotalJobsWaitingForRetry()
76
+ ) {
71
77
  iter += 1;
72
78
  if (iter > maxIterations) {
73
79
  throw new Error(`Exceeded maximum steps (steps=${maxIterations})`);
@@ -13,6 +13,10 @@ import { expect, assert } from 'chai';
13
13
  import sinon from 'sinon';
14
14
  import * as fc from 'fast-check';
15
15
 
16
+ import {
17
+ BadJobError,
18
+ TemporarilyUnableToFetchUrlError,
19
+ } from '../src/errors.js';
16
20
  import JobScheduler from '../src/job-scheduler.js';
17
21
 
18
22
  const SECOND = 1000;
@@ -25,11 +29,11 @@ const YEAR = 365 * DAY;
25
29
  function mockStorage(storageKey) {
26
30
  return {
27
31
  async get(key) {
28
- expect(key).to.equal(storageKey);
32
+ expect(key).to.eql(storageKey);
29
33
  return this._content;
30
34
  },
31
35
  async set(key, obj) {
32
- expect(key).to.equal(storageKey);
36
+ expect(key).to.eql(storageKey);
33
37
  this._content = obj;
34
38
  },
35
39
  };
@@ -88,6 +92,20 @@ describe('#JobScheduler', function () {
88
92
  return { type };
89
93
  }
90
94
 
95
+ function someRecoverableError(msg = '[testing] RecoverableError') {
96
+ const err = new TemporarilyUnableToFetchUrlError(msg);
97
+ expect(err.isRecoverableError).to.be.true;
98
+ expect(err.isPermanentError).to.be.false;
99
+ return err;
100
+ }
101
+
102
+ function somePermanentError(msg = '[testing] PermanentError') {
103
+ const err = new BadJobError(msg);
104
+ expect(err.isRecoverableError).to.be.false;
105
+ expect(err.isPermanentError).to.be.true;
106
+ return err;
107
+ }
108
+
91
109
  async function runScriptedScenario({
92
110
  jobs,
93
111
  events,
@@ -216,7 +234,7 @@ describe('#JobScheduler', function () {
216
234
  expect(uut.getTotalJobs()).to.eql(i + 1);
217
235
  }
218
236
 
219
- // now the limit is reached and jobs will be rejectec
237
+ // now the limit is reached and jobs will be rejected
220
238
  await uut.registerJob(someJob());
221
239
  expect(jobRejectedEvents).to.eql(1);
222
240
  expect(uut.stats.jobRegistered).to.eql(uut.globalJobLimit);
@@ -296,7 +314,7 @@ describe('#JobScheduler', function () {
296
314
  await passesSelfChecks();
297
315
  });
298
316
 
299
- it('should allow to processPendingJobs when the queue, but jobs are registered', async function () {
317
+ it('should allow to processPendingJobs when the queue is empty, but jobs are registered', async function () {
300
318
  uut.registerHandler('dummy', () => expect.fail('should never be called'));
301
319
  await uut.init();
302
320
  await uut.processPendingJobs();
@@ -450,7 +468,7 @@ describe('#JobScheduler', function () {
450
468
  await uut.registerJob(job1);
451
469
  await uut.processPendingJobs();
452
470
  expectJobIsDone(job1);
453
- expect(uut.stats.jobRegistered).to.equal(1);
471
+ expect(uut.stats.jobRegistered).to.eql(1);
454
472
  expect(uut.stats.jobSucceeded).to.eql(1);
455
473
 
456
474
  // job2 -> undefined (does not spawn)
@@ -458,7 +476,7 @@ describe('#JobScheduler', function () {
458
476
  await uut.registerJob(job2);
459
477
  await uut.processPendingJobs();
460
478
  expectJobIsDone(job2);
461
- expect(uut.stats.jobRegistered).to.equal(2);
479
+ expect(uut.stats.jobRegistered).to.eql(2);
462
480
  expect(uut.stats.jobSucceeded).to.eql(2);
463
481
 
464
482
  // job3 -> [] (does not spawn)
@@ -466,7 +484,7 @@ describe('#JobScheduler', function () {
466
484
  await uut.registerJob(job3);
467
485
  await uut.processPendingJobs();
468
486
  expectJobIsDone(job3);
469
- expect(uut.stats.jobRegistered).to.equal(3);
487
+ expect(uut.stats.jobRegistered).to.eql(3);
470
488
  expect(uut.stats.jobSucceeded).to.eql(3);
471
489
 
472
490
  // job4 -> job5
@@ -479,11 +497,76 @@ describe('#JobScheduler', function () {
479
497
  await uut.processPendingJobs();
480
498
  expectJobIsDone(job4);
481
499
  expectJobIsDone(job5);
482
- expectJobIsDone(job6);
500
+
483
501
  expectJobIsDone(job7);
484
- expect(uut.stats.jobRegistered).to.equal(7);
502
+ expect(uut.stats.jobRegistered).to.eql(7);
485
503
  expect(uut.stats.jobSucceeded).to.eql(7);
486
504
  });
505
+
506
+ it('should not let one long-lived job block newly added short-lived jobs forever', async function () {
507
+ this.timeout(20 * SECOND);
508
+
509
+ const type = 'testjob';
510
+ uut.registerHandler(type, () => {});
511
+ await uut.init();
512
+
513
+ const start = Date.now();
514
+ const longLivedJob = {
515
+ type,
516
+ args: {
517
+ name: 'long-lived',
518
+ createdAt: Date.now(),
519
+ },
520
+ config: {
521
+ readyAt: start + DAY,
522
+ ttlInMs: 2 * DAY,
523
+ },
524
+ };
525
+ await uut.registerJob(longLivedJob);
526
+ expect(uut.stats.jobRegistered).to.eql(1);
527
+ expect(uut.stats.jobSucceeded).to.eql(0);
528
+
529
+ let shortLiveJobsCount = 0;
530
+ const mkShortLivedJob = () => {
531
+ return {
532
+ type,
533
+ args: {
534
+ name: ++shortLiveJobsCount,
535
+ createdAt: Date.now(),
536
+ },
537
+ config: {
538
+ readyIn: { min: 10 * SECOND },
539
+ ttlInMs: 2 * HOUR,
540
+ },
541
+ };
542
+ };
543
+ await passesSelfChecks();
544
+
545
+ while (Date.now() < longLivedJob.config.readyAt) {
546
+ expect(uut.stats.jobSucceeded).to.be.below(uut.stats.jobRegistered);
547
+ await uut.processPendingJobs();
548
+ expect(uut.stats.jobSucceeded).to.be.at.most(uut.stats.jobRegistered);
549
+
550
+ await uut.registerJob(mkShortLivedJob());
551
+ expect(uut.stats.jobRejected).to.eql(0);
552
+ expect(uut.stats.jobExpired).to.eql(0);
553
+ expect(uut.stats.jobFailed).to.eql(0);
554
+ expect(uut.stats.jobRegistered).to.eql(1 + shortLiveJobsCount);
555
+ expect(uut.stats.jobSucceeded).to.be.below(uut.stats.jobRegistered);
556
+
557
+ await clock.tickAsync(10 * MINUTE);
558
+ await passesSelfChecks();
559
+ }
560
+
561
+ await uut.processPendingJobs();
562
+ await clock.runAllAsync();
563
+
564
+ expect(uut.stats.jobExpired).to.eql(0);
565
+ expect(uut.stats.jobSucceeded).to.eql(uut.stats.jobRegistered);
566
+ expect(uut.stats.jobRejected).to.eql(0);
567
+ expect(uut.stats.jobFailed).to.eql(0);
568
+ await passesSelfChecks();
569
+ });
487
570
  });
488
571
 
489
572
  describe('after an extension restart', function () {
@@ -507,6 +590,338 @@ describe('#JobScheduler', function () {
507
590
  await uut.sync();
508
591
  expect(uut._describeJobs().queueLength).to.eql(1);
509
592
  });
593
+
594
+ it('should not overwrite newly registered jobs when restoring the queue', async function () {
595
+ const start = Date.now();
596
+ const type = 'testjob';
597
+ const mkJob = () => ({
598
+ type,
599
+ config: {
600
+ readyAt: start + DAY,
601
+ },
602
+ });
603
+
604
+ uut.registerHandler(type, () => {});
605
+ await uut.init();
606
+ await uut.registerJob(mkJob());
607
+ await clock.tickAsync(1 * MINUTE);
608
+ expect(uut._describeJobs().queueLength).to.eql(1);
609
+
610
+ await simulateRestart();
611
+ uut.registerHandler(type, () => {});
612
+ await uut.init();
613
+ await uut.registerJob(mkJob());
614
+ await clock.tickAsync(1 * MINUTE);
615
+ expect(uut._describeJobs().queueLength).to.eql(2);
616
+
617
+ await simulateRestart();
618
+ uut.registerHandler(type, () => {});
619
+ await uut.init();
620
+ await uut.registerJob(mkJob());
621
+ await clock.tickAsync(1 * MINUTE);
622
+ expect(uut._describeJobs().queueLength).to.eql(3);
623
+ });
624
+ });
625
+
626
+ describe('when jobs fail', function () {
627
+ it('should put a job in the "retryable" queue if the error is recoverable', async function () {
628
+ let numCalls = 0;
629
+ uut.registerHandler(someJob().type, () => {
630
+ numCalls += 1;
631
+ if (numCalls === 1) {
632
+ throw someRecoverableError(
633
+ '[testing] expected to fail on the first call',
634
+ );
635
+ }
636
+ });
637
+
638
+ await uut.init();
639
+ await uut.registerJob(someJob());
640
+ await uut.processPendingJobs();
641
+ await clock.runAllAsync();
642
+
643
+ // Initially, it is only put in the retry queue.
644
+ expect(numCalls).to.eql(1);
645
+ expect(uut.stats.jobStarted).to.eql(1);
646
+ expect(uut.stats.jobSucceeded).to.eql(0);
647
+ expect(uut.stats.jobFailed).to.eql(1);
648
+ expect(uut.getTotalJobsWaitingForRetry()).to.eql(1);
649
+ });
650
+
651
+ it('should execute the retry, once a job of the same type succeeded', async function () {
652
+ let numCalls = 0;
653
+ uut.registerHandler(someJob().type, () => {
654
+ numCalls += 1;
655
+ if (numCalls === 1) {
656
+ throw someRecoverableError(
657
+ '[testing] expected to fail on the first call',
658
+ );
659
+ }
660
+ });
661
+ await uut.init();
662
+
663
+ // the first job will fail
664
+ const first = someJob();
665
+ await uut.registerJob(first);
666
+ await uut.processPendingJobs();
667
+ await clock.runAllAsync();
668
+
669
+ expect(numCalls).to.eql(1);
670
+ expect(uut.stats.jobStarted).to.eql(1);
671
+ expect(uut.stats.jobSucceeded).to.eql(0);
672
+ expect(uut.stats.jobFailed).to.eql(1);
673
+ expect(uut.getTotalJobsWaitingForRetry()).to.eql(1);
674
+ await passesSelfChecks();
675
+
676
+ // the second job will succeed
677
+ const second = someJob();
678
+ await uut.registerJob(second);
679
+ await uut.processPendingJobs();
680
+ await clock.runAllAsync();
681
+
682
+ // at this point, the first job may or may not have been retried.
683
+ expect(numCalls).to.be.at.least(2);
684
+ expect(uut.stats.jobStarted).to.be.at.least(2);
685
+ expect(uut.stats.jobSucceeded).to.be.at.least(1);
686
+ expect(uut.stats.jobFailed).to.eql(1);
687
+ expect(uut.getTotalJobsWaitingForRetry()).to.be.at.most(1);
688
+ await passesSelfChecks();
689
+
690
+ // let enough time elapse to ensure that there are no cooldowns
691
+ await clock.tickAsync(1 * DAY);
692
+ await uut.processPendingJobs();
693
+ await clock.runAllAsync();
694
+
695
+ expect(numCalls).to.eql(3);
696
+ expect(uut.stats.jobStarted).to.eql(3);
697
+ expect(uut.stats.jobSucceeded).to.eql(2);
698
+ expect(uut.stats.jobFailed).to.eql(1);
699
+ expect(uut.getTotalJobsWaitingForRetry()).to.eql(0);
700
+ await passesSelfChecks();
701
+ });
702
+
703
+ it('should drop jobs that failed permanently', async function () {
704
+ let numCalls = 0;
705
+ uut.registerHandler(someJob().type, () => {
706
+ numCalls += 1;
707
+ throw somePermanentError('[testing] expected to fail every time');
708
+ });
709
+
710
+ await uut.init();
711
+ await uut.registerJob(someJob());
712
+ await uut.processPendingJobs();
713
+ await clock.runAllAsync();
714
+
715
+ expect(numCalls).to.eql(1);
716
+ expect(uut.stats.jobStarted).to.eql(1);
717
+ expect(uut.stats.jobSucceeded).to.eql(0);
718
+ expect(uut.getTotalJobsWaitingForRetry()).to.eql(0);
719
+ });
720
+
721
+ it('should drop jobs that failed because of unknown error (e.g. bugs in the code)', async function () {
722
+ let numCalls = 0;
723
+ uut.registerHandler(someJob().type, () => {
724
+ numCalls += 1;
725
+ new URL(''); // forces a runtime error (simulating a bug in the code)
726
+ });
727
+
728
+ await uut.init();
729
+ await uut.registerJob(someJob());
730
+ await uut.processPendingJobs();
731
+ await clock.runAllAsync();
732
+
733
+ expect(numCalls).to.eql(1);
734
+ expect(uut.stats.jobStarted).to.eql(1);
735
+ expect(uut.stats.jobSucceeded).to.eql(0);
736
+ expect(uut.getTotalJobsWaitingForRetry()).to.eql(0);
737
+ });
738
+
739
+ it('should eventually drop recoverable jobs if they fail too often', async function () {
740
+ const config = {
741
+ maxAutoRetriesAfterError: 4,
742
+ };
743
+ const handler = async (job) => {
744
+ const { shouldThrow } = job.args;
745
+ if (shouldThrow) {
746
+ throw someRecoverableError('[testing] expected to always fail');
747
+ }
748
+ };
749
+
750
+ const type = 'testjob';
751
+ uut.registerHandler(type, handler, config);
752
+ const mkFailingJob = () => ({
753
+ type,
754
+ args: { shouldThrow: true },
755
+ });
756
+ const mkSucceedingJob = () => ({
757
+ type,
758
+ args: { shouldThrow: false },
759
+ });
760
+
761
+ // 1) register one failing job, which is intended to be repeated "maxRetries" times
762
+ await uut.init();
763
+ await uut.registerJob(mkFailingJob());
764
+ await uut.processPendingJobs();
765
+ await clock.runAllAsync();
766
+
767
+ // 2) to make it being retried, spawn "maxRetries" successful job
768
+ const numSuccessfulJobs = config.maxAutoRetriesAfterError;
769
+ for (let i = 0; i < numSuccessfulJobs; i += 1) {
770
+ await uut.registerJob(mkSucceedingJob());
771
+ await uut.processPendingJobs();
772
+ await clock.runAllAsync();
773
+ }
774
+
775
+ // Expected outcome:
776
+ // - failing: 1 job, plus "maxRetries" retries
777
+ // - succeeding: "maxRetries" jobs to force retries
778
+ //
779
+ // In total, (1 + maxRetries) + maxRetries
780
+ // [ failed ] [ success ]
781
+ expect(uut.stats.jobStarted).to.eql(
782
+ 1 + 2 * config.maxAutoRetriesAfterError,
783
+ );
784
+ expect(uut.stats.jobFailed).to.eql(1 + config.maxAutoRetriesAfterError);
785
+ expect(uut.stats.jobSucceeded).to.eql(config.maxAutoRetriesAfterError);
786
+ expect(uut.getTotalJobs()).to.eql(0);
787
+
788
+ // new successful jobs will also not result in failed jobs getting rerun
789
+ const { jobStarted, jobFailed, jobSucceeded } = uut.stats;
790
+ await uut.registerJob(mkSucceedingJob());
791
+ expect(uut.getTotalJobs()).to.eql(1);
792
+ await uut.processPendingJobs();
793
+ await clock.runAllAsync();
794
+
795
+ // one extra successful one, but no more errors
796
+ expect(uut.stats.jobStarted).to.eql(jobStarted + 1);
797
+ expect(uut.stats.jobSucceeded).to.eql(jobSucceeded + 1);
798
+ expect(uut.stats.jobFailed).to.eql(jobFailed);
799
+ expect(uut.getTotalJobs()).to.eql(0);
800
+ });
801
+
802
+ describe('should not let failed jobs prevent new jobs from being started', function () {
803
+ [0, 1, 2 * SECOND, 2 * MINUTE, 1 * HOUR].forEach((cooldownInMs) => {
804
+ it(`with cooldown=${cooldownInMs} ms`, async function () {
805
+ const type = 'testjob';
806
+ const jobsNeverStarted = new Set();
807
+
808
+ const mkJob = (id) => {
809
+ const job = {
810
+ type,
811
+ args: { id },
812
+ };
813
+ jobsNeverStarted.add(id);
814
+ return job;
815
+ };
816
+
817
+ const handler = async (job) => {
818
+ jobsNeverStarted.delete(job.args.id);
819
+ throw someRecoverableError('[testing] expected to always fail');
820
+ };
821
+
822
+ const maxJobsTotal = 10;
823
+ const config = {
824
+ maxJobsTotal,
825
+ cooldownInMs,
826
+ };
827
+ uut.registerHandler(type, handler, config);
828
+ await uut.init();
829
+
830
+ // When jobs are exected, they will always fail. Still, it should
831
+ // be possible to keep starting new ones.
832
+ const numJobs = 2 * maxJobsTotal;
833
+ for (let i = 1; i <= numJobs; i += 1) {
834
+ await uut.registerJob(mkJob(i));
835
+ expect(uut.stats.jobRejected).to.eql(0);
836
+ expect(uut.stats.jobRegistered).to.eql(i);
837
+ expect(uut.stats.jobStarted).to.be.at.most(i);
838
+ expect(uut.stats.jobFailed).to.be.at.most(i);
839
+ await uut.processPendingJobs();
840
+ await clock.tickAsync(cooldownInMs);
841
+ await clock.runAllAsync();
842
+ }
843
+
844
+ expect(uut.stats.jobRejected).to.eql(0);
845
+ expect(uut.stats.jobRegistered).to.eql(numJobs);
846
+ expect(uut.stats.jobStarted).to.be.at.most(numJobs);
847
+ expect(uut.stats.jobFailed).to.be.at.most(numJobs);
848
+ expect([...jobsNeverStarted]).to.be.empty;
849
+ });
850
+ });
851
+ });
852
+ });
853
+
854
+ describe('should keep the persisted state minimal', function () {
855
+ it('should eventually remove queues from removed jobs', async function () {
856
+ const garbage = someJob(`garbage-${Math.random()}`);
857
+ const current = someJob(`current-${Math.random()}`);
858
+
859
+ uut.registerHandler(garbage.type, () => {});
860
+ uut.registerHandler(current.type, () => {});
861
+ await uut.init();
862
+ await uut.registerJob(garbage);
863
+ await uut.registerJob(current);
864
+ expect(uut.jobQueues[garbage.type]).to.exist;
865
+ expect(uut.jobQueues[current.type]).to.exist;
866
+ await clock.runAllAsync();
867
+
868
+ await simulateRestart();
869
+ uut.registerHandler(garbage.type, () => {}); // here it still exists
870
+ uut.registerHandler(current.type, () => {});
871
+ await uut.init();
872
+ await uut.processPendingJobs();
873
+ await clock.runAllAsync();
874
+ expect(uut.jobQueues[garbage.type]).to.exist;
875
+ expect(uut.jobQueues[current.type]).to.exist;
876
+ await clock.tickAsync(1 * YEAR);
877
+
878
+ await simulateRestart();
879
+ uut.registerHandler(current.type, () => {}); // Note that 'garbage' is missing
880
+ await uut.init();
881
+ await uut.processPendingJobs();
882
+ await clock.runAllAsync();
883
+ expect(uut.jobQueues[garbage.type]).to.not.exist;
884
+ expect(uut.jobQueues[current.type]).to.exist;
885
+ });
886
+
887
+ it('should clean-up left-overs after an extensive clock-jump, followed by a correction', async function () {
888
+ const type = 'testjob';
889
+ const mkJob = () => {
890
+ const job = {
891
+ type,
892
+ args: {},
893
+ config: {
894
+ readyIn: { min: 1 * HOUR },
895
+ },
896
+ };
897
+ return job;
898
+ };
899
+ const handler = () =>
900
+ expect.fail('jobs were not supposed to run in this test');
901
+
902
+ const start = Date.now();
903
+ clock.setSystemTime(start + 20 * YEAR); // let the clock be in an inconsistent state
904
+
905
+ uut.registerHandler(type, handler);
906
+ await uut.init();
907
+ await uut.registerJob(mkJob());
908
+ await uut.registerJob(mkJob());
909
+ await clock.runAllAsync();
910
+ expect(uut.getTotalJobs()).to.eql(2);
911
+
912
+ await simulateRestart();
913
+ uut.registerHandler(type, handler);
914
+ await uut.init();
915
+ await clock.runAllAsync();
916
+ expect(uut.getTotalJobs()).to.eql(2); // still exist
917
+
918
+ await simulateRestart();
919
+ clock.setSystemTime(start); // now the clock corrects
920
+ uut.registerHandler(type, handler);
921
+ await uut.init();
922
+ await clock.runAllAsync();
923
+ expect(uut.getTotalJobs()).to.eql(0); // the jobs are gone
924
+ });
510
925
  });
511
926
 
512
927
  describe('[scripted scenarios]', function () {
@@ -562,6 +977,8 @@ describe('#JobScheduler', function () {
562
977
  maxJobTypes = 20,
563
978
  minReadyIn = 0,
564
979
  maxReadyIn = 1 * MONTH,
980
+ minExpireIn = 1 * SECOND,
981
+ maxExpireIn = 1 * MONTH,
565
982
  minTTL = 1 * SECOND,
566
983
  maxTTL = 12 * MONTH,
567
984
  maxJobsPerType = 10000,
@@ -569,31 +986,56 @@ describe('#JobScheduler', function () {
569
986
  maxAutoRetriesAfterError = 100,
570
987
  maxClockJump = 6 * MONTH, // also simulates if a machines goes to sleep
571
988
  } = {}) {
989
+ // these fields are reserved for the config passed to the jobHandler
990
+ const commonJobConfigFields = () => ({
991
+ priority: fc.integer(),
992
+ ttlInMs: fc.integer({ min: minTTL, max: maxTTL }),
993
+ maxJobsTotal: fc.integer({ min: 1, max: maxJobsPerType }),
994
+ cooldownInMs: fc.nat(maxCooldown),
995
+ maxAutoRetriesAfterError: fc.nat(maxAutoRetriesAfterError),
996
+ });
997
+ const individualJobConfigFields = () => ({
998
+ readyIn: fc.record(
999
+ {
1000
+ min: fc.nat(minReadyIn),
1001
+ max: fc.option(fc.integer({ min: minReadyIn, max: maxReadyIn })),
1002
+ },
1003
+ {
1004
+ requiredKeys: ['min'],
1005
+ },
1006
+ ),
1007
+ expireIn: fc.record(
1008
+ {
1009
+ min: fc.nat(minExpireIn),
1010
+ max: fc.option(fc.integer({ min: minExpireIn, max: maxExpireIn })),
1011
+ },
1012
+ {
1013
+ requiredKeys: ['min'],
1014
+ },
1015
+ ),
1016
+ });
1017
+
572
1018
  const numToJobType = (x) => `testjob${x}`;
573
1019
  const arbitraryJobType = () => fc.nat(maxJobTypes - 1).map(numToJobType);
574
1020
  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
- };
1021
+ const arbitraryJobConfig = () =>
1022
+ fc.record(commonJobConfigFields(), { requiredKeys: [] });
591
1023
  const arbitraryJob = () => {
592
1024
  return fc
593
1025
  .tuple(
594
1026
  arbitraryJobType(),
595
1027
  fc.option(arbitraryJobArgs()),
596
- fc.option(arbitraryJobConfig()),
1028
+ fc.option(
1029
+ fc.record(
1030
+ {
1031
+ ...commonJobConfigFields(),
1032
+ ...individualJobConfigFields(),
1033
+ },
1034
+ {
1035
+ requiredKeys: [],
1036
+ },
1037
+ ),
1038
+ ),
597
1039
  )
598
1040
  .map(([type, args, config]) => ({
599
1041
  type,