@whotracksme/reporting 5.1.17
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/.editorconfig +12 -0
- package/.eslintignore +3 -0
- package/.eslintrc +16 -0
- package/.github/workflows/release.yml +34 -0
- package/.github/workflows/tests.yml +20 -0
- package/.prettierrc +9 -0
- package/.tool-versions +1 -0
- package/CHANGELOG.md +795 -0
- package/LICENSE +373 -0
- package/README.md +1 -0
- package/communication/README.md +11 -0
- package/communication/example/index.js +43 -0
- package/communication/example/manifest.json +16 -0
- package/communication/karma.conf.cjs +19 -0
- package/communication/package.json +52 -0
- package/communication/rollup.common-config.cjs +17 -0
- package/communication/rollup.config.cjs +10 -0
- package/communication/src/encoding.js +54 -0
- package/communication/src/errors.js +84 -0
- package/communication/src/index.js +76 -0
- package/communication/src/logger.js +41 -0
- package/communication/src/padding.js +60 -0
- package/communication/src/proxied-http.js +231 -0
- package/communication/src/server-public-key-accessor.js +123 -0
- package/communication/src/timestamps.js +37 -0
- package/communication/src/trusted-clock.js +58 -0
- package/communication/src/utils.js +28 -0
- package/communication/src/zlib.js +17 -0
- package/communication/test/helpers/in-memory-database.js +43 -0
- package/communication/test/server-public-key-accessor.spec.js +135 -0
- package/communication/test/utils.spec.js +43 -0
- package/package.json +50 -0
- package/reporting/TODO.md +2 -0
- package/reporting/assets/request/bloom_filter.dat +0 -0
- package/reporting/assets/request/update.json +1 -0
- package/reporting/example/content.js +11 -0
- package/reporting/example/index.js +132 -0
- package/reporting/example/inspector/index.html +17 -0
- package/reporting/example/inspector/index.js +27 -0
- package/reporting/example/manifests/chromium.json +37 -0
- package/reporting/example/manifests/firefox.json +35 -0
- package/reporting/example/rules.json +62 -0
- package/reporting/example/setup.js +1 -0
- package/reporting/example/tests/test1.html +10 -0
- package/reporting/karma.conf.cjs +22 -0
- package/reporting/package.json +63 -0
- package/reporting/rollup.common-config.cjs +19 -0
- package/reporting/rollup.config.cjs +20 -0
- package/reporting/src/LRU.js +149 -0
- package/reporting/src/activity-estimator.js +298 -0
- package/reporting/src/alive-check.js +139 -0
- package/reporting/src/alive-message-generator.js +142 -0
- package/reporting/src/bloom-filters.js +345 -0
- package/reporting/src/country-provider.js +295 -0
- package/reporting/src/cyrb53.js +32 -0
- package/reporting/src/digest.js +33 -0
- package/reporting/src/doublefetch-page-handler.js +548 -0
- package/reporting/src/duplicate-detector.js +233 -0
- package/reporting/src/errors.js +84 -0
- package/reporting/src/event-listener-queue.js +121 -0
- package/reporting/src/fixed-size-cache.js +63 -0
- package/reporting/src/hash-detector.js +1526 -0
- package/reporting/src/html-parser.js +17 -0
- package/reporting/src/http.js +265 -0
- package/reporting/src/index.js +14 -0
- package/reporting/src/job-scheduler.js +912 -0
- package/reporting/src/logger.js +121 -0
- package/reporting/src/md5.js +334 -0
- package/reporting/src/message-sender.js +51 -0
- package/reporting/src/network.js +140 -0
- package/reporting/src/new-page-approver.js +119 -0
- package/reporting/src/page-aggregator.js +185 -0
- package/reporting/src/page-quorum-check-handler.js +200 -0
- package/reporting/src/page-structure.js +136 -0
- package/reporting/src/pagedb.js +671 -0
- package/reporting/src/pages.js +1798 -0
- package/reporting/src/patterns-updater.js +310 -0
- package/reporting/src/patterns.js +416 -0
- package/reporting/src/persisted-bitarray.js +265 -0
- package/reporting/src/persisted-hashes.js +189 -0
- package/reporting/src/quorum-checker.js +327 -0
- package/reporting/src/random.js +39 -0
- package/reporting/src/reporting.js +290 -0
- package/reporting/src/request/config.js +116 -0
- package/reporting/src/request/content-script.js +77 -0
- package/reporting/src/request/database.js +147 -0
- package/reporting/src/request/dnt.js +24 -0
- package/reporting/src/request/hash.js +101 -0
- package/reporting/src/request/index.js +874 -0
- package/reporting/src/request/page-telemetry.js +42 -0
- package/reporting/src/request/qs-whitelist2.js +247 -0
- package/reporting/src/request/resources/prob.js +601 -0
- package/reporting/src/request/steps/block-rules.js +40 -0
- package/reporting/src/request/steps/check-context.js +37 -0
- package/reporting/src/request/steps/cookie-context.js +209 -0
- package/reporting/src/request/steps/oauth-detector.js +101 -0
- package/reporting/src/request/steps/page-logger.js +177 -0
- package/reporting/src/request/steps/redirect-tagger.js +75 -0
- package/reporting/src/request/steps/subdomain-check.js +34 -0
- package/reporting/src/request/steps/token-checker/index.js +189 -0
- package/reporting/src/request/steps/token-checker/token-domain.js +129 -0
- package/reporting/src/request/steps/token-examiner.js +182 -0
- package/reporting/src/request/steps/token-telemetry/cached-entry-pipeline.js +210 -0
- package/reporting/src/request/steps/token-telemetry/index.js +234 -0
- package/reporting/src/request/steps/token-telemetry/key-pipeline.js +109 -0
- package/reporting/src/request/steps/token-telemetry/token-pipeline.js +105 -0
- package/reporting/src/request/time.js +73 -0
- package/reporting/src/request/utils/bloom-filter-packed.js +107 -0
- package/reporting/src/request/utils/chrome-storage-map.js +282 -0
- package/reporting/src/request/utils/subject.js +37 -0
- package/reporting/src/request/utils/temp-set.js +56 -0
- package/reporting/src/request/utils/tlds.js +55 -0
- package/reporting/src/request/utils.js +41 -0
- package/reporting/src/request-reporter.js +111 -0
- package/reporting/src/sanitizer.js +519 -0
- package/reporting/src/search-extractor.js +338 -0
- package/reporting/src/self-check.js +105 -0
- package/reporting/src/seq-executor.js +43 -0
- package/reporting/src/session-storage.js +399 -0
- package/reporting/src/url-analyzer.js +161 -0
- package/reporting/src/url-cleaner.js +60 -0
- package/reporting/src/utils/pacemaker.js +279 -0
- package/reporting/src/utils/url.js +114 -0
- package/reporting/src/utils.js +345 -0
- package/reporting/src/webrequest-pipeline/cname-uncloak.js +110 -0
- package/reporting/src/webrequest-pipeline/index.js +287 -0
- package/reporting/src/webrequest-pipeline/logger.js +14 -0
- package/reporting/src/webrequest-pipeline/page-store.js +282 -0
- package/reporting/src/webrequest-pipeline/page.js +140 -0
- package/reporting/src/webrequest-pipeline/pipeline.js +249 -0
- package/reporting/src/webrequest-pipeline/utils/webrequest.js +113 -0
- package/reporting/src/webrequest-pipeline/webrequest-context.js +153 -0
- package/reporting/test/README.md +2 -0
- package/reporting/test/activity-estimator.spec.js +356 -0
- package/reporting/test/alive-check.spec.js +156 -0
- package/reporting/test/alive-message-generator.spec.js +186 -0
- package/reporting/test/country-provider.spec.js +263 -0
- package/reporting/test/doublefetch-page-handler.spec.js +818 -0
- package/reporting/test/duplicate-detector.spec.js +689 -0
- package/reporting/test/helpers/dom-parsers.js +41 -0
- package/reporting/test/helpers/fake-session-storage.js +69 -0
- package/reporting/test/helpers/fast-check-utils.js +28 -0
- package/reporting/test/helpers/fetch-mock.js +57 -0
- package/reporting/test/helpers/in-memory-database.js +14 -0
- package/reporting/test/helpers/memory-map.js +72 -0
- package/reporting/test/helpers/pagedb-mocks.js +41 -0
- package/reporting/test/index.js +47 -0
- package/reporting/test/job-scheduler.spec.js +691 -0
- package/reporting/test/network.spec.js +72 -0
- package/reporting/test/page-aggregator.spec.js +104 -0
- package/reporting/test/page-quorum-check-handler.spec.js +86 -0
- package/reporting/test/pagedb.spec.js +250 -0
- package/reporting/test/pages.spec.js +693 -0
- package/reporting/test/patterns-updater.spec.js +446 -0
- package/reporting/test/patterns.spec.js +751 -0
- package/reporting/test/persisted-hashes.spec.js +169 -0
- package/reporting/test/reporting.spec.js +205 -0
- package/reporting/test/request/database.spec.js +59 -0
- package/reporting/test/request/hash.spec.js +108 -0
- package/reporting/test/request/index.spec.js +378 -0
- package/reporting/test/request/qs-whitelist2.spec.js +189 -0
- package/reporting/test/request/steps/check-context.spec.js +51 -0
- package/reporting/test/request/steps/oauth-detector.spec.js +339 -0
- package/reporting/test/request/test-pages.js +1246 -0
- package/reporting/test/request/utils/bloom-filter-packed.spec.js +37 -0
- package/reporting/test/request/utils/chrome-storage-map.spec.js +28 -0
- package/reporting/test/request/utils/tldts.spec.js +62 -0
- package/reporting/test/request/utils.spec.js +168 -0
- package/reporting/test/sanitizer.spec.js +1087 -0
- package/reporting/test/search-extractor.spec.js +590 -0
- package/reporting/test/seq-executor.spec.js +158 -0
- package/reporting/test/session-storage.spec.js +400 -0
- package/reporting/test/setup.js +24 -0
- package/reporting/test/url-analyzer.spec.js +451 -0
- package/reporting/test/url-cleaner.spec.js +102 -0
- package/reporting/test/utils/pacemaker.spec.js +222 -0
- package/reporting/test/utils/url.spec.js +660 -0
- package/reporting/test/utils.spec.js +299 -0
- package/reporting/test/webrequest-pipeline/pipeline.spec.js +251 -0
|
@@ -0,0 +1,912 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WhoTracks.Me
|
|
3
|
+
* https://whotracks.me/
|
|
4
|
+
*
|
|
5
|
+
* Copyright 2017-present Ghostery GmbH. All rights reserved.
|
|
6
|
+
*
|
|
7
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
8
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
9
|
+
* file, You can obtain one at http://mozilla.org/MPL/2.0
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import logger from './logger';
|
|
13
|
+
import { randomBetween } from './random';
|
|
14
|
+
import { BadJobError } from './errors';
|
|
15
|
+
import SeqExecutor from './seq-executor';
|
|
16
|
+
import { equalityCanBeProven } from './utils';
|
|
17
|
+
import SelfCheck from './self-check';
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* If you need to introduce incompatible changes to the the job
|
|
21
|
+
* persistence or need to recover from a bug that left the data
|
|
22
|
+
* in a corrupted state, you can bump this number.
|
|
23
|
+
*
|
|
24
|
+
* But be aware that doing it will result in all pending jobs being
|
|
25
|
+
* dropped! To avoid that, you can define an optional migration
|
|
26
|
+
* (see _tryDataMigration).
|
|
27
|
+
*/
|
|
28
|
+
const DB_VERSION = 1;
|
|
29
|
+
|
|
30
|
+
const SECOND = 1000;
|
|
31
|
+
const MINUTE = 60 * SECOND;
|
|
32
|
+
const HOUR = 60 * MINUTE;
|
|
33
|
+
const DAY = 24 * HOUR;
|
|
34
|
+
const WEEK = 7 * DAY;
|
|
35
|
+
const MONTH = 30 * DAY;
|
|
36
|
+
|
|
37
|
+
class JobTester {
|
|
38
|
+
constructor(now = Date.now()) {
|
|
39
|
+
this.now = now;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
isJobReady(jobEntry) {
|
|
43
|
+
return this.now >= jobEntry._meta.readyAt;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
isJobExpired(jobEntry) {
|
|
47
|
+
return this.now >= jobEntry._meta.expireAt;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
expireJobs(jobEntries) {
|
|
51
|
+
let pos = 0;
|
|
52
|
+
while (pos < jobEntries.length && this.isJobExpired(jobEntries[pos])) {
|
|
53
|
+
pos += 1;
|
|
54
|
+
}
|
|
55
|
+
return jobEntries.splice(0, pos);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Note: smaller is of higher priority
|
|
59
|
+
computePriority(jobEntry) {
|
|
60
|
+
// TODO: this could be improved (though prefer old jobs is not a bad strategy)
|
|
61
|
+
return jobEntry._meta.createdAt;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
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;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
sortJobs(jobEntries) {
|
|
76
|
+
jobEntries.sort((x, y) => this.compareJobsByPriority(x, y));
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Provides a persisted job queue with jobs that can scheduled in the future.
|
|
82
|
+
* Also, it provides limited support for priorities and throttling.
|
|
83
|
+
*
|
|
84
|
+
* Definition of a job: { type, args, config }
|
|
85
|
+
* - type
|
|
86
|
+
* - args: the scheduler will not into it, but merely passes it on
|
|
87
|
+
* - config (optional): to overwrite job specific configurations
|
|
88
|
+
*
|
|
89
|
+
* Notes:
|
|
90
|
+
* - The args of a job must be trivially serializable. It is recommended to use only:
|
|
91
|
+
* 1) strings
|
|
92
|
+
* 2) finite numbers
|
|
93
|
+
* 3) arrays
|
|
94
|
+
* 4) null
|
|
95
|
+
* 5) nested object (but only with the simple types)
|
|
96
|
+
*
|
|
97
|
+
* Example:
|
|
98
|
+
* {
|
|
99
|
+
* type: 'test-job',
|
|
100
|
+
* args: { foo: null, nested: { bar: ["one", 2, 3.0] } },
|
|
101
|
+
* }
|
|
102
|
+
*
|
|
103
|
+
* Throttling:
|
|
104
|
+
* - Only one job will be executed at the same time.
|
|
105
|
+
* - Optionally, you can define cooldowns between jobs of identical category
|
|
106
|
+
* (these cooldowns will not be persisted, so they should be short lived).
|
|
107
|
+
* - The job scheduler starts with a delay to have a higher chance of running
|
|
108
|
+
* in the background and not compete with a page load.
|
|
109
|
+
* - Jobs have TTLs and each queue can have size limits. By dropping jobs,
|
|
110
|
+
* the scheduler can provide stronger guarantees about resource usage.
|
|
111
|
+
*
|
|
112
|
+
* Priorities:
|
|
113
|
+
* - Each job type has an optional static priority. Jobs queue with higher
|
|
114
|
+
* priorities will be scheduled for execution before jobs with the
|
|
115
|
+
* lesser priorities.
|
|
116
|
+
* - With queues itself and queues of the same priority, older jobs
|
|
117
|
+
* will be executed before newer jobs.
|
|
118
|
+
*
|
|
119
|
+
* Note:
|
|
120
|
+
* - At the moment, it is intentionally not installing additional timers
|
|
121
|
+
* through the alert API. The assumption is that it will still be possible
|
|
122
|
+
* to clean up the queues fast enough. The second assumption is that
|
|
123
|
+
* executing jobs when the service worker is already running should be
|
|
124
|
+
* 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
|
+
*/
|
|
128
|
+
export default class JobScheduler {
|
|
129
|
+
static STATES = ['running', 'ready', 'waiting', 'dlq'];
|
|
130
|
+
|
|
131
|
+
static EVENTS = [
|
|
132
|
+
'jobRegistered',
|
|
133
|
+
'jobStarted',
|
|
134
|
+
'jobSucceeded',
|
|
135
|
+
'jobFailed', // TODO: what is the semantic? (permanently failed or retried?)
|
|
136
|
+
'jobExpired',
|
|
137
|
+
'jobRejected',
|
|
138
|
+
'syncedToDisk',
|
|
139
|
+
];
|
|
140
|
+
|
|
141
|
+
constructor({ storage, storageKey }) {
|
|
142
|
+
this.storage = storage;
|
|
143
|
+
this.storageKey = storageKey;
|
|
144
|
+
|
|
145
|
+
this.active = false;
|
|
146
|
+
this.handlers = {};
|
|
147
|
+
this.jobExecutor = new SeqExecutor();
|
|
148
|
+
|
|
149
|
+
this.defaultTTL = 2 * WEEK;
|
|
150
|
+
this.maxTTL = 6 * MONTH;
|
|
151
|
+
this.globalJobLimit = 10000;
|
|
152
|
+
|
|
153
|
+
this.defaultConfig = {
|
|
154
|
+
priority: 0, // higher values will be executed before
|
|
155
|
+
|
|
156
|
+
// quotas:
|
|
157
|
+
ttlInMs: this.defaultTTL,
|
|
158
|
+
maxJobsTotal: 1000,
|
|
159
|
+
|
|
160
|
+
// throttling:
|
|
161
|
+
cooldownInMs: 0,
|
|
162
|
+
|
|
163
|
+
// 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)
|
|
168
|
+
};
|
|
169
|
+
this.handlerConfigs = {};
|
|
170
|
+
|
|
171
|
+
// Note: this data structure is intended to be in a format that can be
|
|
172
|
+
// stored and loaded from local storage. Ideally, use only simple data
|
|
173
|
+
// types (plain objects, arrays, strings and numbers).
|
|
174
|
+
this.jobQueues = {}; // type -> [jobEntry] where jobEntry == { job, _meta }
|
|
175
|
+
|
|
176
|
+
this.lastCheck = 0; // Unix epoch
|
|
177
|
+
this.nextCheckTimer = null;
|
|
178
|
+
|
|
179
|
+
// local cooldowns (not persisted across restarts)
|
|
180
|
+
this.cooldowns = {}; // type -> Unix epoch
|
|
181
|
+
this._resetPrecomputed();
|
|
182
|
+
|
|
183
|
+
this._observers = Object.fromEntries(
|
|
184
|
+
JobScheduler.EVENTS.map((event) => [event, []]),
|
|
185
|
+
);
|
|
186
|
+
this.stats = Object.fromEntries(
|
|
187
|
+
JobScheduler.EVENTS.map((event) => [event, 0]),
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
registerHandler(type, handler, config = {}) {
|
|
192
|
+
if (this.active) {
|
|
193
|
+
logger.warn(
|
|
194
|
+
'Job handler for type',
|
|
195
|
+
type,
|
|
196
|
+
'was register when the scheduler is already running.',
|
|
197
|
+
'This is an anti-pattern, because it introduces a race',
|
|
198
|
+
'(jobs will be dropped if their handler is installed too late)',
|
|
199
|
+
);
|
|
200
|
+
}
|
|
201
|
+
if (this.handlers[type]) {
|
|
202
|
+
logger.warn('Redefining handler for type:', type);
|
|
203
|
+
}
|
|
204
|
+
this.handlers[type] = handler;
|
|
205
|
+
this.handlerConfigs[type] = { ...this.defaultConfig, ...config };
|
|
206
|
+
logger.debug(
|
|
207
|
+
'Registered job handler for',
|
|
208
|
+
type,
|
|
209
|
+
'with config:',
|
|
210
|
+
this.handlerConfigs[type],
|
|
211
|
+
);
|
|
212
|
+
this._resetPrecomputed();
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
addObserver(eventType, cb, { ignoreAfterInitWarning = false } = {}) {
|
|
216
|
+
if (!this._observers[eventType]) {
|
|
217
|
+
throw new Error(`Unknown event type: ${eventType}`);
|
|
218
|
+
}
|
|
219
|
+
if (this.active && !ignoreAfterInitWarning) {
|
|
220
|
+
logger.warn(
|
|
221
|
+
'Observer for event',
|
|
222
|
+
eventType,
|
|
223
|
+
'was added when the scheduler was already running.',
|
|
224
|
+
'This is an anti-pattern because it may introduce a race.',
|
|
225
|
+
);
|
|
226
|
+
}
|
|
227
|
+
this._observers[eventType].push(cb);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
notifyObservers(eventType, ...args) {
|
|
231
|
+
const handlers = this._observers[eventType];
|
|
232
|
+
if (!handlers) {
|
|
233
|
+
throw new Error(`Internal error: unknown event type: ${eventType}`);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
this.stats[eventType] += 1;
|
|
237
|
+
for (const handler of handlers) {
|
|
238
|
+
try {
|
|
239
|
+
handler(...args);
|
|
240
|
+
} catch (e) {
|
|
241
|
+
logger.error(
|
|
242
|
+
`Unexpected error in observer of type=${eventType}:`,
|
|
243
|
+
...args,
|
|
244
|
+
e,
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
async init() {
|
|
251
|
+
this.active = true;
|
|
252
|
+
this._scheduleProcessPendingJobs();
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
async ready() {
|
|
256
|
+
if (!this._ready) {
|
|
257
|
+
this._ready = this._restoreJobsFromDisk();
|
|
258
|
+
}
|
|
259
|
+
await this._ready;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Synchronizes the cached and persisted state.
|
|
264
|
+
*/
|
|
265
|
+
async sync() {
|
|
266
|
+
await this.ready();
|
|
267
|
+
await this._writeJobsToDisk();
|
|
268
|
+
this.notifyObservers('syncedToDisk');
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
unload() {
|
|
272
|
+
this.active = false;
|
|
273
|
+
this._clearNextCheckTimer();
|
|
274
|
+
this._clearAutoFlushTimer();
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
async registerJob(job, { now = Date.now(), autoTrigger = true } = {}) {
|
|
278
|
+
return this.registerJobs([job], { now, autoTrigger });
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
async registerJobs(jobs, { now = Date.now(), autoTrigger = true } = {}) {
|
|
282
|
+
jobs.forEach((job) => this._registerJob(job, now));
|
|
283
|
+
if (autoTrigger) {
|
|
284
|
+
this._scheduleProcessPendingJobs();
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
_registerJob(job, now = Date.now()) {
|
|
289
|
+
this._ensureValidJob(job);
|
|
290
|
+
const { type } = job;
|
|
291
|
+
if (!this.handlers[type]) {
|
|
292
|
+
logger.warn(
|
|
293
|
+
'Trying to initialize a job for type',
|
|
294
|
+
type,
|
|
295
|
+
'which no handler is present',
|
|
296
|
+
);
|
|
297
|
+
}
|
|
298
|
+
const config = job.config || {};
|
|
299
|
+
|
|
300
|
+
const createdAt = now;
|
|
301
|
+
|
|
302
|
+
// The "readyIn" field exists for convenience and can be converted
|
|
303
|
+
// the absolute time in "readyAt". It must define a non-negative
|
|
304
|
+
// "min" value and an optional "max" value (if you want randomness).
|
|
305
|
+
//
|
|
306
|
+
// Examples:
|
|
307
|
+
// - { min: 2000} will delay by (at least) 2 seconds
|
|
308
|
+
// - { min: 2000, max: 3000 } will delay by (at least) 2-3 seconds
|
|
309
|
+
//
|
|
310
|
+
// Note: the real delay can be higher, since there is no guarantee
|
|
311
|
+
// that the job will be executed as soon it is ready for execution.
|
|
312
|
+
const toReadyAt = (readyIn) => {
|
|
313
|
+
if (readyIn === undefined || readyIn === null) {
|
|
314
|
+
return undefined;
|
|
315
|
+
}
|
|
316
|
+
let { min = -1, max } = readyIn;
|
|
317
|
+
if (min < 0) {
|
|
318
|
+
throw new BadJobError(
|
|
319
|
+
'Config error: readyIn must be present and non-negative',
|
|
320
|
+
);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
max = max ?? min;
|
|
324
|
+
if (max > this.maxTTL) {
|
|
325
|
+
throw new BadJobError('Config error: readyIn must not exceed maxTTL');
|
|
326
|
+
}
|
|
327
|
+
return now + randomBetween(min, max);
|
|
328
|
+
};
|
|
329
|
+
|
|
330
|
+
// If a job does not define an absolute time when it can be run,
|
|
331
|
+
// assume that it is immediately ready.
|
|
332
|
+
const readyAt = config.readyAt ?? toReadyAt(config.readyIn) ?? 0;
|
|
333
|
+
if (!Number.isFinite(readyAt)) {
|
|
334
|
+
throw new BadJobError(`readyAt is invalid: ${readyAt}`);
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// If a job defines an absolute time in "expireAt", take it;
|
|
338
|
+
// otherwise, use a relative TTL (with fallbacks).
|
|
339
|
+
// Note: TTLs are enforced here to improve fault tolerance.
|
|
340
|
+
let { expireAt } = config;
|
|
341
|
+
if (!expireAt) {
|
|
342
|
+
const ttl =
|
|
343
|
+
config.ttlInMs ?? this.handlerConfigs[type]?.ttlInMs ?? this.maxTTL;
|
|
344
|
+
expireAt = now + ttl;
|
|
345
|
+
}
|
|
346
|
+
if (expireAt > now + this.maxTTL) {
|
|
347
|
+
expireAt = now + this.maxTTL;
|
|
348
|
+
logger.warn("job's TTL has been truncated:", job);
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
const jobEntry = {
|
|
352
|
+
job,
|
|
353
|
+
_meta: {
|
|
354
|
+
createdAt,
|
|
355
|
+
readyAt,
|
|
356
|
+
expireAt,
|
|
357
|
+
},
|
|
358
|
+
};
|
|
359
|
+
|
|
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);
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
this.notifyObservers('jobRegistered', job);
|
|
371
|
+
if (now < expireAt) {
|
|
372
|
+
this._pushToQueue({ jobEntry, state: 'waiting', now });
|
|
373
|
+
} else {
|
|
374
|
+
logger.warn('New job immediately expired:', jobEntry);
|
|
375
|
+
this.notifyObservers('jobExpired', jobEntry);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
_pushToQueue({ jobEntry, state, now = Date.now() }) {
|
|
380
|
+
this._ensureValidState(state);
|
|
381
|
+
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] || [];
|
|
388
|
+
const len = this.jobQueues[type][state].length;
|
|
389
|
+
if (len > 0 && state === 'waiting') {
|
|
390
|
+
const lastJob = this.jobQueues[type][state][len - 1];
|
|
391
|
+
if (new JobTester(now).compareJobsByPriority(lastJob, jobEntry) > 0) {
|
|
392
|
+
this._markWaitingQueueAsUnsorted(type);
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
this.jobQueues[type][state].push(jobEntry);
|
|
396
|
+
this._markAsDirty();
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
_removeFromRunningQueue(jobEntry, now = Date.now()) {
|
|
400
|
+
const { type } = jobEntry.job;
|
|
401
|
+
if (this.jobQueues[type].running.pop()) {
|
|
402
|
+
const { cooldownInMs = 0 } = this.handlerConfigs[type];
|
|
403
|
+
if (cooldownInMs > 0) {
|
|
404
|
+
this.cooldowns[type] = now + cooldownInMs;
|
|
405
|
+
}
|
|
406
|
+
this._markAsDirty();
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
async processPendingJobs({
|
|
411
|
+
maxJobsToRun = Number.MAX_SAFE_INTEGER,
|
|
412
|
+
autoResumeAfterCooldowns = false,
|
|
413
|
+
} = {}) {
|
|
414
|
+
this._clearNextCheckTimer();
|
|
415
|
+
if (!this.active) {
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
await this.ready();
|
|
419
|
+
await this.jobExecutor.run(async () => {
|
|
420
|
+
let numJobsExecuted = 0;
|
|
421
|
+
let now = Date.now();
|
|
422
|
+
while (this.active) {
|
|
423
|
+
if (numJobsExecuted >= maxJobsToRun) {
|
|
424
|
+
autoResumeAfterCooldowns = false;
|
|
425
|
+
break;
|
|
426
|
+
}
|
|
427
|
+
numJobsExecuted += 1;
|
|
428
|
+
const jobEntry = this._findNextJobToRun(now);
|
|
429
|
+
if (!jobEntry) {
|
|
430
|
+
break;
|
|
431
|
+
}
|
|
432
|
+
this._pushToQueue({ jobEntry, state: 'running', now });
|
|
433
|
+
let newJobs;
|
|
434
|
+
try {
|
|
435
|
+
this.notifyObservers('jobStarted', jobEntry);
|
|
436
|
+
newJobs = await this._runJob(jobEntry.job);
|
|
437
|
+
this.notifyObservers('jobSucceeded', jobEntry);
|
|
438
|
+
} catch (e) {
|
|
439
|
+
if (e.isPermanentError) {
|
|
440
|
+
logger.warn('Job failed:', jobEntry.job, e.message);
|
|
441
|
+
} else if (e.isRecoverableError) {
|
|
442
|
+
// TODO: implement retry
|
|
443
|
+
logger.warn('Job failed (skip retry):', jobEntry.job, e);
|
|
444
|
+
} else {
|
|
445
|
+
logger.error('Job failed (unexpected error):', jobEntry.job, e);
|
|
446
|
+
}
|
|
447
|
+
this.notifyObservers('jobFailed', jobEntry);
|
|
448
|
+
} finally {
|
|
449
|
+
now = Date.now();
|
|
450
|
+
this._removeFromRunningQueue(jobEntry, now);
|
|
451
|
+
}
|
|
452
|
+
|
|
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);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
});
|
|
465
|
+
|
|
466
|
+
if (
|
|
467
|
+
this.nextCheckTimer === null &&
|
|
468
|
+
autoResumeAfterCooldowns &&
|
|
469
|
+
this.active
|
|
470
|
+
) {
|
|
471
|
+
const now = Date.now();
|
|
472
|
+
const expirations = [];
|
|
473
|
+
for (const [type, expireAt] of Object.entries(this.cooldowns)) {
|
|
474
|
+
if (expireAt !== null && this.jobQueues[type].ready.length > 0) {
|
|
475
|
+
logger.debug('Jobs of type', type, 'are being throttled...');
|
|
476
|
+
expirations.push(expireAt - now);
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
if (expirations.length > 0) {
|
|
480
|
+
const delayInMs = Math.max(Math.min(...expirations), 0);
|
|
481
|
+
logger.debug('Scheduling next job to run in', delayInMs, 'ms');
|
|
482
|
+
this._scheduleProcessPendingJobs({ delayInMs });
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
|
|
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);
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
_findNextJobToRun(now = Date.now()) {
|
|
500
|
+
const jobTester = new JobTester(now);
|
|
501
|
+
|
|
502
|
+
for (const types of this.queuesByPriority) {
|
|
503
|
+
// 1) if there is a ready job, take it
|
|
504
|
+
const queuesToRescan = [];
|
|
505
|
+
for (const type of types) {
|
|
506
|
+
if (this.cooldowns[type]) {
|
|
507
|
+
if (now < this.cooldowns[type]) {
|
|
508
|
+
continue;
|
|
509
|
+
}
|
|
510
|
+
this.cooldowns[type] = null;
|
|
511
|
+
}
|
|
512
|
+
const { ready = [], waiting = [] } = this.jobQueues[type] || {};
|
|
513
|
+
this._expireJobsInQueue(ready, jobTester);
|
|
514
|
+
const nextJob = ready.shift();
|
|
515
|
+
if (nextJob) {
|
|
516
|
+
types.unshift(types.pop()); // to improve fairness
|
|
517
|
+
return nextJob;
|
|
518
|
+
}
|
|
519
|
+
this._expireJobsInQueue(waiting, jobTester);
|
|
520
|
+
if (waiting.length > 0) {
|
|
521
|
+
queuesToRescan.push(type);
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
// 2) no ready job found, so scan the waiting jobs
|
|
526
|
+
let bestPrio;
|
|
527
|
+
let bestType = null;
|
|
528
|
+
for (const type of queuesToRescan) {
|
|
529
|
+
const { waiting = [] } = this.jobQueues[type];
|
|
530
|
+
if (waiting.length > 0) {
|
|
531
|
+
this._sortWaitingQueue(type, jobTester);
|
|
532
|
+
this._expireJobsInQueue(waiting, jobTester);
|
|
533
|
+
let pos = 0;
|
|
534
|
+
while (pos < waiting.length && jobTester.isJobReady(waiting[pos])) {
|
|
535
|
+
pos += 1;
|
|
536
|
+
}
|
|
537
|
+
if (pos > 0) {
|
|
538
|
+
const newReady = waiting.splice(0, pos);
|
|
539
|
+
this.jobQueues[type].ready = newReady;
|
|
540
|
+
const prio = jobTester.computePriority(newReady[0]);
|
|
541
|
+
if (!bestType || prio < bestPrio) {
|
|
542
|
+
bestPrio = prio;
|
|
543
|
+
bestType = type;
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
if (bestType) {
|
|
549
|
+
return this.jobQueues[bestType].ready.shift();
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
return null;
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
async _runJob(job) {
|
|
557
|
+
const handler = this.handlers[job.type];
|
|
558
|
+
if (!handler) {
|
|
559
|
+
throw new Error(`Unexpected type: ${job.type}`);
|
|
560
|
+
}
|
|
561
|
+
return handler(job);
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
_scheduleProcessPendingJobs({
|
|
565
|
+
delayInMs = 2000,
|
|
566
|
+
autoResumeAfterCooldowns = true,
|
|
567
|
+
} = {}) {
|
|
568
|
+
if (this.nextCheckTimer === null) {
|
|
569
|
+
this.nextCheckTimer = setTimeout(() => {
|
|
570
|
+
this.nextCheckTimer = null;
|
|
571
|
+
this.processPendingJobs({ autoResumeAfterCooldowns }).catch(
|
|
572
|
+
logger.error,
|
|
573
|
+
);
|
|
574
|
+
}, delayInMs);
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
_clearNextCheckTimer() {
|
|
579
|
+
clearTimeout(this.nextCheckTimer);
|
|
580
|
+
this.nextCheckTimer = null;
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
async _restoreJobsFromDisk() {
|
|
584
|
+
let persistedState = await this.storage.get(this.storageKey);
|
|
585
|
+
if (persistedState && persistedState.dbVersion !== DB_VERSION) {
|
|
586
|
+
logger.warn(
|
|
587
|
+
'DB_VERSION of persisted jobs does not match:',
|
|
588
|
+
persistedState.dbVersion,
|
|
589
|
+
'!=',
|
|
590
|
+
DB_VERSION,
|
|
591
|
+
);
|
|
592
|
+
try {
|
|
593
|
+
persistedState = this._tryDataMigration(persistedState);
|
|
594
|
+
if (persistedState && persistedState.dbVersion !== DB_VERSION) {
|
|
595
|
+
logger.warn('Migration forget to update DB_VERSION. Fixing it...');
|
|
596
|
+
persistedState.dbVersion = DB_VERSION;
|
|
597
|
+
}
|
|
598
|
+
} catch (e) {
|
|
599
|
+
logger.error(
|
|
600
|
+
'Failed to migrate state. Dropping the state:',
|
|
601
|
+
persistedState,
|
|
602
|
+
e,
|
|
603
|
+
);
|
|
604
|
+
persistedState = null;
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
if (persistedState?.jobQueues) {
|
|
609
|
+
const now = Date.now();
|
|
610
|
+
const jobTester = new JobTester(now);
|
|
611
|
+
for (const [type, queues] of Object.entries(persistedState.jobQueues)) {
|
|
612
|
+
try {
|
|
613
|
+
if (!queues) {
|
|
614
|
+
throw new Error('Missing queue');
|
|
615
|
+
}
|
|
616
|
+
for (const [state, jobEntries] of Object.entries(queues)) {
|
|
617
|
+
this._ensureValidState(state);
|
|
618
|
+
if (!Array.isArray(jobEntries)) {
|
|
619
|
+
throw new Error(`Bad job queue in state=${state}`);
|
|
620
|
+
}
|
|
621
|
+
jobEntries.forEach((x) => this._ensureValidJobEntry(x));
|
|
622
|
+
}
|
|
623
|
+
if (queues.running && queues.running.length > 0) {
|
|
624
|
+
// TODO: potentially add the running job into the queue again (it is repeatible)
|
|
625
|
+
logger.warn(
|
|
626
|
+
'Detected unfinished running jobs (delete them):',
|
|
627
|
+
queues.running,
|
|
628
|
+
);
|
|
629
|
+
queues.running = [];
|
|
630
|
+
}
|
|
631
|
+
for (const state of JobScheduler.STATES) {
|
|
632
|
+
if (queues[state]) {
|
|
633
|
+
this._expireJobsInQueue(queues[state], jobTester);
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
} catch (e) {
|
|
637
|
+
logger.warn(
|
|
638
|
+
`Detected corrupted queue for type=<${type}>. Delete and continue...`,
|
|
639
|
+
queues,
|
|
640
|
+
e,
|
|
641
|
+
);
|
|
642
|
+
delete persistedState.jobQueues[type];
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
this.jobQueues = persistedState.jobQueues;
|
|
646
|
+
|
|
647
|
+
logger.info(
|
|
648
|
+
'Successfully restored jobQueue:',
|
|
649
|
+
this.getTotalJobs(),
|
|
650
|
+
'jobs in total',
|
|
651
|
+
);
|
|
652
|
+
logger.debug('Restored jobQueue:', this.jobQueues);
|
|
653
|
+
} else {
|
|
654
|
+
logger.info(
|
|
655
|
+
'No persisted jobs found.',
|
|
656
|
+
'This should only happen on the first time the extension is started',
|
|
657
|
+
'(or in rare cases if the data format changed).',
|
|
658
|
+
);
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
_markAsDirty() {
|
|
663
|
+
if (!this._autoFlushTimer) {
|
|
664
|
+
setTimeout(() => this._writeJobsToDisk(), 0);
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
_clearAutoFlushTimer() {
|
|
669
|
+
if (this._autoFlushTimer) {
|
|
670
|
+
clearTimeout(this._autoFlushTimer);
|
|
671
|
+
this._autoFlushTimer = null;
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
async _writeJobsToDisk() {
|
|
676
|
+
this._clearAutoFlushTimer();
|
|
677
|
+
return this.storage.set(this.storageKey, {
|
|
678
|
+
dbVersion: DB_VERSION,
|
|
679
|
+
jobQueues: this.jobQueues,
|
|
680
|
+
});
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
/**
|
|
684
|
+
* This hook is intended to support data migration after a version change.
|
|
685
|
+
* Whether a (full or partial) migration should be attempted, depends on
|
|
686
|
+
* the concrete situation.
|
|
687
|
+
*
|
|
688
|
+
* The default implemenation of discarding the old state (returning "null")
|
|
689
|
+
* is always correct; depending on how difficult it is to migrate, it can
|
|
690
|
+
* be the best solution. For instance, if you are forced to increased the
|
|
691
|
+
* version to recover from a bug that corrupted the data. However, purging
|
|
692
|
+
* jobs will temporarily lead to a drop of signals. If you want to avoid
|
|
693
|
+
* that, you can migrate jobs (either all or only selected types).
|
|
694
|
+
*/
|
|
695
|
+
_tryDataMigration(persistedState) {
|
|
696
|
+
logger.warn(
|
|
697
|
+
'DB_VERSION changed. Discarding the old state:',
|
|
698
|
+
persistedState,
|
|
699
|
+
);
|
|
700
|
+
return null;
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
/**
|
|
704
|
+
* This function exists primarily for testing and troubleshooting.
|
|
705
|
+
* It is not intended to be used by other components.
|
|
706
|
+
*
|
|
707
|
+
* Since the use case are limited, there are also no performance constraints.
|
|
708
|
+
* Thus, do not try to tune data structures for this function.
|
|
709
|
+
*/
|
|
710
|
+
_describeJobs() {
|
|
711
|
+
const byType = Object.fromEntries(
|
|
712
|
+
Object.entries(this.jobQueues).map(([type, queue]) => {
|
|
713
|
+
const all = [];
|
|
714
|
+
const byState = {};
|
|
715
|
+
for (const state of JobScheduler.STATES) {
|
|
716
|
+
const jobs = queue[state] || [];
|
|
717
|
+
jobs.forEach((x) => all.push(x));
|
|
718
|
+
byState[state] = [...jobs];
|
|
719
|
+
}
|
|
720
|
+
return [type, { all, byState }];
|
|
721
|
+
}),
|
|
722
|
+
);
|
|
723
|
+
const all = Object.values(byType).flatMap((x) => x.all);
|
|
724
|
+
const byState = {};
|
|
725
|
+
Object.values(this.jobQueues).forEach((queues) => {
|
|
726
|
+
JobScheduler.STATES.forEach((state) => {
|
|
727
|
+
byState[state] = byState[state] || [];
|
|
728
|
+
(queues[state] || []).forEach((job) => byState[state].push(job));
|
|
729
|
+
});
|
|
730
|
+
});
|
|
731
|
+
return {
|
|
732
|
+
active: this.active,
|
|
733
|
+
handlers: Object.keys(this.handlers),
|
|
734
|
+
queues: {
|
|
735
|
+
all,
|
|
736
|
+
byState,
|
|
737
|
+
byType,
|
|
738
|
+
},
|
|
739
|
+
queueLength: all.length,
|
|
740
|
+
};
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
// [[type]] (first set of queues are of highest priority)
|
|
744
|
+
get queuesByPriority() {
|
|
745
|
+
return this._precomputed().queuesByPriority;
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
_markWaitingQueueAsUnsorted(type) {
|
|
749
|
+
if (this._cachedPrecomputed?.waitingQueueSortedFlags[type]) {
|
|
750
|
+
this._cachedPrecomputed.waitingQueueSortedFlags[type] = false;
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
_sortWaitingQueue(type, jobTester) {
|
|
755
|
+
if (!this._precomputed().waitingQueueSortedFlags[type]) {
|
|
756
|
+
jobTester.sortJobs(this.jobQueues[type].waiting);
|
|
757
|
+
this._precomputed().waitingQueueSortedFlags[type] = true;
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
getTotalJobsOfType(type) {
|
|
762
|
+
let count = 0;
|
|
763
|
+
const queue = this.jobQueues[type];
|
|
764
|
+
if (queue) {
|
|
765
|
+
for (const state of JobScheduler.STATES) {
|
|
766
|
+
if (queue[state]) {
|
|
767
|
+
count += queue[state].length;
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
return count;
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
getTotalJobs() {
|
|
775
|
+
let count = 0;
|
|
776
|
+
for (const queue of Object.values(this.jobQueues)) {
|
|
777
|
+
for (const state of JobScheduler.STATES) {
|
|
778
|
+
if (queue[state]) {
|
|
779
|
+
count += queue[state].length;
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
return count;
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
_precomputed() {
|
|
787
|
+
if (!this._cachedPrecomputed) {
|
|
788
|
+
// Group the different types into set with the same priority and sort
|
|
789
|
+
// them, so in the final two-dim array, the first set has max priority.
|
|
790
|
+
const queueSet = {};
|
|
791
|
+
for (const [type, { priority }] of Object.entries(this.handlerConfigs)) {
|
|
792
|
+
queueSet[priority] = queueSet[priority] || [];
|
|
793
|
+
queueSet[priority].push(type);
|
|
794
|
+
}
|
|
795
|
+
const queuesByPriority = Object.entries(queueSet)
|
|
796
|
+
.sort(([prio1], [prio2]) => prio2 - prio1)
|
|
797
|
+
.map((x) => x[1]);
|
|
798
|
+
|
|
799
|
+
this._cachedPrecomputed = {
|
|
800
|
+
queuesByPriority,
|
|
801
|
+
waitingQueueSortedFlags: {},
|
|
802
|
+
};
|
|
803
|
+
}
|
|
804
|
+
return this._cachedPrecomputed;
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
_resetPrecomputed() {
|
|
808
|
+
this._cachedPrecomputed = null;
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
_ensureValidJob(job) {
|
|
812
|
+
if (typeof job?.type !== 'string') {
|
|
813
|
+
throw new BadJobError('invalid job: expected a "type"');
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
_ensureValidJobMetaData(_meta) {
|
|
818
|
+
if (!_meta) {
|
|
819
|
+
throw new BadJobError('no meta data found');
|
|
820
|
+
}
|
|
821
|
+
for (const timestamp of ['expireAt', 'readyAt', 'createdAt']) {
|
|
822
|
+
if (!Number.isFinite(_meta[timestamp])) {
|
|
823
|
+
throw new BadJobError(`${timestamp} corrupted`);
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
_ensureValidJobEntry({ job, _meta }) {
|
|
829
|
+
this._ensureValidJob(job);
|
|
830
|
+
this._ensureValidJobMetaData(_meta);
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
_ensureValidState(state) {
|
|
834
|
+
if (!JobScheduler.STATES.includes(state)) {
|
|
835
|
+
throw new Error(`Invalid state: ${state}`);
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
async selfChecks(check = new SelfCheck()) {
|
|
840
|
+
const restoredJobs = JSON.parse(JSON.stringify(this.jobQueues));
|
|
841
|
+
if (!equalityCanBeProven(this.jobQueues, restoredJobs)) {
|
|
842
|
+
check.warn('Jobs may lose information when persisting and restoring');
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
const numJobsInTotal = this.getTotalJobs();
|
|
846
|
+
if (numJobsInTotal > this.globalJobLimit) {
|
|
847
|
+
check.warn('total number of jobs in the queue exceeds the global limit', {
|
|
848
|
+
numJobsInTotal,
|
|
849
|
+
globalJobLimit: this.globalJobLimit,
|
|
850
|
+
});
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
for (const [type, queue] of Object.entries(this.jobQueues)) {
|
|
854
|
+
if (
|
|
855
|
+
!this.handlers[type] &&
|
|
856
|
+
JobScheduler.STATES.some(
|
|
857
|
+
(state) => queue[state] && queue[state].length > 0,
|
|
858
|
+
)
|
|
859
|
+
) {
|
|
860
|
+
check.warn(`Found jobs with type=${type} that have no handler`, queue);
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
const jobDesc = this._describeJobs();
|
|
865
|
+
|
|
866
|
+
// all jobs must be well-formed
|
|
867
|
+
const corruptedJobEntries = [];
|
|
868
|
+
for (const jobEntry of jobDesc.queues.all) {
|
|
869
|
+
try {
|
|
870
|
+
this._ensureValidJobEntry(jobEntry);
|
|
871
|
+
} catch (e) {
|
|
872
|
+
corruptedJobEntries.push({ jobEntry, error: `${e}` });
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
if (corruptedJobEntries.length > 0) {
|
|
876
|
+
check.fail('Corrupted job entries found', {
|
|
877
|
+
total: corruptedJobEntries.length,
|
|
878
|
+
samples: corruptedJobEntries.slice(0, 10),
|
|
879
|
+
});
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
// the job's configurations should not include unknown fields
|
|
883
|
+
// (these fields will be ignored, so it is an indicator of a logical bug)
|
|
884
|
+
const expectedKeys = [
|
|
885
|
+
'readyAt',
|
|
886
|
+
'readyIn',
|
|
887
|
+
'expireAt',
|
|
888
|
+
'expireIn',
|
|
889
|
+
...Object.keys(this.defaultConfig),
|
|
890
|
+
];
|
|
891
|
+
const unexpectedConfigs = [];
|
|
892
|
+
for (const { job } of jobDesc.queues.all) {
|
|
893
|
+
const unexpectedKeys = Object.keys(job.config || {}).filter(
|
|
894
|
+
(x) => !expectedKeys.includes(x),
|
|
895
|
+
);
|
|
896
|
+
if (unexpectedKeys.length > 0) {
|
|
897
|
+
unexpectedConfigs.push({ job, unexpectedKeys });
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
if (unexpectedConfigs.length > 0) {
|
|
901
|
+
check.warn('Unexpected keys in the config found', {
|
|
902
|
+
total: unexpectedConfigs.length,
|
|
903
|
+
samples: unexpectedConfigs.slice(0, 10),
|
|
904
|
+
expectedKeys,
|
|
905
|
+
});
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
// TODO: warn if there are jobs that should have run long time ago
|
|
909
|
+
|
|
910
|
+
return check;
|
|
911
|
+
}
|
|
912
|
+
}
|