@orieljs/queue 0.1.0-alpha.15 → 0.1.0-alpha.16
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/dist/index.d.ts +69 -9
- package/dist/index.js +173 -35
- package/dist/index.js.map +1 -1
- package/package.json +16 -6
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { OrielError, ModelNotFoundError, Job, ClassRegistry, Class, ModelInstance, QueuePayload, Container, QueueJob, Queue as Queue$1, QueueManager as QueueManager$1, DatabaseConnection, FailedJobProvider, FailedJob, ConfigRepository, Batch as Batch$1, BatchRepository, PendingBatchOptions, Application, ConsoleKernel } from '@orieljs/contracts';
|
|
1
|
+
import { OrielError, ModelNotFoundError, Job, ClassRegistry, Class, ModelInstance, QueuePayload, Container, QueueJob, Queue as Queue$1, QueueManager as QueueManager$1, QueueJobEvent, QueueJobFailedEvent, DatabaseConnection, FailedJobProvider, FailedJob, ConfigRepository, Batch as Batch$1, BatchRepository, PendingBatchOptions, Application, ConsoleKernel } from '@orieljs/contracts';
|
|
2
2
|
import { Redis } from 'ioredis';
|
|
3
3
|
import { SpawnOptions, ChildProcess } from 'node:child_process';
|
|
4
4
|
import * as _orieljs_support from '@orieljs/support';
|
|
@@ -196,7 +196,8 @@ declare abstract class BaseJob implements QueueJob {
|
|
|
196
196
|
fire(): Promise<void>;
|
|
197
197
|
/**
|
|
198
198
|
* Marks the job as failed, deletes it, runs the handler's failure bookkeeping (unique lock, batch, chain catch,
|
|
199
|
-
* the job's failed() hook)
|
|
199
|
+
* the job's failed() hook), stores it with the FailedJobProvider and dispatches JobFailed. A job that was already
|
|
200
|
+
* deleted is ignored.
|
|
200
201
|
*/
|
|
201
202
|
fail(error?: unknown): Promise<void>;
|
|
202
203
|
}
|
|
@@ -233,20 +234,65 @@ declare class WithoutOverlapping {
|
|
|
233
234
|
handle(job: Job, next: (job: Job) => Promise<unknown>): Promise<unknown>;
|
|
234
235
|
}
|
|
235
236
|
|
|
237
|
+
/** Laravel's JobQueued: a job was pushed onto a queue (the sync queue runs it instead, and dispatches none). */
|
|
238
|
+
declare class JobQueued {
|
|
239
|
+
readonly connectionName: string;
|
|
240
|
+
readonly queue: string;
|
|
241
|
+
readonly id: string;
|
|
242
|
+
readonly job: Job;
|
|
243
|
+
readonly payload: QueuePayload;
|
|
244
|
+
readonly delay: number | undefined;
|
|
245
|
+
constructor(connectionName: string, queue: string, id: string, job: Job, payload: QueuePayload, delay: number | undefined);
|
|
246
|
+
}
|
|
247
|
+
/** Laravel's JobProcessing: a worker (or the sync queue) is about to run a job. */
|
|
248
|
+
declare class JobProcessing {
|
|
249
|
+
readonly connectionName: string;
|
|
250
|
+
readonly job: QueueJob;
|
|
251
|
+
constructor(connectionName: string, job: QueueJob);
|
|
252
|
+
}
|
|
253
|
+
/** Laravel's JobProcessed: a job ran without throwing. */
|
|
254
|
+
declare class JobProcessed {
|
|
255
|
+
readonly connectionName: string;
|
|
256
|
+
readonly job: QueueJob;
|
|
257
|
+
constructor(connectionName: string, job: QueueJob);
|
|
258
|
+
}
|
|
259
|
+
/** Laravel's JobFailed: a job failed for good, with no attempts left (or was failed on purpose). */
|
|
260
|
+
declare class JobFailed {
|
|
261
|
+
readonly connectionName: string;
|
|
262
|
+
readonly job: QueueJob;
|
|
263
|
+
readonly exception: unknown;
|
|
264
|
+
constructor(connectionName: string, job: QueueJob, exception: unknown);
|
|
265
|
+
}
|
|
266
|
+
|
|
236
267
|
/** Shared driver behaviour (Laravel's Illuminate\Queue\Queue): payload creation, queue names, the job context. */
|
|
237
268
|
declare abstract class QueueBase implements Queue$1 {
|
|
238
269
|
protected readonly container: Container;
|
|
239
270
|
protected readonly defaultQueue: string;
|
|
240
271
|
protected connectionName: string;
|
|
272
|
+
/** `queue.connections.<name>.after_commit`: work dispatched inside a transaction waits for its commit. */
|
|
273
|
+
protected dispatchAfterCommit: boolean;
|
|
241
274
|
protected readonly handler: CallQueuedHandler;
|
|
242
275
|
constructor(container: Container, defaultQueue?: string);
|
|
243
276
|
setConnectionName(name: string): this;
|
|
244
277
|
getConnectionName(): string;
|
|
278
|
+
setDispatchAfterCommit(value: boolean): this;
|
|
245
279
|
/** The queue name to use: the given one, else the connection's default. */
|
|
246
280
|
getQueue(queue?: string): string;
|
|
247
281
|
createPayload(job: Job): QueueJobPayload;
|
|
248
282
|
push(job: Job, queue?: string): Promise<string>;
|
|
249
283
|
later(delaySeconds: number, job: Job, queue?: string): Promise<string>;
|
|
284
|
+
/** Waits for the push, then dispatches JobQueued with its id. */
|
|
285
|
+
private pushed;
|
|
286
|
+
/** Laravel's raiseJobQueuedEvent(). */
|
|
287
|
+
protected raiseJobQueued(queue: string, id: string, job: Job, payload: QueuePayload, delay: number | undefined): Promise<void>;
|
|
288
|
+
/** The job's own `afterCommit`, else the connection's `after_commit`. */
|
|
289
|
+
protected shouldDispatchAfterCommit(job: Job): boolean;
|
|
290
|
+
/**
|
|
291
|
+
* Laravel's enqueueUsing(): pushes now, or, for a job that waits for the commit, once the database transaction open
|
|
292
|
+
* here commits (resolving '' meanwhile). The payload is made first, so a job that can't be queued fails at dispatch.
|
|
293
|
+
* A rollback drops the push and frees a unique job's lock, as does a push that fails after the commit.
|
|
294
|
+
*/
|
|
295
|
+
protected enqueue(job: Job, push: () => Promise<string>): Promise<string>;
|
|
250
296
|
abstract pushRaw(payload: QueuePayload, queue?: string, delaySeconds?: number): Promise<string>;
|
|
251
297
|
abstract pop(queue?: string): Promise<QueueJob | undefined>;
|
|
252
298
|
abstract size(queue?: string): Promise<number>;
|
|
@@ -268,9 +314,12 @@ declare abstract class QueueBase implements Queue$1 {
|
|
|
268
314
|
/**
|
|
269
315
|
* Runs jobs immediately, in the dispatching process (delays are ignored). The payload is still built and the job
|
|
270
316
|
* restored from it, so sync behaves like a real worker. A failure is stored with the FailedJobProvider and rethrown.
|
|
317
|
+
* As Laravel 11's, it dispatches JobProcessing, JobProcessed and JobFailed, and no JobQueued.
|
|
271
318
|
*/
|
|
272
319
|
declare class SyncQueue extends QueueBase {
|
|
273
320
|
pushRaw(payload: QueuePayload, queue?: string): Promise<string>;
|
|
321
|
+
/** The job has run already: nothing was queued. */
|
|
322
|
+
protected raiseJobQueued(_queue: string, _id: string, _job: Job, _payload: QueuePayload, _delay: number | undefined): Promise<void>;
|
|
274
323
|
pop(): Promise<QueueJob | undefined>;
|
|
275
324
|
size(): Promise<number>;
|
|
276
325
|
clear(): Promise<number>;
|
|
@@ -299,6 +348,9 @@ declare class QueueManager implements QueueManager$1 {
|
|
|
299
348
|
* exported `BaseJob` subclasses (or subclasses of `BaseJob`): the Worker relies on their methods.
|
|
300
349
|
*/
|
|
301
350
|
extend(driver: string, factory: (config: ConnectionConfig) => Queue$1): void;
|
|
351
|
+
before(callback: (event: QueueJobEvent) => unknown): void;
|
|
352
|
+
after(callback: (event: QueueJobEvent) => unknown): void;
|
|
353
|
+
failing(callback: (event: QueueJobFailedEvent) => unknown): void;
|
|
302
354
|
getDefaultDriver(): string;
|
|
303
355
|
setDefaultDriver(name: string): void;
|
|
304
356
|
getConnectionConfig(name: string): ConnectionConfig | undefined;
|
|
@@ -436,8 +488,12 @@ interface RedisConnectionConfig {
|
|
|
436
488
|
url?: string;
|
|
437
489
|
[option: string]: unknown;
|
|
438
490
|
}
|
|
439
|
-
/**
|
|
440
|
-
|
|
491
|
+
/**
|
|
492
|
+
* An ioredis client. With a URL, the other options (such as `db`) apply where the URL doesn't set them. ioredis is an
|
|
493
|
+
* optional package, imported here, when the connection is first used: without it, this throws MissingPackageError.
|
|
494
|
+
* A prebuilt client imports nothing.
|
|
495
|
+
*/
|
|
496
|
+
declare function makeRedisClient(config: RedisConnectionConfig): Promise<Redis>;
|
|
441
497
|
/**
|
|
442
498
|
* The client config for a redis queue connection. An inline `client` or `url` wins; otherwise, as in Laravel, the
|
|
443
499
|
* `database.redis.<connection ?? 'default'>` entry (merged by Database). The connection's own inline ioredis
|
|
@@ -449,8 +505,9 @@ declare class RedisQueue extends QueueBase {
|
|
|
449
505
|
private readonly connect;
|
|
450
506
|
private client;
|
|
451
507
|
private readonly retryAfter;
|
|
452
|
-
|
|
453
|
-
|
|
508
|
+
/** `connect` gives the client (or a promise of it), at the queue's first command. */
|
|
509
|
+
constructor(container: Container, connect: () => Redis | Promise<Redis>, options?: RedisQueueOptions);
|
|
510
|
+
redis(): Promise<Redis>;
|
|
454
511
|
/** The list key for a queue name: `queues:<name>`. */
|
|
455
512
|
key(queue?: string): string;
|
|
456
513
|
pushRaw(payload: QueuePayload, queue?: string, delaySeconds?: number): Promise<string>;
|
|
@@ -610,8 +667,11 @@ declare class Worker {
|
|
|
610
667
|
listenForSignals(): () => void;
|
|
611
668
|
/** F2: installs the process-wide unhandledRejection guard; returns a function that removes it. */
|
|
612
669
|
private guardUnhandledRejections;
|
|
613
|
-
/**
|
|
614
|
-
|
|
670
|
+
/**
|
|
671
|
+
* Processes one job: max-attempts check, fire (with timeout), and failure handling. Dispatches JobProcessing first
|
|
672
|
+
* and JobProcessed once the job has run without failing (BaseJob.fail() dispatches JobFailed).
|
|
673
|
+
*/
|
|
674
|
+
process(connectionName: string, job: QueueJob, options: WorkerOptions): Promise<void>;
|
|
615
675
|
sleep(seconds: number): Promise<void>;
|
|
616
676
|
/** Runs one job in its own scope. Nothing it throws escapes: an error from the failure handling itself (a failed()
|
|
617
677
|
* hook, the failed-job provider, a release) is reported like any other, as Laravel's Worker::runJob does. */
|
|
@@ -760,4 +820,4 @@ declare class QueueServiceProvider extends ServiceProvider {
|
|
|
760
820
|
boot(): void;
|
|
761
821
|
}
|
|
762
822
|
|
|
763
|
-
export { BaseJob, Batch, type BatchAttributes, CHAIN, CallQueuedHandler, type ChainSpec, type ConnectionConfig, DatabaseBatchRepository, DatabaseFailedJobProvider, DatabaseJob, type DatabaseJobRecord, DatabaseQueue, type DatabaseQueueOptions, type Encoded, JOBS_TABLE_MIGRATION, JobClassNotFoundError, type JobContext, type JobMiddleware, JobSerializationError, Listener, type ListenerConfig, type ListenerOptions, type ListenerOutput, ManuallyFailedError, MaxAttemptsExceededError, MissingModelError, NullFailedJobProvider, NullQueue, QUEUE_JOB, Queue, QueueBase, type QueueCommandContext, QueueError, type QueueJobPayload, QueueManager, QueueServiceProvider, RESTART_CACHE_KEY, type RedisConnectionConfig, RedisJob, RedisQueue, type RedisQueueOptions, type SpawnWorker, type StoredBatchOptions, SyncJob, SyncQueue, TimeoutExceededError, UNIQUE_LOCK, type UniqueLockSpec, UnknownQueueConnectionError, UnknownQueueDriverError, WORKER_DISCOVERY_DIRECTORIES, WithoutOverlapping, Worker, type WorkerListener, type WorkerOptions, classNameOf, createPayload, decodePayload, defaultListenerOptions, defaultWorkerOptions, describeError, discoverClasses, discoverJobs, encodePayload, ensureAppClasses, formatTimestamp, isModel, listenerOptionsFrom, makeFailedJobProvider, makeRedisClient, normalizeBackoff, queueConfigDefaults, registerAppClasses, registerQueueCommands, resolveRedisConfig, restoreJob, restoreValue, serializeValue, workerOptionsFrom };
|
|
823
|
+
export { BaseJob, Batch, type BatchAttributes, CHAIN, CallQueuedHandler, type ChainSpec, type ConnectionConfig, DatabaseBatchRepository, DatabaseFailedJobProvider, DatabaseJob, type DatabaseJobRecord, DatabaseQueue, type DatabaseQueueOptions, type Encoded, JOBS_TABLE_MIGRATION, JobClassNotFoundError, type JobContext, JobFailed, type JobMiddleware, JobProcessed, JobProcessing, JobQueued, JobSerializationError, Listener, type ListenerConfig, type ListenerOptions, type ListenerOutput, ManuallyFailedError, MaxAttemptsExceededError, MissingModelError, NullFailedJobProvider, NullQueue, QUEUE_JOB, Queue, QueueBase, type QueueCommandContext, QueueError, type QueueJobPayload, QueueManager, QueueServiceProvider, RESTART_CACHE_KEY, type RedisConnectionConfig, RedisJob, RedisQueue, type RedisQueueOptions, type SpawnWorker, type StoredBatchOptions, SyncJob, SyncQueue, TimeoutExceededError, UNIQUE_LOCK, type UniqueLockSpec, UnknownQueueConnectionError, UnknownQueueDriverError, WORKER_DISCOVERY_DIRECTORIES, WithoutOverlapping, Worker, type WorkerListener, type WorkerOptions, classNameOf, createPayload, decodePayload, defaultListenerOptions, defaultWorkerOptions, describeError, discoverClasses, discoverJobs, encodePayload, ensureAppClasses, formatTimestamp, isModel, listenerOptionsFrom, makeFailedJobProvider, makeRedisClient, normalizeBackoff, queueConfigDefaults, registerAppClasses, registerQueueCommands, resolveRedisConfig, restoreJob, restoreValue, serializeValue, workerOptionsFrom };
|
package/dist/index.js
CHANGED
|
@@ -348,6 +348,56 @@ function decodePayload(raw) {
|
|
|
348
348
|
|
|
349
349
|
// jobs/BaseJob.ts
|
|
350
350
|
import { FailedJobProvider } from "@orieljs/contracts";
|
|
351
|
+
|
|
352
|
+
// events.ts
|
|
353
|
+
import { EventDispatcher } from "@orieljs/contracts";
|
|
354
|
+
var JobQueued = class {
|
|
355
|
+
constructor(connectionName, queue, id, job, payload, delay) {
|
|
356
|
+
this.connectionName = connectionName;
|
|
357
|
+
this.queue = queue;
|
|
358
|
+
this.id = id;
|
|
359
|
+
this.job = job;
|
|
360
|
+
this.payload = payload;
|
|
361
|
+
this.delay = delay;
|
|
362
|
+
}
|
|
363
|
+
connectionName;
|
|
364
|
+
queue;
|
|
365
|
+
id;
|
|
366
|
+
job;
|
|
367
|
+
payload;
|
|
368
|
+
delay;
|
|
369
|
+
};
|
|
370
|
+
var JobProcessing = class {
|
|
371
|
+
constructor(connectionName, job) {
|
|
372
|
+
this.connectionName = connectionName;
|
|
373
|
+
this.job = job;
|
|
374
|
+
}
|
|
375
|
+
connectionName;
|
|
376
|
+
job;
|
|
377
|
+
};
|
|
378
|
+
var JobProcessed = class {
|
|
379
|
+
constructor(connectionName, job) {
|
|
380
|
+
this.connectionName = connectionName;
|
|
381
|
+
this.job = job;
|
|
382
|
+
}
|
|
383
|
+
connectionName;
|
|
384
|
+
job;
|
|
385
|
+
};
|
|
386
|
+
var JobFailed = class {
|
|
387
|
+
constructor(connectionName, job, exception) {
|
|
388
|
+
this.connectionName = connectionName;
|
|
389
|
+
this.job = job;
|
|
390
|
+
this.exception = exception;
|
|
391
|
+
}
|
|
392
|
+
connectionName;
|
|
393
|
+
job;
|
|
394
|
+
exception;
|
|
395
|
+
};
|
|
396
|
+
async function dispatchQueueEvent(container, event) {
|
|
397
|
+
if (container.bound(EventDispatcher)) await container.make(EventDispatcher).dispatch(event);
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
// jobs/BaseJob.ts
|
|
351
401
|
var BaseJob = class {
|
|
352
402
|
constructor(context, queue) {
|
|
353
403
|
this.context = context;
|
|
@@ -416,7 +466,8 @@ var BaseJob = class {
|
|
|
416
466
|
}
|
|
417
467
|
/**
|
|
418
468
|
* Marks the job as failed, deletes it, runs the handler's failure bookkeeping (unique lock, batch, chain catch,
|
|
419
|
-
* the job's failed() hook)
|
|
469
|
+
* the job's failed() hook), stores it with the FailedJobProvider and dispatches JobFailed. A job that was already
|
|
470
|
+
* deleted is ignored.
|
|
420
471
|
*/
|
|
421
472
|
async fail(error) {
|
|
422
473
|
this.markAsFailed();
|
|
@@ -427,8 +478,12 @@ var BaseJob = class {
|
|
|
427
478
|
await this.context.handler.failed(this, reason);
|
|
428
479
|
} finally {
|
|
429
480
|
const { container } = this.context;
|
|
430
|
-
|
|
431
|
-
|
|
481
|
+
try {
|
|
482
|
+
if (container.bound(FailedJobProvider)) {
|
|
483
|
+
await container.make(FailedJobProvider).log(this.getConnectionName(), this.getQueue(), this.payload(), reason);
|
|
484
|
+
}
|
|
485
|
+
} finally {
|
|
486
|
+
await dispatchQueueEvent(container, new JobFailed(this.getConnectionName(), this, reason));
|
|
432
487
|
}
|
|
433
488
|
}
|
|
434
489
|
}
|
|
@@ -554,13 +609,15 @@ var CallQueuedHandler = class {
|
|
|
554
609
|
await this.container.make(BatchRepository).recordSuccessfulJob(payload.batchId, payload.uuid);
|
|
555
610
|
}
|
|
556
611
|
async releaseUniqueLock(payload) {
|
|
557
|
-
|
|
558
|
-
if (!lock || !this.container.bound(CacheManager)) return;
|
|
559
|
-
const cache = this.container.make(CacheManager);
|
|
560
|
-
const store = lock.store !== void 0 ? cache.store(lock.store) : cache;
|
|
561
|
-
await store.lock(lock.key).forceRelease();
|
|
612
|
+
await releaseUniqueLock(this.container, payload.uniqueLock);
|
|
562
613
|
}
|
|
563
614
|
};
|
|
615
|
+
async function releaseUniqueLock(container, lock) {
|
|
616
|
+
if (!lock || !container.bound(CacheManager)) return;
|
|
617
|
+
const cache = container.make(CacheManager);
|
|
618
|
+
const store = lock.store !== void 0 ? cache.store(lock.store) : cache;
|
|
619
|
+
await store.lock(lock.key).forceRelease();
|
|
620
|
+
}
|
|
564
621
|
|
|
565
622
|
// middleware/WithoutOverlapping.ts
|
|
566
623
|
import { CacheManager as CacheManager2 } from "@orieljs/contracts";
|
|
@@ -617,7 +674,12 @@ var WithoutOverlapping = class {
|
|
|
617
674
|
|
|
618
675
|
// queues/QueueBase.ts
|
|
619
676
|
import { randomUUID as randomUUID2 } from "crypto";
|
|
620
|
-
import {
|
|
677
|
+
import {
|
|
678
|
+
ClassRegistry as ClassRegistry2,
|
|
679
|
+
DatabaseManager,
|
|
680
|
+
ExceptionHandler,
|
|
681
|
+
FailedJobProvider as FailedJobProvider2
|
|
682
|
+
} from "@orieljs/contracts";
|
|
621
683
|
|
|
622
684
|
// console/discoverJobs.ts
|
|
623
685
|
import { existsSync, readdirSync, statSync } from "fs";
|
|
@@ -719,6 +781,8 @@ var QueueBase = class {
|
|
|
719
781
|
container;
|
|
720
782
|
defaultQueue;
|
|
721
783
|
connectionName = "default";
|
|
784
|
+
/** `queue.connections.<name>.after_commit`: work dispatched inside a transaction waits for its commit. */
|
|
785
|
+
dispatchAfterCommit = false;
|
|
722
786
|
handler;
|
|
723
787
|
setConnectionName(name) {
|
|
724
788
|
this.connectionName = name;
|
|
@@ -727,6 +791,10 @@ var QueueBase = class {
|
|
|
727
791
|
getConnectionName() {
|
|
728
792
|
return this.connectionName;
|
|
729
793
|
}
|
|
794
|
+
setDispatchAfterCommit(value) {
|
|
795
|
+
this.dispatchAfterCommit = value;
|
|
796
|
+
return this;
|
|
797
|
+
}
|
|
730
798
|
/** The queue name to use: the given one, else the connection's default. */
|
|
731
799
|
getQueue(queue) {
|
|
732
800
|
return optionalString(queue) || this.defaultQueue;
|
|
@@ -736,11 +804,49 @@ var QueueBase = class {
|
|
|
736
804
|
}
|
|
737
805
|
async push(job, queue) {
|
|
738
806
|
await ensureAppClasses(this.container);
|
|
739
|
-
|
|
807
|
+
const payload = this.createPayload(job);
|
|
808
|
+
const name = queue ?? (optionalString(job.queue) || void 0);
|
|
809
|
+
return this.enqueue(job, () => this.pushed(job, payload, name, void 0, this.pushRaw(payload, name)));
|
|
740
810
|
}
|
|
741
811
|
async later(delaySeconds, job, queue) {
|
|
742
812
|
await ensureAppClasses(this.container);
|
|
743
|
-
|
|
813
|
+
const payload = this.createPayload(job);
|
|
814
|
+
const name = queue ?? (optionalString(job.queue) || void 0);
|
|
815
|
+
return this.enqueue(job, () => this.pushed(job, payload, name, delaySeconds, this.pushRaw(payload, name, delaySeconds)));
|
|
816
|
+
}
|
|
817
|
+
/** Waits for the push, then dispatches JobQueued with its id. */
|
|
818
|
+
async pushed(job, payload, queue, delay, push) {
|
|
819
|
+
const id = await push;
|
|
820
|
+
await this.raiseJobQueued(this.getQueue(queue), id, job, payload, delay);
|
|
821
|
+
return id;
|
|
822
|
+
}
|
|
823
|
+
/** Laravel's raiseJobQueuedEvent(). */
|
|
824
|
+
async raiseJobQueued(queue, id, job, payload, delay) {
|
|
825
|
+
await dispatchQueueEvent(this.container, new JobQueued(this.connectionName, queue, id, job, payload, delay));
|
|
826
|
+
}
|
|
827
|
+
/** The job's own `afterCommit`, else the connection's `after_commit`. */
|
|
828
|
+
shouldDispatchAfterCommit(job) {
|
|
829
|
+
return typeof job.afterCommit === "boolean" ? job.afterCommit : this.dispatchAfterCommit;
|
|
830
|
+
}
|
|
831
|
+
/**
|
|
832
|
+
* Laravel's enqueueUsing(): pushes now, or, for a job that waits for the commit, once the database transaction open
|
|
833
|
+
* here commits (resolving '' meanwhile). The payload is made first, so a job that can't be queued fails at dispatch.
|
|
834
|
+
* A rollback drops the push and frees a unique job's lock, as does a push that fails after the commit.
|
|
835
|
+
*/
|
|
836
|
+
async enqueue(job, push) {
|
|
837
|
+
if (!this.shouldDispatchAfterCommit(job) || !this.container.bound(DatabaseManager)) return push();
|
|
838
|
+
const lock = symbolValue(job, UNIQUE_LOCK);
|
|
839
|
+
const release = lock === void 0 ? void 0 : () => releaseUniqueLock(this.container, lock);
|
|
840
|
+
let id = "";
|
|
841
|
+
await this.container.make(DatabaseManager).afterCommit(async () => {
|
|
842
|
+
try {
|
|
843
|
+
id = await push();
|
|
844
|
+
} catch (error) {
|
|
845
|
+
await release?.();
|
|
846
|
+
throw error;
|
|
847
|
+
}
|
|
848
|
+
}, release);
|
|
849
|
+
return id;
|
|
744
850
|
}
|
|
745
851
|
/** Closes network connections (redis). No-op by default. */
|
|
746
852
|
async disconnect() {
|
|
@@ -777,13 +883,18 @@ var SyncQueue = class extends QueueBase {
|
|
|
777
883
|
async pushRaw(payload, queue) {
|
|
778
884
|
const job = new SyncJob(this.jobContext(), payload, this.getQueue(queue));
|
|
779
885
|
try {
|
|
886
|
+
await dispatchQueueEvent(this.container, new JobProcessing(this.connectionName, job));
|
|
780
887
|
await job.fire();
|
|
888
|
+
await dispatchQueueEvent(this.container, new JobProcessed(this.connectionName, job));
|
|
781
889
|
} catch (error) {
|
|
782
890
|
if (!job.hasFailed()) await job.fail(error);
|
|
783
891
|
throw error;
|
|
784
892
|
}
|
|
785
893
|
return payload.uuid;
|
|
786
894
|
}
|
|
895
|
+
/** The job has run already: nothing was queued. */
|
|
896
|
+
async raiseJobQueued(_queue, _id, _job, _payload, _delay) {
|
|
897
|
+
}
|
|
787
898
|
async pop() {
|
|
788
899
|
return void 0;
|
|
789
900
|
}
|
|
@@ -820,7 +931,8 @@ var NullQueue = class extends QueueBase {
|
|
|
820
931
|
// QueueManager.ts
|
|
821
932
|
import {
|
|
822
933
|
ConfigRepository,
|
|
823
|
-
DatabaseManager
|
|
934
|
+
DatabaseManager as DatabaseManager2,
|
|
935
|
+
EventDispatcher as EventDispatcher2
|
|
824
936
|
} from "@orieljs/contracts";
|
|
825
937
|
|
|
826
938
|
// jobs/DatabaseJob.ts
|
|
@@ -949,7 +1061,7 @@ var DatabaseQueue = class extends QueueBase {
|
|
|
949
1061
|
};
|
|
950
1062
|
|
|
951
1063
|
// queues/RedisQueue.ts
|
|
952
|
-
import {
|
|
1064
|
+
import { importOptional } from "@orieljs/support";
|
|
953
1065
|
|
|
954
1066
|
// jobs/RedisJob.ts
|
|
955
1067
|
var RedisJob = class extends BaseJob {
|
|
@@ -1037,8 +1149,9 @@ return size
|
|
|
1037
1149
|
|
|
1038
1150
|
// queues/RedisQueue.ts
|
|
1039
1151
|
var QUEUE_KEYS = ["driver", "connection", "queue", "retry_after", "block_for", "after_commit", "client", "url"];
|
|
1040
|
-
function makeRedisClient(config) {
|
|
1152
|
+
async function makeRedisClient(config) {
|
|
1041
1153
|
if (config.client) return config.client;
|
|
1154
|
+
const { Redis } = await importOptional("ioredis", "The redis queue connection", () => import("ioredis"));
|
|
1042
1155
|
const options = Object.fromEntries(
|
|
1043
1156
|
Object.entries(config).filter(([key, value]) => value !== void 0 && !QUEUE_KEYS.includes(key))
|
|
1044
1157
|
);
|
|
@@ -1051,6 +1164,7 @@ function resolveRedisConfig(config, appConfig) {
|
|
|
1051
1164
|
return appConfig.get(`database.redis.${name}`) ?? config;
|
|
1052
1165
|
}
|
|
1053
1166
|
var RedisQueue = class extends QueueBase {
|
|
1167
|
+
/** `connect` gives the client (or a promise of it), at the queue's first command. */
|
|
1054
1168
|
constructor(container, connect, options = {}) {
|
|
1055
1169
|
super(container, options.queue ?? "default");
|
|
1056
1170
|
this.connect = connect;
|
|
@@ -1060,7 +1174,7 @@ var RedisQueue = class extends QueueBase {
|
|
|
1060
1174
|
client;
|
|
1061
1175
|
retryAfter;
|
|
1062
1176
|
redis() {
|
|
1063
|
-
return this.client ??= this.connect();
|
|
1177
|
+
return this.client ??= Promise.resolve().then(() => this.connect());
|
|
1064
1178
|
}
|
|
1065
1179
|
/** The list key for a queue name: `queues:<name>`. */
|
|
1066
1180
|
key(queue) {
|
|
@@ -1069,44 +1183,47 @@ var RedisQueue = class extends QueueBase {
|
|
|
1069
1183
|
async pushRaw(payload, queue, delaySeconds = 0) {
|
|
1070
1184
|
const key = this.key(queue);
|
|
1071
1185
|
const body = encodePayload({ ...payload, attempts: payload.attempts ?? 0 });
|
|
1072
|
-
|
|
1073
|
-
|
|
1186
|
+
const redis = await this.redis();
|
|
1187
|
+
if (delaySeconds > 0) await redis.zadd(`${key}:delayed`, this.now() + delaySeconds, body);
|
|
1188
|
+
else await redis.eval(PUSH, 2, key, `${key}:notify`, body);
|
|
1074
1189
|
return payload.uuid;
|
|
1075
1190
|
}
|
|
1076
1191
|
async pop(queue) {
|
|
1077
1192
|
const key = this.key(queue);
|
|
1078
1193
|
const now = this.now();
|
|
1079
|
-
await this.redis()
|
|
1080
|
-
await
|
|
1194
|
+
const redis = await this.redis();
|
|
1195
|
+
await redis.eval(MIGRATE_EXPIRED_JOBS, 3, `${key}:delayed`, key, `${key}:notify`, now);
|
|
1196
|
+
await redis.eval(MIGRATE_EXPIRED_JOBS, 3, `${key}:reserved`, key, `${key}:notify`, now);
|
|
1081
1197
|
for (; ; ) {
|
|
1082
|
-
const [job, reserved] = await
|
|
1198
|
+
const [job, reserved] = await redis.eval(POP, 3, key, `${key}:reserved`, `${key}:notify`, now + this.retryAfter);
|
|
1083
1199
|
if (!job || !reserved) return void 0;
|
|
1084
1200
|
try {
|
|
1085
1201
|
return new RedisJob(this.jobContext(), this, job, reserved, this.getQueue(queue));
|
|
1086
1202
|
} catch (error) {
|
|
1087
1203
|
await this.failCorrupt(this.getQueue(queue), job, error);
|
|
1088
|
-
await
|
|
1204
|
+
await redis.zrem(`${key}:reserved`, reserved);
|
|
1089
1205
|
}
|
|
1090
1206
|
}
|
|
1091
1207
|
}
|
|
1092
1208
|
async size(queue) {
|
|
1093
1209
|
const key = this.key(queue);
|
|
1094
|
-
return Number(await this.redis().eval(SIZE, 3, key, `${key}:delayed`, `${key}:reserved`));
|
|
1210
|
+
return Number(await (await this.redis()).eval(SIZE, 3, key, `${key}:delayed`, `${key}:reserved`));
|
|
1095
1211
|
}
|
|
1096
1212
|
async clear(queue) {
|
|
1097
1213
|
const key = this.key(queue);
|
|
1098
|
-
return Number(await this.redis().eval(CLEAR, 4, key, `${key}:delayed`, `${key}:reserved`, `${key}:notify`));
|
|
1214
|
+
return Number(await (await this.redis()).eval(CLEAR, 4, key, `${key}:delayed`, `${key}:reserved`, `${key}:notify`));
|
|
1099
1215
|
}
|
|
1100
1216
|
async deleteReserved(queue, job) {
|
|
1101
|
-
await this.redis().zrem(`${this.key(queue)}:reserved`, job.getReservedJob());
|
|
1217
|
+
await (await this.redis()).zrem(`${this.key(queue)}:reserved`, job.getReservedJob());
|
|
1102
1218
|
}
|
|
1103
1219
|
async deleteAndRelease(queue, job, delaySeconds) {
|
|
1104
1220
|
const key = this.key(queue);
|
|
1105
|
-
await this.redis().eval(RELEASE, 2, `${key}:delayed`, `${key}:reserved`, job.getReservedJob(), this.now() + Math.max(0, delaySeconds));
|
|
1221
|
+
await (await this.redis()).eval(RELEASE, 2, `${key}:delayed`, `${key}:reserved`, job.getReservedJob(), this.now() + Math.max(0, delaySeconds));
|
|
1106
1222
|
}
|
|
1107
1223
|
async disconnect() {
|
|
1108
|
-
const
|
|
1224
|
+
const pending = this.client;
|
|
1109
1225
|
this.client = void 0;
|
|
1226
|
+
const client = await pending?.catch(() => void 0);
|
|
1110
1227
|
if (client && client.status !== "end") await client.quit();
|
|
1111
1228
|
}
|
|
1112
1229
|
/** Unix seconds, with milliseconds as the fraction (sorted-set scores). */
|
|
@@ -1124,7 +1241,7 @@ var QueueManager2 = class {
|
|
|
1124
1241
|
this.drivers.set("null", (config) => new NullQueue(container, optionalString(config.queue) || "default"));
|
|
1125
1242
|
this.drivers.set(
|
|
1126
1243
|
"database",
|
|
1127
|
-
(config) => new DatabaseQueue(container, () => container.make(
|
|
1244
|
+
(config) => new DatabaseQueue(container, () => container.make(DatabaseManager2).connection(optionalString(config.connection) || void 0), {
|
|
1128
1245
|
table: optionalString(config.table) || "jobs",
|
|
1129
1246
|
queue: optionalString(config.queue) || "default",
|
|
1130
1247
|
retryAfter: number(config.retry_after, 90)
|
|
@@ -1157,6 +1274,15 @@ var QueueManager2 = class {
|
|
|
1157
1274
|
extend(driver, factory) {
|
|
1158
1275
|
this.drivers.set(driver, factory);
|
|
1159
1276
|
}
|
|
1277
|
+
before(callback) {
|
|
1278
|
+
this.container.make(EventDispatcher2).listen(JobProcessing, callback);
|
|
1279
|
+
}
|
|
1280
|
+
after(callback) {
|
|
1281
|
+
this.container.make(EventDispatcher2).listen(JobProcessed, callback);
|
|
1282
|
+
}
|
|
1283
|
+
failing(callback) {
|
|
1284
|
+
this.container.make(EventDispatcher2).listen(JobFailed, callback);
|
|
1285
|
+
}
|
|
1160
1286
|
getDefaultDriver() {
|
|
1161
1287
|
return optionalString(this.config().get("queue.default")) || "sync";
|
|
1162
1288
|
}
|
|
@@ -1207,6 +1333,7 @@ var QueueManager2 = class {
|
|
|
1207
1333
|
if (!driver) throw new UnknownQueueDriverError(driverName);
|
|
1208
1334
|
const queue = driver(config, name);
|
|
1209
1335
|
queue.setConnectionName?.(name);
|
|
1336
|
+
queue.setDispatchAfterCommit?.(config.after_commit === true);
|
|
1210
1337
|
return queue;
|
|
1211
1338
|
}
|
|
1212
1339
|
config() {
|
|
@@ -1644,12 +1771,16 @@ var Worker = class _Worker {
|
|
|
1644
1771
|
process.on("unhandledRejection", onUnhandledRejection);
|
|
1645
1772
|
return () => process.off("unhandledRejection", onUnhandledRejection);
|
|
1646
1773
|
}
|
|
1647
|
-
/**
|
|
1648
|
-
|
|
1774
|
+
/**
|
|
1775
|
+
* Processes one job: max-attempts check, fire (with timeout), and failure handling. Dispatches JobProcessing first
|
|
1776
|
+
* and JobProcessed once the job has run without failing (BaseJob.fail() dispatches JobFailed).
|
|
1777
|
+
*/
|
|
1778
|
+
async process(connectionName, job, options) {
|
|
1649
1779
|
const workable = job;
|
|
1650
1780
|
const started = Date.now();
|
|
1651
1781
|
try {
|
|
1652
1782
|
this.listener.processing?.(job);
|
|
1783
|
+
await dispatchQueueEvent(this.container, new JobProcessing(connectionName, job));
|
|
1653
1784
|
await this.markJobAsFailedIfAlreadyExceedsMaxAttempts(workable, options.maxTries);
|
|
1654
1785
|
if (job.isDeleted()) return;
|
|
1655
1786
|
await this.fireWithTimeout(workable, options);
|
|
@@ -1658,7 +1789,10 @@ var Worker = class _Worker {
|
|
|
1658
1789
|
this.pendingRejection = void 0;
|
|
1659
1790
|
await pending;
|
|
1660
1791
|
}
|
|
1661
|
-
if (!workable.hasFailed())
|
|
1792
|
+
if (!workable.hasFailed()) {
|
|
1793
|
+
this.listener.processed?.(job, Date.now() - started);
|
|
1794
|
+
await dispatchQueueEvent(this.container, new JobProcessed(connectionName, job));
|
|
1795
|
+
}
|
|
1662
1796
|
} catch (error) {
|
|
1663
1797
|
await this.handleJobException(workable, options, error);
|
|
1664
1798
|
}
|
|
@@ -2194,7 +2328,7 @@ import {
|
|
|
2194
2328
|
BatchRepository as BatchRepository2,
|
|
2195
2329
|
ConfigRepository as ConfigRepository3,
|
|
2196
2330
|
ConsoleKernel,
|
|
2197
|
-
DatabaseManager as
|
|
2331
|
+
DatabaseManager as DatabaseManager3,
|
|
2198
2332
|
FailedJobProvider as FailedJobProvider4,
|
|
2199
2333
|
QueueManager as QueueManagerToken
|
|
2200
2334
|
} from "@orieljs/contracts";
|
|
@@ -2204,10 +2338,10 @@ function makeFailedJobProvider(container) {
|
|
|
2204
2338
|
const driver = String(config.get("queue.failed.driver", "database-uuids"));
|
|
2205
2339
|
if (driver === "null") return new NullFailedJobProvider();
|
|
2206
2340
|
if (driver !== "database-uuids" && driver !== "database") throw new UnknownQueueDriverError(driver);
|
|
2207
|
-
if (!container.bound(
|
|
2341
|
+
if (!container.bound(DatabaseManager3)) return new NullFailedJobProvider();
|
|
2208
2342
|
const database = optionalString(config.get("queue.failed.database")) || void 0;
|
|
2209
2343
|
const table = String(config.get("queue.failed.table", "failed_jobs"));
|
|
2210
|
-
return new DatabaseFailedJobProvider(() => container.make(
|
|
2344
|
+
return new DatabaseFailedJobProvider(() => container.make(DatabaseManager3).connection(database), table);
|
|
2211
2345
|
}
|
|
2212
2346
|
var QueueServiceProvider = class extends ServiceProvider {
|
|
2213
2347
|
register() {
|
|
@@ -2219,12 +2353,12 @@ var QueueServiceProvider = class extends ServiceProvider {
|
|
|
2219
2353
|
if (!this.app.resolved(QueueManagerToken)) return;
|
|
2220
2354
|
await this.app.make(QueueManagerToken).disconnectAll?.();
|
|
2221
2355
|
});
|
|
2222
|
-
if (this.app.bound(
|
|
2356
|
+
if (this.app.bound(DatabaseManager3)) {
|
|
2223
2357
|
this.app.singleton(BatchRepository2, (container) => {
|
|
2224
2358
|
const config = container.make(ConfigRepository3);
|
|
2225
2359
|
const database = optionalString(config.get("queue.batching.database")) || void 0;
|
|
2226
2360
|
const table = String(config.get("queue.batching.table", "job_batches"));
|
|
2227
|
-
return new DatabaseBatchRepository(container, () => container.make(
|
|
2361
|
+
return new DatabaseBatchRepository(container, () => container.make(DatabaseManager3).connection(database), table);
|
|
2228
2362
|
});
|
|
2229
2363
|
}
|
|
2230
2364
|
}
|
|
@@ -2243,6 +2377,10 @@ export {
|
|
|
2243
2377
|
DatabaseQueue,
|
|
2244
2378
|
JOBS_TABLE_MIGRATION,
|
|
2245
2379
|
JobClassNotFoundError,
|
|
2380
|
+
JobFailed,
|
|
2381
|
+
JobProcessed,
|
|
2382
|
+
JobProcessing,
|
|
2383
|
+
JobQueued,
|
|
2246
2384
|
JobSerializationError,
|
|
2247
2385
|
Listener,
|
|
2248
2386
|
ManuallyFailedError,
|