@orieljs/queue 0.1.0-alpha.5 → 0.1.0-alpha.7

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 CHANGED
@@ -7,3 +7,10 @@ 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.
13
+
14
+ @orieljs/notifications (and @orieljs/framework, which bundles it) includes the HTML and CSS of
15
+ Laravel's default notification mail (laravel/framework, https://github.com/laravel/framework),
16
+ Copyright (c) Taylor Otwell, MIT License.
package/README.md ADDED
@@ -0,0 +1,37 @@
1
+ # @orieljs/queue
2
+
3
+ Queues for Oriel: run slow work, such as sending mail or processing a file, in a worker process instead of during the request, as Laravel's queues. It is part of `@orieljs/framework`, which every Oriel app already installs, and is re-exported from it. In an app, import it from `@orieljs/framework`; `@orieljs/queue` is also published on its own.
4
+
5
+ ```bash
6
+ npm install @orieljs/framework
7
+ ```
8
+
9
+ ```ts title="app/Jobs/ProcessPodcast.ts"
10
+ import { Log, Queueable } from '@orieljs/framework'
11
+ import type { Podcast } from '../Models/Podcast'
12
+
13
+ export class ProcessPodcast extends Queueable {
14
+ tries = 3
15
+ backoff = [10, 60]
16
+
17
+ constructor(public podcast: Podcast) {
18
+ super()
19
+ }
20
+
21
+ async handle(): Promise<void> {
22
+ Log.info('Processing a podcast', { file: this.podcast.audio_path })
23
+ }
24
+ }
25
+ ```
26
+
27
+ Dispatch a job with `await ProcessPodcast.dispatch(podcast)`, adding `delay()`, `onQueue()` or `onConnection()`, and run `node oriel queue:work` to process it. Connections use the `sync`, `database`, `redis` or `null` driver (`config/queue.ts`), and the `Queue` facade pushes jobs directly. Failed jobs are stored for `queue:failed` and `queue:retry`, and `WithoutOverlapping` is a job middleware.
28
+
29
+ Documentation: https://orieljs.vercel.app/docs/queues
30
+
31
+ Status: early alpha. APIs will change.
32
+
33
+ ## License
34
+
35
+ Oriel is open-source software licensed under the Apache License 2.0 (Apache-2.0; see `LICENSE` and `NOTICE`). The Oriel name and logo are trademarks; see `TRADEMARKS.md`.
36
+
37
+ Website: https://orieljs.vercel.app
package/TRADEMARKS.md ADDED
@@ -0,0 +1,33 @@
1
+ # Oriel trademark policy
2
+
3
+ The Oriel code is open source under the Apache License 2.0. The **Oriel name and logo** are not: the license covers
4
+ the code only (section 6 of the license says so), and the name and logo stay with the project. This page explains
5
+ what you can and can't do with them. The goal is simple: people should always be able to tell what is the real Oriel
6
+ and what isn't.
7
+
8
+ ## You can, without asking
9
+
10
+ - Use, change, ship and sell the code, as the license allows.
11
+ - Say that your app or package is "built with Oriel", "for Oriel" or "compatible with Oriel".
12
+ - Name a package `oriel-<something>` or `<something>-for-oriel` when it works with Oriel, as long as it is clear that
13
+ it is not official (for example, don't publish it under the `@orieljs` npm scope).
14
+ - Use the name and logo to write about Oriel, teach it, or link to it, in articles, talks, videos and courses.
15
+ - Use the unmodified logo to point to the project, as it is (no recolouring, cropping or
16
+ distortion).
17
+
18
+ ## You can't, without written permission
19
+
20
+ - Call a fork, a modified copy or a competing product "Oriel", or anything likely to be confused with it.
21
+ - Use the name or logo as the name, logo or domain of your own product, company or service.
22
+ - Suggest that the Oriel project made, endorses or supports your work when it doesn't.
23
+ - Sell merchandise with the name or logo.
24
+
25
+ ## Forks
26
+
27
+ Forks are welcome. Please give yours a different name and logo, keep the `LICENSE` and `NOTICE` files, and say that
28
+ it is based on Oriel.
29
+
30
+ ## Questions
31
+
32
+ Open an issue at https://github.com/orieljs/framework or email meeeet.dev@gmail.com. If you're unsure whether a use
33
+ is fine, ask; the answer is usually yes.
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 }`; other class instances keep their
93
- * class name and fields; Date, Map, Set and byte arrays (any ArrayBuffer view, as base64) are tagged. Functions,
94
- * symbols, bigints, unsaved models and cycles throw.
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; a missing one throws
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
- /** MB of V8 heap after which the worker stops (exit 12). 0 disables the check. */
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;
@@ -578,6 +584,10 @@ declare class Worker {
578
584
  /** F2: the promise handling the most recently leaked unhandled rejection, awaited by process() before it decides
579
585
  * whether the job succeeded, so failing it is never racing the "processed" event. */
580
586
  private pendingRejection;
587
+ /** Laravel's $lastRestart: the restart flag when the daemon started, or UNREAD while the cache can't be read. */
588
+ private lastRestart;
589
+ /** Whether the last read of the restart flag failed, so an outage is reported once rather than after every job. */
590
+ private restartFlagFailing;
581
591
  constructor(manager: QueueManager$1, container: Container, listener?: WorkerListener);
582
592
  /** Runs until a stop condition; returns the exit code. `queue` may be a comma-separated priority list. */
583
593
  daemon(connectionName: string, queue: string, options: WorkerOptions): Promise<number>;
@@ -610,7 +620,13 @@ declare class Worker {
610
620
  private calculateBackoff;
611
621
  private stopIfNecessary;
612
622
  memoryExceeded(limitMb: number): boolean;
623
+ /**
624
+ * Laravel's queueShouldRestart(), except that a cache that fails doesn't stop the worker: while the flag can't be
625
+ * read the worker keeps going, and when it couldn't be read at start, the first value read becomes the baseline,
626
+ * so a queue:restart broadcast after that still stops it.
627
+ */
613
628
  private queueShouldRestart;
629
+ /** The restart flag, or UNREAD when the cache fails (reported once per outage, never thrown). */
614
630
  private getTimestampOfLastQueueRestart;
615
631
  /** Reports through the ExceptionHandler when bound, and tells the listener. Never throws. */
616
632
  private report;
@@ -622,6 +638,68 @@ declare class Worker {
622
638
  private handleUnhandledRejection;
623
639
  }
624
640
 
641
+ /** `queue:listen` options (Laravel's ListenerOptions). Seconds unless noted. */
642
+ interface ListenerOptions {
643
+ name: string;
644
+ /** Passed on to each `queue:work`: seconds before a failed job is retried. */
645
+ backoff: number | number[] | string;
646
+ /** MB of V8 heap, passed on to each `queue:work`; the listener also stops once its own heap reaches it. */
647
+ memory: number;
648
+ /** Seconds a process may run before the listener kills it, also passed on as the job's timeout. 0 disables it. */
649
+ timeout: number;
650
+ /** Passed on to each `queue:work`: seconds it sleeps when no job is available. */
651
+ sleep: number;
652
+ /** Passed on to each `queue:work` as `--tries`. */
653
+ maxTries: number;
654
+ /** Seconds to rest between processes. */
655
+ rest: number;
656
+ /** Stop once every listed queue is empty (not in Laravel's queue:listen; queue:work has it). */
657
+ stopWhenEmpty: boolean;
658
+ }
659
+ declare const defaultListenerOptions: () => ListenerOptions;
660
+ /** node:child_process's spawn(), replaceable in tests. */
661
+ type SpawnWorker = (command: string, args: string[], options: SpawnOptions) => ChildProcess;
662
+ /** Receives each line a worker process prints, from its stdout ('out') or its stderr ('err'). */
663
+ type ListenerOutput = (type: 'out' | 'err', line: string) => void;
664
+ interface ListenerConfig {
665
+ /** The folder the processes run in: the app's base path (Laravel's commandPath). */
666
+ commandPath: string;
667
+ /** The app's CLI: this process's runtime, its flags and its script by default (`node oriel`, `bun oriel`). */
668
+ runtime?: {
669
+ command: string;
670
+ args: string[];
671
+ };
672
+ output?: ListenerOutput;
673
+ spawn?: SpawnWorker;
674
+ }
675
+ /**
676
+ * Laravel's Illuminate\Queue\Listener: runs `queue:work --once` in a new process, again and again, so every job runs
677
+ * in a fresh process and code changes apply to the next job without a restart. Each process's output is passed on
678
+ * line by line. Unlike Laravel's, it also passes `--timeout` on (Laravel's processes keep the 60-second default), a
679
+ * process that outlives `--timeout` is killed and reported while the listener carries on (Laravel's throws), and a
680
+ * stop signal is passed to the running process before the listener returns.
681
+ */
682
+ declare class Listener {
683
+ private readonly manager;
684
+ private readonly config;
685
+ static readonly EXIT_SUCCESS = 0;
686
+ private shouldQuit;
687
+ private child;
688
+ private resting;
689
+ constructor(manager: QueueManager$1, config: ListenerConfig);
690
+ /** Runs until stopped, the queue is empty (with stopWhenEmpty) or the memory limit is reached. Returns the exit code. */
691
+ listen(connection: string, queue: string, options: ListenerOptions): Promise<number>;
692
+ /** Laravel's createCommand(): the runtime, the CLI script and `queue:work <connection> --once …`, plus `--timeout`. */
693
+ makeCommand(connection: string, queue: string, options: ListenerOptions): string[];
694
+ /** Stops after the running process, which gets the same signal (SIGTERM/SIGINT/SIGQUIT call this). */
695
+ stop(signal?: NodeJS.Signals): void;
696
+ memoryExceeded(limitMb: number): boolean;
697
+ private listenForSignals;
698
+ private isEmpty;
699
+ private runProcess;
700
+ private rest;
701
+ }
702
+
625
703
  /** The app directories whose classes travel inside wrapper jobs (queued listeners, mailables, notifications). */
626
704
  declare const WORKER_DISCOVERY_DIRECTORIES: readonly ["Events", "Listeners", "Mail", "Notifications"];
627
705
  /**
@@ -636,9 +714,13 @@ declare function discoverClasses(directory: string, registry: ClassRegistry, fil
636
714
  declare function discoverJobs(directory: string, registry: ClassRegistry): Promise<string[]>;
637
715
 
638
716
  interface QueueCommandContext {
639
- app: Pick<Application, 'isProduction' | 'appPath'>;
717
+ app: Pick<Application, 'isProduction' | 'appPath' | 'basePath'>;
640
718
  container: Container;
719
+ /** How queue:listen starts its processes (node:child_process's spawn by default). */
720
+ spawn?: SpawnWorker;
641
721
  }
722
+ /** Laravel's queue:listen options from the parsed command options. */
723
+ declare function listenerOptionsFrom(option: (name: string) => unknown): ListenerOptions;
642
724
  /** Laravel's queue:work options from the parsed command options. */
643
725
  declare function workerOptionsFrom(option: (name: string) => unknown): WorkerOptions;
644
726
  /** The queue:* commands, registered as closure commands (PC1). */
@@ -660,4 +742,4 @@ declare class QueueServiceProvider extends ServiceProvider {
660
742
  boot(): void;
661
743
  }
662
744
 
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 };
745
+ 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
- return { [TAG]: "model", class: name2, key: serializeValue(object.getKey(), registry, `${path}.key`, seen) ?? null };
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 query = typeof model.withoutGlobalScopes === "function" ? model.withoutGlobalScopes() : model;
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: 128,
1448
+ memory: 512,
1409
1449
  timeout: 60,
1410
1450
  sleep: 3,
1411
1451
  maxTries: 1,
@@ -1415,6 +1455,7 @@ var defaultWorkerOptions = () => ({
1415
1455
  rest: 0
1416
1456
  });
1417
1457
  var RESTART_CACHE_KEY = "oriel:queue:restart";
1458
+ var UNREAD = /* @__PURE__ */ Symbol("unread");
1418
1459
  var Worker = class _Worker {
1419
1460
  constructor(manager, container, listener = {}) {
1420
1461
  this.manager = manager;
@@ -1434,12 +1475,16 @@ var Worker = class _Worker {
1434
1475
  /** F2: the promise handling the most recently leaked unhandled rejection, awaited by process() before it decides
1435
1476
  * whether the job succeeded, so failing it is never racing the "processed" event. */
1436
1477
  pendingRejection;
1478
+ /** Laravel's $lastRestart: the restart flag when the daemon started, or UNREAD while the cache can't be read. */
1479
+ lastRestart = UNREAD;
1480
+ /** Whether the last read of the restart flag failed, so an outage is reported once rather than after every job. */
1481
+ restartFlagFailing = false;
1437
1482
  /** Runs until a stop condition; returns the exit code. `queue` may be a comma-separated priority list. */
1438
1483
  async daemon(connectionName, queue, options) {
1439
1484
  const stopListening = this.listenForSignals();
1440
1485
  try {
1441
1486
  const startTime = Date.now();
1442
- const lastRestart = await this.getTimestampOfLastQueueRestart();
1487
+ this.lastRestart = await this.getTimestampOfLastQueueRestart();
1443
1488
  let jobsProcessed = 0;
1444
1489
  for (; ; ) {
1445
1490
  const job = await this.getNextJob(connectionName, queue);
@@ -1450,7 +1495,7 @@ var Worker = class _Worker {
1450
1495
  } else if (!options.stopWhenEmpty) {
1451
1496
  await this.sleep(options.sleep);
1452
1497
  }
1453
- const status = await this.stopIfNecessary(options, lastRestart, startTime, jobsProcessed, job);
1498
+ const status = await this.stopIfNecessary(options, startTime, jobsProcessed, job);
1454
1499
  if (status !== void 0) return status;
1455
1500
  }
1456
1501
  } finally {
@@ -1618,11 +1663,11 @@ var Worker = class _Worker {
1618
1663
  const backoff = job.backoff() ?? normalizeBackoff(options.backoff) ?? [0];
1619
1664
  return backoff[job.attempts() - 1] ?? backoff.at(-1) ?? 0;
1620
1665
  }
1621
- async stopIfNecessary(options, lastRestart, startTime, jobsProcessed, job) {
1666
+ async stopIfNecessary(options, startTime, jobsProcessed, job) {
1622
1667
  if (this.shouldQuit) return _Worker.EXIT_SUCCESS;
1623
1668
  if (this.timedOut) return _Worker.EXIT_ERROR;
1624
1669
  if (this.memoryExceeded(options.memory)) return _Worker.EXIT_MEMORY_LIMIT;
1625
- if (await this.queueShouldRestart(lastRestart)) return _Worker.EXIT_SUCCESS;
1670
+ if (await this.queueShouldRestart()) return _Worker.EXIT_SUCCESS;
1626
1671
  if (options.stopWhenEmpty && !job) return _Worker.EXIT_SUCCESS;
1627
1672
  if (options.maxTime > 0 && Date.now() - startTime >= options.maxTime * 1e3) return _Worker.EXIT_SUCCESS;
1628
1673
  if (options.maxJobs > 0 && jobsProcessed >= options.maxJobs) return _Worker.EXIT_SUCCESS;
@@ -1631,12 +1676,32 @@ var Worker = class _Worker {
1631
1676
  memoryExceeded(limitMb) {
1632
1677
  return limitMb > 0 && process.memoryUsage().heapUsed / 1024 / 1024 >= limitMb;
1633
1678
  }
1634
- async queueShouldRestart(lastRestart) {
1635
- return await this.getTimestampOfLastQueueRestart() !== lastRestart;
1679
+ /**
1680
+ * Laravel's queueShouldRestart(), except that a cache that fails doesn't stop the worker: while the flag can't be
1681
+ * read the worker keeps going, and when it couldn't be read at start, the first value read becomes the baseline,
1682
+ * so a queue:restart broadcast after that still stops it.
1683
+ */
1684
+ async queueShouldRestart() {
1685
+ const current = await this.getTimestampOfLastQueueRestart();
1686
+ if (current === UNREAD) return false;
1687
+ if (this.lastRestart === UNREAD) {
1688
+ this.lastRestart = current;
1689
+ return false;
1690
+ }
1691
+ return current !== this.lastRestart;
1636
1692
  }
1693
+ /** The restart flag, or UNREAD when the cache fails (reported once per outage, never thrown). */
1637
1694
  async getTimestampOfLastQueueRestart() {
1638
1695
  if (!this.container.bound(CacheManager3)) return void 0;
1639
- return this.container.make(CacheManager3).get(RESTART_CACHE_KEY);
1696
+ try {
1697
+ const value = await this.container.make(CacheManager3).get(RESTART_CACHE_KEY);
1698
+ this.restartFlagFailing = false;
1699
+ return value;
1700
+ } catch (error) {
1701
+ if (!this.restartFlagFailing) await this.report(error);
1702
+ this.restartFlagFailing = true;
1703
+ return UNREAD;
1704
+ }
1640
1705
  }
1641
1706
  /** Reports through the ExceptionHandler when bound, and tells the listener. Never throws. */
1642
1707
  async report(error, job) {
@@ -1664,6 +1729,146 @@ var Worker = class _Worker {
1664
1729
  }
1665
1730
  };
1666
1731
 
1732
+ // Listener.ts
1733
+ import { spawn as spawnProcess } from "child_process";
1734
+ import { setTimeout as sleep2 } from "timers/promises";
1735
+ var defaultListenerOptions = () => ({
1736
+ name: "default",
1737
+ backoff: 0,
1738
+ memory: 512,
1739
+ timeout: 60,
1740
+ sleep: 3,
1741
+ maxTries: 1,
1742
+ rest: 0,
1743
+ stopWhenEmpty: false
1744
+ });
1745
+ function lineSplitter(emit) {
1746
+ let rest = "";
1747
+ return {
1748
+ push(chunk) {
1749
+ const lines = (rest + chunk).split("\n");
1750
+ rest = lines.pop() ?? "";
1751
+ for (const line of lines) emit(line.endsWith("\r") ? line.slice(0, -1) : line);
1752
+ },
1753
+ end() {
1754
+ if (rest !== "") emit(rest);
1755
+ rest = "";
1756
+ }
1757
+ };
1758
+ }
1759
+ function currentRuntime() {
1760
+ const script = process.argv[1];
1761
+ if (script === void 0) throw new QueueError("queue:listen can't tell which script started this process, so it can't start workers.");
1762
+ return { command: process.execPath, args: [...process.execArgv, script] };
1763
+ }
1764
+ var Listener = class _Listener {
1765
+ constructor(manager, config) {
1766
+ this.manager = manager;
1767
+ this.config = config;
1768
+ }
1769
+ manager;
1770
+ config;
1771
+ static EXIT_SUCCESS = 0;
1772
+ shouldQuit = false;
1773
+ child;
1774
+ resting;
1775
+ /** Runs until stopped, the queue is empty (with stopWhenEmpty) or the memory limit is reached. Returns the exit code. */
1776
+ async listen(connection, queue, options) {
1777
+ const stopListening = this.listenForSignals();
1778
+ try {
1779
+ const command = this.makeCommand(connection, queue, options);
1780
+ while (!this.shouldQuit) {
1781
+ if (options.stopWhenEmpty && await this.isEmpty(connection, queue)) break;
1782
+ if (this.shouldQuit) break;
1783
+ await this.runProcess(command, options.timeout);
1784
+ if (this.shouldQuit || this.memoryExceeded(options.memory)) break;
1785
+ if (options.rest > 0) await this.rest(options.rest);
1786
+ }
1787
+ return _Listener.EXIT_SUCCESS;
1788
+ } finally {
1789
+ stopListening();
1790
+ }
1791
+ }
1792
+ /** Laravel's createCommand(): the runtime, the CLI script and `queue:work <connection> --once …`, plus `--timeout`. */
1793
+ makeCommand(connection, queue, options) {
1794
+ const { command, args } = this.config.runtime ?? currentRuntime();
1795
+ const backoff = Array.isArray(options.backoff) ? options.backoff.join(",") : String(options.backoff);
1796
+ return [
1797
+ command,
1798
+ ...args,
1799
+ "queue:work",
1800
+ connection,
1801
+ "--once",
1802
+ `--name=${options.name}`,
1803
+ `--queue=${queue}`,
1804
+ `--backoff=${backoff}`,
1805
+ `--memory=${options.memory}`,
1806
+ `--sleep=${options.sleep}`,
1807
+ `--tries=${options.maxTries}`,
1808
+ `--timeout=${options.timeout}`
1809
+ ];
1810
+ }
1811
+ /** Stops after the running process, which gets the same signal (SIGTERM/SIGINT/SIGQUIT call this). */
1812
+ stop(signal = "SIGTERM") {
1813
+ this.shouldQuit = true;
1814
+ this.child?.kill(signal);
1815
+ this.resting?.abort();
1816
+ }
1817
+ memoryExceeded(limitMb) {
1818
+ return limitMb > 0 && process.memoryUsage().heapUsed / 1024 / 1024 >= limitMb;
1819
+ }
1820
+ listenForSignals() {
1821
+ const signals = ["SIGTERM", "SIGINT", "SIGQUIT"];
1822
+ const handlers = signals.map((signal) => [signal, () => this.stop(signal)]);
1823
+ for (const [signal, handler] of handlers) process.on(signal, handler);
1824
+ return () => {
1825
+ for (const [signal, handler] of handlers) process.off(signal, handler);
1826
+ };
1827
+ }
1828
+ async isEmpty(connection, queue) {
1829
+ const queues = this.manager.connection(connection);
1830
+ for (const name of queue.split(",")) if (await queues.size(name.trim()) > 0) return false;
1831
+ return true;
1832
+ }
1833
+ runProcess([command, ...args], timeout) {
1834
+ const output = this.config.output ?? (() => {
1835
+ });
1836
+ return new Promise((resolve, reject) => {
1837
+ const child = (this.config.spawn ?? spawnProcess)(command, args, { cwd: this.config.commandPath, env: process.env, stdio: ["ignore", "pipe", "pipe"] });
1838
+ this.child = child;
1839
+ const stdout = lineSplitter((line) => output("out", line));
1840
+ const stderr = lineSplitter((line) => output("err", line));
1841
+ child.stdout?.setEncoding("utf8").on("data", (chunk) => stdout.push(chunk));
1842
+ child.stderr?.setEncoding("utf8").on("data", (chunk) => stderr.push(chunk));
1843
+ const timer = timeout > 0 ? setTimeout(() => {
1844
+ output("err", `The process "${[command, ...args].join(" ")}" exceeded the timeout of ${timeout} seconds.`);
1845
+ child.kill("SIGKILL");
1846
+ }, timeout * 1e3) : void 0;
1847
+ let settled = false;
1848
+ const settle = () => {
1849
+ if (settled) return false;
1850
+ settled = true;
1851
+ clearTimeout(timer);
1852
+ this.child = void 0;
1853
+ stdout.end();
1854
+ stderr.end();
1855
+ return true;
1856
+ };
1857
+ child.once("error", (error) => settle() && reject(error));
1858
+ child.once("close", () => settle() && resolve());
1859
+ });
1860
+ }
1861
+ async rest(seconds) {
1862
+ this.resting = new AbortController();
1863
+ try {
1864
+ await sleep2(seconds * 1e3, void 0, { signal: this.resting.signal });
1865
+ } catch {
1866
+ } finally {
1867
+ this.resting = void 0;
1868
+ }
1869
+ }
1870
+ };
1871
+
1667
1872
  // console/discoverJobs.ts
1668
1873
  import { existsSync, readdirSync, statSync } from "fs";
1669
1874
  import { join } from "path";
@@ -1716,6 +1921,22 @@ function localTimestamp(date = /* @__PURE__ */ new Date()) {
1716
1921
  const pad = (n) => String(n).padStart(2, "0");
1717
1922
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
1718
1923
  }
1924
+ function processingMessage(queue) {
1925
+ return `Processing jobs from the [${queue}] ${Str.plural("queue", queue.split(",").length)}.`;
1926
+ }
1927
+ function listenerOptionsFrom(option) {
1928
+ const defaults = defaultListenerOptions();
1929
+ return {
1930
+ name: text(option("name")) ?? defaults.name,
1931
+ backoff: text(option("backoff")) ?? defaults.backoff,
1932
+ memory: number2(option("memory"), defaults.memory),
1933
+ timeout: number2(option("timeout"), defaults.timeout),
1934
+ sleep: number2(option("sleep"), defaults.sleep),
1935
+ maxTries: number2(option("tries"), defaults.maxTries),
1936
+ rest: number2(option("rest"), defaults.rest),
1937
+ stopWhenEmpty: option("stop-when-empty") === true
1938
+ };
1939
+ }
1719
1940
  function workerOptionsFrom(option) {
1720
1941
  const defaults = defaultWorkerOptions();
1721
1942
  return {
@@ -1746,7 +1967,7 @@ function registerQueueCommands(kernel, context) {
1746
1967
  return false;
1747
1968
  };
1748
1969
  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}",
1970
+ "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
1971
  "Start processing jobs on the queue as a daemon",
1751
1972
  async (out) => {
1752
1973
  const connection = text(out.argument("connection")) ?? defaultConnection();
@@ -1763,13 +1984,34 @@ function registerQueueCommands(kernel, context) {
1763
1984
  exception: (error, job) => out.error(`${job ? `${name(job)}: ` : ""}${errorClass(error)}`)
1764
1985
  });
1765
1986
  const options = workerOptionsFrom((option) => out.option(option));
1766
- out.info(`Processing jobs from the [${queue}] ${Str.plural("queue", queue.split(",").length)}.`);
1987
+ out.info(processingMessage(queue));
1767
1988
  if (out.option("once") === true) {
1768
1989
  return worker.runNextJob(connection, queue, options);
1769
1990
  }
1770
1991
  return worker.daemon(connection, queue, options);
1771
1992
  }
1772
1993
  );
1994
+ define(
1995
+ "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}",
1996
+ "Listen to a given queue",
1997
+ async (out) => {
1998
+ const connection = text(out.argument("connection")) ?? defaultConnection();
1999
+ const queue = text(out.option("queue")) ?? defaultQueue(connection);
2000
+ const banner = processingMessage(queue);
2001
+ out.info(banner);
2002
+ const listener = new Listener(container.make(QueueManager3), {
2003
+ commandPath: context.app.basePath(),
2004
+ spawn: context.spawn,
2005
+ // Each `queue:work` starts with the same line as this command; it's shown once.
2006
+ output: (type, line) => {
2007
+ if (line === banner) return;
2008
+ if (type === "out") out.line(line);
2009
+ else out.error(line);
2010
+ }
2011
+ });
2012
+ return listener.listen(connection, queue, listenerOptionsFrom((option) => out.option(option)));
2013
+ }
2014
+ );
1773
2015
  define("queue:restart", "Restart queue worker daemons after their current job", async (out) => {
1774
2016
  if (!container.bound(CacheManager4)) {
1775
2017
  out.error("queue:restart needs a cache store. Register the CacheServiceProvider.");
@@ -1905,6 +2147,10 @@ var QueueServiceProvider = class extends ServiceProvider {
1905
2147
  this.app.singleton(QueueManagerToken, (container) => new QueueManager2(container));
1906
2148
  this.app.singleton(QueueManager2, (container) => container.make(QueueManagerToken));
1907
2149
  this.app.singleton(FailedJobProvider4, (container) => makeFailedJobProvider(container));
2150
+ this.app.onShutdown(async () => {
2151
+ if (!this.app.resolved(QueueManagerToken)) return;
2152
+ await this.app.make(QueueManagerToken).disconnectAll?.();
2153
+ });
1908
2154
  if (this.app.bound(DatabaseManager2)) {
1909
2155
  this.app.singleton(BatchRepository2, (container) => {
1910
2156
  const config = container.make(ConfigRepository3);
@@ -1930,6 +2176,7 @@ export {
1930
2176
  JOBS_TABLE_MIGRATION,
1931
2177
  JobClassNotFoundError,
1932
2178
  JobSerializationError,
2179
+ Listener,
1933
2180
  ManuallyFailedError,
1934
2181
  MaxAttemptsExceededError,
1935
2182
  MissingModelError,
@@ -1956,6 +2203,7 @@ export {
1956
2203
  classNameOf,
1957
2204
  createPayload,
1958
2205
  decodePayload,
2206
+ defaultListenerOptions,
1959
2207
  defaultWorkerOptions,
1960
2208
  describeError,
1961
2209
  discoverClasses,
@@ -1963,6 +2211,7 @@ export {
1963
2211
  encodePayload,
1964
2212
  formatTimestamp,
1965
2213
  isModel,
2214
+ listenerOptionsFrom,
1966
2215
  makeFailedJobProvider,
1967
2216
  makeRedisClient,
1968
2217
  normalizeBackoff,