@orieljs/queue 0.1.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +9 -0
- package/dist/index.d.ts +663 -0
- package/dist/index.js +1977 -0
- package/dist/index.js.map +1 -0
- package/package.json +40 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1977 @@
|
|
|
1
|
+
// errors.ts
|
|
2
|
+
var QueueError = class extends Error {
|
|
3
|
+
kind = "Server";
|
|
4
|
+
status = 500;
|
|
5
|
+
name = "QueueError";
|
|
6
|
+
};
|
|
7
|
+
var JobSerializationError = class extends QueueError {
|
|
8
|
+
name = "JobSerializationError";
|
|
9
|
+
};
|
|
10
|
+
var JobClassNotFoundError = class extends QueueError {
|
|
11
|
+
constructor(className) {
|
|
12
|
+
super(
|
|
13
|
+
`Job class [${className}] is not registered in the ClassRegistry. Register it in a service provider (app.make(ClassRegistry).register(${className})), or put it in app/Jobs so queue:work discovers it.`
|
|
14
|
+
);
|
|
15
|
+
this.className = className;
|
|
16
|
+
}
|
|
17
|
+
className;
|
|
18
|
+
name = "JobClassNotFoundError";
|
|
19
|
+
};
|
|
20
|
+
var MissingModelError = class extends Error {
|
|
21
|
+
constructor(model, ids) {
|
|
22
|
+
super(`No query results for model [${model}] ${ids.join(", ")}`);
|
|
23
|
+
this.model = model;
|
|
24
|
+
this.ids = ids;
|
|
25
|
+
}
|
|
26
|
+
model;
|
|
27
|
+
ids;
|
|
28
|
+
kind = "ModelNotFound";
|
|
29
|
+
status = 404;
|
|
30
|
+
name = "MissingModelError";
|
|
31
|
+
};
|
|
32
|
+
var MaxAttemptsExceededError = class extends QueueError {
|
|
33
|
+
constructor(job) {
|
|
34
|
+
super(`${job} has been attempted too many times.`);
|
|
35
|
+
this.job = job;
|
|
36
|
+
}
|
|
37
|
+
job;
|
|
38
|
+
name = "MaxAttemptsExceededError";
|
|
39
|
+
};
|
|
40
|
+
var TimeoutExceededError = class extends QueueError {
|
|
41
|
+
constructor(job) {
|
|
42
|
+
super(`${job} has timed out.`);
|
|
43
|
+
this.job = job;
|
|
44
|
+
}
|
|
45
|
+
job;
|
|
46
|
+
name = "TimeoutExceededError";
|
|
47
|
+
};
|
|
48
|
+
var ManuallyFailedError = class extends QueueError {
|
|
49
|
+
name = "ManuallyFailedError";
|
|
50
|
+
constructor() {
|
|
51
|
+
super("The job was manually marked as failed.");
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
var UnknownQueueConnectionError = class extends QueueError {
|
|
55
|
+
constructor(connection) {
|
|
56
|
+
super(`The [${connection}] queue connection has not been configured.`);
|
|
57
|
+
this.connection = connection;
|
|
58
|
+
}
|
|
59
|
+
connection;
|
|
60
|
+
name = "UnknownQueueConnectionError";
|
|
61
|
+
};
|
|
62
|
+
var UnknownQueueDriverError = class extends QueueError {
|
|
63
|
+
constructor(driver) {
|
|
64
|
+
super(`No connector for [${driver}].`);
|
|
65
|
+
this.driver = driver;
|
|
66
|
+
}
|
|
67
|
+
driver;
|
|
68
|
+
name = "UnknownQueueDriverError";
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
// symbols.ts
|
|
72
|
+
var QUEUE_JOB = /* @__PURE__ */ Symbol.for("oriel:queue.job");
|
|
73
|
+
var CHAIN = /* @__PURE__ */ Symbol.for("oriel:queue.chain");
|
|
74
|
+
var UNIQUE_LOCK = /* @__PURE__ */ Symbol.for("oriel:queue.uniqueLock");
|
|
75
|
+
var BATCH_CALLBACK = /* @__PURE__ */ Symbol.for("oriel:queue.batchCallback");
|
|
76
|
+
function setSymbolValue(target, key, value) {
|
|
77
|
+
;
|
|
78
|
+
target[key] = value;
|
|
79
|
+
}
|
|
80
|
+
function symbolValue(target, key) {
|
|
81
|
+
return target[key];
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// serialization.ts
|
|
85
|
+
import { Buffer } from "buffer";
|
|
86
|
+
var TAG = "__oriel";
|
|
87
|
+
function isModel(value) {
|
|
88
|
+
if (typeof value !== "object" || value === null) return false;
|
|
89
|
+
const candidate = value;
|
|
90
|
+
return typeof candidate.getKey === "function" && typeof candidate.getKeyName === "function" && typeof candidate.getTable === "function" && typeof candidate.exists === "boolean";
|
|
91
|
+
}
|
|
92
|
+
function classNameOf(registry, cls) {
|
|
93
|
+
const existing = registry.nameOf(cls);
|
|
94
|
+
if (existing !== void 0) return existing;
|
|
95
|
+
try {
|
|
96
|
+
return registry.register(cls);
|
|
97
|
+
} catch (error) {
|
|
98
|
+
const name = cls.name || "AnonymousClass";
|
|
99
|
+
throw new JobSerializationError(
|
|
100
|
+
`Cannot register [${name}] in the ClassRegistry: another class is already registered under that name. Register this one explicitly under a namespaced name, e.g. app.make(ClassRegistry).register(${name}, 'Mail.${name}').`,
|
|
101
|
+
{ cause: error }
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
function resolveClass(registry, name) {
|
|
106
|
+
if (!registry.has(name)) throw new JobClassNotFoundError(name);
|
|
107
|
+
return registry.resolve(name);
|
|
108
|
+
}
|
|
109
|
+
function isPlainObject(value) {
|
|
110
|
+
const proto = Object.getPrototypeOf(value);
|
|
111
|
+
return proto === Object.prototype || proto === null;
|
|
112
|
+
}
|
|
113
|
+
function serializeFields(target, registry, path, seen = /* @__PURE__ */ new Set()) {
|
|
114
|
+
const out = {};
|
|
115
|
+
for (const [key, field] of Object.entries(target)) {
|
|
116
|
+
const encoded = serializeValue(field, registry, `${path}.${key}`, seen);
|
|
117
|
+
if (encoded !== void 0) out[key] = encoded;
|
|
118
|
+
}
|
|
119
|
+
return out;
|
|
120
|
+
}
|
|
121
|
+
function serializeValue(value, registry, path = "data", seen = /* @__PURE__ */ new Set()) {
|
|
122
|
+
switch (typeof value) {
|
|
123
|
+
case "undefined":
|
|
124
|
+
return void 0;
|
|
125
|
+
case "string":
|
|
126
|
+
case "number":
|
|
127
|
+
case "boolean":
|
|
128
|
+
return value;
|
|
129
|
+
case "bigint":
|
|
130
|
+
case "symbol":
|
|
131
|
+
case "function":
|
|
132
|
+
throw new JobSerializationError(`Cannot serialize [${path}]: a ${typeof value} can't be queued. Store plain data instead.`);
|
|
133
|
+
}
|
|
134
|
+
if (value === null) return null;
|
|
135
|
+
const object = value;
|
|
136
|
+
if (seen.has(object)) throw new JobSerializationError(`Cannot serialize [${path}]: it contains a circular reference.`);
|
|
137
|
+
seen.add(object);
|
|
138
|
+
try {
|
|
139
|
+
if (object instanceof Date) return { [TAG]: "date", value: object.toISOString() };
|
|
140
|
+
if (ArrayBuffer.isView(object)) {
|
|
141
|
+
return { [TAG]: "bytes", value: Buffer.from(object.buffer, object.byteOffset, object.byteLength).toString("base64") };
|
|
142
|
+
}
|
|
143
|
+
if (Array.isArray(object)) return object.map((item, i) => serializeValue(item, registry, `${path}[${i}]`, seen) ?? null);
|
|
144
|
+
if (object instanceof Map) {
|
|
145
|
+
return {
|
|
146
|
+
[TAG]: "map",
|
|
147
|
+
entries: [...object.entries()].map(([k, v], i) => [
|
|
148
|
+
serializeValue(k, registry, `${path}<key ${i}>`, seen) ?? null,
|
|
149
|
+
serializeValue(v, registry, `${path}<value ${i}>`, seen) ?? null
|
|
150
|
+
])
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
if (object instanceof Set) {
|
|
154
|
+
return { [TAG]: "set", values: [...object].map((v, i) => serializeValue(v, registry, `${path}<${i}>`, seen) ?? null) };
|
|
155
|
+
}
|
|
156
|
+
if (isModel(object)) {
|
|
157
|
+
const name2 = classNameOf(registry, object.constructor);
|
|
158
|
+
if (!object.exists) {
|
|
159
|
+
throw new JobSerializationError(`Cannot serialize [${path}]: the [${name2}] model hasn't been saved, so it has no key to store.`);
|
|
160
|
+
}
|
|
161
|
+
return { [TAG]: "model", class: name2, key: serializeValue(object.getKey(), registry, `${path}.key`, seen) ?? null };
|
|
162
|
+
}
|
|
163
|
+
if (isPlainObject(object)) {
|
|
164
|
+
const fields = serializeFields(object, registry, path, seen);
|
|
165
|
+
return Object.hasOwn(fields, TAG) ? { [TAG]: "object", value: fields } : fields;
|
|
166
|
+
}
|
|
167
|
+
const name = classNameOf(registry, object.constructor);
|
|
168
|
+
return { [TAG]: "instance", class: name, data: serializeFields(object, registry, path, seen) };
|
|
169
|
+
} finally {
|
|
170
|
+
seen.delete(object);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
async function restoreInstance(prototype, fields, registry) {
|
|
174
|
+
const target = Object.create(prototype);
|
|
175
|
+
for (const [key, value] of Object.entries(await restoreFields(fields, registry))) {
|
|
176
|
+
Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });
|
|
177
|
+
}
|
|
178
|
+
return target;
|
|
179
|
+
}
|
|
180
|
+
async function restoreFields(fields, registry) {
|
|
181
|
+
const out = {};
|
|
182
|
+
for (const [key, field] of Object.entries(fields)) {
|
|
183
|
+
Object.defineProperty(out, key, { value: await restoreValue(field, registry), enumerable: true, writable: true, configurable: true });
|
|
184
|
+
}
|
|
185
|
+
return out;
|
|
186
|
+
}
|
|
187
|
+
async function restoreValue(value, registry) {
|
|
188
|
+
if (value === null || typeof value !== "object") return value;
|
|
189
|
+
if (Array.isArray(value)) {
|
|
190
|
+
const out = [];
|
|
191
|
+
for (const item of value) out.push(await restoreValue(item, registry));
|
|
192
|
+
return out;
|
|
193
|
+
}
|
|
194
|
+
switch (value[TAG]) {
|
|
195
|
+
case void 0:
|
|
196
|
+
return restoreFields(value, registry);
|
|
197
|
+
case "object":
|
|
198
|
+
return restoreFields(value.value, registry);
|
|
199
|
+
case "date":
|
|
200
|
+
return new Date(value.value);
|
|
201
|
+
case "bytes":
|
|
202
|
+
return new Uint8Array(Buffer.from(value.value, "base64"));
|
|
203
|
+
case "map": {
|
|
204
|
+
const map = /* @__PURE__ */ new Map();
|
|
205
|
+
for (const [k, v] of value.entries) map.set(await restoreValue(k, registry), await restoreValue(v, registry));
|
|
206
|
+
return map;
|
|
207
|
+
}
|
|
208
|
+
case "set": {
|
|
209
|
+
const set = /* @__PURE__ */ new Set();
|
|
210
|
+
for (const v of value.values) set.add(await restoreValue(v, registry));
|
|
211
|
+
return set;
|
|
212
|
+
}
|
|
213
|
+
case "model": {
|
|
214
|
+
const name = value.class;
|
|
215
|
+
const model = resolveClass(registry, name);
|
|
216
|
+
const key = await restoreValue(value.key, registry);
|
|
217
|
+
const query = typeof model.withoutGlobalScopes === "function" ? model.withoutGlobalScopes() : model;
|
|
218
|
+
const found = await query.find(key);
|
|
219
|
+
if (found === void 0 || found === null) throw new MissingModelError(name, [key]);
|
|
220
|
+
return found;
|
|
221
|
+
}
|
|
222
|
+
case "instance": {
|
|
223
|
+
const cls = resolveClass(registry, value.class);
|
|
224
|
+
return restoreInstance(cls.prototype, value.data, registry);
|
|
225
|
+
}
|
|
226
|
+
default:
|
|
227
|
+
throw new JobSerializationError(`Unknown encoded value type [${String(value[TAG])}] in a queue payload.`);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// payload.ts
|
|
232
|
+
import { randomUUID } from "crypto";
|
|
233
|
+
function normalizeBackoff(backoff) {
|
|
234
|
+
if (typeof backoff === "number") return [backoff];
|
|
235
|
+
if (typeof backoff === "string" && backoff !== "") return backoff.split(",").map((part) => Number(part.trim()));
|
|
236
|
+
if (Array.isArray(backoff)) return backoff.map(Number);
|
|
237
|
+
return void 0;
|
|
238
|
+
}
|
|
239
|
+
function toUnixMs(value) {
|
|
240
|
+
if (value instanceof Date) return value.getTime();
|
|
241
|
+
if (typeof value === "number") return value;
|
|
242
|
+
return void 0;
|
|
243
|
+
}
|
|
244
|
+
function optionalString(value) {
|
|
245
|
+
return typeof value === "string" ? value : void 0;
|
|
246
|
+
}
|
|
247
|
+
var call = (target, value) => typeof value === "function" ? value.call(target) : value;
|
|
248
|
+
function createPayload(job, registry) {
|
|
249
|
+
const cls = job.constructor;
|
|
250
|
+
if (typeof job !== "object" || job === null || cls === void 0 || cls === Object) {
|
|
251
|
+
throw new JobSerializationError("Only class instances with a handle() method can be queued, not plain objects.");
|
|
252
|
+
}
|
|
253
|
+
const name = classNameOf(registry, cls);
|
|
254
|
+
const options = job;
|
|
255
|
+
const displayName = call(job, options.displayName);
|
|
256
|
+
const payload = {
|
|
257
|
+
uuid: randomUUID(),
|
|
258
|
+
job: name,
|
|
259
|
+
displayName: optionalString(displayName) || name,
|
|
260
|
+
data: serializeFields(job, registry, name),
|
|
261
|
+
attempts: 0,
|
|
262
|
+
pushedAt: Date.now()
|
|
263
|
+
};
|
|
264
|
+
const tries = call(job, options.tries);
|
|
265
|
+
if (typeof tries === "number") payload.maxTries = tries;
|
|
266
|
+
const backoff = normalizeBackoff(call(job, options.backoff));
|
|
267
|
+
if (backoff) payload.backoff = backoff;
|
|
268
|
+
if (typeof options.timeout === "number") payload.timeout = options.timeout;
|
|
269
|
+
const retryUntil = typeof options.retryUntil === "function" ? toUnixMs(call(job, options.retryUntil)) : void 0;
|
|
270
|
+
if (retryUntil !== void 0) payload.retryUntil = retryUntil;
|
|
271
|
+
if (options.failOnTimeout === true) payload.failOnTimeout = true;
|
|
272
|
+
if (options.deleteWhenMissingModels === true || cls.deleteWhenMissingModels === true) {
|
|
273
|
+
payload.deleteWhenMissingModels = true;
|
|
274
|
+
}
|
|
275
|
+
const batchId = optionalString(options.batchId);
|
|
276
|
+
if (batchId !== void 0) payload.batchId = batchId;
|
|
277
|
+
if (symbolValue(job, BATCH_CALLBACK) === true) payload.batchCallback = true;
|
|
278
|
+
const chain = symbolValue(job, CHAIN);
|
|
279
|
+
if (chain && chain.jobs.length > 0) payload.chain = chain.jobs.map((next) => createPayload(next, registry));
|
|
280
|
+
if (chain?.connection !== void 0) payload.chainConnection = chain.connection;
|
|
281
|
+
if (chain?.queue !== void 0) payload.chainQueue = chain.queue;
|
|
282
|
+
if (chain && chain.catch.length > 0) payload.chainCatch = chain.catch.map((callback) => createPayload(callback, registry));
|
|
283
|
+
const uniqueLock = symbolValue(job, UNIQUE_LOCK);
|
|
284
|
+
if (uniqueLock) payload.uniqueLock = uniqueLock;
|
|
285
|
+
return payload;
|
|
286
|
+
}
|
|
287
|
+
async function restoreJob(payload, registry) {
|
|
288
|
+
const cls = resolveClass(registry, payload.job);
|
|
289
|
+
return restoreInstance(cls.prototype, payload.data, registry);
|
|
290
|
+
}
|
|
291
|
+
function encodePayload(payload) {
|
|
292
|
+
const { attempts, ...rest } = payload;
|
|
293
|
+
return JSON.stringify({ attempts, ...rest });
|
|
294
|
+
}
|
|
295
|
+
function decodePayload(raw) {
|
|
296
|
+
let decoded;
|
|
297
|
+
try {
|
|
298
|
+
decoded = JSON.parse(raw);
|
|
299
|
+
} catch {
|
|
300
|
+
throw new JobSerializationError("Invalid queue payload: not JSON.");
|
|
301
|
+
}
|
|
302
|
+
const payload = decoded;
|
|
303
|
+
if (!payload || typeof payload.job !== "string" || typeof payload.uuid !== "string") {
|
|
304
|
+
throw new JobSerializationError('Invalid queue payload: missing "job" or "uuid".');
|
|
305
|
+
}
|
|
306
|
+
return { ...payload, attempts: Number(payload.attempts ?? 0), data: payload.data ?? {} };
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// jobs/BaseJob.ts
|
|
310
|
+
import { FailedJobProvider } from "@orieljs/contracts";
|
|
311
|
+
var BaseJob = class {
|
|
312
|
+
constructor(context, queue) {
|
|
313
|
+
this.context = context;
|
|
314
|
+
this.queue = queue;
|
|
315
|
+
}
|
|
316
|
+
context;
|
|
317
|
+
queue;
|
|
318
|
+
deleted = false;
|
|
319
|
+
released = false;
|
|
320
|
+
failedFlag = false;
|
|
321
|
+
attempts() {
|
|
322
|
+
return this.payload().attempts;
|
|
323
|
+
}
|
|
324
|
+
getQueue() {
|
|
325
|
+
return this.queue;
|
|
326
|
+
}
|
|
327
|
+
getConnectionName() {
|
|
328
|
+
return this.context.connectionName;
|
|
329
|
+
}
|
|
330
|
+
uuid() {
|
|
331
|
+
return this.payload().uuid;
|
|
332
|
+
}
|
|
333
|
+
/** The job's display name (its class name unless it defines displayName()). */
|
|
334
|
+
resolveName() {
|
|
335
|
+
return this.payload().displayName;
|
|
336
|
+
}
|
|
337
|
+
maxTries() {
|
|
338
|
+
return this.payload().maxTries;
|
|
339
|
+
}
|
|
340
|
+
backoff() {
|
|
341
|
+
return this.payload().backoff;
|
|
342
|
+
}
|
|
343
|
+
timeout() {
|
|
344
|
+
return this.payload().timeout;
|
|
345
|
+
}
|
|
346
|
+
retryUntil() {
|
|
347
|
+
return this.payload().retryUntil;
|
|
348
|
+
}
|
|
349
|
+
shouldFailOnTimeout() {
|
|
350
|
+
return this.payload().failOnTimeout === true;
|
|
351
|
+
}
|
|
352
|
+
async delete() {
|
|
353
|
+
this.deleted = true;
|
|
354
|
+
}
|
|
355
|
+
async release(_delaySeconds = 0) {
|
|
356
|
+
this.released = true;
|
|
357
|
+
}
|
|
358
|
+
isDeleted() {
|
|
359
|
+
return this.deleted;
|
|
360
|
+
}
|
|
361
|
+
isReleased() {
|
|
362
|
+
return this.released;
|
|
363
|
+
}
|
|
364
|
+
isDeletedOrReleased() {
|
|
365
|
+
return this.deleted || this.released;
|
|
366
|
+
}
|
|
367
|
+
hasFailed() {
|
|
368
|
+
return this.failedFlag;
|
|
369
|
+
}
|
|
370
|
+
markAsFailed() {
|
|
371
|
+
this.failedFlag = true;
|
|
372
|
+
}
|
|
373
|
+
/** Runs the job through CallQueuedHandler. */
|
|
374
|
+
async fire() {
|
|
375
|
+
await this.context.handler.call(this);
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Marks the job as failed, deletes it, runs the handler's failure bookkeeping (unique lock, batch, chain catch,
|
|
379
|
+
* the job's failed() hook) and stores it with the FailedJobProvider. A job that was already deleted is ignored.
|
|
380
|
+
*/
|
|
381
|
+
async fail(error) {
|
|
382
|
+
this.markAsFailed();
|
|
383
|
+
if (this.deleted) return;
|
|
384
|
+
const reason = error ?? new ManuallyFailedError();
|
|
385
|
+
try {
|
|
386
|
+
await this.delete();
|
|
387
|
+
await this.context.handler.failed(this, reason);
|
|
388
|
+
} finally {
|
|
389
|
+
const { container } = this.context;
|
|
390
|
+
if (container.bound(FailedJobProvider)) {
|
|
391
|
+
await container.make(FailedJobProvider).log(this.getConnectionName(), this.getQueue(), this.payload(), reason);
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
};
|
|
396
|
+
|
|
397
|
+
// jobs/SyncJob.ts
|
|
398
|
+
var SyncJob = class extends BaseJob {
|
|
399
|
+
constructor(context, raw, queue) {
|
|
400
|
+
super(context, queue);
|
|
401
|
+
this.raw = raw;
|
|
402
|
+
}
|
|
403
|
+
raw;
|
|
404
|
+
getJobId() {
|
|
405
|
+
return this.raw.uuid;
|
|
406
|
+
}
|
|
407
|
+
payload() {
|
|
408
|
+
return this.raw;
|
|
409
|
+
}
|
|
410
|
+
attempts() {
|
|
411
|
+
return 1;
|
|
412
|
+
}
|
|
413
|
+
};
|
|
414
|
+
|
|
415
|
+
// CallQueuedHandler.ts
|
|
416
|
+
import {
|
|
417
|
+
BatchRepository,
|
|
418
|
+
BusDispatcher,
|
|
419
|
+
CacheManager,
|
|
420
|
+
ClassRegistry,
|
|
421
|
+
QueueManager
|
|
422
|
+
} from "@orieljs/contracts";
|
|
423
|
+
var CallQueuedHandler = class {
|
|
424
|
+
constructor(container) {
|
|
425
|
+
this.container = container;
|
|
426
|
+
}
|
|
427
|
+
container;
|
|
428
|
+
async call(job) {
|
|
429
|
+
const payload = job.payload();
|
|
430
|
+
let instance;
|
|
431
|
+
try {
|
|
432
|
+
instance = await restoreJob(payload, this.container.make(ClassRegistry));
|
|
433
|
+
} catch (error) {
|
|
434
|
+
if (error instanceof MissingModelError) return this.handleModelNotFound(job, payload, error);
|
|
435
|
+
throw error;
|
|
436
|
+
}
|
|
437
|
+
;
|
|
438
|
+
instance[QUEUE_JOB] = job;
|
|
439
|
+
const untilProcessing = payload.uniqueLock?.untilProcessing === true;
|
|
440
|
+
if (untilProcessing) await this.releaseUniqueLock(payload);
|
|
441
|
+
await this.dispatchThroughMiddleware(instance);
|
|
442
|
+
if (!job.isReleased() && !job.hasFailed() && !untilProcessing) await this.releaseUniqueLock(payload);
|
|
443
|
+
try {
|
|
444
|
+
if (!job.hasFailed() && !job.isReleased()) {
|
|
445
|
+
await this.dispatchNextJobInChain(payload);
|
|
446
|
+
await this.recordSuccessfulBatchJob(payload);
|
|
447
|
+
}
|
|
448
|
+
} catch (error) {
|
|
449
|
+
if (!job.isDeletedOrReleased()) await job.delete();
|
|
450
|
+
throw error;
|
|
451
|
+
}
|
|
452
|
+
if (!job.isDeletedOrReleased()) await job.delete();
|
|
453
|
+
}
|
|
454
|
+
/** Called by BaseJob.fail() after the job was deleted. */
|
|
455
|
+
async failed(job, error) {
|
|
456
|
+
const payload = job.payload();
|
|
457
|
+
let instance;
|
|
458
|
+
try {
|
|
459
|
+
instance = await restoreJob(payload, this.container.make(ClassRegistry));
|
|
460
|
+
} catch {
|
|
461
|
+
instance = void 0;
|
|
462
|
+
}
|
|
463
|
+
if (payload.uniqueLock?.untilProcessing !== true) await this.releaseUniqueLock(payload);
|
|
464
|
+
if (payload.batchId !== void 0 && payload.batchCallback !== true && this.container.bound(BatchRepository)) {
|
|
465
|
+
await this.container.make(BatchRepository).recordFailedJob(payload.batchId, payload.uuid, error);
|
|
466
|
+
}
|
|
467
|
+
for (const callback of payload.chainCatch ?? []) {
|
|
468
|
+
await this.dispatchCallback(await restoreJob(callback, this.container.make(ClassRegistry)));
|
|
469
|
+
}
|
|
470
|
+
if (instance && typeof instance.failed === "function") await instance.failed(error);
|
|
471
|
+
}
|
|
472
|
+
/** Dispatches a callback job (chain catch, batch then/catch/finally) through the Bus, or runs it inline. */
|
|
473
|
+
async dispatchCallback(callback) {
|
|
474
|
+
if (this.container.bound(BusDispatcher)) await this.container.make(BusDispatcher).dispatch(callback);
|
|
475
|
+
else await callback.handle();
|
|
476
|
+
}
|
|
477
|
+
async handleModelNotFound(job, payload, error) {
|
|
478
|
+
if (payload.deleteWhenMissingModels === true) return job.delete();
|
|
479
|
+
return job.fail(error);
|
|
480
|
+
}
|
|
481
|
+
async dispatchThroughMiddleware(instance) {
|
|
482
|
+
const declared = instance.middleware;
|
|
483
|
+
const middleware = (typeof declared === "function" ? declared.call(instance) : declared) ?? [];
|
|
484
|
+
const run = async (index, current) => {
|
|
485
|
+
const layer = middleware[index];
|
|
486
|
+
if (layer === void 0) return current.handle();
|
|
487
|
+
const next = (passed) => run(index + 1, passed ?? current);
|
|
488
|
+
return typeof layer === "function" ? layer(current, next) : layer.handle(current, next);
|
|
489
|
+
};
|
|
490
|
+
await run(0, instance);
|
|
491
|
+
}
|
|
492
|
+
async dispatchNextJobInChain(payload) {
|
|
493
|
+
const [next, ...rest] = payload.chain ?? [];
|
|
494
|
+
if (next === void 0) return;
|
|
495
|
+
const nextPayload = { ...next, attempts: 0, pushedAt: Date.now() };
|
|
496
|
+
if (rest.length > 0) nextPayload.chain = rest;
|
|
497
|
+
else delete nextPayload.chain;
|
|
498
|
+
if (payload.chainConnection !== void 0) nextPayload.chainConnection = payload.chainConnection;
|
|
499
|
+
if (payload.chainQueue !== void 0) nextPayload.chainQueue = payload.chainQueue;
|
|
500
|
+
if (payload.chainCatch !== void 0) nextPayload.chainCatch = payload.chainCatch;
|
|
501
|
+
const connection = optionalString(next.data.connection) || payload.chainConnection || void 0;
|
|
502
|
+
const queue = optionalString(next.data.queue) || payload.chainQueue || void 0;
|
|
503
|
+
const delay = typeof next.data.delay === "number" ? next.data.delay : 0;
|
|
504
|
+
await this.container.make(QueueManager).connection(connection).pushRaw(nextPayload, queue, delay);
|
|
505
|
+
}
|
|
506
|
+
async recordSuccessfulBatchJob(payload) {
|
|
507
|
+
if (payload.batchId === void 0 || payload.batchCallback === true || !this.container.bound(BatchRepository)) return;
|
|
508
|
+
await this.container.make(BatchRepository).recordSuccessfulJob(payload.batchId, payload.uuid);
|
|
509
|
+
}
|
|
510
|
+
async releaseUniqueLock(payload) {
|
|
511
|
+
const lock = payload.uniqueLock;
|
|
512
|
+
if (!lock || !this.container.bound(CacheManager)) return;
|
|
513
|
+
const cache = this.container.make(CacheManager);
|
|
514
|
+
const store = lock.store !== void 0 ? cache.store(lock.store) : cache;
|
|
515
|
+
await store.lock(lock.key).forceRelease();
|
|
516
|
+
}
|
|
517
|
+
};
|
|
518
|
+
|
|
519
|
+
// middleware/WithoutOverlapping.ts
|
|
520
|
+
import { CacheManager as CacheManager2 } from "@orieljs/contracts";
|
|
521
|
+
import { inject } from "@orieljs/container";
|
|
522
|
+
var WithoutOverlapping = class {
|
|
523
|
+
constructor(key = "", releaseAfter = 0, expiresAfter = 0) {
|
|
524
|
+
this.key = key;
|
|
525
|
+
this.releaseAfter = releaseAfter;
|
|
526
|
+
this.expiresAfter = expiresAfter;
|
|
527
|
+
}
|
|
528
|
+
key;
|
|
529
|
+
releaseAfter;
|
|
530
|
+
expiresAfter;
|
|
531
|
+
prefix = "oriel-queue-overlap:";
|
|
532
|
+
shareKey = false;
|
|
533
|
+
releaseAfterSeconds(seconds) {
|
|
534
|
+
this.releaseAfter = seconds;
|
|
535
|
+
return this;
|
|
536
|
+
}
|
|
537
|
+
dontRelease() {
|
|
538
|
+
this.releaseAfter = void 0;
|
|
539
|
+
return this;
|
|
540
|
+
}
|
|
541
|
+
/** Lock expiry in seconds, so a crashed worker can't hold the lock forever. 0 (the default) = no expiry. */
|
|
542
|
+
expireAfter(seconds) {
|
|
543
|
+
this.expiresAfter = seconds;
|
|
544
|
+
return this;
|
|
545
|
+
}
|
|
546
|
+
withPrefix(prefix) {
|
|
547
|
+
this.prefix = prefix;
|
|
548
|
+
return this;
|
|
549
|
+
}
|
|
550
|
+
/** Share the lock across job classes that use the same key. */
|
|
551
|
+
shared() {
|
|
552
|
+
this.shareKey = true;
|
|
553
|
+
return this;
|
|
554
|
+
}
|
|
555
|
+
getLockKey(job) {
|
|
556
|
+
return this.shareKey ? `${this.prefix}${this.key}` : `${this.prefix}${job.constructor.name}:${this.key}`;
|
|
557
|
+
}
|
|
558
|
+
async handle(job, next) {
|
|
559
|
+
const lock = inject(CacheManager2).lock(this.getLockKey(job), this.expiresAfter > 0 ? this.expiresAfter : void 0);
|
|
560
|
+
if (await lock.get()) {
|
|
561
|
+
try {
|
|
562
|
+
return await next(job);
|
|
563
|
+
} finally {
|
|
564
|
+
await lock.release();
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
if (this.releaseAfter !== void 0) await symbolValue(job, QUEUE_JOB)?.release(this.releaseAfter);
|
|
568
|
+
return void 0;
|
|
569
|
+
}
|
|
570
|
+
};
|
|
571
|
+
|
|
572
|
+
// queues/QueueBase.ts
|
|
573
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
574
|
+
import { ClassRegistry as ClassRegistry2, ExceptionHandler, FailedJobProvider as FailedJobProvider2 } from "@orieljs/contracts";
|
|
575
|
+
var QueueBase = class {
|
|
576
|
+
constructor(container, defaultQueue = "default") {
|
|
577
|
+
this.container = container;
|
|
578
|
+
this.defaultQueue = defaultQueue;
|
|
579
|
+
this.handler = new CallQueuedHandler(container);
|
|
580
|
+
}
|
|
581
|
+
container;
|
|
582
|
+
defaultQueue;
|
|
583
|
+
connectionName = "default";
|
|
584
|
+
handler;
|
|
585
|
+
setConnectionName(name) {
|
|
586
|
+
this.connectionName = name;
|
|
587
|
+
return this;
|
|
588
|
+
}
|
|
589
|
+
getConnectionName() {
|
|
590
|
+
return this.connectionName;
|
|
591
|
+
}
|
|
592
|
+
/** The queue name to use: the given one, else the connection's default. */
|
|
593
|
+
getQueue(queue) {
|
|
594
|
+
return optionalString(queue) || this.defaultQueue;
|
|
595
|
+
}
|
|
596
|
+
createPayload(job) {
|
|
597
|
+
return createPayload(job, this.container.make(ClassRegistry2));
|
|
598
|
+
}
|
|
599
|
+
push(job, queue) {
|
|
600
|
+
return this.pushRaw(this.createPayload(job), queue ?? (optionalString(job.queue) || void 0));
|
|
601
|
+
}
|
|
602
|
+
later(delaySeconds, job, queue) {
|
|
603
|
+
return this.pushRaw(this.createPayload(job), queue ?? (optionalString(job.queue) || void 0), delaySeconds);
|
|
604
|
+
}
|
|
605
|
+
/** Closes network connections (redis). No-op by default. */
|
|
606
|
+
async disconnect() {
|
|
607
|
+
}
|
|
608
|
+
/**
|
|
609
|
+
* A row whose payload can't be decoded can never run: record it as failed (with a minimal payload holding the raw
|
|
610
|
+
* text) and report the original error. If the failed-job provider throws, that error propagates so the caller
|
|
611
|
+
* keeps the row (it is retried after retry_after) instead of losing the payload. With no provider bound the row
|
|
612
|
+
* is only reported, like Laravel. A reporter failure never blocks the move.
|
|
613
|
+
*/
|
|
614
|
+
async failCorrupt(queue, raw, error) {
|
|
615
|
+
const payload = { uuid: randomUUID2(), displayName: "CorruptPayload", job: "CorruptPayload", data: { raw } };
|
|
616
|
+
try {
|
|
617
|
+
if (this.container.bound(FailedJobProvider2)) await this.container.make(FailedJobProvider2).log(this.connectionName, queue, payload, error);
|
|
618
|
+
} finally {
|
|
619
|
+
try {
|
|
620
|
+
if (this.container.bound(ExceptionHandler)) await this.container.make(ExceptionHandler).report(error);
|
|
621
|
+
} catch (reportingError) {
|
|
622
|
+
console.error(reportingError);
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
jobContext() {
|
|
627
|
+
return { container: this.container, handler: this.handler, connectionName: this.connectionName };
|
|
628
|
+
}
|
|
629
|
+
/** Unix seconds, like Laravel's availableAt()/currentTime(). */
|
|
630
|
+
currentTime() {
|
|
631
|
+
return Math.floor(Date.now() / 1e3);
|
|
632
|
+
}
|
|
633
|
+
};
|
|
634
|
+
|
|
635
|
+
// queues/SyncQueue.ts
|
|
636
|
+
var SyncQueue = class extends QueueBase {
|
|
637
|
+
async pushRaw(payload, queue) {
|
|
638
|
+
const job = new SyncJob(this.jobContext(), payload, this.getQueue(queue));
|
|
639
|
+
try {
|
|
640
|
+
await job.fire();
|
|
641
|
+
} catch (error) {
|
|
642
|
+
if (!job.hasFailed()) await job.fail(error);
|
|
643
|
+
throw error;
|
|
644
|
+
}
|
|
645
|
+
return payload.uuid;
|
|
646
|
+
}
|
|
647
|
+
async pop() {
|
|
648
|
+
return void 0;
|
|
649
|
+
}
|
|
650
|
+
async size() {
|
|
651
|
+
return 0;
|
|
652
|
+
}
|
|
653
|
+
async clear() {
|
|
654
|
+
return 0;
|
|
655
|
+
}
|
|
656
|
+
};
|
|
657
|
+
|
|
658
|
+
// queues/NullQueue.ts
|
|
659
|
+
var NullQueue = class extends QueueBase {
|
|
660
|
+
async push(_job) {
|
|
661
|
+
return "";
|
|
662
|
+
}
|
|
663
|
+
async later(_delaySeconds, _job) {
|
|
664
|
+
return "";
|
|
665
|
+
}
|
|
666
|
+
async pushRaw() {
|
|
667
|
+
return "";
|
|
668
|
+
}
|
|
669
|
+
async pop() {
|
|
670
|
+
return void 0;
|
|
671
|
+
}
|
|
672
|
+
async size() {
|
|
673
|
+
return 0;
|
|
674
|
+
}
|
|
675
|
+
async clear() {
|
|
676
|
+
return 0;
|
|
677
|
+
}
|
|
678
|
+
};
|
|
679
|
+
|
|
680
|
+
// QueueManager.ts
|
|
681
|
+
import {
|
|
682
|
+
ConfigRepository,
|
|
683
|
+
DatabaseManager
|
|
684
|
+
} from "@orieljs/contracts";
|
|
685
|
+
|
|
686
|
+
// jobs/DatabaseJob.ts
|
|
687
|
+
var DatabaseJob = class extends BaseJob {
|
|
688
|
+
constructor(context, database, record, queue) {
|
|
689
|
+
super(context, queue);
|
|
690
|
+
this.database = database;
|
|
691
|
+
this.record = record;
|
|
692
|
+
this.decoded = { ...decodePayload(record.payload), attempts: Number(record.attempts) };
|
|
693
|
+
}
|
|
694
|
+
database;
|
|
695
|
+
record;
|
|
696
|
+
decoded;
|
|
697
|
+
getJobId() {
|
|
698
|
+
return String(this.record.id);
|
|
699
|
+
}
|
|
700
|
+
payload() {
|
|
701
|
+
return this.decoded;
|
|
702
|
+
}
|
|
703
|
+
attempts() {
|
|
704
|
+
return Number(this.record.attempts);
|
|
705
|
+
}
|
|
706
|
+
getJobRecord() {
|
|
707
|
+
return this.record;
|
|
708
|
+
}
|
|
709
|
+
/** Deletes the reserved row and inserts a fresh one, keeping the attempt count (Laravel's deleteAndRelease). */
|
|
710
|
+
async release(delaySeconds = 0) {
|
|
711
|
+
await super.release(delaySeconds);
|
|
712
|
+
await this.database.deleteAndRelease(this.queue, this, delaySeconds);
|
|
713
|
+
}
|
|
714
|
+
async delete() {
|
|
715
|
+
await super.delete();
|
|
716
|
+
await this.database.deleteReserved(this.getJobId());
|
|
717
|
+
}
|
|
718
|
+
};
|
|
719
|
+
|
|
720
|
+
// queues/DatabaseQueue.ts
|
|
721
|
+
var RESERVE_ATTEMPTS = 3;
|
|
722
|
+
var DatabaseQueue = class extends QueueBase {
|
|
723
|
+
constructor(container, database, options = {}) {
|
|
724
|
+
super(container, options.queue ?? "default");
|
|
725
|
+
this.database = database;
|
|
726
|
+
this.table = options.table ?? "jobs";
|
|
727
|
+
this.retryAfter = options.retryAfter ?? 90;
|
|
728
|
+
}
|
|
729
|
+
database;
|
|
730
|
+
table;
|
|
731
|
+
retryAfter;
|
|
732
|
+
async pushRaw(payload, queue, delaySeconds = 0) {
|
|
733
|
+
return this.pushToDatabase(this.getQueue(queue), payload, delaySeconds, 0);
|
|
734
|
+
}
|
|
735
|
+
async pop(queue) {
|
|
736
|
+
const name = this.getQueue(queue);
|
|
737
|
+
let attempt = 0;
|
|
738
|
+
while (attempt < RESERVE_ATTEMPTS) {
|
|
739
|
+
const outcome = await this.database().transaction(async (db) => {
|
|
740
|
+
const record = await this.getNextAvailableJob(db, name);
|
|
741
|
+
if (!record) return "empty";
|
|
742
|
+
return await this.markJobAsReserved(db, record) ? record : "taken";
|
|
743
|
+
});
|
|
744
|
+
if (outcome === "empty") return void 0;
|
|
745
|
+
if (outcome === "taken") {
|
|
746
|
+
attempt++;
|
|
747
|
+
continue;
|
|
748
|
+
}
|
|
749
|
+
try {
|
|
750
|
+
return new DatabaseJob(this.jobContext(), this, outcome, name);
|
|
751
|
+
} catch (error) {
|
|
752
|
+
await this.failCorrupt(name, outcome.payload, error);
|
|
753
|
+
await this.deleteReserved(String(outcome.id));
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
return void 0;
|
|
757
|
+
}
|
|
758
|
+
async size(queue) {
|
|
759
|
+
return this.database().table(this.table).where("queue", this.getQueue(queue)).count();
|
|
760
|
+
}
|
|
761
|
+
async clear(queue) {
|
|
762
|
+
return this.database().table(this.table).where("queue", this.getQueue(queue)).delete();
|
|
763
|
+
}
|
|
764
|
+
async deleteReserved(id) {
|
|
765
|
+
await this.database().table(this.table).where("id", this.key(id)).delete();
|
|
766
|
+
}
|
|
767
|
+
async deleteAndRelease(queue, job, delaySeconds) {
|
|
768
|
+
await this.database().transaction(async (db) => {
|
|
769
|
+
await db.table(this.table).where("id", this.key(job.getJobId())).delete();
|
|
770
|
+
await this.pushToDatabase(queue, job.payload(), delaySeconds, job.attempts(), db);
|
|
771
|
+
});
|
|
772
|
+
}
|
|
773
|
+
async pushToDatabase(queue, payload, delaySeconds, attempts, db = this.database()) {
|
|
774
|
+
const now = this.currentTime();
|
|
775
|
+
const id = await db.table(this.table).insertGetId({
|
|
776
|
+
queue,
|
|
777
|
+
payload: encodePayload({ ...payload, attempts: 0 }),
|
|
778
|
+
attempts,
|
|
779
|
+
reserved_at: null,
|
|
780
|
+
available_at: now + Math.max(0, Math.round(delaySeconds)),
|
|
781
|
+
created_at: now
|
|
782
|
+
});
|
|
783
|
+
return String(id);
|
|
784
|
+
}
|
|
785
|
+
/** The oldest available row, or the oldest reservation older than retry_after, whichever has the lower id. */
|
|
786
|
+
async getNextAvailableJob(db, queue) {
|
|
787
|
+
const now = this.currentTime();
|
|
788
|
+
const available = await db.table(this.table).where("queue", queue).whereNull("reserved_at").where("available_at", "<=", now).orderBy("id", "asc").lockForUpdate().first();
|
|
789
|
+
const expired = await db.table(this.table).where("queue", queue).whereNotNull("reserved_at").where("reserved_at", "<=", now - this.retryAfter).orderBy("id", "asc").lockForUpdate().first();
|
|
790
|
+
if (!available || !expired) return available ?? expired;
|
|
791
|
+
return Number(available.id) <= Number(expired.id) ? available : expired;
|
|
792
|
+
}
|
|
793
|
+
/** Reserves the row only if nobody else changed it since we read it. */
|
|
794
|
+
async markJobAsReserved(db, record) {
|
|
795
|
+
const now = this.currentTime();
|
|
796
|
+
const query = db.table(this.table).where("id", record.id).where("attempts", record.attempts);
|
|
797
|
+
if (record.reserved_at === null) query.whereNull("reserved_at");
|
|
798
|
+
else query.where("reserved_at", record.reserved_at);
|
|
799
|
+
const affected = await query.update({ reserved_at: now, attempts: Number(record.attempts) + 1 });
|
|
800
|
+
if (affected === 0) return false;
|
|
801
|
+
record.reserved_at = now;
|
|
802
|
+
record.attempts = Number(record.attempts) + 1;
|
|
803
|
+
return true;
|
|
804
|
+
}
|
|
805
|
+
/** Job ids are stored as numbers; getJobId() hands them out as strings. */
|
|
806
|
+
key(id) {
|
|
807
|
+
return /^\d+$/.test(id) ? Number(id) : id;
|
|
808
|
+
}
|
|
809
|
+
};
|
|
810
|
+
|
|
811
|
+
// queues/RedisQueue.ts
|
|
812
|
+
import { Redis } from "ioredis";
|
|
813
|
+
|
|
814
|
+
// jobs/RedisJob.ts
|
|
815
|
+
var RedisJob = class extends BaseJob {
|
|
816
|
+
constructor(context, redis, job, reserved, queue) {
|
|
817
|
+
super(context, queue);
|
|
818
|
+
this.redis = redis;
|
|
819
|
+
this.job = job;
|
|
820
|
+
this.reserved = reserved;
|
|
821
|
+
this.decoded = decodePayload(reserved);
|
|
822
|
+
}
|
|
823
|
+
redis;
|
|
824
|
+
job;
|
|
825
|
+
reserved;
|
|
826
|
+
decoded;
|
|
827
|
+
getJobId() {
|
|
828
|
+
return this.decoded.uuid;
|
|
829
|
+
}
|
|
830
|
+
payload() {
|
|
831
|
+
return this.decoded;
|
|
832
|
+
}
|
|
833
|
+
/** The payload as it was pushed (before the attempt was counted). */
|
|
834
|
+
getRawBody() {
|
|
835
|
+
return this.job;
|
|
836
|
+
}
|
|
837
|
+
getReservedJob() {
|
|
838
|
+
return this.reserved;
|
|
839
|
+
}
|
|
840
|
+
async delete() {
|
|
841
|
+
await super.delete();
|
|
842
|
+
await this.redis.deleteReserved(this.queue, this);
|
|
843
|
+
}
|
|
844
|
+
async release(delaySeconds = 0) {
|
|
845
|
+
await super.release(delaySeconds);
|
|
846
|
+
await this.redis.deleteAndRelease(this.queue, this, delaySeconds);
|
|
847
|
+
}
|
|
848
|
+
};
|
|
849
|
+
|
|
850
|
+
// queues/redisScripts.ts
|
|
851
|
+
var PUSH = `
|
|
852
|
+
redis.call('rpush', KEYS[1], ARGV[1])
|
|
853
|
+
redis.call('rpush', KEYS[2], 1)
|
|
854
|
+
return 1
|
|
855
|
+
`;
|
|
856
|
+
var POP = `
|
|
857
|
+
local job = redis.call('lpop', KEYS[1])
|
|
858
|
+
local reserved = false
|
|
859
|
+
if (job ~= false) then
|
|
860
|
+
local attempts = string.match(job, '^{"attempts":(%d+),')
|
|
861
|
+
if attempts then
|
|
862
|
+
reserved = '{"attempts":' .. (tonumber(attempts) + 1) .. ',' .. string.sub(job, string.len(attempts) + 14)
|
|
863
|
+
else
|
|
864
|
+
reserved = job
|
|
865
|
+
end
|
|
866
|
+
redis.call('zadd', KEYS[2], ARGV[1], reserved)
|
|
867
|
+
redis.call('lpop', KEYS[3])
|
|
868
|
+
end
|
|
869
|
+
return {job, reserved}
|
|
870
|
+
`;
|
|
871
|
+
var RELEASE = `
|
|
872
|
+
redis.call('zrem', KEYS[2], ARGV[1])
|
|
873
|
+
redis.call('zadd', KEYS[1], ARGV[2], ARGV[1])
|
|
874
|
+
return 1
|
|
875
|
+
`;
|
|
876
|
+
var MIGRATE_EXPIRED_JOBS = `
|
|
877
|
+
local val = redis.call('zrangebyscore', KEYS[1], '-inf', ARGV[1])
|
|
878
|
+
if (next(val) ~= nil) then
|
|
879
|
+
redis.call('zremrangebyrank', KEYS[1], 0, #val - 1)
|
|
880
|
+
for i = 1, #val, 100 do
|
|
881
|
+
redis.call('rpush', KEYS[2], unpack(val, i, math.min(i + 99, #val)))
|
|
882
|
+
for j = i, math.min(i + 99, #val) do
|
|
883
|
+
redis.call('rpush', KEYS[3], 1)
|
|
884
|
+
end
|
|
885
|
+
end
|
|
886
|
+
end
|
|
887
|
+
return #val
|
|
888
|
+
`;
|
|
889
|
+
var SIZE = `
|
|
890
|
+
return redis.call('llen', KEYS[1]) + redis.call('zcard', KEYS[2]) + redis.call('zcard', KEYS[3])
|
|
891
|
+
`;
|
|
892
|
+
var CLEAR = `
|
|
893
|
+
local size = redis.call('llen', KEYS[1]) + redis.call('zcard', KEYS[2]) + redis.call('zcard', KEYS[3])
|
|
894
|
+
redis.call('del', KEYS[1], KEYS[2], KEYS[3], KEYS[4])
|
|
895
|
+
return size
|
|
896
|
+
`;
|
|
897
|
+
|
|
898
|
+
// queues/RedisQueue.ts
|
|
899
|
+
var QUEUE_KEYS = ["driver", "connection", "queue", "retry_after", "block_for", "after_commit", "client", "url"];
|
|
900
|
+
function makeRedisClient(config) {
|
|
901
|
+
if (config.client) return config.client;
|
|
902
|
+
const options = Object.fromEntries(
|
|
903
|
+
Object.entries(config).filter(([key, value]) => value !== void 0 && !QUEUE_KEYS.includes(key))
|
|
904
|
+
);
|
|
905
|
+
if (typeof config.url === "string" && config.url !== "") return new Redis(config.url, options);
|
|
906
|
+
return new Redis(options);
|
|
907
|
+
}
|
|
908
|
+
function resolveRedisConfig(config, appConfig) {
|
|
909
|
+
if (config.client !== void 0 || typeof config.url === "string" && config.url !== "") return config;
|
|
910
|
+
const name = typeof config.connection === "string" && config.connection !== "" ? config.connection : "default";
|
|
911
|
+
return appConfig.get(`database.redis.${name}`) ?? config;
|
|
912
|
+
}
|
|
913
|
+
var RedisQueue = class extends QueueBase {
|
|
914
|
+
constructor(container, connect, options = {}) {
|
|
915
|
+
super(container, options.queue ?? "default");
|
|
916
|
+
this.connect = connect;
|
|
917
|
+
this.retryAfter = options.retryAfter ?? 90;
|
|
918
|
+
}
|
|
919
|
+
connect;
|
|
920
|
+
client;
|
|
921
|
+
retryAfter;
|
|
922
|
+
redis() {
|
|
923
|
+
return this.client ??= this.connect();
|
|
924
|
+
}
|
|
925
|
+
/** The list key for a queue name: `queues:<name>`. */
|
|
926
|
+
key(queue) {
|
|
927
|
+
return `queues:${this.getQueue(queue)}`;
|
|
928
|
+
}
|
|
929
|
+
async pushRaw(payload, queue, delaySeconds = 0) {
|
|
930
|
+
const key = this.key(queue);
|
|
931
|
+
const body = encodePayload({ ...payload, attempts: payload.attempts ?? 0 });
|
|
932
|
+
if (delaySeconds > 0) await this.redis().zadd(`${key}:delayed`, this.now() + delaySeconds, body);
|
|
933
|
+
else await this.redis().eval(PUSH, 2, key, `${key}:notify`, body);
|
|
934
|
+
return payload.uuid;
|
|
935
|
+
}
|
|
936
|
+
async pop(queue) {
|
|
937
|
+
const key = this.key(queue);
|
|
938
|
+
const now = this.now();
|
|
939
|
+
await this.redis().eval(MIGRATE_EXPIRED_JOBS, 3, `${key}:delayed`, key, `${key}:notify`, now);
|
|
940
|
+
await this.redis().eval(MIGRATE_EXPIRED_JOBS, 3, `${key}:reserved`, key, `${key}:notify`, now);
|
|
941
|
+
for (; ; ) {
|
|
942
|
+
const [job, reserved] = await this.redis().eval(POP, 3, key, `${key}:reserved`, `${key}:notify`, now + this.retryAfter);
|
|
943
|
+
if (!job || !reserved) return void 0;
|
|
944
|
+
try {
|
|
945
|
+
return new RedisJob(this.jobContext(), this, job, reserved, this.getQueue(queue));
|
|
946
|
+
} catch (error) {
|
|
947
|
+
await this.failCorrupt(this.getQueue(queue), job, error);
|
|
948
|
+
await this.redis().zrem(`${key}:reserved`, reserved);
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
async size(queue) {
|
|
953
|
+
const key = this.key(queue);
|
|
954
|
+
return Number(await this.redis().eval(SIZE, 3, key, `${key}:delayed`, `${key}:reserved`));
|
|
955
|
+
}
|
|
956
|
+
async clear(queue) {
|
|
957
|
+
const key = this.key(queue);
|
|
958
|
+
return Number(await this.redis().eval(CLEAR, 4, key, `${key}:delayed`, `${key}:reserved`, `${key}:notify`));
|
|
959
|
+
}
|
|
960
|
+
async deleteReserved(queue, job) {
|
|
961
|
+
await this.redis().zrem(`${this.key(queue)}:reserved`, job.getReservedJob());
|
|
962
|
+
}
|
|
963
|
+
async deleteAndRelease(queue, job, delaySeconds) {
|
|
964
|
+
const key = this.key(queue);
|
|
965
|
+
await this.redis().eval(RELEASE, 2, `${key}:delayed`, `${key}:reserved`, job.getReservedJob(), this.now() + Math.max(0, delaySeconds));
|
|
966
|
+
}
|
|
967
|
+
async disconnect() {
|
|
968
|
+
const client = this.client;
|
|
969
|
+
this.client = void 0;
|
|
970
|
+
if (client && client.status !== "end") await client.quit();
|
|
971
|
+
}
|
|
972
|
+
/** Unix seconds, with milliseconds as the fraction (sorted-set scores). */
|
|
973
|
+
now() {
|
|
974
|
+
return Date.now() / 1e3;
|
|
975
|
+
}
|
|
976
|
+
};
|
|
977
|
+
|
|
978
|
+
// QueueManager.ts
|
|
979
|
+
var number = (value, fallback) => typeof value === "number" && Number.isFinite(value) ? value : fallback;
|
|
980
|
+
var QueueManager2 = class {
|
|
981
|
+
constructor(container) {
|
|
982
|
+
this.container = container;
|
|
983
|
+
this.drivers.set("sync", (config) => new SyncQueue(container, optionalString(config.queue) || "default"));
|
|
984
|
+
this.drivers.set("null", (config) => new NullQueue(container, optionalString(config.queue) || "default"));
|
|
985
|
+
this.drivers.set(
|
|
986
|
+
"database",
|
|
987
|
+
(config) => new DatabaseQueue(container, () => container.make(DatabaseManager).connection(optionalString(config.connection) || void 0), {
|
|
988
|
+
table: optionalString(config.table) || "jobs",
|
|
989
|
+
queue: optionalString(config.queue) || "default",
|
|
990
|
+
retryAfter: number(config.retry_after, 90)
|
|
991
|
+
})
|
|
992
|
+
);
|
|
993
|
+
this.drivers.set(
|
|
994
|
+
"redis",
|
|
995
|
+
(config) => new RedisQueue(container, () => makeRedisClient(resolveRedisConfig(config, this.config())), {
|
|
996
|
+
queue: optionalString(config.queue) || "default",
|
|
997
|
+
retryAfter: number(config.retry_after, 90)
|
|
998
|
+
})
|
|
999
|
+
);
|
|
1000
|
+
}
|
|
1001
|
+
container;
|
|
1002
|
+
connections = /* @__PURE__ */ new Map();
|
|
1003
|
+
drivers = /* @__PURE__ */ new Map();
|
|
1004
|
+
connection(name) {
|
|
1005
|
+
const connectionName = name ?? this.getDefaultDriver();
|
|
1006
|
+
let queue = this.connections.get(connectionName);
|
|
1007
|
+
if (!queue) {
|
|
1008
|
+
queue = this.resolve(connectionName);
|
|
1009
|
+
this.connections.set(connectionName, queue);
|
|
1010
|
+
}
|
|
1011
|
+
return queue;
|
|
1012
|
+
}
|
|
1013
|
+
/**
|
|
1014
|
+
* Registers a custom driver (`queue.connections.<name>.driver`). The driver's `pop()` must return instances of the
|
|
1015
|
+
* exported `BaseJob` subclasses (or subclasses of `BaseJob`): the Worker relies on their methods.
|
|
1016
|
+
*/
|
|
1017
|
+
extend(driver, factory) {
|
|
1018
|
+
this.drivers.set(driver, factory);
|
|
1019
|
+
}
|
|
1020
|
+
getDefaultDriver() {
|
|
1021
|
+
return optionalString(this.config().get("queue.default")) || "sync";
|
|
1022
|
+
}
|
|
1023
|
+
setDefaultDriver(name) {
|
|
1024
|
+
this.config().set("queue.default", name);
|
|
1025
|
+
}
|
|
1026
|
+
getConnectionConfig(name) {
|
|
1027
|
+
return this.config().get(`queue.connections.${name}`);
|
|
1028
|
+
}
|
|
1029
|
+
/** Whether the connection has been built already. */
|
|
1030
|
+
connected(name) {
|
|
1031
|
+
return this.connections.has(name ?? this.getDefaultDriver());
|
|
1032
|
+
}
|
|
1033
|
+
/** Disconnects and forgets one connection (default: the default one). */
|
|
1034
|
+
async disconnect(name) {
|
|
1035
|
+
const connectionName = name ?? this.getDefaultDriver();
|
|
1036
|
+
const queue = this.connections.get(connectionName);
|
|
1037
|
+
this.connections.delete(connectionName);
|
|
1038
|
+
await queue?.disconnect?.();
|
|
1039
|
+
}
|
|
1040
|
+
/** Disconnects every built connection. */
|
|
1041
|
+
async disconnectAll() {
|
|
1042
|
+
for (const name of [...this.connections.keys()]) await this.disconnect(name);
|
|
1043
|
+
}
|
|
1044
|
+
push(job, queue) {
|
|
1045
|
+
return this.connection().push(job, queue);
|
|
1046
|
+
}
|
|
1047
|
+
later(delaySeconds, job, queue) {
|
|
1048
|
+
return this.connection().later(delaySeconds, job, queue);
|
|
1049
|
+
}
|
|
1050
|
+
pushRaw(payload, queue, delaySeconds) {
|
|
1051
|
+
return this.connection().pushRaw(payload, queue, delaySeconds);
|
|
1052
|
+
}
|
|
1053
|
+
pop(queue) {
|
|
1054
|
+
return this.connection().pop(queue);
|
|
1055
|
+
}
|
|
1056
|
+
size(queue) {
|
|
1057
|
+
return this.connection().size(queue);
|
|
1058
|
+
}
|
|
1059
|
+
clear(queue) {
|
|
1060
|
+
return this.connection().clear(queue);
|
|
1061
|
+
}
|
|
1062
|
+
resolve(name) {
|
|
1063
|
+
const config = this.getConnectionConfig(name);
|
|
1064
|
+
if (!config) throw new UnknownQueueConnectionError(name);
|
|
1065
|
+
const driverName = optionalString(config.driver) || "";
|
|
1066
|
+
const driver = this.drivers.get(driverName);
|
|
1067
|
+
if (!driver) throw new UnknownQueueDriverError(driverName);
|
|
1068
|
+
const queue = driver(config, name);
|
|
1069
|
+
queue.setConnectionName?.(name);
|
|
1070
|
+
return queue;
|
|
1071
|
+
}
|
|
1072
|
+
config() {
|
|
1073
|
+
return this.container.make(ConfigRepository);
|
|
1074
|
+
}
|
|
1075
|
+
};
|
|
1076
|
+
|
|
1077
|
+
// failed/NullFailedJobProvider.ts
|
|
1078
|
+
var NullFailedJobProvider = class {
|
|
1079
|
+
async log() {
|
|
1080
|
+
return "";
|
|
1081
|
+
}
|
|
1082
|
+
async all() {
|
|
1083
|
+
return [];
|
|
1084
|
+
}
|
|
1085
|
+
async find() {
|
|
1086
|
+
return void 0;
|
|
1087
|
+
}
|
|
1088
|
+
async forget() {
|
|
1089
|
+
return false;
|
|
1090
|
+
}
|
|
1091
|
+
async flush() {
|
|
1092
|
+
}
|
|
1093
|
+
};
|
|
1094
|
+
|
|
1095
|
+
// failed/DatabaseFailedJobProvider.ts
|
|
1096
|
+
function formatTimestamp(date) {
|
|
1097
|
+
return date.toISOString().slice(0, 19).replace("T", " ");
|
|
1098
|
+
}
|
|
1099
|
+
function parseTimestamp(value) {
|
|
1100
|
+
if (value instanceof Date) return value;
|
|
1101
|
+
return new Date(/[zZ]|[+-]\d\d:?\d\d$/.test(value) ? value : `${value.replace(" ", "T")}Z`);
|
|
1102
|
+
}
|
|
1103
|
+
function describeError(error) {
|
|
1104
|
+
if (error instanceof Error) return error.stack ?? `${error.name}: ${error.message}`;
|
|
1105
|
+
return String(error);
|
|
1106
|
+
}
|
|
1107
|
+
var DatabaseFailedJobProvider = class {
|
|
1108
|
+
constructor(database, table = "failed_jobs") {
|
|
1109
|
+
this.database = database;
|
|
1110
|
+
this.table = table;
|
|
1111
|
+
}
|
|
1112
|
+
database;
|
|
1113
|
+
table;
|
|
1114
|
+
async log(connection, queue, payload, error) {
|
|
1115
|
+
await this.database().table(this.table).insert({
|
|
1116
|
+
uuid: payload.uuid,
|
|
1117
|
+
connection,
|
|
1118
|
+
queue,
|
|
1119
|
+
payload: encodePayload(payload),
|
|
1120
|
+
exception: describeError(error),
|
|
1121
|
+
failed_at: formatTimestamp(new Date(Date.now()))
|
|
1122
|
+
});
|
|
1123
|
+
return payload.uuid;
|
|
1124
|
+
}
|
|
1125
|
+
async all() {
|
|
1126
|
+
const rows = await this.database().table(this.table).orderBy("id", "desc").get();
|
|
1127
|
+
return rows.all().map((row) => this.toFailedJob(row));
|
|
1128
|
+
}
|
|
1129
|
+
async find(id) {
|
|
1130
|
+
const row = await this.database().table(this.table).where("uuid", id).first();
|
|
1131
|
+
return row ? this.toFailedJob(row) : void 0;
|
|
1132
|
+
}
|
|
1133
|
+
async forget(id) {
|
|
1134
|
+
return await this.database().table(this.table).where("uuid", id).delete() > 0;
|
|
1135
|
+
}
|
|
1136
|
+
async flush() {
|
|
1137
|
+
await this.database().table(this.table).delete();
|
|
1138
|
+
}
|
|
1139
|
+
toFailedJob(row) {
|
|
1140
|
+
return {
|
|
1141
|
+
id: row.uuid,
|
|
1142
|
+
connection: row.connection,
|
|
1143
|
+
queue: row.queue,
|
|
1144
|
+
payload: decodePayload(row.payload),
|
|
1145
|
+
exception: row.exception,
|
|
1146
|
+
failedAt: parseTimestamp(row.failed_at)
|
|
1147
|
+
};
|
|
1148
|
+
}
|
|
1149
|
+
};
|
|
1150
|
+
|
|
1151
|
+
// migrations.ts
|
|
1152
|
+
var JOBS_TABLE_MIGRATION = `import { Migration, Schema } from '@orieljs/framework'
|
|
1153
|
+
|
|
1154
|
+
export default class extends Migration {
|
|
1155
|
+
async up() {
|
|
1156
|
+
await Schema.create('jobs', (t) => {
|
|
1157
|
+
t.id()
|
|
1158
|
+
t.string('queue').index()
|
|
1159
|
+
t.longText('payload')
|
|
1160
|
+
t.unsignedTinyInteger('attempts')
|
|
1161
|
+
t.unsignedInteger('reserved_at').nullable()
|
|
1162
|
+
t.unsignedInteger('available_at')
|
|
1163
|
+
t.unsignedInteger('created_at')
|
|
1164
|
+
})
|
|
1165
|
+
|
|
1166
|
+
await Schema.create('job_batches', (t) => {
|
|
1167
|
+
t.string('id').primary()
|
|
1168
|
+
t.string('name')
|
|
1169
|
+
t.integer('total_jobs')
|
|
1170
|
+
t.integer('pending_jobs')
|
|
1171
|
+
t.integer('failed_jobs')
|
|
1172
|
+
t.longText('failed_job_ids')
|
|
1173
|
+
t.mediumText('options').nullable()
|
|
1174
|
+
t.integer('cancelled_at').nullable()
|
|
1175
|
+
t.integer('created_at')
|
|
1176
|
+
t.integer('finished_at').nullable()
|
|
1177
|
+
})
|
|
1178
|
+
|
|
1179
|
+
await Schema.create('failed_jobs', (t) => {
|
|
1180
|
+
t.id()
|
|
1181
|
+
t.string('uuid').unique()
|
|
1182
|
+
t.text('connection')
|
|
1183
|
+
t.text('queue')
|
|
1184
|
+
t.longText('payload')
|
|
1185
|
+
t.longText('exception')
|
|
1186
|
+
t.timestamp('failed_at').useCurrent()
|
|
1187
|
+
})
|
|
1188
|
+
}
|
|
1189
|
+
|
|
1190
|
+
async down() {
|
|
1191
|
+
await Schema.dropIfExists('jobs')
|
|
1192
|
+
await Schema.dropIfExists('job_batches')
|
|
1193
|
+
await Schema.dropIfExists('failed_jobs')
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
`;
|
|
1197
|
+
|
|
1198
|
+
// batching/Batch.ts
|
|
1199
|
+
var Batch = class {
|
|
1200
|
+
constructor(repository, attributes) {
|
|
1201
|
+
this.repository = repository;
|
|
1202
|
+
this.id = attributes.id;
|
|
1203
|
+
this.name = attributes.name;
|
|
1204
|
+
this.totalJobs = attributes.totalJobs;
|
|
1205
|
+
this.pendingJobs = attributes.pendingJobs;
|
|
1206
|
+
this.failedJobs = attributes.failedJobs;
|
|
1207
|
+
this.failedJobIds = attributes.failedJobIds;
|
|
1208
|
+
this.options = attributes.options;
|
|
1209
|
+
this.createdAt = attributes.createdAt;
|
|
1210
|
+
this.cancelledAt = attributes.cancelledAt;
|
|
1211
|
+
this.finishedAt = attributes.finishedAt;
|
|
1212
|
+
}
|
|
1213
|
+
repository;
|
|
1214
|
+
id;
|
|
1215
|
+
name;
|
|
1216
|
+
totalJobs;
|
|
1217
|
+
pendingJobs;
|
|
1218
|
+
failedJobs;
|
|
1219
|
+
failedJobIds;
|
|
1220
|
+
options;
|
|
1221
|
+
createdAt;
|
|
1222
|
+
cancelledAt;
|
|
1223
|
+
finishedAt;
|
|
1224
|
+
processedJobs() {
|
|
1225
|
+
return this.totalJobs - this.pendingJobs;
|
|
1226
|
+
}
|
|
1227
|
+
/** Percentage of processed jobs, 0–100. */
|
|
1228
|
+
progress() {
|
|
1229
|
+
return this.totalJobs > 0 ? Math.round(this.processedJobs() / this.totalJobs * 100) : 0;
|
|
1230
|
+
}
|
|
1231
|
+
finished() {
|
|
1232
|
+
return this.finishedAt !== void 0;
|
|
1233
|
+
}
|
|
1234
|
+
cancelled() {
|
|
1235
|
+
return this.cancelledAt !== void 0;
|
|
1236
|
+
}
|
|
1237
|
+
hasFailures() {
|
|
1238
|
+
return this.failedJobs > 0;
|
|
1239
|
+
}
|
|
1240
|
+
allowsFailures() {
|
|
1241
|
+
return this.options.allowFailures;
|
|
1242
|
+
}
|
|
1243
|
+
cancel() {
|
|
1244
|
+
return this.repository.cancel(this.id);
|
|
1245
|
+
}
|
|
1246
|
+
delete() {
|
|
1247
|
+
return this.repository.delete(this.id);
|
|
1248
|
+
}
|
|
1249
|
+
fresh() {
|
|
1250
|
+
return this.repository.find(this.id);
|
|
1251
|
+
}
|
|
1252
|
+
toJSON() {
|
|
1253
|
+
return {
|
|
1254
|
+
id: this.id,
|
|
1255
|
+
name: this.name,
|
|
1256
|
+
totalJobs: this.totalJobs,
|
|
1257
|
+
pendingJobs: this.pendingJobs,
|
|
1258
|
+
processedJobs: this.processedJobs(),
|
|
1259
|
+
progress: this.progress(),
|
|
1260
|
+
failedJobs: this.failedJobs,
|
|
1261
|
+
createdAt: this.createdAt,
|
|
1262
|
+
cancelledAt: this.cancelledAt,
|
|
1263
|
+
finishedAt: this.finishedAt
|
|
1264
|
+
};
|
|
1265
|
+
}
|
|
1266
|
+
};
|
|
1267
|
+
|
|
1268
|
+
// batching/DatabaseBatchRepository.ts
|
|
1269
|
+
import { randomUUID as randomUUID3 } from "crypto";
|
|
1270
|
+
import {
|
|
1271
|
+
ClassRegistry as ClassRegistry3
|
|
1272
|
+
} from "@orieljs/contracts";
|
|
1273
|
+
var toDate = (seconds) => seconds === null || seconds === void 0 ? void 0 : new Date(Number(seconds) * 1e3);
|
|
1274
|
+
var DatabaseBatchRepository = class {
|
|
1275
|
+
constructor(container, database, table = "job_batches") {
|
|
1276
|
+
this.container = container;
|
|
1277
|
+
this.database = database;
|
|
1278
|
+
this.table = table;
|
|
1279
|
+
this.handler = new CallQueuedHandler(container);
|
|
1280
|
+
}
|
|
1281
|
+
container;
|
|
1282
|
+
database;
|
|
1283
|
+
table;
|
|
1284
|
+
handler;
|
|
1285
|
+
async store(options) {
|
|
1286
|
+
const id = randomUUID3();
|
|
1287
|
+
const registry = this.container.make(ClassRegistry3);
|
|
1288
|
+
const payloads = (jobs) => jobs.map((job) => createPayload(job, registry));
|
|
1289
|
+
const stored = {
|
|
1290
|
+
allowFailures: options.allowFailures,
|
|
1291
|
+
then: payloads(options.then),
|
|
1292
|
+
catch: payloads(options.catch),
|
|
1293
|
+
finally: payloads(options.finally)
|
|
1294
|
+
};
|
|
1295
|
+
if (options.connection !== void 0) stored.connection = options.connection;
|
|
1296
|
+
if (options.queue !== void 0) stored.queue = options.queue;
|
|
1297
|
+
await this.database().table(this.table).insert({
|
|
1298
|
+
id,
|
|
1299
|
+
name: options.name,
|
|
1300
|
+
total_jobs: 0,
|
|
1301
|
+
pending_jobs: 0,
|
|
1302
|
+
failed_jobs: 0,
|
|
1303
|
+
failed_job_ids: "[]",
|
|
1304
|
+
options: JSON.stringify(stored),
|
|
1305
|
+
created_at: this.now(),
|
|
1306
|
+
cancelled_at: null,
|
|
1307
|
+
finished_at: null
|
|
1308
|
+
});
|
|
1309
|
+
return await this.find(id);
|
|
1310
|
+
}
|
|
1311
|
+
async find(id) {
|
|
1312
|
+
const row = await this.database().table(this.table).where("id", id).first();
|
|
1313
|
+
return row ? this.toBatch(row) : void 0;
|
|
1314
|
+
}
|
|
1315
|
+
async incrementTotalJobs(id, amount) {
|
|
1316
|
+
await this.database().transaction(async (db) => {
|
|
1317
|
+
await db.table(this.table).where("id", id).increment("total_jobs", amount, { finished_at: null });
|
|
1318
|
+
await db.table(this.table).where("id", id).increment("pending_jobs", amount);
|
|
1319
|
+
});
|
|
1320
|
+
}
|
|
1321
|
+
async recordSuccessfulJob(id, jobUuid) {
|
|
1322
|
+
const counts = await this.updateAtomicValues(id, (row, failedIds) => ({
|
|
1323
|
+
pending_jobs: Number(row.pending_jobs) - 1,
|
|
1324
|
+
failed_jobs: Number(row.failed_jobs),
|
|
1325
|
+
failed_job_ids: failedIds.filter((failed) => failed !== jobUuid)
|
|
1326
|
+
}));
|
|
1327
|
+
if (!counts) return;
|
|
1328
|
+
if (counts.pendingJobs === 0) await this.markAsFinished(id);
|
|
1329
|
+
const batch = await this.find(id);
|
|
1330
|
+
if (!batch) return;
|
|
1331
|
+
if (counts.pendingJobs === 0) await this.invoke(batch, batch.options.then);
|
|
1332
|
+
if (counts.pendingJobs - counts.failedJobs === 0) await this.invoke(batch, batch.options.finally);
|
|
1333
|
+
}
|
|
1334
|
+
async recordFailedJob(id, jobUuid, _error) {
|
|
1335
|
+
const counts = await this.updateAtomicValues(id, (row, failedIds) => ({
|
|
1336
|
+
pending_jobs: Number(row.pending_jobs),
|
|
1337
|
+
failed_jobs: Number(row.failed_jobs) + 1,
|
|
1338
|
+
failed_job_ids: [.../* @__PURE__ */ new Set([...failedIds, jobUuid])]
|
|
1339
|
+
}));
|
|
1340
|
+
if (!counts) return;
|
|
1341
|
+
const before = await this.find(id);
|
|
1342
|
+
if (!before) return;
|
|
1343
|
+
if (counts.failedJobs === 1 && !before.allowsFailures()) await this.cancel(id);
|
|
1344
|
+
const batch = await this.find(id);
|
|
1345
|
+
if (counts.failedJobs === 1) await this.invoke(batch, batch.options.catch);
|
|
1346
|
+
if (counts.pendingJobs - counts.failedJobs === 0) await this.invoke(batch, batch.options.finally);
|
|
1347
|
+
}
|
|
1348
|
+
async markAsFinished(id) {
|
|
1349
|
+
await this.database().table(this.table).where("id", id).update({ finished_at: this.now() });
|
|
1350
|
+
}
|
|
1351
|
+
async cancel(id) {
|
|
1352
|
+
const now = this.now();
|
|
1353
|
+
await this.database().table(this.table).where("id", id).update({ cancelled_at: now, finished_at: now });
|
|
1354
|
+
}
|
|
1355
|
+
async delete(id) {
|
|
1356
|
+
await this.database().table(this.table).where("id", id).delete();
|
|
1357
|
+
}
|
|
1358
|
+
/** Read-modify-write of the counters under a row lock (Laravel's updateAtomicValues). */
|
|
1359
|
+
async updateAtomicValues(id, change) {
|
|
1360
|
+
return this.database().transaction(async (db) => {
|
|
1361
|
+
const row = await db.table(this.table).where("id", id).lockForUpdate().first();
|
|
1362
|
+
if (!row) return void 0;
|
|
1363
|
+
const values = change(row, JSON.parse(row.failed_job_ids || "[]"));
|
|
1364
|
+
await db.table(this.table).where("id", id).update({ ...values, failed_job_ids: JSON.stringify(values.failed_job_ids) });
|
|
1365
|
+
return { pendingJobs: values.pending_jobs, failedJobs: values.failed_jobs };
|
|
1366
|
+
});
|
|
1367
|
+
}
|
|
1368
|
+
/** Restores each callback job, gives it the batch id, marks it as a callback (so it isn't counted) and dispatches it. */
|
|
1369
|
+
async invoke(batch, callbacks) {
|
|
1370
|
+
const registry = this.container.make(ClassRegistry3);
|
|
1371
|
+
for (const payload of callbacks) {
|
|
1372
|
+
const job = await restoreJob(payload, registry);
|
|
1373
|
+
job.batchId = batch.id;
|
|
1374
|
+
setSymbolValue(job, BATCH_CALLBACK, true);
|
|
1375
|
+
await this.handler.dispatchCallback(job);
|
|
1376
|
+
}
|
|
1377
|
+
}
|
|
1378
|
+
toBatch(row) {
|
|
1379
|
+
const options = row.options ? JSON.parse(row.options) : {};
|
|
1380
|
+
return new Batch(this, {
|
|
1381
|
+
id: row.id,
|
|
1382
|
+
name: row.name,
|
|
1383
|
+
totalJobs: Number(row.total_jobs),
|
|
1384
|
+
pendingJobs: Number(row.pending_jobs),
|
|
1385
|
+
failedJobs: Number(row.failed_jobs),
|
|
1386
|
+
failedJobIds: JSON.parse(row.failed_job_ids || "[]"),
|
|
1387
|
+
options: { allowFailures: false, then: [], catch: [], finally: [], ...options },
|
|
1388
|
+
createdAt: toDate(row.created_at),
|
|
1389
|
+
cancelledAt: toDate(row.cancelled_at),
|
|
1390
|
+
finishedAt: toDate(row.finished_at)
|
|
1391
|
+
});
|
|
1392
|
+
}
|
|
1393
|
+
now() {
|
|
1394
|
+
return Math.floor(Date.now() / 1e3);
|
|
1395
|
+
}
|
|
1396
|
+
};
|
|
1397
|
+
|
|
1398
|
+
// Worker.ts
|
|
1399
|
+
import { setTimeout as sleep } from "timers/promises";
|
|
1400
|
+
import {
|
|
1401
|
+
BusDispatcher as BusDispatcher2,
|
|
1402
|
+
CacheManager as CacheManager3,
|
|
1403
|
+
ExceptionHandler as ExceptionHandler2
|
|
1404
|
+
} from "@orieljs/contracts";
|
|
1405
|
+
var defaultWorkerOptions = () => ({
|
|
1406
|
+
name: "default",
|
|
1407
|
+
backoff: 0,
|
|
1408
|
+
memory: 128,
|
|
1409
|
+
timeout: 60,
|
|
1410
|
+
sleep: 3,
|
|
1411
|
+
maxTries: 1,
|
|
1412
|
+
stopWhenEmpty: false,
|
|
1413
|
+
maxJobs: 0,
|
|
1414
|
+
maxTime: 0,
|
|
1415
|
+
rest: 0
|
|
1416
|
+
});
|
|
1417
|
+
var RESTART_CACHE_KEY = "oriel:queue:restart";
|
|
1418
|
+
var Worker = class _Worker {
|
|
1419
|
+
constructor(manager, container, listener = {}) {
|
|
1420
|
+
this.manager = manager;
|
|
1421
|
+
this.container = container;
|
|
1422
|
+
this.listener = listener;
|
|
1423
|
+
}
|
|
1424
|
+
manager;
|
|
1425
|
+
container;
|
|
1426
|
+
listener;
|
|
1427
|
+
static EXIT_SUCCESS = 0;
|
|
1428
|
+
static EXIT_ERROR = 1;
|
|
1429
|
+
static EXIT_MEMORY_LIMIT = 12;
|
|
1430
|
+
shouldQuit = false;
|
|
1431
|
+
timedOut = false;
|
|
1432
|
+
sleeping;
|
|
1433
|
+
currentJob;
|
|
1434
|
+
/** F2: the promise handling the most recently leaked unhandled rejection, awaited by process() before it decides
|
|
1435
|
+
* whether the job succeeded, so failing it is never racing the "processed" event. */
|
|
1436
|
+
pendingRejection;
|
|
1437
|
+
/** Runs until a stop condition; returns the exit code. `queue` may be a comma-separated priority list. */
|
|
1438
|
+
async daemon(connectionName, queue, options) {
|
|
1439
|
+
const stopListening = this.listenForSignals();
|
|
1440
|
+
try {
|
|
1441
|
+
const startTime = Date.now();
|
|
1442
|
+
const lastRestart = await this.getTimestampOfLastQueueRestart();
|
|
1443
|
+
let jobsProcessed = 0;
|
|
1444
|
+
for (; ; ) {
|
|
1445
|
+
const job = await this.getNextJob(connectionName, queue);
|
|
1446
|
+
if (job) {
|
|
1447
|
+
jobsProcessed++;
|
|
1448
|
+
await this.runJob(job, connectionName, options);
|
|
1449
|
+
if (options.rest > 0) await this.sleep(options.rest);
|
|
1450
|
+
} else if (!options.stopWhenEmpty) {
|
|
1451
|
+
await this.sleep(options.sleep);
|
|
1452
|
+
}
|
|
1453
|
+
const status = await this.stopIfNecessary(options, lastRestart, startTime, jobsProcessed, job);
|
|
1454
|
+
if (status !== void 0) return status;
|
|
1455
|
+
}
|
|
1456
|
+
} finally {
|
|
1457
|
+
stopListening();
|
|
1458
|
+
}
|
|
1459
|
+
}
|
|
1460
|
+
/**
|
|
1461
|
+
* `--once`: processes the next job, or sleeps when there is none. Laravel's runNextJob doesn't listen for stop
|
|
1462
|
+
* signals, but spec §7 still binds here: the unhandled-rejection guard (F2) is installed for the duration of the
|
|
1463
|
+
* single run, through the same helper listenForSignals() uses, so a leaked rejection fails the job instead of
|
|
1464
|
+
* crashing the process. Returns EXIT_ERROR when the job timed out, EXIT_SUCCESS otherwise.
|
|
1465
|
+
*/
|
|
1466
|
+
async runNextJob(connectionName, queue, options) {
|
|
1467
|
+
const stopGuarding = this.guardUnhandledRejections();
|
|
1468
|
+
try {
|
|
1469
|
+
const job = await this.getNextJob(connectionName, queue);
|
|
1470
|
+
if (job) await this.runJob(job, connectionName, options);
|
|
1471
|
+
else await this.sleep(options.sleep);
|
|
1472
|
+
return this.timedOut ? _Worker.EXIT_ERROR : _Worker.EXIT_SUCCESS;
|
|
1473
|
+
} finally {
|
|
1474
|
+
stopGuarding();
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
/** Stops after the current job (SIGTERM/SIGINT/SIGQUIT call this). */
|
|
1478
|
+
stop() {
|
|
1479
|
+
this.shouldQuit = true;
|
|
1480
|
+
this.sleeping?.abort();
|
|
1481
|
+
}
|
|
1482
|
+
/** Registers graceful-stop signal handlers and the unhandled-rejection guard; returns a function that removes them. */
|
|
1483
|
+
listenForSignals() {
|
|
1484
|
+
const signals = ["SIGTERM", "SIGINT", "SIGQUIT"];
|
|
1485
|
+
const handler = () => this.stop();
|
|
1486
|
+
for (const signal of signals) process.on(signal, handler);
|
|
1487
|
+
const stopGuarding = this.guardUnhandledRejections();
|
|
1488
|
+
return () => {
|
|
1489
|
+
for (const signal of signals) process.off(signal, handler);
|
|
1490
|
+
stopGuarding();
|
|
1491
|
+
};
|
|
1492
|
+
}
|
|
1493
|
+
/** F2: installs the process-wide unhandledRejection guard; returns a function that removes it. */
|
|
1494
|
+
guardUnhandledRejections() {
|
|
1495
|
+
const onUnhandledRejection = (error) => {
|
|
1496
|
+
this.pendingRejection = this.handleUnhandledRejection(error);
|
|
1497
|
+
};
|
|
1498
|
+
process.on("unhandledRejection", onUnhandledRejection);
|
|
1499
|
+
return () => process.off("unhandledRejection", onUnhandledRejection);
|
|
1500
|
+
}
|
|
1501
|
+
/** Processes one job: max-attempts check, fire (with timeout), and failure handling. `_connectionName` is unused (kept for Laravel's signature). */
|
|
1502
|
+
async process(_connectionName, job, options) {
|
|
1503
|
+
const workable = job;
|
|
1504
|
+
const started = Date.now();
|
|
1505
|
+
try {
|
|
1506
|
+
this.listener.processing?.(job);
|
|
1507
|
+
await this.markJobAsFailedIfAlreadyExceedsMaxAttempts(workable, options.maxTries);
|
|
1508
|
+
if (job.isDeleted()) return;
|
|
1509
|
+
await this.fireWithTimeout(workable, options);
|
|
1510
|
+
if (this.pendingRejection) {
|
|
1511
|
+
const pending = this.pendingRejection;
|
|
1512
|
+
this.pendingRejection = void 0;
|
|
1513
|
+
await pending;
|
|
1514
|
+
}
|
|
1515
|
+
if (!workable.hasFailed()) this.listener.processed?.(job, Date.now() - started);
|
|
1516
|
+
} catch (error) {
|
|
1517
|
+
await this.handleJobException(workable, options, error);
|
|
1518
|
+
}
|
|
1519
|
+
}
|
|
1520
|
+
async sleep(seconds) {
|
|
1521
|
+
if (seconds <= 0 || this.shouldQuit) return;
|
|
1522
|
+
this.sleeping = new AbortController();
|
|
1523
|
+
try {
|
|
1524
|
+
await sleep(seconds * 1e3, void 0, { signal: this.sleeping.signal });
|
|
1525
|
+
} catch {
|
|
1526
|
+
} finally {
|
|
1527
|
+
this.sleeping = void 0;
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
/** Runs one job in its own scope. Nothing it throws escapes: an error from the failure handling itself (a failed()
|
|
1531
|
+
* hook, the failed-job provider, a release) is reported like any other, as Laravel's Worker::runJob does. */
|
|
1532
|
+
async runJob(job, connectionName, options) {
|
|
1533
|
+
const scope = this.container.createScope();
|
|
1534
|
+
await scope.run(async () => {
|
|
1535
|
+
this.currentJob = job;
|
|
1536
|
+
try {
|
|
1537
|
+
await this.process(connectionName, job, options);
|
|
1538
|
+
} catch (error) {
|
|
1539
|
+
await this.report(error, job);
|
|
1540
|
+
} finally {
|
|
1541
|
+
this.currentJob = void 0;
|
|
1542
|
+
}
|
|
1543
|
+
try {
|
|
1544
|
+
if (scope.bound(BusDispatcher2)) await scope.make(BusDispatcher2).flushAfterResponse?.();
|
|
1545
|
+
} catch (error) {
|
|
1546
|
+
await this.report(error);
|
|
1547
|
+
}
|
|
1548
|
+
});
|
|
1549
|
+
}
|
|
1550
|
+
async getNextJob(connectionName, queue) {
|
|
1551
|
+
try {
|
|
1552
|
+
const connection = this.manager.connection(connectionName);
|
|
1553
|
+
for (const name of queue.split(",")) {
|
|
1554
|
+
const job = await connection.pop(name.trim());
|
|
1555
|
+
if (job) return job;
|
|
1556
|
+
}
|
|
1557
|
+
} catch (error) {
|
|
1558
|
+
await this.report(error);
|
|
1559
|
+
await this.sleep(1);
|
|
1560
|
+
}
|
|
1561
|
+
return void 0;
|
|
1562
|
+
}
|
|
1563
|
+
async fireWithTimeout(job, options) {
|
|
1564
|
+
const timeout = job.timeout() ?? options.timeout;
|
|
1565
|
+
if (!timeout || timeout <= 0) return job.fire();
|
|
1566
|
+
let timer;
|
|
1567
|
+
const expired = new Promise((_, reject) => {
|
|
1568
|
+
timer = setTimeout(() => reject(new TimeoutExceededError(job.resolveName())), timeout * 1e3);
|
|
1569
|
+
});
|
|
1570
|
+
try {
|
|
1571
|
+
await Promise.race([job.fire(), expired]);
|
|
1572
|
+
} finally {
|
|
1573
|
+
clearTimeout(timer);
|
|
1574
|
+
}
|
|
1575
|
+
}
|
|
1576
|
+
/** Releases or fails the job. The job's error is reported even when handling it throws (runJob reports that too). */
|
|
1577
|
+
async handleJobException(job, options, error) {
|
|
1578
|
+
try {
|
|
1579
|
+
if (error instanceof TimeoutExceededError) {
|
|
1580
|
+
this.timedOut = true;
|
|
1581
|
+
await this.markJobAsFailedIfWillExceedMaxAttempts(job, options.maxTries, error);
|
|
1582
|
+
if (!job.hasFailed() && job.shouldFailOnTimeout()) await this.failJob(job, error);
|
|
1583
|
+
} else {
|
|
1584
|
+
try {
|
|
1585
|
+
if (!job.hasFailed()) await this.markJobAsFailedIfWillExceedMaxAttempts(job, options.maxTries, error);
|
|
1586
|
+
} finally {
|
|
1587
|
+
if (!job.isDeleted() && !job.isReleased() && !job.hasFailed()) await job.release(this.calculateBackoff(job, options));
|
|
1588
|
+
}
|
|
1589
|
+
}
|
|
1590
|
+
} finally {
|
|
1591
|
+
await this.report(error, job);
|
|
1592
|
+
}
|
|
1593
|
+
}
|
|
1594
|
+
async markJobAsFailedIfAlreadyExceedsMaxAttempts(job, maxTries) {
|
|
1595
|
+
const max = job.maxTries() ?? maxTries;
|
|
1596
|
+
const retryUntil = job.retryUntil();
|
|
1597
|
+
if (retryUntil !== void 0 && Date.now() <= retryUntil) return;
|
|
1598
|
+
if (retryUntil === void 0 && (max === 0 || job.attempts() <= max)) return;
|
|
1599
|
+
const error = new MaxAttemptsExceededError(job.resolveName());
|
|
1600
|
+
await this.failJob(job, error);
|
|
1601
|
+
throw error;
|
|
1602
|
+
}
|
|
1603
|
+
async markJobAsFailedIfWillExceedMaxAttempts(job, maxTries, error) {
|
|
1604
|
+
const max = job.maxTries() ?? maxTries;
|
|
1605
|
+
const retryUntil = job.retryUntil();
|
|
1606
|
+
if (retryUntil !== void 0 && retryUntil <= Date.now()) return this.failJob(job, error);
|
|
1607
|
+
if (retryUntil === void 0 && max > 0 && job.attempts() >= max) return this.failJob(job, error);
|
|
1608
|
+
}
|
|
1609
|
+
async failJob(job, error) {
|
|
1610
|
+
if (job.hasFailed()) return;
|
|
1611
|
+
try {
|
|
1612
|
+
await job.fail(error);
|
|
1613
|
+
} finally {
|
|
1614
|
+
this.listener.failed?.(job, error);
|
|
1615
|
+
}
|
|
1616
|
+
}
|
|
1617
|
+
calculateBackoff(job, options) {
|
|
1618
|
+
const backoff = job.backoff() ?? normalizeBackoff(options.backoff) ?? [0];
|
|
1619
|
+
return backoff[job.attempts() - 1] ?? backoff.at(-1) ?? 0;
|
|
1620
|
+
}
|
|
1621
|
+
async stopIfNecessary(options, lastRestart, startTime, jobsProcessed, job) {
|
|
1622
|
+
if (this.shouldQuit) return _Worker.EXIT_SUCCESS;
|
|
1623
|
+
if (this.timedOut) return _Worker.EXIT_ERROR;
|
|
1624
|
+
if (this.memoryExceeded(options.memory)) return _Worker.EXIT_MEMORY_LIMIT;
|
|
1625
|
+
if (await this.queueShouldRestart(lastRestart)) return _Worker.EXIT_SUCCESS;
|
|
1626
|
+
if (options.stopWhenEmpty && !job) return _Worker.EXIT_SUCCESS;
|
|
1627
|
+
if (options.maxTime > 0 && Date.now() - startTime >= options.maxTime * 1e3) return _Worker.EXIT_SUCCESS;
|
|
1628
|
+
if (options.maxJobs > 0 && jobsProcessed >= options.maxJobs) return _Worker.EXIT_SUCCESS;
|
|
1629
|
+
return void 0;
|
|
1630
|
+
}
|
|
1631
|
+
memoryExceeded(limitMb) {
|
|
1632
|
+
return limitMb > 0 && process.memoryUsage().heapUsed / 1024 / 1024 >= limitMb;
|
|
1633
|
+
}
|
|
1634
|
+
async queueShouldRestart(lastRestart) {
|
|
1635
|
+
return await this.getTimestampOfLastQueueRestart() !== lastRestart;
|
|
1636
|
+
}
|
|
1637
|
+
async getTimestampOfLastQueueRestart() {
|
|
1638
|
+
if (!this.container.bound(CacheManager3)) return void 0;
|
|
1639
|
+
return this.container.make(CacheManager3).get(RESTART_CACHE_KEY);
|
|
1640
|
+
}
|
|
1641
|
+
/** Reports through the ExceptionHandler when bound, and tells the listener. Never throws. */
|
|
1642
|
+
async report(error, job) {
|
|
1643
|
+
this.listener.exception?.(error, job);
|
|
1644
|
+
try {
|
|
1645
|
+
if (this.container.bound(ExceptionHandler2)) await this.container.make(ExceptionHandler2).report(error);
|
|
1646
|
+
else if (!this.listener.exception) console.error(error);
|
|
1647
|
+
} catch (reportingError) {
|
|
1648
|
+
console.error(reportingError);
|
|
1649
|
+
}
|
|
1650
|
+
}
|
|
1651
|
+
/**
|
|
1652
|
+
* Spec §7: an unhandled rejection leaked from a job's handle() must not crash the worker. It's reported through
|
|
1653
|
+
* the same path as any other job error, and the job currently running — if there is one, and it hasn't already
|
|
1654
|
+
* failed — is failed with it, exactly as handleJobException fails a job.
|
|
1655
|
+
*/
|
|
1656
|
+
async handleUnhandledRejection(error) {
|
|
1657
|
+
const job = this.currentJob;
|
|
1658
|
+
await this.report(error, job);
|
|
1659
|
+
try {
|
|
1660
|
+
if (job && !job.hasFailed()) await this.failJob(job, error);
|
|
1661
|
+
} catch (failingError) {
|
|
1662
|
+
await this.report(failingError, job);
|
|
1663
|
+
}
|
|
1664
|
+
}
|
|
1665
|
+
};
|
|
1666
|
+
|
|
1667
|
+
// console/discoverJobs.ts
|
|
1668
|
+
import { existsSync, readdirSync, statSync } from "fs";
|
|
1669
|
+
import { join } from "path";
|
|
1670
|
+
import { pathToFileURL } from "url";
|
|
1671
|
+
var EXTENSIONS = [".ts", ".js", ".mts", ".mjs"];
|
|
1672
|
+
function files(directory) {
|
|
1673
|
+
const found = [];
|
|
1674
|
+
for (const entry of readdirSync(directory).sort()) {
|
|
1675
|
+
const path = join(directory, entry);
|
|
1676
|
+
if (statSync(path).isDirectory()) found.push(...files(path));
|
|
1677
|
+
else if (EXTENSIONS.some((extension) => entry.endsWith(extension)) && !entry.endsWith(".d.ts")) found.push(path);
|
|
1678
|
+
}
|
|
1679
|
+
return found;
|
|
1680
|
+
}
|
|
1681
|
+
var WORKER_DISCOVERY_DIRECTORIES = ["Events", "Listeners", "Mail", "Notifications"];
|
|
1682
|
+
var isClass = (value) => typeof value === "function" && /^class[\s{]/.test(Function.prototype.toString.call(value));
|
|
1683
|
+
var isJobClass = (value) => typeof value.prototype.handle === "function";
|
|
1684
|
+
async function discoverClasses(directory, registry, filter = () => true) {
|
|
1685
|
+
if (!existsSync(directory)) return [];
|
|
1686
|
+
const names = [];
|
|
1687
|
+
for (const file of files(directory)) {
|
|
1688
|
+
const module = await import(pathToFileURL(file).href);
|
|
1689
|
+
for (const exported of Object.values(module)) {
|
|
1690
|
+
if (isClass(exported) && filter(exported)) names.push(classNameOf(registry, exported));
|
|
1691
|
+
}
|
|
1692
|
+
}
|
|
1693
|
+
return names;
|
|
1694
|
+
}
|
|
1695
|
+
function discoverJobs(directory, registry) {
|
|
1696
|
+
return discoverClasses(directory, registry, isJobClass);
|
|
1697
|
+
}
|
|
1698
|
+
|
|
1699
|
+
// console/commands.ts
|
|
1700
|
+
import {
|
|
1701
|
+
CacheManager as CacheManager4,
|
|
1702
|
+
ClassRegistry as ClassRegistry4,
|
|
1703
|
+
ConfigRepository as ConfigRepository2,
|
|
1704
|
+
FailedJobProvider as FailedJobProvider3,
|
|
1705
|
+
QueueManager as QueueManager3
|
|
1706
|
+
} from "@orieljs/contracts";
|
|
1707
|
+
import { Str } from "@orieljs/support";
|
|
1708
|
+
var text = (value) => optionalString(value) || void 0;
|
|
1709
|
+
var list = (value) => Array.isArray(value) ? value.map(String) : text(value) ? [String(value)] : [];
|
|
1710
|
+
var number2 = (value, fallback) => {
|
|
1711
|
+
const parsed = Number(value);
|
|
1712
|
+
return value === void 0 || value === null || value === "" || Number.isNaN(parsed) ? fallback : parsed;
|
|
1713
|
+
};
|
|
1714
|
+
var errorClass = (error) => error instanceof Error ? error.constructor.name || error.name : error === null ? "null" : typeof error === "object" ? error.constructor?.name || "object" : typeof error;
|
|
1715
|
+
function localTimestamp(date = /* @__PURE__ */ new Date()) {
|
|
1716
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
1717
|
+
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
|
1718
|
+
}
|
|
1719
|
+
function workerOptionsFrom(option) {
|
|
1720
|
+
const defaults = defaultWorkerOptions();
|
|
1721
|
+
return {
|
|
1722
|
+
name: text(option("name")) ?? defaults.name,
|
|
1723
|
+
backoff: text(option("backoff")) ?? defaults.backoff,
|
|
1724
|
+
memory: number2(option("memory"), defaults.memory),
|
|
1725
|
+
timeout: number2(option("timeout"), defaults.timeout),
|
|
1726
|
+
sleep: number2(option("sleep"), defaults.sleep),
|
|
1727
|
+
maxTries: number2(option("tries"), defaults.maxTries),
|
|
1728
|
+
stopWhenEmpty: option("stop-when-empty") === true,
|
|
1729
|
+
maxJobs: number2(option("max-jobs"), defaults.maxJobs),
|
|
1730
|
+
maxTime: number2(option("max-time"), defaults.maxTime),
|
|
1731
|
+
rest: number2(option("rest"), defaults.rest)
|
|
1732
|
+
};
|
|
1733
|
+
}
|
|
1734
|
+
function registerQueueCommands(kernel, context) {
|
|
1735
|
+
const { container } = context;
|
|
1736
|
+
const define = (signature, description, handler) => kernel.command(signature, async function() {
|
|
1737
|
+
return handler(this);
|
|
1738
|
+
}).purpose(description);
|
|
1739
|
+
const config = () => container.make(ConfigRepository2);
|
|
1740
|
+
const defaultConnection = () => String(config().get("queue.default", "sync"));
|
|
1741
|
+
const defaultQueue = (connection) => String(config().get(`queue.connections.${connection}.queue`, "default"));
|
|
1742
|
+
const failer = () => container.make(FailedJobProvider3);
|
|
1743
|
+
const confirmToProceed = (out) => {
|
|
1744
|
+
if (!context.app.isProduction() || out.option("force") === true) return true;
|
|
1745
|
+
out.error("Application in production. Use --force to run this command.");
|
|
1746
|
+
return false;
|
|
1747
|
+
};
|
|
1748
|
+
define(
|
|
1749
|
+
"queue:work {connection? : The name of the queue connection to work} {--name=default : The name of the worker} {--queue= : The names of the queues to work} {--once : Only process the next job on the queue} {--stop-when-empty : Stop when the queue is empty} {--backoff=0 : Seconds to wait before retrying a job that failed} {--max-jobs=0 : The number of jobs to process before stopping} {--max-time=0 : The maximum number of seconds the worker should run} {--memory=128 : The memory limit in megabytes} {--sleep=3 : Seconds to sleep when no job is available} {--rest=0 : Seconds to rest between jobs} {--timeout=60 : The number of seconds a child process can run} {--tries=1 : Number of times to attempt a job before logging it failed}",
|
|
1750
|
+
"Start processing jobs on the queue as a daemon",
|
|
1751
|
+
async (out) => {
|
|
1752
|
+
const connection = text(out.argument("connection")) ?? defaultConnection();
|
|
1753
|
+
const queue = text(out.option("queue")) ?? defaultQueue(connection);
|
|
1754
|
+
const registry = container.make(ClassRegistry4);
|
|
1755
|
+
await discoverJobs(context.app.appPath("Jobs"), registry);
|
|
1756
|
+
for (const directory of WORKER_DISCOVERY_DIRECTORIES) await discoverClasses(context.app.appPath(directory), registry);
|
|
1757
|
+
const name = (job) => job.payload().displayName;
|
|
1758
|
+
const worker = new Worker(container.make(QueueManager3), container, {
|
|
1759
|
+
processing: (job) => out.line(` ${localTimestamp()} ${name(job)} RUNNING`),
|
|
1760
|
+
processed: (job, ms) => out.line(` ${localTimestamp()} ${name(job)} ${ms}ms DONE`),
|
|
1761
|
+
failed: (job) => out.line(` ${localTimestamp()} ${name(job)} FAIL`),
|
|
1762
|
+
// Only the error's class: its message may carry payload data, and the ExceptionHandler reports it in full.
|
|
1763
|
+
exception: (error, job) => out.error(`${job ? `${name(job)}: ` : ""}${errorClass(error)}`)
|
|
1764
|
+
});
|
|
1765
|
+
const options = workerOptionsFrom((option) => out.option(option));
|
|
1766
|
+
out.info(`Processing jobs from the [${queue}] ${Str.plural("queue", queue.split(",").length)}.`);
|
|
1767
|
+
if (out.option("once") === true) {
|
|
1768
|
+
return worker.runNextJob(connection, queue, options);
|
|
1769
|
+
}
|
|
1770
|
+
return worker.daemon(connection, queue, options);
|
|
1771
|
+
}
|
|
1772
|
+
);
|
|
1773
|
+
define("queue:restart", "Restart queue worker daemons after their current job", async (out) => {
|
|
1774
|
+
if (!container.bound(CacheManager4)) {
|
|
1775
|
+
out.error("queue:restart needs a cache store. Register the CacheServiceProvider.");
|
|
1776
|
+
return 1;
|
|
1777
|
+
}
|
|
1778
|
+
await container.make(CacheManager4).forever(RESTART_CACHE_KEY, Date.now());
|
|
1779
|
+
out.info("Broadcasting queue restart signal.");
|
|
1780
|
+
return 0;
|
|
1781
|
+
});
|
|
1782
|
+
define("queue:failed", "List all of the failed queue jobs", async (out) => {
|
|
1783
|
+
const jobs = await failer().all();
|
|
1784
|
+
if (jobs.length === 0) {
|
|
1785
|
+
out.info("No failed jobs found.");
|
|
1786
|
+
return 0;
|
|
1787
|
+
}
|
|
1788
|
+
for (const job of jobs) {
|
|
1789
|
+
out.line(` ${formatTimestamp(job.failedAt)} ${job.id} ${job.connection}@${job.queue} ${job.payload.displayName}`);
|
|
1790
|
+
}
|
|
1791
|
+
return 0;
|
|
1792
|
+
});
|
|
1793
|
+
define(
|
|
1794
|
+
'queue:retry {id?* : The ID of the failed job or "all" to retry all jobs} {--queue= : Retry all of the failed jobs for the specified queue}',
|
|
1795
|
+
"Retry a failed queue job",
|
|
1796
|
+
async (out) => {
|
|
1797
|
+
const ids = await retryableIds(list(out.argument("id")), text(out.option("queue")));
|
|
1798
|
+
if (ids.length === 0) {
|
|
1799
|
+
out.info("No retryable jobs found.");
|
|
1800
|
+
return 0;
|
|
1801
|
+
}
|
|
1802
|
+
out.info("Pushing failed queue jobs back onto the queue.");
|
|
1803
|
+
let status = 0;
|
|
1804
|
+
for (const id of ids) {
|
|
1805
|
+
const job = await failer().find(id);
|
|
1806
|
+
if (!job) {
|
|
1807
|
+
out.error(`Unable to find failed job with ID [${id}].`);
|
|
1808
|
+
status = 1;
|
|
1809
|
+
continue;
|
|
1810
|
+
}
|
|
1811
|
+
await retryJob(job);
|
|
1812
|
+
out.line(` ${id} DONE`);
|
|
1813
|
+
await failer().forget(id);
|
|
1814
|
+
}
|
|
1815
|
+
return status;
|
|
1816
|
+
}
|
|
1817
|
+
);
|
|
1818
|
+
define("queue:forget {id : The ID of the failed job}", "Delete a failed queue job", async (out) => {
|
|
1819
|
+
if (await failer().forget(String(out.argument("id")))) {
|
|
1820
|
+
out.info("Failed job deleted successfully.");
|
|
1821
|
+
return 0;
|
|
1822
|
+
}
|
|
1823
|
+
out.error("No failed job matches the given ID.");
|
|
1824
|
+
return 1;
|
|
1825
|
+
});
|
|
1826
|
+
define("queue:flush", "Flush all of the failed queue jobs", async (out) => {
|
|
1827
|
+
await failer().flush();
|
|
1828
|
+
out.info("All failed jobs deleted successfully.");
|
|
1829
|
+
return 0;
|
|
1830
|
+
});
|
|
1831
|
+
define(
|
|
1832
|
+
"queue:clear {connection? : The name of the queue connection to clear} {--queue= : The name of the queue to clear} {--force : Force the operation to run when in production}",
|
|
1833
|
+
"Delete all of the jobs from the specified queue",
|
|
1834
|
+
async (out) => {
|
|
1835
|
+
if (!confirmToProceed(out)) return 1;
|
|
1836
|
+
const connection = text(out.argument("connection")) ?? defaultConnection();
|
|
1837
|
+
const queue = text(out.option("queue")) ?? defaultQueue(connection);
|
|
1838
|
+
const count = await container.make(QueueManager3).connection(connection).clear(queue);
|
|
1839
|
+
out.info(`Cleared ${count} ${Str.plural("job", count)} from the [${queue}] queue`);
|
|
1840
|
+
return 0;
|
|
1841
|
+
}
|
|
1842
|
+
);
|
|
1843
|
+
async function retryableIds(ids, queue) {
|
|
1844
|
+
if (ids.length === 1 && ids[0] === "all") return (await failer().all()).map((job) => job.id);
|
|
1845
|
+
if (queue !== void 0) return (await failer().all()).filter((job) => job.queue === queue).map((job) => job.id);
|
|
1846
|
+
return [...new Set(ids)];
|
|
1847
|
+
}
|
|
1848
|
+
async function retryJob(job) {
|
|
1849
|
+
const payload = { ...job.payload, attempts: 0 };
|
|
1850
|
+
if (payload.retryUntil !== void 0) {
|
|
1851
|
+
try {
|
|
1852
|
+
const restored = await restoreJob(payload, container.make(ClassRegistry4));
|
|
1853
|
+
const retryUntil = restored.retryUntil?.();
|
|
1854
|
+
if (retryUntil instanceof Date) payload.retryUntil = retryUntil.getTime();
|
|
1855
|
+
else if (typeof retryUntil === "number") payload.retryUntil = retryUntil;
|
|
1856
|
+
} catch {
|
|
1857
|
+
}
|
|
1858
|
+
}
|
|
1859
|
+
await container.make(QueueManager3).connection(job.connection).pushRaw(payload, job.queue);
|
|
1860
|
+
}
|
|
1861
|
+
}
|
|
1862
|
+
|
|
1863
|
+
// config.ts
|
|
1864
|
+
function queueConfigDefaults() {
|
|
1865
|
+
return {
|
|
1866
|
+
default: "database",
|
|
1867
|
+
connections: {
|
|
1868
|
+
sync: { driver: "sync" },
|
|
1869
|
+
database: { driver: "database", connection: void 0, table: "jobs", queue: "default", retry_after: 90, after_commit: false },
|
|
1870
|
+
redis: { driver: "redis", connection: "default", queue: "default", retry_after: 90, block_for: null, after_commit: false }
|
|
1871
|
+
},
|
|
1872
|
+
batching: { database: void 0, table: "job_batches" },
|
|
1873
|
+
failed: { driver: "database-uuids", database: void 0, table: "failed_jobs" }
|
|
1874
|
+
};
|
|
1875
|
+
}
|
|
1876
|
+
|
|
1877
|
+
// facade.ts
|
|
1878
|
+
import { QueueManager as QueueManager4 } from "@orieljs/contracts";
|
|
1879
|
+
import { facade } from "@orieljs/support";
|
|
1880
|
+
var Queue = facade(QueueManager4);
|
|
1881
|
+
|
|
1882
|
+
// QueueServiceProvider.ts
|
|
1883
|
+
import {
|
|
1884
|
+
BatchRepository as BatchRepository2,
|
|
1885
|
+
ConfigRepository as ConfigRepository3,
|
|
1886
|
+
ConsoleKernel,
|
|
1887
|
+
DatabaseManager as DatabaseManager2,
|
|
1888
|
+
FailedJobProvider as FailedJobProvider4,
|
|
1889
|
+
QueueManager as QueueManagerToken
|
|
1890
|
+
} from "@orieljs/contracts";
|
|
1891
|
+
import { ServiceProvider } from "@orieljs/support";
|
|
1892
|
+
function makeFailedJobProvider(container) {
|
|
1893
|
+
const config = container.make(ConfigRepository3);
|
|
1894
|
+
const driver = String(config.get("queue.failed.driver", "database-uuids"));
|
|
1895
|
+
if (driver === "null") return new NullFailedJobProvider();
|
|
1896
|
+
if (driver !== "database-uuids" && driver !== "database") throw new UnknownQueueDriverError(driver);
|
|
1897
|
+
if (!container.bound(DatabaseManager2)) return new NullFailedJobProvider();
|
|
1898
|
+
const database = optionalString(config.get("queue.failed.database")) || void 0;
|
|
1899
|
+
const table = String(config.get("queue.failed.table", "failed_jobs"));
|
|
1900
|
+
return new DatabaseFailedJobProvider(() => container.make(DatabaseManager2).connection(database), table);
|
|
1901
|
+
}
|
|
1902
|
+
var QueueServiceProvider = class extends ServiceProvider {
|
|
1903
|
+
register() {
|
|
1904
|
+
this.mergeConfigFrom(queueConfigDefaults(), "queue");
|
|
1905
|
+
this.app.singleton(QueueManagerToken, (container) => new QueueManager2(container));
|
|
1906
|
+
this.app.singleton(QueueManager2, (container) => container.make(QueueManagerToken));
|
|
1907
|
+
this.app.singleton(FailedJobProvider4, (container) => makeFailedJobProvider(container));
|
|
1908
|
+
if (this.app.bound(DatabaseManager2)) {
|
|
1909
|
+
this.app.singleton(BatchRepository2, (container) => {
|
|
1910
|
+
const config = container.make(ConfigRepository3);
|
|
1911
|
+
const database = optionalString(config.get("queue.batching.database")) || void 0;
|
|
1912
|
+
const table = String(config.get("queue.batching.table", "job_batches"));
|
|
1913
|
+
return new DatabaseBatchRepository(container, () => container.make(DatabaseManager2).connection(database), table);
|
|
1914
|
+
});
|
|
1915
|
+
}
|
|
1916
|
+
}
|
|
1917
|
+
boot() {
|
|
1918
|
+
if (this.app.bound(ConsoleKernel)) registerQueueCommands(this.app.make(ConsoleKernel), { app: this.app, container: this.app });
|
|
1919
|
+
}
|
|
1920
|
+
};
|
|
1921
|
+
export {
|
|
1922
|
+
BaseJob,
|
|
1923
|
+
Batch,
|
|
1924
|
+
CHAIN,
|
|
1925
|
+
CallQueuedHandler,
|
|
1926
|
+
DatabaseBatchRepository,
|
|
1927
|
+
DatabaseFailedJobProvider,
|
|
1928
|
+
DatabaseJob,
|
|
1929
|
+
DatabaseQueue,
|
|
1930
|
+
JOBS_TABLE_MIGRATION,
|
|
1931
|
+
JobClassNotFoundError,
|
|
1932
|
+
JobSerializationError,
|
|
1933
|
+
ManuallyFailedError,
|
|
1934
|
+
MaxAttemptsExceededError,
|
|
1935
|
+
MissingModelError,
|
|
1936
|
+
NullFailedJobProvider,
|
|
1937
|
+
NullQueue,
|
|
1938
|
+
QUEUE_JOB,
|
|
1939
|
+
Queue,
|
|
1940
|
+
QueueBase,
|
|
1941
|
+
QueueError,
|
|
1942
|
+
QueueManager2 as QueueManager,
|
|
1943
|
+
QueueServiceProvider,
|
|
1944
|
+
RESTART_CACHE_KEY,
|
|
1945
|
+
RedisJob,
|
|
1946
|
+
RedisQueue,
|
|
1947
|
+
SyncJob,
|
|
1948
|
+
SyncQueue,
|
|
1949
|
+
TimeoutExceededError,
|
|
1950
|
+
UNIQUE_LOCK,
|
|
1951
|
+
UnknownQueueConnectionError,
|
|
1952
|
+
UnknownQueueDriverError,
|
|
1953
|
+
WORKER_DISCOVERY_DIRECTORIES,
|
|
1954
|
+
WithoutOverlapping,
|
|
1955
|
+
Worker,
|
|
1956
|
+
classNameOf,
|
|
1957
|
+
createPayload,
|
|
1958
|
+
decodePayload,
|
|
1959
|
+
defaultWorkerOptions,
|
|
1960
|
+
describeError,
|
|
1961
|
+
discoverClasses,
|
|
1962
|
+
discoverJobs,
|
|
1963
|
+
encodePayload,
|
|
1964
|
+
formatTimestamp,
|
|
1965
|
+
isModel,
|
|
1966
|
+
makeFailedJobProvider,
|
|
1967
|
+
makeRedisClient,
|
|
1968
|
+
normalizeBackoff,
|
|
1969
|
+
queueConfigDefaults,
|
|
1970
|
+
registerQueueCommands,
|
|
1971
|
+
resolveRedisConfig,
|
|
1972
|
+
restoreJob,
|
|
1973
|
+
restoreValue,
|
|
1974
|
+
serializeValue,
|
|
1975
|
+
workerOptionsFrom
|
|
1976
|
+
};
|
|
1977
|
+
//# sourceMappingURL=index.js.map
|