@whotracksme/reporting 7.4.1 β†’ 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,15 @@
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
+
1
13
  # v7.4.1 (Tue Jul 29 2025)
2
14
 
3
15
  #### πŸ› Bug Fix
@@ -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.1",
3
+ "version": "7.5.0",
4
4
  "type": "module",
5
5
  "description": "",
6
6
  "scripts": {
@@ -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;
@@ -139,17 +143,20 @@ class JobTester {
139
143
  * to clean up the queues fast enough. The second assumption is that
140
144
  * executing jobs when the service worker is already running should be
141
145
  * more resource friendly than waking up the user's device.
142
- * (TODO: Revisit this statement in the future. It would not be difficult
143
- * to add if needed: set an alert and call "processPendingJobs".)
144
146
  */
145
147
  export default class JobScheduler {
146
- 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
+ ];
147
154
 
148
155
  static EVENTS = [
149
156
  'jobRegistered',
150
157
  'jobStarted',
151
158
  'jobSucceeded',
152
- 'jobFailed', // TODO: what is the semantic? (permanently failed or retried?)
159
+ 'jobFailed',
153
160
  'jobExpired',
154
161
  'jobRejected',
155
162
  'syncedToDisk',
@@ -178,10 +185,7 @@ export default class JobScheduler {
178
185
  cooldownInMs: 0,
179
186
 
180
187
  // error handling:
181
- autoRetryAfterError: true,
182
- maxAutoRetriesAfterError: 3,
183
- // TODO: maybe add a flag to control if failed jobs should be put in the dlq
184
- // (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)
185
189
  };
186
190
  this._ensureValidHandlerConfig(this.defaultConfig);
187
191
  this.handlerConfigs = {};
@@ -300,6 +304,7 @@ export default class JobScheduler {
300
304
  }
301
305
 
302
306
  async registerJobs(jobs, { now = Date.now(), autoTrigger = true } = {}) {
307
+ await this.ready();
303
308
  jobs.forEach((job) => this._registerJob(job, now));
304
309
  if (autoTrigger) {
305
310
  this._scheduleProcessPendingJobs();
@@ -378,13 +383,9 @@ export default class JobScheduler {
378
383
  },
379
384
  };
380
385
 
381
- if (this.getTotalJobs() >= this.globalJobLimit) {
382
- this.notifyObservers('jobRejected', 'global job limit reached', jobEntry);
383
- return;
384
- }
385
- const localLimit = this.handlerConfigs[type]?.maxJobsTotal;
386
- if (localLimit && this.getTotalJobsOfType(type) >= localLimit) {
387
- 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);
388
389
  return;
389
390
  }
390
391
 
@@ -397,15 +398,65 @@ export default class JobScheduler {
397
398
  }
398
399
  }
399
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
+
400
452
  _pushToQueue({ jobEntry, state, now = Date.now() }) {
401
453
  this._ensureValidState(state);
402
454
  const { type } = jobEntry.job;
403
- if (!this.jobQueues[type]) {
404
- this.jobQueues[type] = Object.fromEntries(
405
- JobScheduler.STATES.map((x) => [x, []]),
406
- );
407
- }
408
- 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
+
409
460
  const len = this.jobQueues[type][state].length;
410
461
  if (len > 0 && state === 'waiting') {
411
462
  const lastJob = this.jobQueues[type][state][len - 1];
@@ -417,6 +468,39 @@ export default class JobScheduler {
417
468
  this._markAsDirty();
418
469
  }
419
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
+
420
504
  _removeFromRunningQueue(jobEntry, now = Date.now()) {
421
505
  const { type } = jobEntry.job;
422
506
  if (this.jobQueues[type].running.pop()) {
@@ -452,32 +536,58 @@ export default class JobScheduler {
452
536
  }
453
537
  this._pushToQueue({ jobEntry, state: 'running', now });
454
538
  let newJobs;
539
+ let success = false;
455
540
  try {
456
541
  this.notifyObservers('jobStarted', jobEntry);
457
- newJobs = await this._runJob(jobEntry.job);
542
+ newJobs = (await this._runJob(jobEntry.job)) || [];
543
+ success = true;
458
544
  this.notifyObservers('jobSucceeded', jobEntry);
459
545
  } catch (e) {
546
+ let pendingRetry = false;
460
547
  if (e.isPermanentError) {
461
- logger.warn('Job failed:', jobEntry.job, e.message);
548
+ logger.error('Job failed:', jobEntry.job, e.message);
462
549
  } else if (e.isRecoverableError) {
463
- // TODO: implement retry
464
- 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
+ }
465
556
  } else {
466
557
  logger.error('Job failed (unexpected error):', jobEntry.job, e);
467
558
  }
468
- this.notifyObservers('jobFailed', jobEntry, e);
559
+ this.notifyObservers('jobFailed', jobEntry, {
560
+ pendingRetry,
561
+ exception: e,
562
+ });
469
563
  } finally {
470
564
  now = Date.now();
471
565
  this._removeFromRunningQueue(jobEntry, now);
472
566
  }
473
567
 
474
- if (newJobs && newJobs.length > 0) {
475
- logger.debug('Job', jobEntry.job, 'spawned', newJobs);
476
- for (const job of newJobs) {
477
- try {
478
- this._registerJob(job, now);
479
- } catch (e) {
480
- 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 });
481
591
  }
482
592
  }
483
593
  }
@@ -505,16 +615,16 @@ export default class JobScheduler {
505
615
  }
506
616
  }
507
617
 
508
- _expireJobsInAllQueue(jobTester) {
509
- for (const queue of Object.values(this.jobQueue)) {
510
- this._expireJobsInQueue(queue, jobTester);
511
- }
512
- }
513
-
514
- _expireJobsInQueue(queue, jobTester) {
515
- for (const jobEntry of jobTester.expireJobs(queue)) {
516
- 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
+ }
517
626
  }
627
+ return { numExpired, expiredJobs };
518
628
  }
519
629
 
520
630
  _findNextJobToRun(now = Date.now()) {
@@ -531,13 +641,13 @@ export default class JobScheduler {
531
641
  this.cooldowns[type] = null;
532
642
  }
533
643
  const { ready = [], waiting = [] } = this.jobQueues[type] || {};
534
- this._expireJobsInQueue(ready, jobTester);
644
+ this._tryExpireJobsInQueue(ready, jobTester);
535
645
  const nextJob = ready.shift();
536
646
  if (nextJob) {
537
647
  types.unshift(types.pop()); // to improve fairness
538
648
  return nextJob;
539
649
  }
540
- this._expireJobsInQueue(waiting, jobTester);
650
+ this._tryExpireJobsInQueue(waiting, jobTester);
541
651
  if (waiting.length > 0) {
542
652
  queuesToRescan.push(type);
543
653
  }
@@ -549,8 +659,7 @@ export default class JobScheduler {
549
659
  for (const type of queuesToRescan) {
550
660
  const { waiting = [] } = this.jobQueues[type];
551
661
  if (waiting.length > 0) {
552
- this._sortWaitingQueue(type, jobTester);
553
- this._expireJobsInQueue(waiting, jobTester);
662
+ this._sortWaitingQueue(type, jobTester, { removeExpiredJobs: true });
554
663
  let pos = 0;
555
664
  while (pos < waiting.length && jobTester.isJobReady(waiting[pos])) {
556
665
  pos += 1;
@@ -629,6 +738,8 @@ export default class JobScheduler {
629
738
  if (persistedState?.jobQueues) {
630
739
  const now = Date.now();
631
740
  const jobTester = new JobTester(now);
741
+ const isJobCreationTimeOK = ({ _meta }) => _meta.createdAt < now + DAY;
742
+
632
743
  for (const [type, queues] of Object.entries(persistedState.jobQueues)) {
633
744
  try {
634
745
  if (!queues) {
@@ -639,7 +750,29 @@ export default class JobScheduler {
639
750
  if (!Array.isArray(jobEntries)) {
640
751
  throw new Error(`Bad job queue in state=${state}`);
641
752
  }
642
- 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
+ }
643
776
  }
644
777
  if (queues.running && queues.running.length > 0) {
645
778
  // TODO: potentially add the running job into the queue again (it is repeatible)
@@ -648,12 +781,25 @@ export default class JobScheduler {
648
781
  queues.running,
649
782
  );
650
783
  queues.running = [];
784
+ this._markAsDirty();
651
785
  }
786
+
787
+ let alive = 0;
652
788
  for (const state of JobScheduler.STATES) {
653
789
  if (queues[state]) {
654
- this._expireJobsInQueue(queues[state], jobTester);
790
+ this._tryExpireJobsInQueue(queues[state], jobTester);
791
+ alive += queues[state].length;
655
792
  }
656
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
+ }
657
803
  } catch (e) {
658
804
  logger.warn(
659
805
  `Detected corrupted queue for type=<${type}>. Delete and continue...`,
@@ -661,6 +807,7 @@ export default class JobScheduler {
661
807
  e,
662
808
  );
663
809
  delete persistedState.jobQueues[type];
810
+ this._markAsDirty();
664
811
  }
665
812
  }
666
813
  this.jobQueues = persistedState.jobQueues;
@@ -714,6 +861,25 @@ export default class JobScheduler {
714
861
  * that, you can migrate jobs (either all or only selected types).
715
862
  */
716
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
+
717
883
  logger.warn(
718
884
  'DB_VERSION changed. Discarding the old state:',
719
885
  persistedState,
@@ -772,9 +938,16 @@ export default class JobScheduler {
772
938
  }
773
939
  }
774
940
 
775
- _sortWaitingQueue(type, jobTester) {
941
+ _sortWaitingQueue(type, jobTester, { removeExpiredJobs = false } = {}) {
942
+ if (removeExpiredJobs) {
943
+ this._tryExpireJobsInQueue(this.jobQueues[type].waiting, jobTester);
944
+ }
945
+
776
946
  if (!this._precomputed().waitingQueueSortedFlags[type]) {
777
947
  jobTester.sortJobs(this.jobQueues[type].waiting);
948
+ if (removeExpiredJobs) {
949
+ this._tryExpireJobsInQueue(this.jobQueues[type].waiting, jobTester);
950
+ }
778
951
  this._precomputed().waitingQueueSortedFlags[type] = true;
779
952
  }
780
953
  }
@@ -804,11 +977,11 @@ export default class JobScheduler {
804
977
  return count;
805
978
  }
806
979
 
807
- getTotalJobsInDlq() {
980
+ getTotalJobsWaitingForRetry() {
808
981
  let count = 0;
809
982
  for (const queue of Object.values(this.jobQueues)) {
810
- if (queue.dlq) {
811
- count += queue.dlq.length;
983
+ if (queue.retryable) {
984
+ count += queue.retryable.length;
812
985
  }
813
986
  }
814
987
  return count;
@@ -886,14 +1059,6 @@ export default class JobScheduler {
886
1059
  }
887
1060
  numCheckedKeys += 1;
888
1061
  };
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
1062
  const nonNegative = (x) => x >= 0;
898
1063
 
899
1064
  expectInt('priority');
@@ -901,7 +1066,6 @@ export default class JobScheduler {
901
1066
  expectInt('maxJobsTotal', nonNegative);
902
1067
  expectInt('cooldownInMs', nonNegative);
903
1068
  expectInt('maxAutoRetriesAfterError', nonNegative);
904
- expectBool('autoRetryAfterError');
905
1069
 
906
1070
  if (numCheckedKeys !== Object.keys(config).length) {
907
1071
  const unexpectedKeys = Object.keys(config).filter(
@@ -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;
@@ -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);
@@ -572,6 +590,338 @@ describe('#JobScheduler', function () {
572
590
  await uut.sync();
573
591
  expect(uut._describeJobs().queueLength).to.eql(1);
574
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
+ });
575
925
  });
576
926
 
577
927
  describe('[scripted scenarios]', function () {
@@ -642,7 +992,6 @@ describe('#JobScheduler', function () {
642
992
  ttlInMs: fc.integer({ min: minTTL, max: maxTTL }),
643
993
  maxJobsTotal: fc.integer({ min: 1, max: maxJobsPerType }),
644
994
  cooldownInMs: fc.nat(maxCooldown),
645
- autoRetryAfterError: fc.boolean(),
646
995
  maxAutoRetriesAfterError: fc.nat(maxAutoRetriesAfterError),
647
996
  });
648
997
  const individualJobConfigFields = () => ({