@sigil-dev/plugin-jobs 0.9.20 → 0.9.22
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/README.md +159 -154
- package/index.ts +480 -452
- package/package.json +3 -3
- package/queue.ts +396 -396
- package/store-bun.ts +137 -137
- package/store-drizzle.ts +86 -86
- package/store.ts +117 -117
- package/worker.ts +128 -128
package/index.ts
CHANGED
|
@@ -1,452 +1,480 @@
|
|
|
1
|
-
import type { CliCommand, GrimoirePlugin } from "@sigil-dev/grimoire";
|
|
2
|
-
import { database } from "@sigil-dev/plugin-sql";
|
|
3
|
-
import { JobQueue } from "./queue.ts";
|
|
4
|
-
import { databaseStore } from "./store-bun.ts";
|
|
5
|
-
import {
|
|
6
|
-
everyMs,
|
|
7
|
-
type EnqueueOptions,
|
|
8
|
-
type Every,
|
|
9
|
-
type JobHandler,
|
|
10
|
-
type JobStore,
|
|
11
|
-
type PayloadOf,
|
|
12
|
-
} from "./store.ts";
|
|
13
|
-
import { JobWorker } from "./worker.ts";
|
|
14
|
-
|
|
15
|
-
export { JobQueue, SCHEMA } from "./queue.ts";
|
|
16
|
-
export type {
|
|
17
|
-
Capabilities,
|
|
18
|
-
EnqueueOptions,
|
|
19
|
-
Every,
|
|
20
|
-
JobContext,
|
|
21
|
-
JobHandler,
|
|
22
|
-
PayloadOf,
|
|
23
|
-
JobRow,
|
|
24
|
-
JobStats,
|
|
25
|
-
JobStore,
|
|
26
|
-
} from "./store.ts";
|
|
27
|
-
export { bunSqlStore, bunStore, databaseStore } from "./store-bun.ts";
|
|
28
|
-
export { drizzleStore, bunSqlRunner } from "./store-drizzle.ts";
|
|
29
|
-
export type { SqlRunner } from "./store-drizzle.ts";
|
|
30
|
-
export { JobWorker } from "./worker.ts";
|
|
31
|
-
export type { WorkerOptions } from "./worker.ts";
|
|
32
|
-
|
|
33
|
-
/** Handlers by name. */
|
|
34
|
-
export type Handlers = Record<string, JobHandler>;
|
|
35
|
-
|
|
36
|
-
export interface JobsOptions<H extends Handlers = Handlers> {
|
|
37
|
-
/**
|
|
38
|
-
* The `@sigil-dev/plugin-sql` database the queue lives in, by name — its
|
|
39
|
-
* `locals` key for `adapter()`. This is the default: with neither `sql`
|
|
40
|
-
* nor `store`, the queue uses the database named "db".
|
|
41
|
-
*
|
|
42
|
-
* Looked up when a query runs, so the order of the plugins array does
|
|
43
|
-
* not matter, and `sigil jobs work` opens it from the config.
|
|
44
|
-
* @default "db"
|
|
45
|
-
*/
|
|
46
|
-
database?: string
|
|
47
|
-
|
|
48
|
-
/**
|
|
49
|
-
* The database client. Required, and not optional-with-a-default,
|
|
50
|
-
* because there is no sensible fallback: a queue that silently kept jobs
|
|
51
|
-
* in memory would look like it worked right up until a restart.
|
|
52
|
-
*/
|
|
53
|
-
/**
|
|
54
|
-
* A `JobStore`: an object with `query(sql, params)`, filling `?`
|
|
55
|
-
* placeholders, and optionally a `capabilities` block declaring what the
|
|
56
|
-
* dialect can do.
|
|
57
|
-
*
|
|
58
|
-
* The queue never opens a connection, so it cannot guess the wrong
|
|
59
|
-
* dialect — a `Bun.SQL` client, a `pg` pool, or Drizzle all work
|
|
60
|
-
* unchanged. A string used to be accepted here and opened for you; it is
|
|
61
|
-
* not any more, because working out which driver a string wanted meant
|
|
62
|
-
* guessing a dialect, and the guessing was wrong more often than not.
|
|
63
|
-
*
|
|
64
|
-
* Either this or `store` is required.
|
|
65
|
-
*/
|
|
66
|
-
sql?: JobStore;
|
|
67
|
-
|
|
68
|
-
/**
|
|
69
|
-
* A store built from the services other plugins published.
|
|
70
|
-
*
|
|
71
|
-
* This is the option to reach for when the app already registered
|
|
72
|
-
* `@sigil-dev/plugin-sql`, because the queue then runs on the connection
|
|
73
|
-
* that plugin opened instead of opening a second pool and dividing the
|
|
74
|
-
* worker budget again:
|
|
75
|
-
*
|
|
76
|
-
* const db = adapter(url, { maxTotal: 12 });
|
|
77
|
-
* const queue = jobs({
|
|
78
|
-
* store: (services) => bunStore(services.db as Bun.SQL),
|
|
79
|
-
* });
|
|
80
|
-
*
|
|
81
|
-
* Register the SQL plugin first — `services` is a snapshot of what ran
|
|
82
|
-
* before this plugin, so a `store` that does not find what it needs
|
|
83
|
-
* should throw rather than fall back to a fresh connection. The function
|
|
84
|
-
* runs inside `services()`, which is the one hook that receives them.
|
|
85
|
-
*
|
|
86
|
-
* Prefer `database`, which needs none of that. At most one of `sql`,
|
|
87
|
-
* `store` and `database`.
|
|
88
|
-
*/
|
|
89
|
-
store?: (services: Record<string, unknown>) => JobStore;
|
|
90
|
-
|
|
91
|
-
/**
|
|
92
|
-
* Named handlers the worker can run. Enqueue a name that is not here and
|
|
93
|
-
* the job fails loudly rather than being dropped.
|
|
94
|
-
*
|
|
95
|
-
* Annotate each handler's payload and `enqueue` checks it.
|
|
96
|
-
*/
|
|
97
|
-
handlers?: H;
|
|
98
|
-
|
|
99
|
-
/**
|
|
100
|
-
* Recurring jobs, by handler name. One row per schedule, so several
|
|
101
|
-
* workers run it once, not once each; a restart keeps its clock.
|
|
102
|
-
*
|
|
103
|
-
* ```ts
|
|
104
|
-
* schedules: { "rankings.snapshot": { every: "5m" } }
|
|
105
|
-
* ```
|
|
106
|
-
*/
|
|
107
|
-
schedules?: { [K in keyof H]?: { every: Every; payload?: PayloadOf<H[K]> } };
|
|
108
|
-
|
|
109
|
-
/** Table name. @default "sigil_jobs" */
|
|
110
|
-
table?: string;
|
|
111
|
-
|
|
112
|
-
/** Create the table on boot. @default true */
|
|
113
|
-
autoMigrate?: boolean;
|
|
114
|
-
|
|
115
|
-
/**
|
|
116
|
-
* Run a worker in the server process.
|
|
117
|
-
*
|
|
118
|
-
* Off by default. A worker in the app means every worker scaled up is
|
|
119
|
-
* also a worker — fine for one process, surprising at three, and the
|
|
120
|
-
* reason `sigil jobs work` exists as a separate process to run instead.
|
|
121
|
-
* @default false
|
|
122
|
-
*/
|
|
123
|
-
inlineWorker?: boolean;
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
/** `enqueue`'s arguments after the name: the payload is optional when the handler takes none. */
|
|
127
|
-
type EnqueueArgs<P> = undefined extends P
|
|
128
|
-
? [payload?: P, options?: EnqueueOptions]
|
|
129
|
-
: [payload: P, options?: EnqueueOptions];
|
|
130
|
-
|
|
131
|
-
export interface JobsApi<H extends Handlers = Handlers> {
|
|
132
|
-
/** Add a job. Returns its id. */
|
|
133
|
-
enqueue<K extends keyof H & string>(name: K, ...args: EnqueueArgs<PayloadOf<H[K]>>): Promise<string>;
|
|
134
|
-
queue: JobQueue;
|
|
135
|
-
handlers: H;
|
|
136
|
-
/**
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
//
|
|
155
|
-
// plugin
|
|
156
|
-
//
|
|
157
|
-
//
|
|
158
|
-
//
|
|
159
|
-
//
|
|
160
|
-
//
|
|
161
|
-
//
|
|
162
|
-
//
|
|
163
|
-
//
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
//
|
|
299
|
-
//
|
|
300
|
-
//
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
const
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
.
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
.
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
})
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
.
|
|
430
|
-
.
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
1
|
+
import type { CliCommand, GrimoirePlugin } from "@sigil-dev/grimoire";
|
|
2
|
+
import { database, type DatabasePlugin } from "@sigil-dev/plugin-sql";
|
|
3
|
+
import { JobQueue } from "./queue.ts";
|
|
4
|
+
import { databaseStore } from "./store-bun.ts";
|
|
5
|
+
import {
|
|
6
|
+
everyMs,
|
|
7
|
+
type EnqueueOptions,
|
|
8
|
+
type Every,
|
|
9
|
+
type JobHandler,
|
|
10
|
+
type JobStore,
|
|
11
|
+
type PayloadOf,
|
|
12
|
+
} from "./store.ts";
|
|
13
|
+
import { JobWorker } from "./worker.ts";
|
|
14
|
+
|
|
15
|
+
export { JobQueue, SCHEMA } from "./queue.ts";
|
|
16
|
+
export type {
|
|
17
|
+
Capabilities,
|
|
18
|
+
EnqueueOptions,
|
|
19
|
+
Every,
|
|
20
|
+
JobContext,
|
|
21
|
+
JobHandler,
|
|
22
|
+
PayloadOf,
|
|
23
|
+
JobRow,
|
|
24
|
+
JobStats,
|
|
25
|
+
JobStore,
|
|
26
|
+
} from "./store.ts";
|
|
27
|
+
export { bunSqlStore, bunStore, databaseStore } from "./store-bun.ts";
|
|
28
|
+
export { drizzleStore, bunSqlRunner } from "./store-drizzle.ts";
|
|
29
|
+
export type { SqlRunner } from "./store-drizzle.ts";
|
|
30
|
+
export { JobWorker } from "./worker.ts";
|
|
31
|
+
export type { WorkerOptions } from "./worker.ts";
|
|
32
|
+
|
|
33
|
+
/** Handlers by name. */
|
|
34
|
+
export type Handlers = Record<string, JobHandler>;
|
|
35
|
+
|
|
36
|
+
export interface JobsOptions<H extends Handlers = Handlers> {
|
|
37
|
+
/**
|
|
38
|
+
* The `@sigil-dev/plugin-sql` database the queue lives in, by name — its
|
|
39
|
+
* `locals` key for `adapter()`. This is the default: with neither `sql`
|
|
40
|
+
* nor `store`, the queue uses the database named "db".
|
|
41
|
+
*
|
|
42
|
+
* Looked up when a query runs, so the order of the plugins array does
|
|
43
|
+
* not matter, and `sigil jobs work` opens it from the config.
|
|
44
|
+
* @default "db"
|
|
45
|
+
*/
|
|
46
|
+
database?: string | DatabasePlugin<any, any>;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The database client. Required, and not optional-with-a-default,
|
|
50
|
+
* because there is no sensible fallback: a queue that silently kept jobs
|
|
51
|
+
* in memory would look like it worked right up until a restart.
|
|
52
|
+
*/
|
|
53
|
+
/**
|
|
54
|
+
* A `JobStore`: an object with `query(sql, params)`, filling `?`
|
|
55
|
+
* placeholders, and optionally a `capabilities` block declaring what the
|
|
56
|
+
* dialect can do.
|
|
57
|
+
*
|
|
58
|
+
* The queue never opens a connection, so it cannot guess the wrong
|
|
59
|
+
* dialect — a `Bun.SQL` client, a `pg` pool, or Drizzle all work
|
|
60
|
+
* unchanged. A string used to be accepted here and opened for you; it is
|
|
61
|
+
* not any more, because working out which driver a string wanted meant
|
|
62
|
+
* guessing a dialect, and the guessing was wrong more often than not.
|
|
63
|
+
*
|
|
64
|
+
* Either this or `store` is required.
|
|
65
|
+
*/
|
|
66
|
+
sql?: JobStore;
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* A store built from the services other plugins published.
|
|
70
|
+
*
|
|
71
|
+
* This is the option to reach for when the app already registered
|
|
72
|
+
* `@sigil-dev/plugin-sql`, because the queue then runs on the connection
|
|
73
|
+
* that plugin opened instead of opening a second pool and dividing the
|
|
74
|
+
* worker budget again:
|
|
75
|
+
*
|
|
76
|
+
* const db = adapter(url, { maxTotal: 12 });
|
|
77
|
+
* const queue = jobs({
|
|
78
|
+
* store: (services) => bunStore(services.db as Bun.SQL),
|
|
79
|
+
* });
|
|
80
|
+
*
|
|
81
|
+
* Register the SQL plugin first — `services` is a snapshot of what ran
|
|
82
|
+
* before this plugin, so a `store` that does not find what it needs
|
|
83
|
+
* should throw rather than fall back to a fresh connection. The function
|
|
84
|
+
* runs inside `services()`, which is the one hook that receives them.
|
|
85
|
+
*
|
|
86
|
+
* Prefer `database`, which needs none of that. At most one of `sql`,
|
|
87
|
+
* `store` and `database`.
|
|
88
|
+
*/
|
|
89
|
+
store?: (services: Record<string, unknown>) => JobStore;
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Named handlers the worker can run. Enqueue a name that is not here and
|
|
93
|
+
* the job fails loudly rather than being dropped.
|
|
94
|
+
*
|
|
95
|
+
* Annotate each handler's payload and `enqueue` checks it.
|
|
96
|
+
*/
|
|
97
|
+
handlers?: H;
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Recurring jobs, by handler name. One row per schedule, so several
|
|
101
|
+
* workers run it once, not once each; a restart keeps its clock.
|
|
102
|
+
*
|
|
103
|
+
* ```ts
|
|
104
|
+
* schedules: { "rankings.snapshot": { every: "5m" } }
|
|
105
|
+
* ```
|
|
106
|
+
*/
|
|
107
|
+
schedules?: { [K in keyof H]?: { every: Every; payload?: PayloadOf<H[K]> } };
|
|
108
|
+
|
|
109
|
+
/** Table name. @default "sigil_jobs" */
|
|
110
|
+
table?: string;
|
|
111
|
+
|
|
112
|
+
/** Create the table on boot. @default true */
|
|
113
|
+
autoMigrate?: boolean;
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Run a worker in the server process.
|
|
117
|
+
*
|
|
118
|
+
* Off by default. A worker in the app means every worker scaled up is
|
|
119
|
+
* also a worker — fine for one process, surprising at three, and the
|
|
120
|
+
* reason `sigil jobs work` exists as a separate process to run instead.
|
|
121
|
+
* @default false
|
|
122
|
+
*/
|
|
123
|
+
inlineWorker?: boolean;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** `enqueue`'s arguments after the name: the payload is optional when the handler takes none. */
|
|
127
|
+
type EnqueueArgs<P> = undefined extends P
|
|
128
|
+
? [payload?: P, options?: EnqueueOptions]
|
|
129
|
+
: [payload: P, options?: EnqueueOptions];
|
|
130
|
+
|
|
131
|
+
export interface JobsApi<H extends Handlers = Handlers> {
|
|
132
|
+
/** Add a job. Returns its id. */
|
|
133
|
+
enqueue<K extends keyof H & string>(name: K, ...args: EnqueueArgs<PayloadOf<H[K]>>): Promise<string>;
|
|
134
|
+
queue: JobQueue;
|
|
135
|
+
handlers: H;
|
|
136
|
+
/**
|
|
137
|
+
* False when `database` was an unconfigured optional adapter: nothing is
|
|
138
|
+
* registered, and `enqueue` throws rather than drop work silently.
|
|
139
|
+
*/
|
|
140
|
+
enabled: boolean;
|
|
141
|
+
/** Register a handler after the plugin was created. */
|
|
142
|
+
register: (name: string, handler: JobHandler) => void;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* The plugin. With no `sql` or `store`, the queue lives in the plugin-sql
|
|
147
|
+
* database named by `database` ("db" by default), looked up when it is
|
|
148
|
+
* used — so a config error is the database's own "no sql database named"
|
|
149
|
+
* at boot, not a failed enqueue at 2am.
|
|
150
|
+
*/
|
|
151
|
+
export function jobs<H extends Handlers = Handlers>(
|
|
152
|
+
options: JobsOptions<H> = {},
|
|
153
|
+
): GrimoirePlugin & { jobs: JobsApi<H> } {
|
|
154
|
+
// The plugin does not open a connection: `sql` is an executor the caller
|
|
155
|
+
// already built, so the plugin can never guess the wrong dialect. That
|
|
156
|
+
// decision is made once, where the user made it.
|
|
157
|
+
//
|
|
158
|
+
// The queue speaks positional `?` placeholders, which is a different
|
|
159
|
+
// interface from the SQL plugin's tagged template — not a worse one. The
|
|
160
|
+
// plugin therefore does not import @sigil-dev/plugin-sql and does not
|
|
161
|
+
// have to. What it does accept is the *client* that plugin opened, via
|
|
162
|
+
// the `store` option, and a tiny adapter in this package translates
|
|
163
|
+
// between the two. Neither side has to know about the other.
|
|
164
|
+
//
|
|
165
|
+
// `store` is resolved at `services()` time, because until then there are
|
|
166
|
+
// no services to read. Everything that needs the queue — migrate, the
|
|
167
|
+
// inline worker, the api object — goes through `getQueue()`, so a
|
|
168
|
+
// config using `store` behaves identically to one using `sql`.
|
|
169
|
+
const factory = options.store;
|
|
170
|
+
const dbOption = options.database;
|
|
171
|
+
const disabled = typeof dbOption === "object" && dbOption.database === undefined;
|
|
172
|
+
if (disabled) {
|
|
173
|
+
const off = (): never => {
|
|
174
|
+
throw new Error(
|
|
175
|
+
`plugin-jobs: the queue is off � database "${dbOption.key}" is not configured. ` +
|
|
176
|
+
"Check the connection URL, or guard the call with `queue.jobs.enabled`.",
|
|
177
|
+
);
|
|
178
|
+
};
|
|
179
|
+
return {
|
|
180
|
+
name: "plugin-jobs (not configured)",
|
|
181
|
+
jobs: {
|
|
182
|
+
enabled: false,
|
|
183
|
+
enqueue: async () => off(),
|
|
184
|
+
get queue(): JobQueue {
|
|
185
|
+
return off();
|
|
186
|
+
},
|
|
187
|
+
handlers: { ...(options.handlers ?? {}) } as H,
|
|
188
|
+
register: () => {},
|
|
189
|
+
},
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
const given = [options.sql, factory, dbOption].filter((x) => x !== undefined);
|
|
193
|
+
if (given.length > 1) {
|
|
194
|
+
throw new Error(
|
|
195
|
+
"plugin-jobs: pass at most one of `sql`, `store` and `database` — " +
|
|
196
|
+
"they are three ways to say where the queue lives.",
|
|
197
|
+
);
|
|
198
|
+
}
|
|
199
|
+
// The default: the plugin-sql database, looked up when a query runs.
|
|
200
|
+
const dbName = factory || options.sql ? undefined : ((typeof dbOption === "object" ? dbOption.key : dbOption) ?? "db");
|
|
201
|
+
const provided = options.sql ?? (dbName !== undefined ? databaseStore(dbName) : undefined);
|
|
202
|
+
/** Open the database the queue lives in, when it is a plugin-sql one. */
|
|
203
|
+
const openDatabase = async () => {
|
|
204
|
+
if (dbName !== undefined) await database(dbName).open();
|
|
205
|
+
};
|
|
206
|
+
let resolved: JobStore | undefined = provided;
|
|
207
|
+
// Assigned by services() before anything reads it. Held in a mutable
|
|
208
|
+
// slot because the api object is built before the services exist.
|
|
209
|
+
let queue: JobQueue | undefined = provided ? new JobQueue(provided, options.table) : undefined;
|
|
210
|
+
const requireQueue = (): JobQueue => {
|
|
211
|
+
if (!queue) {
|
|
212
|
+
throw new Error(
|
|
213
|
+
"plugin-jobs: the queue is not available yet. With `store`, it is " +
|
|
214
|
+
"created during services() — use locals.jobs from a request, or " +
|
|
215
|
+
"pass `sql` if you need it earlier.",
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
return queue;
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
const handlers = { ...(options.handlers ?? {}) } as H;
|
|
222
|
+
const schedules = Object.fromEntries(
|
|
223
|
+
Object.entries(options.schedules ?? {}).flatMap(([name, spec]) => {
|
|
224
|
+
if (!spec) return [];
|
|
225
|
+
const { every, payload } = spec as { every: Every; payload?: unknown };
|
|
226
|
+
if (!(name in handlers)) {
|
|
227
|
+
throw new Error(`plugin-jobs: schedule "${name}" has no handler of that name.`);
|
|
228
|
+
}
|
|
229
|
+
return [[name, { everyMs: everyMs(every), payload }]];
|
|
230
|
+
}),
|
|
231
|
+
);
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Create the table, and start the inline worker if one was asked for.
|
|
235
|
+
*
|
|
236
|
+
* Shared by config() and services() because with `store` the queue only
|
|
237
|
+
* exists once the SQL plugin has published its client, which is strictly
|
|
238
|
+
* after config(). Doing it in one function means the `sql` path and the
|
|
239
|
+
* `store` path cannot disagree about when the table appears.
|
|
240
|
+
*
|
|
241
|
+
* The migrate is awaited, deliberately. A fire-and-forget CREATE TABLE
|
|
242
|
+
* means the first enqueue can race the table and fail with "relation
|
|
243
|
+
* does not exist" on a fresh deploy, which looks like a queue bug and is
|
|
244
|
+
* not one. Only the worker's run loop is left unawaited — it is meant to
|
|
245
|
+
* outlive this call.
|
|
246
|
+
*/
|
|
247
|
+
const migrateAndStart = async (): Promise<Record<string, unknown>> => {
|
|
248
|
+
await openDatabase();
|
|
249
|
+
if (options.autoMigrate !== false) {
|
|
250
|
+
await requireQueue().migrate();
|
|
251
|
+
}
|
|
252
|
+
await requireQueue().ensureSchedules(schedules);
|
|
253
|
+
if (options.inlineWorker) {
|
|
254
|
+
void new JobWorker(requireQueue(), handlers).run();
|
|
255
|
+
}
|
|
256
|
+
return { jobs: api };
|
|
257
|
+
};
|
|
258
|
+
|
|
259
|
+
const api: JobsApi<H> = {
|
|
260
|
+
enabled: true,
|
|
261
|
+
get queue() {
|
|
262
|
+
return requireQueue();
|
|
263
|
+
},
|
|
264
|
+
handlers,
|
|
265
|
+
async enqueue(name, ...[payload, opts]) {
|
|
266
|
+
return requireQueue().enqueue(name, payload, opts);
|
|
267
|
+
},
|
|
268
|
+
register(name, handler) {
|
|
269
|
+
(handlers as Handlers)[name] = handler;
|
|
270
|
+
},
|
|
271
|
+
};
|
|
272
|
+
|
|
273
|
+
const instance: GrimoirePlugin & { jobs: JobsApi<H> } = {
|
|
274
|
+
name: "plugin-jobs",
|
|
275
|
+
jobs: api,
|
|
276
|
+
|
|
277
|
+
async config(config) {
|
|
278
|
+
// With `store` the queue does not exist yet — it is built from
|
|
279
|
+
// the services the SQL plugin publishes, and those are only
|
|
280
|
+
// available in services(), which runs after this. So the same
|
|
281
|
+
// work happens there instead. A config using `sql` keeps
|
|
282
|
+
// migrating here, unchanged.
|
|
283
|
+
// With `database`, it runs in services() too: the database opens
|
|
284
|
+
// there, not in config(), which also runs in the coordinator.
|
|
285
|
+
if (options.sql) await migrateAndStart();
|
|
286
|
+
return config;
|
|
287
|
+
},
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Publishes the queue as `locals.jobs`.
|
|
291
|
+
*
|
|
292
|
+
* This is what lets a route call `locals.jobs.enqueue(...)` with
|
|
293
|
+
* nothing imported and nothing exported from sigil.config.ts. The
|
|
294
|
+
* object is built once at startup, so the same queue instance is
|
|
295
|
+
* shared by every request.
|
|
296
|
+
*/
|
|
297
|
+
services(ctx) {
|
|
298
|
+
// The only hook that can see what other plugins published, and
|
|
299
|
+
// so the only place a `store` can be resolved. This runs after
|
|
300
|
+
// the SQL plugin's own services(), provided it is registered
|
|
301
|
+
// earlier in the plugins array.
|
|
302
|
+
if (factory) {
|
|
303
|
+
resolved = factory(ctx.services);
|
|
304
|
+
queue = new JobQueue(resolved, options.table);
|
|
305
|
+
return migrateAndStart();
|
|
306
|
+
}
|
|
307
|
+
if (dbName !== undefined) return migrateAndStart();
|
|
308
|
+
return { jobs: api };
|
|
309
|
+
},
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* Registers `sigil jobs <subcommand>`.
|
|
313
|
+
*
|
|
314
|
+
* The CLI never starts the app server, so handlers cannot be
|
|
315
|
+
* recovered from a running process — the worker loads the user's
|
|
316
|
+
* config and reads the same handler map, which is why the config is
|
|
317
|
+
* the source of truth rather than module state.
|
|
318
|
+
*/
|
|
319
|
+
cli(program, _context) {
|
|
320
|
+
// Resolved lazily so `sigil --help` and unrelated commands never
|
|
321
|
+
// need a database, and so the error names the real problem instead
|
|
322
|
+
// of surfacing as a failed import.
|
|
323
|
+
//
|
|
324
|
+
// This reads the queue the plugin's own `config` hook built. The
|
|
325
|
+
// CLI loads sigil.config.ts and runs plugin config transforms
|
|
326
|
+
// before calling this, so by the time an action runs the queue
|
|
327
|
+
// exists — and if `config` threw, the CLI already reported that
|
|
328
|
+
// and never got here.
|
|
329
|
+
const connect = (): JobsApi<H> => {
|
|
330
|
+
if (!instance.jobs) {
|
|
331
|
+
throw new Error(
|
|
332
|
+
"plugin-jobs is configured but no queue is available. " +
|
|
333
|
+
"Check the `jobs` option in sigil.config.ts.",
|
|
334
|
+
);
|
|
335
|
+
}
|
|
336
|
+
// A `store` config resolves the queue from the services the
|
|
337
|
+
// SQL plugin published, which only exist inside the server's
|
|
338
|
+
// plugin lifecycle. The CLI runs config() and never
|
|
339
|
+
// services(), so say that plainly instead of reporting the
|
|
340
|
+
// queue as missing.
|
|
341
|
+
if (factory && !queue) {
|
|
342
|
+
throw new Error(
|
|
343
|
+
"plugin-jobs is configured with `store`, which reads the client " +
|
|
344
|
+
"another plugin opened. The `sigil jobs` CLI has no request " +
|
|
345
|
+
"lifecycle to publish that from — use `sql: bunSqlStore(url)` in " +
|
|
346
|
+
"a CLI-capable config, or run the queue commands against a " +
|
|
347
|
+
"server that is up.",
|
|
348
|
+
);
|
|
349
|
+
}
|
|
350
|
+
return instance.jobs;
|
|
351
|
+
};
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* Run one command against the queue: open its database, and close
|
|
355
|
+
* it after, or the open pool keeps the CLI from exiting.
|
|
356
|
+
*/
|
|
357
|
+
const oneShot = async <R>(fn: (q: JobQueue) => Promise<R>): Promise<R> => {
|
|
358
|
+
const q = connect().queue;
|
|
359
|
+
await openDatabase();
|
|
360
|
+
try {
|
|
361
|
+
return await fn(q);
|
|
362
|
+
} finally {
|
|
363
|
+
if (dbName !== undefined) await database(dbName).close();
|
|
364
|
+
}
|
|
365
|
+
};
|
|
366
|
+
|
|
367
|
+
const group = program
|
|
368
|
+
.command("jobs")
|
|
369
|
+
.description("manage the durable job queue");
|
|
370
|
+
|
|
371
|
+
group
|
|
372
|
+
.command("work")
|
|
373
|
+
.description("run the job worker until stopped")
|
|
374
|
+
.option("--interval <ms>", "idle poll interval", (v: string) => Number(v))
|
|
375
|
+
.option("--batch <n>", "jobs per pass", (v: string) => Number(v))
|
|
376
|
+
.action(async (opts: { interval?: number; batch?: number }) => {
|
|
377
|
+
const { queue: q, handlers: h } = connect();
|
|
378
|
+
await openDatabase();
|
|
379
|
+
// The worker completes recurring jobs, so it has to know
|
|
380
|
+
// them: without the schedule a completed one is deleted.
|
|
381
|
+
await q.ensureSchedules(schedules);
|
|
382
|
+
const worker = new JobWorker(q, h, {
|
|
383
|
+
...(opts.interval ? { intervalMs: opts.interval } : {}),
|
|
384
|
+
...(opts.batch ? { batchSize: opts.batch } : {}),
|
|
385
|
+
});
|
|
386
|
+
|
|
387
|
+
// Drain before exiting so a deploy does not abandon claimed
|
|
388
|
+
// jobs. The stale-claim timeout covers a hard kill.
|
|
389
|
+
const shutdown = async () => {
|
|
390
|
+
console.log("\nstopping, draining…");
|
|
391
|
+
await worker.stop();
|
|
392
|
+
process.exit(0);
|
|
393
|
+
};
|
|
394
|
+
process.on("SIGINT", shutdown);
|
|
395
|
+
process.on("SIGTERM", shutdown);
|
|
396
|
+
|
|
397
|
+
console.log(
|
|
398
|
+
`sigil jobs work — ${Object.keys(h).length} handler(s) registered`,
|
|
399
|
+
);
|
|
400
|
+
await worker.run();
|
|
401
|
+
});
|
|
402
|
+
|
|
403
|
+
group
|
|
404
|
+
.command("list")
|
|
405
|
+
.description("list the most recent jobs")
|
|
406
|
+
.option("--limit <n>", "how many rows", (v: string) => Number(v))
|
|
407
|
+
.action(async (opts: { limit?: number }) => {
|
|
408
|
+
const rows = await oneShot((q) => q.list(opts.limit ?? 20));
|
|
409
|
+
if (rows.length === 0) {
|
|
410
|
+
console.log("no jobs");
|
|
411
|
+
return;
|
|
412
|
+
}
|
|
413
|
+
console.log(["ID", "NAME", "RUN_AT", "TRIES", "ERROR"].join(" "));
|
|
414
|
+
for (const row of rows) {
|
|
415
|
+
console.log(
|
|
416
|
+
[
|
|
417
|
+
row.id.slice(0, 8),
|
|
418
|
+
row.name,
|
|
419
|
+
row.run_at,
|
|
420
|
+
`${row.attempts}`,
|
|
421
|
+
row.last_error ? row.last_error.slice(0, 40) : "-",
|
|
422
|
+
].join(" "),
|
|
423
|
+
);
|
|
424
|
+
}
|
|
425
|
+
});
|
|
426
|
+
|
|
427
|
+
group
|
|
428
|
+
.command("stats")
|
|
429
|
+
.description("count jobs by state")
|
|
430
|
+
.action(async () => {
|
|
431
|
+
const s = await oneShot((q) => q.stats());
|
|
432
|
+
console.log(
|
|
433
|
+
`pending ${s.pending} claimed ${s.claimed} failed ${s.failed}`,
|
|
434
|
+
);
|
|
435
|
+
});
|
|
436
|
+
|
|
437
|
+
group
|
|
438
|
+
.command("retry")
|
|
439
|
+
.argument("[id]", "job id, or all failed jobs when omitted")
|
|
440
|
+
.description("requeue a job, clearing its attempt count")
|
|
441
|
+
.action(async (id?: string) => {
|
|
442
|
+
await oneShot(async (q) => {
|
|
443
|
+
if (id) {
|
|
444
|
+
const ok = await q.retry(id);
|
|
445
|
+
console.log(ok ? `requeued ${id}` : `no such job: ${id}`);
|
|
446
|
+
return;
|
|
447
|
+
}
|
|
448
|
+
const failed = (await q.list(1000)).filter(
|
|
449
|
+
(r) => r.attempts >= r.max_attempts,
|
|
450
|
+
);
|
|
451
|
+
for (const job of failed) await q.retry(job.id);
|
|
452
|
+
console.log(`requeued ${failed.length} failed job(s)`);
|
|
453
|
+
});
|
|
454
|
+
});
|
|
455
|
+
|
|
456
|
+
group
|
|
457
|
+
.command("migrate")
|
|
458
|
+
.description("create the jobs table if it does not exist")
|
|
459
|
+
.action(async () => {
|
|
460
|
+
await oneShot((q) => q.migrate());
|
|
461
|
+
console.log("jobs table ready");
|
|
462
|
+
});
|
|
463
|
+
},
|
|
464
|
+
};
|
|
465
|
+
|
|
466
|
+
return instance;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
export const plugin = jobs;
|
|
470
|
+
export default jobs;
|
|
471
|
+
|
|
472
|
+
/**
|
|
473
|
+
* Accept an executor, or fail naming what was expected.
|
|
474
|
+
*
|
|
475
|
+
* A bare string used to be accepted here. It no longer is, and a message
|
|
476
|
+
* that says only "sql is required" would send someone to the docs to
|
|
477
|
+
* discover it. A queue pointed at the wrong database is worse than a boot
|
|
478
|
+
* that fails, so this throws at construction — which is what `sigil start`
|
|
479
|
+
* runs — rather than at the first enqueue.
|
|
480
|
+
*/
|