@orieljs/queue 0.1.0-alpha.4 → 0.1.0-alpha.6
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/NOTICE +3 -0
- package/dist/index.d.ts +80 -8
- package/dist/index.js +226 -6
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/NOTICE
CHANGED
|
@@ -7,3 +7,6 @@ This product includes software developed by the Oriel project
|
|
|
7
7
|
Oriel is licensed under the Apache License, Version 2.0 (see LICENSE).
|
|
8
8
|
The Oriel name and logo are not covered by that license; see TRADEMARKS.md
|
|
9
9
|
(https://github.com/orieljs/framework/blob/main/TRADEMARKS.md).
|
|
10
|
+
|
|
11
|
+
@orieljs/support (and @orieljs/framework, which bundles it) includes transliteration data from
|
|
12
|
+
voku/portable-ascii (https://github.com/voku/portable-ascii), Copyright (C) 2019 Lars Moelleken, MIT License.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
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';
|
|
2
2
|
import { Redis } from 'ioredis';
|
|
3
|
+
import { SpawnOptions, ChildProcess } from 'node:child_process';
|
|
3
4
|
import * as _orieljs_support from '@orieljs/support';
|
|
4
5
|
import { ServiceProvider } from '@orieljs/support';
|
|
5
6
|
|
|
@@ -89,15 +90,16 @@ declare function isModel(value: unknown): value is ModelInstance;
|
|
|
89
90
|
*/
|
|
90
91
|
declare function classNameOf(registry: ClassRegistry, cls: Class<unknown>): string;
|
|
91
92
|
/**
|
|
92
|
-
* Encodes a value for a payload. Models become `{ __oriel: 'model', class, key }
|
|
93
|
-
*
|
|
94
|
-
*
|
|
93
|
+
* Encodes a value for a payload. Models become `{ __oriel: 'model', class, key }`, plus the connection they were read
|
|
94
|
+
* from when they name one and the names of their loaded relations (Laravel's ModelIdentifier); other class instances
|
|
95
|
+
* keep their class name and fields; Date, Map, Set and byte arrays (any ArrayBuffer view, as base64) are tagged.
|
|
96
|
+
* Functions, symbols, bigints, unsaved models and cycles throw.
|
|
95
97
|
*/
|
|
96
98
|
declare function serializeValue(value: unknown, registry: ClassRegistry, path?: string, seen?: Set<object>): Encoded | undefined;
|
|
97
99
|
/**
|
|
98
100
|
* The inverse of serializeValue(). Byte arrays come back as Uint8Array. Models are re-fetched by key without global
|
|
99
|
-
* scopes (Laravel's newQueryForRestoration), so a soft-deleted model still reaches the job
|
|
100
|
-
* MissingModelError.
|
|
101
|
+
* scopes (Laravel's newQueryForRestoration), so a soft-deleted model still reaches the job, and the relations they had
|
|
102
|
+
* loaded are loaded again (loadMissing, as Laravel); a missing one throws MissingModelError.
|
|
101
103
|
*/
|
|
102
104
|
declare function restoreValue(value: Encoded, registry: ClassRegistry): Promise<unknown>;
|
|
103
105
|
|
|
@@ -532,7 +534,11 @@ interface WorkerOptions {
|
|
|
532
534
|
name: string;
|
|
533
535
|
/** Seconds to wait before retrying a failed job: one number or a per-attempt list. */
|
|
534
536
|
backoff: number | number[] | string;
|
|
535
|
-
/**
|
|
537
|
+
/**
|
|
538
|
+
* MB of V8 heap in use (`process.memoryUsage().heapUsed`) after which the worker stops (exit 12). 0 disables the
|
|
539
|
+
* check. Defaults to 512, not Laravel's 128: that figure is PHP's, and a Node app on tsx already holds about 115 MB
|
|
540
|
+
* of heap at idle, so 128 stopped a worker after its first job.
|
|
541
|
+
*/
|
|
536
542
|
memory: number;
|
|
537
543
|
/** Max seconds a job may run. 0 disables it. A job's own `timeout` wins. */
|
|
538
544
|
timeout: number;
|
|
@@ -622,6 +628,68 @@ declare class Worker {
|
|
|
622
628
|
private handleUnhandledRejection;
|
|
623
629
|
}
|
|
624
630
|
|
|
631
|
+
/** `queue:listen` options (Laravel's ListenerOptions). Seconds unless noted. */
|
|
632
|
+
interface ListenerOptions {
|
|
633
|
+
name: string;
|
|
634
|
+
/** Passed on to each `queue:work`: seconds before a failed job is retried. */
|
|
635
|
+
backoff: number | number[] | string;
|
|
636
|
+
/** MB of V8 heap, passed on to each `queue:work`; the listener also stops once its own heap reaches it. */
|
|
637
|
+
memory: number;
|
|
638
|
+
/** Seconds a process may run before the listener kills it, also passed on as the job's timeout. 0 disables it. */
|
|
639
|
+
timeout: number;
|
|
640
|
+
/** Passed on to each `queue:work`: seconds it sleeps when no job is available. */
|
|
641
|
+
sleep: number;
|
|
642
|
+
/** Passed on to each `queue:work` as `--tries`. */
|
|
643
|
+
maxTries: number;
|
|
644
|
+
/** Seconds to rest between processes. */
|
|
645
|
+
rest: number;
|
|
646
|
+
/** Stop once every listed queue is empty (not in Laravel's queue:listen; queue:work has it). */
|
|
647
|
+
stopWhenEmpty: boolean;
|
|
648
|
+
}
|
|
649
|
+
declare const defaultListenerOptions: () => ListenerOptions;
|
|
650
|
+
/** node:child_process's spawn(), replaceable in tests. */
|
|
651
|
+
type SpawnWorker = (command: string, args: string[], options: SpawnOptions) => ChildProcess;
|
|
652
|
+
/** Receives each line a worker process prints, from its stdout ('out') or its stderr ('err'). */
|
|
653
|
+
type ListenerOutput = (type: 'out' | 'err', line: string) => void;
|
|
654
|
+
interface ListenerConfig {
|
|
655
|
+
/** The folder the processes run in: the app's base path (Laravel's commandPath). */
|
|
656
|
+
commandPath: string;
|
|
657
|
+
/** The app's CLI: this process's runtime, its flags and its script by default (`node oriel`, `bun oriel`). */
|
|
658
|
+
runtime?: {
|
|
659
|
+
command: string;
|
|
660
|
+
args: string[];
|
|
661
|
+
};
|
|
662
|
+
output?: ListenerOutput;
|
|
663
|
+
spawn?: SpawnWorker;
|
|
664
|
+
}
|
|
665
|
+
/**
|
|
666
|
+
* Laravel's Illuminate\Queue\Listener: runs `queue:work --once` in a new process, again and again, so every job runs
|
|
667
|
+
* in a fresh process and code changes apply to the next job without a restart. Each process's output is passed on
|
|
668
|
+
* line by line. Unlike Laravel's, it also passes `--timeout` on (Laravel's processes keep the 60-second default), a
|
|
669
|
+
* process that outlives `--timeout` is killed and reported while the listener carries on (Laravel's throws), and a
|
|
670
|
+
* stop signal is passed to the running process before the listener returns.
|
|
671
|
+
*/
|
|
672
|
+
declare class Listener {
|
|
673
|
+
private readonly manager;
|
|
674
|
+
private readonly config;
|
|
675
|
+
static readonly EXIT_SUCCESS = 0;
|
|
676
|
+
private shouldQuit;
|
|
677
|
+
private child;
|
|
678
|
+
private resting;
|
|
679
|
+
constructor(manager: QueueManager$1, config: ListenerConfig);
|
|
680
|
+
/** Runs until stopped, the queue is empty (with stopWhenEmpty) or the memory limit is reached. Returns the exit code. */
|
|
681
|
+
listen(connection: string, queue: string, options: ListenerOptions): Promise<number>;
|
|
682
|
+
/** Laravel's createCommand(): the runtime, the CLI script and `queue:work <connection> --once …`, plus `--timeout`. */
|
|
683
|
+
makeCommand(connection: string, queue: string, options: ListenerOptions): string[];
|
|
684
|
+
/** Stops after the running process, which gets the same signal (SIGTERM/SIGINT/SIGQUIT call this). */
|
|
685
|
+
stop(signal?: NodeJS.Signals): void;
|
|
686
|
+
memoryExceeded(limitMb: number): boolean;
|
|
687
|
+
private listenForSignals;
|
|
688
|
+
private isEmpty;
|
|
689
|
+
private runProcess;
|
|
690
|
+
private rest;
|
|
691
|
+
}
|
|
692
|
+
|
|
625
693
|
/** The app directories whose classes travel inside wrapper jobs (queued listeners, mailables, notifications). */
|
|
626
694
|
declare const WORKER_DISCOVERY_DIRECTORIES: readonly ["Events", "Listeners", "Mail", "Notifications"];
|
|
627
695
|
/**
|
|
@@ -636,9 +704,13 @@ declare function discoverClasses(directory: string, registry: ClassRegistry, fil
|
|
|
636
704
|
declare function discoverJobs(directory: string, registry: ClassRegistry): Promise<string[]>;
|
|
637
705
|
|
|
638
706
|
interface QueueCommandContext {
|
|
639
|
-
app: Pick<Application, 'isProduction' | 'appPath'>;
|
|
707
|
+
app: Pick<Application, 'isProduction' | 'appPath' | 'basePath'>;
|
|
640
708
|
container: Container;
|
|
709
|
+
/** How queue:listen starts its processes (node:child_process's spawn by default). */
|
|
710
|
+
spawn?: SpawnWorker;
|
|
641
711
|
}
|
|
712
|
+
/** Laravel's queue:listen options from the parsed command options. */
|
|
713
|
+
declare function listenerOptionsFrom(option: (name: string) => unknown): ListenerOptions;
|
|
642
714
|
/** Laravel's queue:work options from the parsed command options. */
|
|
643
715
|
declare function workerOptionsFrom(option: (name: string) => unknown): WorkerOptions;
|
|
644
716
|
/** The queue:* commands, registered as closure commands (PC1). */
|
|
@@ -660,4 +732,4 @@ declare class QueueServiceProvider extends ServiceProvider {
|
|
|
660
732
|
boot(): void;
|
|
661
733
|
}
|
|
662
734
|
|
|
663
|
-
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, 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 StoredBatchOptions, SyncJob, SyncQueue, TimeoutExceededError, UNIQUE_LOCK, type UniqueLockSpec, UnknownQueueConnectionError, UnknownQueueDriverError, WORKER_DISCOVERY_DIRECTORIES, WithoutOverlapping, Worker, type WorkerListener, type WorkerOptions, classNameOf, createPayload, decodePayload, defaultWorkerOptions, describeError, discoverClasses, discoverJobs, encodePayload, formatTimestamp, isModel, makeFailedJobProvider, makeRedisClient, normalizeBackoff, queueConfigDefaults, registerQueueCommands, resolveRedisConfig, restoreJob, restoreValue, serializeValue, workerOptionsFrom };
|
|
735
|
+
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, formatTimestamp, isModel, listenerOptionsFrom, makeFailedJobProvider, makeRedisClient, normalizeBackoff, queueConfigDefaults, registerQueueCommands, resolveRedisConfig, restoreJob, restoreValue, serializeValue, workerOptionsFrom };
|
package/dist/index.js
CHANGED
|
@@ -89,6 +89,40 @@ function isModel(value) {
|
|
|
89
89
|
const candidate = value;
|
|
90
90
|
return typeof candidate.getKey === "function" && typeof candidate.getKeyName === "function" && typeof candidate.getTable === "function" && typeof candidate.exists === "boolean";
|
|
91
91
|
}
|
|
92
|
+
var isModelList = (value) => typeof value === "object" && value !== null && !isModel(value) && typeof value[Symbol.iterator] === "function";
|
|
93
|
+
function queueableRelations(model, visiting = /* @__PURE__ */ new Set()) {
|
|
94
|
+
if (visiting.has(model)) return [];
|
|
95
|
+
visiting.add(model);
|
|
96
|
+
try {
|
|
97
|
+
const relations = [];
|
|
98
|
+
for (const [name, value] of Object.entries(model.getRelations?.() ?? {})) {
|
|
99
|
+
if (typeof model[name] !== "function") continue;
|
|
100
|
+
relations.push(name);
|
|
101
|
+
for (const nested of nestedRelations(value, visiting)) relations.push(`${name}.${nested}`);
|
|
102
|
+
}
|
|
103
|
+
return [...new Set(relations)];
|
|
104
|
+
} finally {
|
|
105
|
+
visiting.delete(model);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
function nestedRelations(value, visiting) {
|
|
109
|
+
if (isModel(value)) return queueableRelations(value, visiting);
|
|
110
|
+
if (!isModelList(value)) return [];
|
|
111
|
+
const members = [...value].filter(isModel).map((member) => queueableRelations(member, visiting));
|
|
112
|
+
if (members.length === 0) return [];
|
|
113
|
+
return members.reduce((shared, next) => shared.filter((path) => next.includes(path)));
|
|
114
|
+
}
|
|
115
|
+
async function findForRestoration(model, key, connection) {
|
|
116
|
+
if (connection !== void 0) {
|
|
117
|
+
const instance = new model();
|
|
118
|
+
if (typeof instance.setConnection === "function" && typeof instance.newQueryWithoutScopes === "function") {
|
|
119
|
+
instance.setConnection(connection);
|
|
120
|
+
return instance.newQueryWithoutScopes().find(key);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const query = typeof model.withoutGlobalScopes === "function" ? model.withoutGlobalScopes() : model;
|
|
124
|
+
return query.find(key);
|
|
125
|
+
}
|
|
92
126
|
function classNameOf(registry, cls) {
|
|
93
127
|
const existing = registry.nameOf(cls);
|
|
94
128
|
if (existing !== void 0) return existing;
|
|
@@ -158,7 +192,12 @@ function serializeValue(value, registry, path = "data", seen = /* @__PURE__ */ n
|
|
|
158
192
|
if (!object.exists) {
|
|
159
193
|
throw new JobSerializationError(`Cannot serialize [${path}]: the [${name2}] model hasn't been saved, so it has no key to store.`);
|
|
160
194
|
}
|
|
161
|
-
|
|
195
|
+
const encoded = { [TAG]: "model", class: name2, key: serializeValue(object.getKey(), registry, `${path}.key`, seen) ?? null };
|
|
196
|
+
const connection = object.getConnectionName?.();
|
|
197
|
+
if (connection !== void 0) encoded.connection = connection;
|
|
198
|
+
const relations = queueableRelations(object);
|
|
199
|
+
if (relations.length > 0) encoded.relations = relations;
|
|
200
|
+
return encoded;
|
|
162
201
|
}
|
|
163
202
|
if (isPlainObject(object)) {
|
|
164
203
|
const fields = serializeFields(object, registry, path, seen);
|
|
@@ -214,9 +253,10 @@ async function restoreValue(value, registry) {
|
|
|
214
253
|
const name = value.class;
|
|
215
254
|
const model = resolveClass(registry, name);
|
|
216
255
|
const key = await restoreValue(value.key, registry);
|
|
217
|
-
const
|
|
218
|
-
const found = await query.find(key);
|
|
256
|
+
const found = await findForRestoration(model, key, typeof value.connection === "string" ? value.connection : void 0);
|
|
219
257
|
if (found === void 0 || found === null) throw new MissingModelError(name, [key]);
|
|
258
|
+
const relations = Array.isArray(value.relations) ? value.relations.map(String) : [];
|
|
259
|
+
if (relations.length > 0) await (found.loadMissing ?? found.load)?.call(found, ...relations);
|
|
220
260
|
return found;
|
|
221
261
|
}
|
|
222
262
|
case "instance": {
|
|
@@ -1405,7 +1445,7 @@ import {
|
|
|
1405
1445
|
var defaultWorkerOptions = () => ({
|
|
1406
1446
|
name: "default",
|
|
1407
1447
|
backoff: 0,
|
|
1408
|
-
memory:
|
|
1448
|
+
memory: 512,
|
|
1409
1449
|
timeout: 60,
|
|
1410
1450
|
sleep: 3,
|
|
1411
1451
|
maxTries: 1,
|
|
@@ -1664,6 +1704,146 @@ var Worker = class _Worker {
|
|
|
1664
1704
|
}
|
|
1665
1705
|
};
|
|
1666
1706
|
|
|
1707
|
+
// Listener.ts
|
|
1708
|
+
import { spawn as spawnProcess } from "child_process";
|
|
1709
|
+
import { setTimeout as sleep2 } from "timers/promises";
|
|
1710
|
+
var defaultListenerOptions = () => ({
|
|
1711
|
+
name: "default",
|
|
1712
|
+
backoff: 0,
|
|
1713
|
+
memory: 512,
|
|
1714
|
+
timeout: 60,
|
|
1715
|
+
sleep: 3,
|
|
1716
|
+
maxTries: 1,
|
|
1717
|
+
rest: 0,
|
|
1718
|
+
stopWhenEmpty: false
|
|
1719
|
+
});
|
|
1720
|
+
function lineSplitter(emit) {
|
|
1721
|
+
let rest = "";
|
|
1722
|
+
return {
|
|
1723
|
+
push(chunk) {
|
|
1724
|
+
const lines = (rest + chunk).split("\n");
|
|
1725
|
+
rest = lines.pop() ?? "";
|
|
1726
|
+
for (const line of lines) emit(line.endsWith("\r") ? line.slice(0, -1) : line);
|
|
1727
|
+
},
|
|
1728
|
+
end() {
|
|
1729
|
+
if (rest !== "") emit(rest);
|
|
1730
|
+
rest = "";
|
|
1731
|
+
}
|
|
1732
|
+
};
|
|
1733
|
+
}
|
|
1734
|
+
function currentRuntime() {
|
|
1735
|
+
const script = process.argv[1];
|
|
1736
|
+
if (script === void 0) throw new QueueError("queue:listen can't tell which script started this process, so it can't start workers.");
|
|
1737
|
+
return { command: process.execPath, args: [...process.execArgv, script] };
|
|
1738
|
+
}
|
|
1739
|
+
var Listener = class _Listener {
|
|
1740
|
+
constructor(manager, config) {
|
|
1741
|
+
this.manager = manager;
|
|
1742
|
+
this.config = config;
|
|
1743
|
+
}
|
|
1744
|
+
manager;
|
|
1745
|
+
config;
|
|
1746
|
+
static EXIT_SUCCESS = 0;
|
|
1747
|
+
shouldQuit = false;
|
|
1748
|
+
child;
|
|
1749
|
+
resting;
|
|
1750
|
+
/** Runs until stopped, the queue is empty (with stopWhenEmpty) or the memory limit is reached. Returns the exit code. */
|
|
1751
|
+
async listen(connection, queue, options) {
|
|
1752
|
+
const stopListening = this.listenForSignals();
|
|
1753
|
+
try {
|
|
1754
|
+
const command = this.makeCommand(connection, queue, options);
|
|
1755
|
+
while (!this.shouldQuit) {
|
|
1756
|
+
if (options.stopWhenEmpty && await this.isEmpty(connection, queue)) break;
|
|
1757
|
+
if (this.shouldQuit) break;
|
|
1758
|
+
await this.runProcess(command, options.timeout);
|
|
1759
|
+
if (this.shouldQuit || this.memoryExceeded(options.memory)) break;
|
|
1760
|
+
if (options.rest > 0) await this.rest(options.rest);
|
|
1761
|
+
}
|
|
1762
|
+
return _Listener.EXIT_SUCCESS;
|
|
1763
|
+
} finally {
|
|
1764
|
+
stopListening();
|
|
1765
|
+
}
|
|
1766
|
+
}
|
|
1767
|
+
/** Laravel's createCommand(): the runtime, the CLI script and `queue:work <connection> --once …`, plus `--timeout`. */
|
|
1768
|
+
makeCommand(connection, queue, options) {
|
|
1769
|
+
const { command, args } = this.config.runtime ?? currentRuntime();
|
|
1770
|
+
const backoff = Array.isArray(options.backoff) ? options.backoff.join(",") : String(options.backoff);
|
|
1771
|
+
return [
|
|
1772
|
+
command,
|
|
1773
|
+
...args,
|
|
1774
|
+
"queue:work",
|
|
1775
|
+
connection,
|
|
1776
|
+
"--once",
|
|
1777
|
+
`--name=${options.name}`,
|
|
1778
|
+
`--queue=${queue}`,
|
|
1779
|
+
`--backoff=${backoff}`,
|
|
1780
|
+
`--memory=${options.memory}`,
|
|
1781
|
+
`--sleep=${options.sleep}`,
|
|
1782
|
+
`--tries=${options.maxTries}`,
|
|
1783
|
+
`--timeout=${options.timeout}`
|
|
1784
|
+
];
|
|
1785
|
+
}
|
|
1786
|
+
/** Stops after the running process, which gets the same signal (SIGTERM/SIGINT/SIGQUIT call this). */
|
|
1787
|
+
stop(signal = "SIGTERM") {
|
|
1788
|
+
this.shouldQuit = true;
|
|
1789
|
+
this.child?.kill(signal);
|
|
1790
|
+
this.resting?.abort();
|
|
1791
|
+
}
|
|
1792
|
+
memoryExceeded(limitMb) {
|
|
1793
|
+
return limitMb > 0 && process.memoryUsage().heapUsed / 1024 / 1024 >= limitMb;
|
|
1794
|
+
}
|
|
1795
|
+
listenForSignals() {
|
|
1796
|
+
const signals = ["SIGTERM", "SIGINT", "SIGQUIT"];
|
|
1797
|
+
const handlers = signals.map((signal) => [signal, () => this.stop(signal)]);
|
|
1798
|
+
for (const [signal, handler] of handlers) process.on(signal, handler);
|
|
1799
|
+
return () => {
|
|
1800
|
+
for (const [signal, handler] of handlers) process.off(signal, handler);
|
|
1801
|
+
};
|
|
1802
|
+
}
|
|
1803
|
+
async isEmpty(connection, queue) {
|
|
1804
|
+
const queues = this.manager.connection(connection);
|
|
1805
|
+
for (const name of queue.split(",")) if (await queues.size(name.trim()) > 0) return false;
|
|
1806
|
+
return true;
|
|
1807
|
+
}
|
|
1808
|
+
runProcess([command, ...args], timeout) {
|
|
1809
|
+
const output = this.config.output ?? (() => {
|
|
1810
|
+
});
|
|
1811
|
+
return new Promise((resolve, reject) => {
|
|
1812
|
+
const child = (this.config.spawn ?? spawnProcess)(command, args, { cwd: this.config.commandPath, env: process.env, stdio: ["ignore", "pipe", "pipe"] });
|
|
1813
|
+
this.child = child;
|
|
1814
|
+
const stdout = lineSplitter((line) => output("out", line));
|
|
1815
|
+
const stderr = lineSplitter((line) => output("err", line));
|
|
1816
|
+
child.stdout?.setEncoding("utf8").on("data", (chunk) => stdout.push(chunk));
|
|
1817
|
+
child.stderr?.setEncoding("utf8").on("data", (chunk) => stderr.push(chunk));
|
|
1818
|
+
const timer = timeout > 0 ? setTimeout(() => {
|
|
1819
|
+
output("err", `The process "${[command, ...args].join(" ")}" exceeded the timeout of ${timeout} seconds.`);
|
|
1820
|
+
child.kill("SIGKILL");
|
|
1821
|
+
}, timeout * 1e3) : void 0;
|
|
1822
|
+
let settled = false;
|
|
1823
|
+
const settle = () => {
|
|
1824
|
+
if (settled) return false;
|
|
1825
|
+
settled = true;
|
|
1826
|
+
clearTimeout(timer);
|
|
1827
|
+
this.child = void 0;
|
|
1828
|
+
stdout.end();
|
|
1829
|
+
stderr.end();
|
|
1830
|
+
return true;
|
|
1831
|
+
};
|
|
1832
|
+
child.once("error", (error) => settle() && reject(error));
|
|
1833
|
+
child.once("close", () => settle() && resolve());
|
|
1834
|
+
});
|
|
1835
|
+
}
|
|
1836
|
+
async rest(seconds) {
|
|
1837
|
+
this.resting = new AbortController();
|
|
1838
|
+
try {
|
|
1839
|
+
await sleep2(seconds * 1e3, void 0, { signal: this.resting.signal });
|
|
1840
|
+
} catch {
|
|
1841
|
+
} finally {
|
|
1842
|
+
this.resting = void 0;
|
|
1843
|
+
}
|
|
1844
|
+
}
|
|
1845
|
+
};
|
|
1846
|
+
|
|
1667
1847
|
// console/discoverJobs.ts
|
|
1668
1848
|
import { existsSync, readdirSync, statSync } from "fs";
|
|
1669
1849
|
import { join } from "path";
|
|
@@ -1716,6 +1896,22 @@ function localTimestamp(date = /* @__PURE__ */ new Date()) {
|
|
|
1716
1896
|
const pad = (n) => String(n).padStart(2, "0");
|
|
1717
1897
|
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
|
1718
1898
|
}
|
|
1899
|
+
function processingMessage(queue) {
|
|
1900
|
+
return `Processing jobs from the [${queue}] ${Str.plural("queue", queue.split(",").length)}.`;
|
|
1901
|
+
}
|
|
1902
|
+
function listenerOptionsFrom(option) {
|
|
1903
|
+
const defaults = defaultListenerOptions();
|
|
1904
|
+
return {
|
|
1905
|
+
name: text(option("name")) ?? defaults.name,
|
|
1906
|
+
backoff: text(option("backoff")) ?? defaults.backoff,
|
|
1907
|
+
memory: number2(option("memory"), defaults.memory),
|
|
1908
|
+
timeout: number2(option("timeout"), defaults.timeout),
|
|
1909
|
+
sleep: number2(option("sleep"), defaults.sleep),
|
|
1910
|
+
maxTries: number2(option("tries"), defaults.maxTries),
|
|
1911
|
+
rest: number2(option("rest"), defaults.rest),
|
|
1912
|
+
stopWhenEmpty: option("stop-when-empty") === true
|
|
1913
|
+
};
|
|
1914
|
+
}
|
|
1719
1915
|
function workerOptionsFrom(option) {
|
|
1720
1916
|
const defaults = defaultWorkerOptions();
|
|
1721
1917
|
return {
|
|
@@ -1746,7 +1942,7 @@ function registerQueueCommands(kernel, context) {
|
|
|
1746
1942
|
return false;
|
|
1747
1943
|
};
|
|
1748
1944
|
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=
|
|
1945
|
+
"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=512 : The memory limit in megabytes, measured as V8 heap in use (a Node app on tsx uses about 115 MB at idle)} {--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
1946
|
"Start processing jobs on the queue as a daemon",
|
|
1751
1947
|
async (out) => {
|
|
1752
1948
|
const connection = text(out.argument("connection")) ?? defaultConnection();
|
|
@@ -1763,13 +1959,34 @@ function registerQueueCommands(kernel, context) {
|
|
|
1763
1959
|
exception: (error, job) => out.error(`${job ? `${name(job)}: ` : ""}${errorClass(error)}`)
|
|
1764
1960
|
});
|
|
1765
1961
|
const options = workerOptionsFrom((option) => out.option(option));
|
|
1766
|
-
out.info(
|
|
1962
|
+
out.info(processingMessage(queue));
|
|
1767
1963
|
if (out.option("once") === true) {
|
|
1768
1964
|
return worker.runNextJob(connection, queue, options);
|
|
1769
1965
|
}
|
|
1770
1966
|
return worker.daemon(connection, queue, options);
|
|
1771
1967
|
}
|
|
1772
1968
|
);
|
|
1969
|
+
define(
|
|
1970
|
+
"queue:listen {connection? : The name of connection} {--name=default : The name of the worker} {--backoff=0 : The number of seconds to wait before retrying a job that encountered an uncaught exception} {--memory=512 : The memory limit in megabytes, measured as V8 heap in use (a Node app on tsx uses about 115 MB at idle)} {--queue= : The queue to listen on} {--sleep=3 : Number of seconds to sleep when no job is available} {--rest=0 : Number of 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} {--stop-when-empty : Stop when the queue is empty}",
|
|
1971
|
+
"Listen to a given queue",
|
|
1972
|
+
async (out) => {
|
|
1973
|
+
const connection = text(out.argument("connection")) ?? defaultConnection();
|
|
1974
|
+
const queue = text(out.option("queue")) ?? defaultQueue(connection);
|
|
1975
|
+
const banner = processingMessage(queue);
|
|
1976
|
+
out.info(banner);
|
|
1977
|
+
const listener = new Listener(container.make(QueueManager3), {
|
|
1978
|
+
commandPath: context.app.basePath(),
|
|
1979
|
+
spawn: context.spawn,
|
|
1980
|
+
// Each `queue:work` starts with the same line as this command; it's shown once.
|
|
1981
|
+
output: (type, line) => {
|
|
1982
|
+
if (line === banner) return;
|
|
1983
|
+
if (type === "out") out.line(line);
|
|
1984
|
+
else out.error(line);
|
|
1985
|
+
}
|
|
1986
|
+
});
|
|
1987
|
+
return listener.listen(connection, queue, listenerOptionsFrom((option) => out.option(option)));
|
|
1988
|
+
}
|
|
1989
|
+
);
|
|
1773
1990
|
define("queue:restart", "Restart queue worker daemons after their current job", async (out) => {
|
|
1774
1991
|
if (!container.bound(CacheManager4)) {
|
|
1775
1992
|
out.error("queue:restart needs a cache store. Register the CacheServiceProvider.");
|
|
@@ -1930,6 +2147,7 @@ export {
|
|
|
1930
2147
|
JOBS_TABLE_MIGRATION,
|
|
1931
2148
|
JobClassNotFoundError,
|
|
1932
2149
|
JobSerializationError,
|
|
2150
|
+
Listener,
|
|
1933
2151
|
ManuallyFailedError,
|
|
1934
2152
|
MaxAttemptsExceededError,
|
|
1935
2153
|
MissingModelError,
|
|
@@ -1956,6 +2174,7 @@ export {
|
|
|
1956
2174
|
classNameOf,
|
|
1957
2175
|
createPayload,
|
|
1958
2176
|
decodePayload,
|
|
2177
|
+
defaultListenerOptions,
|
|
1959
2178
|
defaultWorkerOptions,
|
|
1960
2179
|
describeError,
|
|
1961
2180
|
discoverClasses,
|
|
@@ -1963,6 +2182,7 @@ export {
|
|
|
1963
2182
|
encodePayload,
|
|
1964
2183
|
formatTimestamp,
|
|
1965
2184
|
isModel,
|
|
2185
|
+
listenerOptionsFrom,
|
|
1966
2186
|
makeFailedJobProvider,
|
|
1967
2187
|
makeRedisClient,
|
|
1968
2188
|
normalizeBackoff,
|