@sigil-dev/plugin-jobs 0.9.21 → 0.9.23

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.
Files changed (8) hide show
  1. package/README.md +159 -154
  2. package/index.ts +480 -452
  3. package/package.json +3 -3
  4. package/queue.ts +396 -396
  5. package/store-bun.ts +137 -137
  6. package/store-drizzle.ts +86 -86
  7. package/store.ts +117 -117
  8. 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
- /** Register a handler after the plugin was created. */
137
- register: (name: string, handler: JobHandler) => void;
138
- }
139
-
140
- /**
141
- * The plugin. With no `sql` or `store`, the queue lives in the plugin-sql
142
- * database named by `database` ("db" by default), looked up when it is
143
- * used — so a config error is the database's own "no sql database named"
144
- * at boot, not a failed enqueue at 2am.
145
- */
146
- export function jobs<H extends Handlers = Handlers>(
147
- options: JobsOptions<H> = {},
148
- ): GrimoirePlugin & { jobs: JobsApi<H> } {
149
- // The plugin does not open a connection: `sql` is an executor the caller
150
- // already built, so the plugin can never guess the wrong dialect. That
151
- // decision is made once, where the user made it.
152
- //
153
- // The queue speaks positional `?` placeholders, which is a different
154
- // interface from the SQL plugin's tagged template — not a worse one. The
155
- // plugin therefore does not import @sigil-dev/plugin-sql and does not
156
- // have to. What it does accept is the *client* that plugin opened, via
157
- // the `store` option, and a tiny adapter in this package translates
158
- // between the two. Neither side has to know about the other.
159
- //
160
- // `store` is resolved at `services()` time, because until then there are
161
- // no services to read. Everything that needs the queue — migrate, the
162
- // inline worker, the api object — goes through `getQueue()`, so a
163
- // config using `store` behaves identically to one using `sql`.
164
- const factory = options.store;
165
- const given = [options.sql, factory, options.database].filter((x) => x !== undefined);
166
- if (given.length > 1) {
167
- throw new Error(
168
- "plugin-jobs: pass at most one of `sql`, `store` and `database` — " +
169
- "they are three ways to say where the queue lives.",
170
- );
171
- }
172
- // The default: the plugin-sql database, looked up when a query runs.
173
- const dbName = factory || options.sql ? undefined : (options.database ?? "db");
174
- const provided = options.sql ?? (dbName !== undefined ? databaseStore(dbName) : undefined);
175
- /** Open the database the queue lives in, when it is a plugin-sql one. */
176
- const openDatabase = async () => {
177
- if (dbName !== undefined) await database(dbName).open();
178
- };
179
- let resolved: JobStore | undefined = provided;
180
- // Assigned by services() before anything reads it. Held in a mutable
181
- // slot because the api object is built before the services exist.
182
- let queue: JobQueue | undefined = provided ? new JobQueue(provided, options.table) : undefined;
183
- const requireQueue = (): JobQueue => {
184
- if (!queue) {
185
- throw new Error(
186
- "plugin-jobs: the queue is not available yet. With `store`, it is " +
187
- "created during services() — use locals.jobs from a request, or " +
188
- "pass `sql` if you need it earlier.",
189
- );
190
- }
191
- return queue;
192
- };
193
-
194
- const handlers = { ...(options.handlers ?? {}) } as H;
195
- const schedules = Object.fromEntries(
196
- Object.entries(options.schedules ?? {}).flatMap(([name, spec]) => {
197
- if (!spec) return [];
198
- const { every, payload } = spec as { every: Every; payload?: unknown };
199
- if (!(name in handlers)) {
200
- throw new Error(`plugin-jobs: schedule "${name}" has no handler of that name.`);
201
- }
202
- return [[name, { everyMs: everyMs(every), payload }]];
203
- }),
204
- );
205
-
206
- /**
207
- * Create the table, and start the inline worker if one was asked for.
208
- *
209
- * Shared by config() and services() because with `store` the queue only
210
- * exists once the SQL plugin has published its client, which is strictly
211
- * after config(). Doing it in one function means the `sql` path and the
212
- * `store` path cannot disagree about when the table appears.
213
- *
214
- * The migrate is awaited, deliberately. A fire-and-forget CREATE TABLE
215
- * means the first enqueue can race the table and fail with "relation
216
- * does not exist" on a fresh deploy, which looks like a queue bug and is
217
- * not one. Only the worker's run loop is left unawaited — it is meant to
218
- * outlive this call.
219
- */
220
- const migrateAndStart = async (): Promise<Record<string, unknown>> => {
221
- await openDatabase();
222
- if (options.autoMigrate !== false) {
223
- await requireQueue().migrate();
224
- }
225
- await requireQueue().ensureSchedules(schedules);
226
- if (options.inlineWorker) {
227
- void new JobWorker(requireQueue(), handlers).run();
228
- }
229
- return { jobs: api };
230
- };
231
-
232
- const api: JobsApi<H> = {
233
- get queue() {
234
- return requireQueue();
235
- },
236
- handlers,
237
- async enqueue(name, ...[payload, opts]) {
238
- return requireQueue().enqueue(name, payload, opts);
239
- },
240
- register(name, handler) {
241
- (handlers as Handlers)[name] = handler;
242
- },
243
- };
244
-
245
- const instance: GrimoirePlugin & { jobs: JobsApi<H> } = {
246
- name: "plugin-jobs",
247
- jobs: api,
248
-
249
- async config(config) {
250
- // With `store` the queue does not exist yet — it is built from
251
- // the services the SQL plugin publishes, and those are only
252
- // available in services(), which runs after this. So the same
253
- // work happens there instead. A config using `sql` keeps
254
- // migrating here, unchanged.
255
- // With `database`, it runs in services() too: the database opens
256
- // there, not in config(), which also runs in the coordinator.
257
- if (options.sql) await migrateAndStart();
258
- return config;
259
- },
260
-
261
- /**
262
- * Publishes the queue as `locals.jobs`.
263
- *
264
- * This is what lets a route call `locals.jobs.enqueue(...)` with
265
- * nothing imported and nothing exported from sigil.config.ts. The
266
- * object is built once at startup, so the same queue instance is
267
- * shared by every request.
268
- */
269
- services(ctx) {
270
- // The only hook that can see what other plugins published, and
271
- // so the only place a `store` can be resolved. This runs after
272
- // the SQL plugin's own services(), provided it is registered
273
- // earlier in the plugins array.
274
- if (factory) {
275
- resolved = factory(ctx.services);
276
- queue = new JobQueue(resolved, options.table);
277
- return migrateAndStart();
278
- }
279
- if (dbName !== undefined) return migrateAndStart();
280
- return { jobs: api };
281
- },
282
-
283
- /**
284
- * Registers `sigil jobs <subcommand>`.
285
- *
286
- * The CLI never starts the app server, so handlers cannot be
287
- * recovered from a running process — the worker loads the user's
288
- * config and reads the same handler map, which is why the config is
289
- * the source of truth rather than module state.
290
- */
291
- cli(program, _context) {
292
- // Resolved lazily so `sigil --help` and unrelated commands never
293
- // need a database, and so the error names the real problem instead
294
- // of surfacing as a failed import.
295
- //
296
- // This reads the queue the plugin's own `config` hook built. The
297
- // CLI loads sigil.config.ts and runs plugin config transforms
298
- // before calling this, so by the time an action runs the queue
299
- // exists — and if `config` threw, the CLI already reported that
300
- // and never got here.
301
- const connect = (): JobsApi<H> => {
302
- if (!instance.jobs) {
303
- throw new Error(
304
- "plugin-jobs is configured but no queue is available. " +
305
- "Check the `jobs` option in sigil.config.ts.",
306
- );
307
- }
308
- // A `store` config resolves the queue from the services the
309
- // SQL plugin published, which only exist inside the server's
310
- // plugin lifecycle. The CLI runs config() and never
311
- // services(), so say that plainly instead of reporting the
312
- // queue as missing.
313
- if (factory && !queue) {
314
- throw new Error(
315
- "plugin-jobs is configured with `store`, which reads the client " +
316
- "another plugin opened. The `sigil jobs` CLI has no request " +
317
- "lifecycle to publish that from — use `sql: bunSqlStore(url)` in " +
318
- "a CLI-capable config, or run the queue commands against a " +
319
- "server that is up.",
320
- );
321
- }
322
- return instance.jobs;
323
- };
324
-
325
- /**
326
- * Run one command against the queue: open its database, and close
327
- * it after, or the open pool keeps the CLI from exiting.
328
- */
329
- const oneShot = async <R>(fn: (q: JobQueue) => Promise<R>): Promise<R> => {
330
- const q = connect().queue;
331
- await openDatabase();
332
- try {
333
- return await fn(q);
334
- } finally {
335
- if (dbName !== undefined) await database(dbName).close();
336
- }
337
- };
338
-
339
- const group = program
340
- .command("jobs")
341
- .description("manage the durable job queue");
342
-
343
- group
344
- .command("work")
345
- .description("run the job worker until stopped")
346
- .option("--interval <ms>", "idle poll interval", (v: string) => Number(v))
347
- .option("--batch <n>", "jobs per pass", (v: string) => Number(v))
348
- .action(async (opts: { interval?: number; batch?: number }) => {
349
- const { queue: q, handlers: h } = connect();
350
- await openDatabase();
351
- // The worker completes recurring jobs, so it has to know
352
- // them: without the schedule a completed one is deleted.
353
- await q.ensureSchedules(schedules);
354
- const worker = new JobWorker(q, h, {
355
- ...(opts.interval ? { intervalMs: opts.interval } : {}),
356
- ...(opts.batch ? { batchSize: opts.batch } : {}),
357
- });
358
-
359
- // Drain before exiting so a deploy does not abandon claimed
360
- // jobs. The stale-claim timeout covers a hard kill.
361
- const shutdown = async () => {
362
- console.log("\nstopping, draining…");
363
- await worker.stop();
364
- process.exit(0);
365
- };
366
- process.on("SIGINT", shutdown);
367
- process.on("SIGTERM", shutdown);
368
-
369
- console.log(
370
- `sigil jobs work — ${Object.keys(h).length} handler(s) registered`,
371
- );
372
- await worker.run();
373
- });
374
-
375
- group
376
- .command("list")
377
- .description("list the most recent jobs")
378
- .option("--limit <n>", "how many rows", (v: string) => Number(v))
379
- .action(async (opts: { limit?: number }) => {
380
- const rows = await oneShot((q) => q.list(opts.limit ?? 20));
381
- if (rows.length === 0) {
382
- console.log("no jobs");
383
- return;
384
- }
385
- console.log(["ID", "NAME", "RUN_AT", "TRIES", "ERROR"].join(" "));
386
- for (const row of rows) {
387
- console.log(
388
- [
389
- row.id.slice(0, 8),
390
- row.name,
391
- row.run_at,
392
- `${row.attempts}`,
393
- row.last_error ? row.last_error.slice(0, 40) : "-",
394
- ].join(" "),
395
- );
396
- }
397
- });
398
-
399
- group
400
- .command("stats")
401
- .description("count jobs by state")
402
- .action(async () => {
403
- const s = await oneShot((q) => q.stats());
404
- console.log(
405
- `pending ${s.pending} claimed ${s.claimed} failed ${s.failed}`,
406
- );
407
- });
408
-
409
- group
410
- .command("retry")
411
- .argument("[id]", "job id, or all failed jobs when omitted")
412
- .description("requeue a job, clearing its attempt count")
413
- .action(async (id?: string) => {
414
- await oneShot(async (q) => {
415
- if (id) {
416
- const ok = await q.retry(id);
417
- console.log(ok ? `requeued ${id}` : `no such job: ${id}`);
418
- return;
419
- }
420
- const failed = (await q.list(1000)).filter(
421
- (r) => r.attempts >= r.max_attempts,
422
- );
423
- for (const job of failed) await q.retry(job.id);
424
- console.log(`requeued ${failed.length} failed job(s)`);
425
- });
426
- });
427
-
428
- group
429
- .command("migrate")
430
- .description("create the jobs table if it does not exist")
431
- .action(async () => {
432
- await oneShot((q) => q.migrate());
433
- console.log("jobs table ready");
434
- });
435
- },
436
- };
437
-
438
- return instance;
439
- }
440
-
441
- export const plugin = jobs;
442
- export default jobs;
443
-
444
- /**
445
- * Accept an executor, or fail naming what was expected.
446
- *
447
- * A bare string used to be accepted here. It no longer is, and a message
448
- * that says only "sql is required" would send someone to the docs to
449
- * discover it. A queue pointed at the wrong database is worse than a boot
450
- * that fails, so this throws at construction — which is what `sigil start`
451
- * runs — rather than at the first enqueue.
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
+ */