@appweaver/skill 0.0.0-stage → 3.0.0

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.
@@ -0,0 +1,281 @@
1
+ # Queue
2
+
3
+ The queue module provides background job processing with support for workers, retries, and lifecycle event hooks. The
4
+ `BullQueue` driver (provider `bullmq`) of `@appweaver/bullmq` uses [BullMQ](https://docs.bullmq.io/) on the Redis
5
+ connection of the `Memory` provider, and is selected when the package is installed (it brings `@appweaver/redis`, and
6
+ requires `MEMORY_PROVIDER` resolving to `redis`).
7
+ Otherwise the `MemoryQueue` of core (provider `memory`) runs the jobs in the process, losing them on a restart, which a
8
+ production application logs as a warning on startup.
9
+
10
+ A queue worker needs no server: disable `@appweaver/web` (`APP_MODULES_DISABLED=@appweaver/web`), and its workers keep
11
+ the application running. Set `HEALTH_CHECK_PORT` to answer the health checks of its container.
12
+
13
+ ## Injecting Queue
14
+
15
+ ```ts
16
+ import { inject } from '@appweaver/core';
17
+ import { Queue } from '@appweaver/common';
18
+
19
+ const queue = inject(Queue);
20
+ ```
21
+
22
+ ---
23
+
24
+ ## `Queue` — manager
25
+
26
+ #### `queue.get<Data, Response>(name)`
27
+
28
+ Returns a `QueueProcessor` for the named queue. Creates the queue if it does not exist yet.
29
+
30
+ ```ts
31
+ const emailQueue = queue.get<EmailJobData, void>('emails');
32
+ ```
33
+
34
+ #### `queue.close(name)`
35
+
36
+ Closes a named queue and releases its resources. Returns `true` if closed.
37
+
38
+ ```ts
39
+ await queue.close('emails');
40
+ ```
41
+
42
+ #### `queue.closeAll()`
43
+
44
+ Closes all open queues.
45
+
46
+ ```ts
47
+ await queue.closeAll();
48
+ ```
49
+
50
+ #### `queue.checkHealth()`
51
+
52
+ Returns a `HealthCheckResult` indicating whether the underlying queue backend is reachable.
53
+
54
+ ### Unavailable backend
55
+
56
+ `BullQueue` needs Redis and has no fallback. The application still starts while Redis is down, but `sendJob` and
57
+ `sendBulkJobs` throw a `QueueError` with the `QUEUE_UNAVAILABLE` code right away instead of waiting for
58
+ the reconnection, so callers that must not fail should catch it. Workers pick jobs up again once Redis reconnects.
59
+
60
+ ---
61
+
62
+ ## `QueueProcessor` — per-queue API
63
+
64
+ Obtained via `queue.get(name)`.
65
+
66
+ #### `processor.sendJob(data, name?, options?)`
67
+
68
+ Enqueues a single job. Returns the created `QueueJob`. A `jobId` is the identity of the job in the queue: a send with
69
+ the id of a job still in it (waiting, delayed, running, or a finished job the queue keeps) is ignored and returns the
70
+ existing job, with every driver, so a send can be made idempotent (``{ jobId: `invoice-${id}` }``).
71
+
72
+ | Parameter | Type | Description |
73
+ | --------- | ----------------- | ---------------------------- |
74
+ | `data` | `Data` | Job payload |
75
+ | `name` | `string` | Optional job name/type label |
76
+ | `options` | `QueueJobOptions` | Job options, see below |
77
+
78
+ **`QueueJobOptions`** (the same for every queue):
79
+
80
+ | Field | Type | Description |
81
+ | ----------------- | --------------------------------------------------- | --------------------------------------------------------- |
82
+ | `delay` | `number` | Milliseconds to wait before the job is processed |
83
+ | `attempts` | `number` | Attempts, the first one included (`QUEUE_RETRY_ATTEMPTS`) |
84
+ | `backoff` | `{ type: 'fixed' \| 'exponential'; delay: number }` | Wait between the attempts (`QUEUE_RETRY_BACKOFF*`) |
85
+ | `priority` | `number` | A lower number is processed first |
86
+ | `jobId` | `string` | A custom job id |
87
+ | `providerOptions` | `Record<string, unknown>` | Options of the driver, i.e. the `JobsOptions` of BullMQ |
88
+
89
+ ```ts
90
+ const job = await emailQueue.sendJob(
91
+ { to: 'alice@example.com', template: 'welcome' },
92
+ 'welcome',
93
+ { delay: 60_000 }
94
+ );
95
+ ```
96
+
97
+ #### `processor.sendBulkJobs(jobs)`
98
+
99
+ Enqueues multiple jobs in a single call. Returns an array of created `QueueJob` instances.
100
+
101
+ ```ts
102
+ await emailQueue.sendBulkJobs([
103
+ { data: { to: 'alice@example.com', template: 'welcome' } },
104
+ { data: { to: 'bob@example.com', template: 'welcome' } }
105
+ ]);
106
+ ```
107
+
108
+ #### `processor.addWorker(processor, options?)`
109
+
110
+ Registers a worker function that processes jobs from the queue. Returns the created worker handle. The
111
+ `QueueWorkerOptions` take the `concurrency` (jobs processed at once) and the `providerOptions` of the driver.
112
+
113
+ ```ts
114
+ emailQueue.addWorker(
115
+ async (job) => {
116
+ await sendEmail(job.data.to, job.data.template);
117
+ },
118
+ { concurrency: 5 }
119
+ );
120
+ ```
121
+
122
+ #### `processor.removeWorker(id)`
123
+
124
+ Removes a registered worker by ID.
125
+
126
+ ```ts
127
+ await emailQueue.removeWorker(workerId);
128
+ ```
129
+
130
+ #### `processor.close()`
131
+
132
+ Closes this processor and its workers.
133
+
134
+ ---
135
+
136
+ ## Event listeners
137
+
138
+ Each listener registration method returns a listener ID. Pass it to `removeListener` to unsubscribe.
139
+
140
+ | Method | Trigger |
141
+ | ---------------------- | -------------------------------------- |
142
+ | `onCompleted(handler)` | Job finished successfully |
143
+ | `onFailed(handler)` | Job failed (BullMQ: every attempt) |
144
+ | `onError(handler)` | Worker or queue error |
145
+ | `onProgress(handler)` | Job reported progress |
146
+ | `onActive(handler)` | Job moved from waiting to active |
147
+ | `onStalled(handler)` | Job stalled (worker did not heartbeat) |
148
+ | `onDrained(handler)` | Queue became empty |
149
+ | `onReady(handler)` | Queue is ready to process jobs |
150
+ | `onPaused(handler)` | Queue was paused |
151
+ | `onResumed(handler)` | Queue was resumed |
152
+ | `onClosing(handler)` | Queue is closing |
153
+ | `onClosed(handler)` | Queue closed |
154
+
155
+ ```ts
156
+ const listenerId = emailQueue.onCompleted((job, result) => {
157
+ logger.info(`Email job ${job.id} completed`);
158
+ });
159
+
160
+ emailQueue.onFailed((job, err) => {
161
+ logger.error(err, `Email job failed:`);
162
+ });
163
+
164
+ // Unsubscribe later
165
+ emailQueue.removeListener(listenerId);
166
+ ```
167
+
168
+ The memory queue calls the `onFailed` handlers once a job failed its last attempt, BullMQ after every attempt:
169
+ `processor.willRetry(job)` tells a failure that is retried apart.
170
+
171
+ ### Waiting for a job on any instance
172
+
173
+ `JobResults` of `@appweaver/core` sends a job and waits for its result on whichever instance its worker runs, the way
174
+ `sendEmailAndWait`, `sendSmsAndWait` and `AiService.generateQueued` do. The waited job gets an ID of its own, and its
175
+ result (or the error of its last attempt) goes through the `PubSub` on the channel `queue:<name>:results`, straight to
176
+ the caller without a `PubSub`. Only the results of the waited jobs are published:
177
+
178
+ ```ts
179
+ const results = new JobResults(reportQueue, 'reports', {
180
+ toError: (error) => new Error(error.message)
181
+ });
182
+ const report = await results.wait((jobId) =>
183
+ reportQueue.sendJob(params, 'build', { jobId })
184
+ );
185
+ ```
186
+
187
+ A caller waits `queue.waitTimeout` (30 s) at most, its `timeout` option replacing it, for the subscription to the
188
+ results and the result together: beyond it the call fails with `QUEUE_JOB_TIMEOUT` (`504`), the job left to run, and a
189
+ subscription that never came is attempted again by the next call.
190
+
191
+ ---
192
+
193
+ ## `QueueJob` shape
194
+
195
+ ```ts
196
+ type QueueJob<Data, Response> = {
197
+ id?: string;
198
+ name: string;
199
+ data: Data;
200
+ returnvalue: Response;
201
+ };
202
+ ```
203
+
204
+ ---
205
+
206
+ ## Tracing
207
+
208
+ A job carries the OpenTelemetry trace context of the code that sent it, so the request, the `send <queue>` span, the
209
+ `process <queue>` span of every attempt and everything the worker does are one trace, across processes. Nothing is
210
+ needed in the application code, see [telemetry](./telemetry.md). A custom `Queue` driver wraps its send and its
211
+ processor with `traceQueueSend` and `traceQueueProcess` of `@appweaver/common`.
212
+
213
+ ---
214
+
215
+ ## Configuration
216
+
217
+ | Key | Type | Default | Description |
218
+ | ------------------------------ | -------- | --------- | ------------------------------------------------------------------------------------------------------------ |
219
+ | `QUEUE_PROVIDER` | `string` | `'auto'` | `auto` (`bullmq` with `@appweaver/bullmq`, otherwise `memory`), `memory`, `bullmq`, `none`, or a module path |
220
+ | `QUEUE_KEEP_COMPLETED_COUNT` | `int` | `0` | How many completed jobs to retain (0 = remove all) |
221
+ | `QUEUE_KEEP_COMPLETED` | duration? | - | How long to retain the completed jobs, milliseconds or a duration string (`'30d'`) |
222
+ | `QUEUE_KEEP_FAILED_COUNT` | `int` | `50` | How many failed jobs to retain for inspection |
223
+ | `QUEUE_KEEP_FAILED` | duration? | - | How long to retain the failed jobs, milliseconds or a duration string |
224
+ | `QUEUE_RETRY_ATTEMPTS` | `int` | `3` | Number of retry attempts on failure |
225
+ | `QUEUE_RETRY_BACKOFF` | duration | `3000` | Backoff delay, milliseconds or a duration string |
226
+ | `QUEUE_RETRY_BACKOFF_TYPE` | `enum` | `'fixed'` | `fixed` or `exponential` |
227
+
228
+ ### Keeping the finished jobs
229
+
230
+ BullMQ keeps the finished jobs of each queue in Redis by the `QUEUE_KEEP_*` keys, with a count and an age together (i.e.
231
+ `keepCompletedCount: 5000` and `keepCompleted: '30d'` keep at most 5000 jobs of the last 30 days),
232
+ which a dashboard such as Bull Board shows. The memory queue removes them right away. The queue keeps no audit trail:
233
+ a worker needs to record what it works on and the results in the database itself.
234
+
235
+ **Use `MemoryQueue` in the tests:**
236
+
237
+ ```json
238
+ {
239
+ "environments": {
240
+ "test": {
241
+ "queue": {
242
+ "provider": "memory"
243
+ }
244
+ }
245
+ }
246
+ }
247
+ ```
248
+
249
+ ---
250
+
251
+ ## Real-world example
252
+
253
+ ```ts
254
+ import { inject } from '@appweaver/core';
255
+ import { createLogger, Queue } from '@appweaver/common';
256
+
257
+ const logger = createLogger('reports');
258
+
259
+ type ReportJob = { userId: number; reportType: string };
260
+
261
+ export class ReportService {
262
+ private readonly _processor = inject(Queue).get<ReportJob, void>('reports');
263
+
264
+ constructor() {
265
+ this._processor.addWorker(async (job) => {
266
+ await generateReport(job.data.userId, job.data.reportType);
267
+ });
268
+
269
+ this._processor.onFailed((job, err) => {
270
+ logger.error(
271
+ err,
272
+ `Report generation failed for user ${job?.data.userId}:`
273
+ );
274
+ });
275
+ }
276
+
277
+ async requestReport(userId: number, reportType: string): Promise<void> {
278
+ await this._processor.sendJob({ userId, reportType });
279
+ }
280
+ }
281
+ ```