@vantedev/groundwork 0.3.2 → 1.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.
Files changed (90) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/README.md +10 -9
  3. package/dist/api-keys/api-keys.d.ts +6 -1
  4. package/dist/api-keys/api-keys.d.ts.map +1 -1
  5. package/dist/api-keys/api-keys.js +50 -43
  6. package/dist/api-keys/api-keys.js.map +1 -1
  7. package/dist/api-keys/audit.js +4 -4
  8. package/dist/api-keys/audit.js.map +1 -1
  9. package/dist/api-keys/types.d.ts +28 -14
  10. package/dist/api-keys/types.d.ts.map +1 -1
  11. package/dist/audit/audit-log.d.ts.map +1 -1
  12. package/dist/audit/audit-log.js +17 -5
  13. package/dist/audit/audit-log.js.map +1 -1
  14. package/dist/audit/json.d.ts.map +1 -1
  15. package/dist/audit/json.js +5 -1
  16. package/dist/audit/json.js.map +1 -1
  17. package/dist/idempotency/idempotency.d.ts +7 -1
  18. package/dist/idempotency/idempotency.d.ts.map +1 -1
  19. package/dist/idempotency/idempotency.js +171 -48
  20. package/dist/idempotency/idempotency.js.map +1 -1
  21. package/dist/index.d.ts +18 -4
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +7 -2
  24. package/dist/index.js.map +1 -1
  25. package/dist/internal/cidr.d.ts +6 -0
  26. package/dist/internal/cidr.d.ts.map +1 -1
  27. package/dist/internal/cidr.js +14 -0
  28. package/dist/internal/cidr.js.map +1 -1
  29. package/dist/internal/crypto.d.ts +14 -1
  30. package/dist/internal/crypto.d.ts.map +1 -1
  31. package/dist/internal/crypto.js +37 -5
  32. package/dist/internal/crypto.js.map +1 -1
  33. package/dist/internal/db.d.ts +13 -1
  34. package/dist/internal/db.d.ts.map +1 -1
  35. package/dist/internal/db.js +42 -1
  36. package/dist/internal/db.js.map +1 -1
  37. package/dist/internal/errors.d.ts +7 -3
  38. package/dist/internal/errors.d.ts.map +1 -1
  39. package/dist/internal/errors.js.map +1 -1
  40. package/dist/internal/text.d.ts +7 -0
  41. package/dist/internal/text.d.ts.map +1 -0
  42. package/dist/internal/text.js +25 -0
  43. package/dist/internal/text.js.map +1 -0
  44. package/dist/jobs/index.d.ts +1 -2
  45. package/dist/jobs/index.d.ts.map +1 -1
  46. package/dist/jobs/index.js +0 -1
  47. package/dist/jobs/index.js.map +1 -1
  48. package/dist/jobs/jobs.d.ts +4 -1
  49. package/dist/jobs/jobs.d.ts.map +1 -1
  50. package/dist/jobs/jobs.js +411 -74
  51. package/dist/jobs/jobs.js.map +1 -1
  52. package/dist/jobs/types.d.ts +32 -3
  53. package/dist/jobs/types.d.ts.map +1 -1
  54. package/dist/next/jobs-route.d.ts +8 -4
  55. package/dist/next/jobs-route.d.ts.map +1 -1
  56. package/dist/next/jobs-route.js +38 -8
  57. package/dist/next/jobs-route.js.map +1 -1
  58. package/dist/rate-limit/index.d.ts +2 -1
  59. package/dist/rate-limit/index.d.ts.map +1 -1
  60. package/dist/rate-limit/index.js +1 -0
  61. package/dist/rate-limit/index.js.map +1 -1
  62. package/dist/rate-limit/ip-subject.d.ts +26 -0
  63. package/dist/rate-limit/ip-subject.d.ts.map +1 -0
  64. package/dist/rate-limit/ip-subject.js +21 -0
  65. package/dist/rate-limit/ip-subject.js.map +1 -0
  66. package/dist/rate-limit/limiter.d.ts +1 -1
  67. package/dist/rate-limit/limiter.d.ts.map +1 -1
  68. package/dist/rate-limit/limiter.js +7 -3
  69. package/dist/rate-limit/limiter.js.map +1 -1
  70. package/dist/rate-limit/memory-store.d.ts +6 -2
  71. package/dist/rate-limit/memory-store.d.ts.map +1 -1
  72. package/dist/rate-limit/memory-store.js +8 -0
  73. package/dist/rate-limit/memory-store.js.map +1 -1
  74. package/dist/rate-limit/postgres-store.d.ts +2 -2
  75. package/dist/rate-limit/postgres-store.d.ts.map +1 -1
  76. package/dist/rate-limit/postgres-store.js +23 -9
  77. package/dist/rate-limit/postgres-store.js.map +1 -1
  78. package/dist/rate-limit/redis-store.d.ts +2 -4
  79. package/dist/rate-limit/redis-store.d.ts.map +1 -1
  80. package/dist/rate-limit/redis-store.js +10 -1
  81. package/dist/rate-limit/redis-store.js.map +1 -1
  82. package/dist/rate-limit/types.d.ts +21 -6
  83. package/dist/rate-limit/types.d.ts.map +1 -1
  84. package/dist/rate-limit/types.js +4 -1
  85. package/dist/rate-limit/types.js.map +1 -1
  86. package/dist/schema/jobs.d.ts +23 -3
  87. package/dist/schema/jobs.d.ts.map +1 -1
  88. package/dist/schema/jobs.js +7 -2
  89. package/dist/schema/jobs.js.map +1 -1
  90. package/package.json +1 -1
package/dist/jobs/jobs.js CHANGED
@@ -1,28 +1,43 @@
1
- import { randomBytes } from "node:crypto";
1
+ import { randomBytes, randomUUID } from "node:crypto";
2
2
  import { hostname } from "node:os";
3
3
  import { sql } from "drizzle-orm";
4
4
  import { toJsonValue } from "../audit/json.js";
5
- import { jsonbParam, rowsOf, toNumber } from "../internal/db.js";
5
+ import { jsonbParam, pgCode, pgMessage, rowsOf, toNumber, } from "../internal/db.js";
6
6
  import { isDuration, MAX_TIMER_MS, parseDuration } from "../internal/duration.js";
7
- import { errorText, GroundworkError } from "../internal/errors.js";
7
+ import { errorText, GroundworkError, isGroundworkError } from "../internal/errors.js";
8
8
  import { renewEveryMs } from "../internal/lease.js";
9
9
  import { consoleLogger, createOnceLogger } from "../internal/logger.js";
10
10
  import { validateWith } from "../internal/standard-schema.js";
11
11
  import { assertTableColumns } from "../internal/table.js";
12
+ import { isStorable, storable } from "../internal/text.js";
12
13
  import { JOB_COLUMNS, JOB_SCHEDULE_COLUMNS, } from "../schema/jobs.js";
13
14
  import { backoffDelayMs, ladderDelayMs } from "./backoff.js";
14
15
  const NAME_PATTERN = /^[A-Za-z0-9_.:-]{1,100}$/;
15
16
  const SCHEDULE_PREFIX = "schedule:";
16
17
  const MAX_LIST = 1_000;
18
+ const MAX_ENQUEUE_MANY = 1_000;
17
19
  const PRUNE_BATCH = 5_000;
18
20
  const MAX_ERROR_LENGTH = 2_000;
21
+ /**
22
+ * SQLSTATEs for a value Postgres can't store, which retrying doesn't change: invalid JSON or text
23
+ * (22P02), a character the encoding can't hold such as `\u0000` (22P05, 22021), and a value over
24
+ * a size limit (54000).
25
+ */
26
+ const UNSTORABLE = new Set(["22P02", "22P05", "22021", "54000"]);
19
27
  const MAX_BACKOFF_STEPS = 100;
28
+ /**
29
+ * The largest `maxAttempts`: one less than Postgres's `integer`, which `attempts` and
30
+ * `max_attempts` are, because a claim can take `attempts` one past `max_attempts`.
31
+ */
32
+ const MAX_ATTEMPTS = 2_147_483_646;
33
+ /** Postgres's largest `integer`. */
34
+ const MAX_INT = 2_147_483_647;
20
35
  /** A schedule's tick may run this early at most (and never more than a tenth of `every`). */
21
36
  const SCHEDULE_EARLY_MAX_MS = 5_000;
22
37
  const ms = (column) => `(extract(epoch from ${column}) * 1000)::float8`;
23
38
  const RECORD = sql.raw(`jsonb_build_object(
24
39
  'id', j.id::text, 'type', j.type, 'payload', j.payload, 'status', j.status, 'priority', j.priority,
25
- 'attempts', j.attempts, 'max_attempts', j.max_attempts, 'run_at', ${ms("j.run_at")},
40
+ 'attempts', j.attempts, 'max_attempts', j.max_attempts, 'claims', j.claims, 'run_at', ${ms("j.run_at")},
26
41
  'locked_until', ${ms("j.locked_until")}, 'locked_by', j.locked_by, 'dedupe_key', j.dedupe_key,
27
42
  'last_error', j.last_error, 'result', j.result, 'created_at', ${ms("j.created_at")},
28
43
  'started_at', ${ms("j.started_at")}, 'completed_at', ${ms("j.completed_at")}, 'updated_at', ${ms("j.updated_at")}
@@ -44,6 +59,7 @@ function toRecord(row) {
44
59
  priority: row.priority,
45
60
  attempts: row.attempts,
46
61
  maxAttempts: row.max_attempts,
62
+ claims: row.claims,
47
63
  runAt: new Date(row.run_at),
48
64
  lockedUntil: toDate(row.locked_until),
49
65
  lockedBy: row.locked_by,
@@ -68,6 +84,12 @@ function positiveInt(value, label, code) {
68
84
  }
69
85
  return value;
70
86
  }
87
+ function attemptsLimit(value, label, code) {
88
+ if (!Number.isSafeInteger(value) || value < 1 || value > MAX_ATTEMPTS) {
89
+ throw new GroundworkError(code, `${label} must be an integer from 1 to 2,147,483,646.`);
90
+ }
91
+ return value;
92
+ }
71
93
  function integer(value, label, code) {
72
94
  if (!Number.isSafeInteger(value) || Math.abs(value) > 1_000_000) {
73
95
  throw new GroundworkError(code, `${label} must be an integer between -1,000,000 and 1,000,000.`);
@@ -114,6 +136,11 @@ export function createJobs(options) {
114
136
  let schedulesSynced = false;
115
137
  /** The time a statement works with: the injected clock, else Postgres's `now()`. */
116
138
  const now = () => (clock ? sql `${clock.now().toISOString()}::timestamptz` : sql `now()`);
139
+ /**
140
+ * The time to judge a lease by. `now()` is when the transaction began, which inside a caller's
141
+ * long transaction can be well before the lease ran out.
142
+ */
143
+ const current = () => clock ? sql `${clock.now().toISOString()}::timestamptz` : sql `statement_timestamp()`;
117
144
  const lease = sql `${leaseMs}::float8 * interval '1 millisecond'`;
118
145
  function addHandler(type, definition, defaults, schedule) {
119
146
  if (handlers.has(type)) {
@@ -150,7 +177,7 @@ export function createJobs(options) {
150
177
  onExhausted: definition.onExhausted,
151
178
  maxAttempts: definition.maxAttempts === undefined
152
179
  ? defaults.maxAttempts
153
- : positiveInt(definition.maxAttempts, `maxAttempts of "${type}"`, "invalid_config"),
180
+ : attemptsLimit(definition.maxAttempts, `maxAttempts of "${type}"`, "invalid_config"),
154
181
  backoffBaseMs: parseDuration((backoff.base ?? defaults.base), {
155
182
  label: `backoff.base of "${type}"`,
156
183
  }),
@@ -182,58 +209,280 @@ export function createJobs(options) {
182
209
  }
183
210
  return toJsonValue(payload);
184
211
  }
185
- async function enqueue(handler, payload, enqueueOptions = {}) {
212
+ /** Validates one job's payload and options, as `enqueue` and `enqueueMany` both need. */
213
+ async function prepare(handler, payload, enqueueOptions) {
186
214
  const json = await payloadFor(handler, payload);
187
215
  const priority = enqueueOptions.priority === undefined
188
216
  ? handler.priority
189
217
  : integer(enqueueOptions.priority, "priority", "invalid_argument");
190
218
  const maxAttempts = enqueueOptions.maxAttempts === undefined
191
219
  ? handler.maxAttempts
192
- : positiveInt(enqueueOptions.maxAttempts, "maxAttempts", "invalid_argument");
220
+ : attemptsLimit(enqueueOptions.maxAttempts, "maxAttempts", "invalid_argument");
193
221
  const dedupeKey = enqueueOptions.dedupeKey ?? null;
194
222
  if (dedupeKey !== null &&
195
- (typeof dedupeKey !== "string" || dedupeKey === "" || dedupeKey.length > 500)) {
196
- throw new GroundworkError("invalid_argument", "dedupeKey must be a non-empty string of at most 500 characters.");
223
+ (typeof dedupeKey !== "string" ||
224
+ dedupeKey === "" ||
225
+ dedupeKey.length > 500 ||
226
+ !isStorable(dedupeKey))) {
227
+ // Not cleaned like free text: two different keys must never become the same one.
228
+ throw new GroundworkError("invalid_argument", "dedupeKey must be a non-empty string of at most 500 characters, without \\u0000 or a lone surrogate.");
197
229
  }
198
230
  if (enqueueOptions.runAt !== undefined && enqueueOptions.delay !== undefined) {
199
231
  throw new GroundworkError("invalid_argument", "Pass runAt or delay, not both.");
200
232
  }
201
- let runAt = sql `input.now`;
233
+ let runAt = null;
234
+ let delayMs = null;
202
235
  if (enqueueOptions.runAt !== undefined) {
203
236
  if (!(enqueueOptions.runAt instanceof Date) || Number.isNaN(enqueueOptions.runAt.getTime())) {
204
237
  throw new GroundworkError("invalid_argument", "runAt must be a valid Date.");
205
238
  }
206
- runAt = sql `${enqueueOptions.runAt.toISOString()}::timestamptz`;
239
+ runAt = enqueueOptions.runAt;
207
240
  }
208
241
  else if (enqueueOptions.delay !== undefined) {
209
- const delayMs = parseDuration(enqueueOptions.delay, { label: "delay" });
210
- runAt = sql `input.now + ${delayMs}::float8 * interval '1 millisecond'`;
242
+ delayMs = parseDuration(enqueueOptions.delay, { label: "delay" });
211
243
  }
244
+ return { json, priority, maxAttempts, dedupeKey, runAt, delayMs };
245
+ }
246
+ async function enqueue(handler, payload, enqueueOptions = {}) {
247
+ const replace = enqueueOptions.replace ?? false;
248
+ if (typeof replace !== "boolean") {
249
+ throw new GroundworkError("invalid_argument", "replace must be true or false.");
250
+ }
251
+ const prepared = await prepare(handler, payload, enqueueOptions);
252
+ const { json, priority, maxAttempts, dedupeKey, ...when } = prepared;
253
+ const runAt = when.runAt !== null
254
+ ? sql `${when.runAt.toISOString()}::timestamptz`
255
+ : when.delayMs !== null
256
+ ? sql `input.now + ${when.delayMs}::float8 * interval '1 millisecond'`
257
+ : sql `input.now`;
212
258
  const target = enqueueOptions.tx ?? db;
213
- const rows = rowsOf(await target.execute(sql `
259
+ if (replace) {
260
+ if (dedupeKey === null) {
261
+ throw new GroundworkError("invalid_argument", "replace needs a dedupeKey: it replaces the pending job with that key.");
262
+ }
263
+ return enqueueReplacing(handler, prepared, dedupeKey, runAt, target);
264
+ }
265
+ for (let round = 0; round < 3; round++) {
266
+ const rows = rowsOf(await target.execute(sql `
267
+ with input as materialized (select ${now()} as now),
268
+ inserted as (
269
+ insert into ${table} as j (type, payload, priority, max_attempts, run_at, dedupe_key, created_at, updated_at)
270
+ select ${handler.type}::text, ${jsonbParam(JSON.stringify(json))}, ${priority}::int, ${maxAttempts}::int,
271
+ ${runAt}, ${dedupeKey}::text, input.now, input.now
272
+ from input
273
+ on conflict (type, dedupe_key) where dedupe_key is not null and status in ('pending', 'running') do nothing
274
+ returning j.id::text as id
275
+ )
276
+ select id, true as created from inserted
277
+ union all
278
+ select j.id::text, false from ${table} j
279
+ where ${dedupeKey}::text is not null and j.type = ${handler.type}::text and j.dedupe_key = ${dedupeKey}::text
280
+ and j.status in ('pending', 'running') and not exists (select 1 from inserted)
281
+ limit 1`));
282
+ const row = rows[0];
283
+ if (row)
284
+ return { id: row.id, created: row.created === true };
285
+ // The duplicate committed after this statement's snapshot was taken: look for it again.
286
+ const [existing] = rowsOf(await target.execute(sql `select id::text as id from ${table} where type = ${handler.type}::text and dedupe_key = ${dedupeKey}::text
287
+ and status in ('pending', 'running') limit 1`));
288
+ if (existing)
289
+ return { id: existing.id, created: false };
290
+ // No live job has the key any more: the duplicate finished, or a replace took its key. The
291
+ // key is free, as if this call had come a moment later, so try again. A finished job with
292
+ // the key isn't the answer: it may be any earlier job that had it.
293
+ }
294
+ throw new Error("enqueue found neither a new job nor the duplicate it collided with");
295
+ }
296
+ /**
297
+ * `enqueue` with `replace`, to debounce, as graphile-worker's "replace" mode does:
298
+ *
299
+ * - A pending job with the key gets this call's payload, timing, priority and maxAttempts, and
300
+ * keeps its id. Its attempts start again from 0; its claims don't, since they fence workers.
301
+ * - So does a running job whose lease ran out (its worker is gone): it goes back to pending,
302
+ * so the old worker can no longer finish it.
303
+ * - A running job that's alive keeps running, but gives up the key, and a new job is enqueued.
304
+ * Its payload may be out of date, and dropping this call would lose the latest one.
305
+ *
306
+ * The first statement replaces or inserts. If it does neither, a live running job holds the
307
+ * key: the second statement takes the key from it, and the first runs again.
308
+ */
309
+ async function enqueueReplacing(handler, job, dedupeKey, runAt, target) {
310
+ const payload = jsonbParam(JSON.stringify(job.json));
311
+ const mine = sql `j.type = ${handler.type}::text and j.dedupe_key = ${dedupeKey}::text`;
312
+ for (let attempt = 0; attempt < 5; attempt++) {
313
+ const [row] = rowsOf(await target.execute(sql `
314
+ with input as materialized (select ${now()} as now, ${current()} as current),
315
+ replaced as (
316
+ update ${table} as j set payload = ${payload}, run_at = ${runAt},
317
+ priority = ${job.priority}::int,
318
+ -- The new payload's tries start from 0. Claims fence workers, so they stay.
319
+ attempts = 0, max_attempts = ${job.maxAttempts}::int, last_error = null,
320
+ status = 'pending', locked_by = null, locked_until = null, updated_at = input.now
321
+ from input
322
+ where ${mine}
323
+ and (j.status = 'pending' or (j.status = 'running' and j.locked_until <= input.current))
324
+ returning j.id::text as id
325
+ ),
326
+ inserted as (
327
+ insert into ${table} as j (type, payload, priority, max_attempts, run_at, dedupe_key, created_at, updated_at)
328
+ select ${handler.type}::text, ${payload}, ${job.priority}::int, ${job.maxAttempts}::int,
329
+ ${runAt}, ${dedupeKey}::text, input.now, input.now
330
+ from input
331
+ where not exists (select 1 from replaced)
332
+ on conflict (type, dedupe_key) where dedupe_key is not null and status in ('pending', 'running') do nothing
333
+ returning j.id::text as id
334
+ )
335
+ select id, false as created from replaced
336
+ union all
337
+ select id, true from inserted`));
338
+ if (row)
339
+ return { id: row.id, created: row.created === true };
340
+ // A live running job holds the key. It keeps running without it, and the loop enqueues
341
+ // this one. Its current attempt becomes its last, as graphile-worker does it: its payload
342
+ // is out of date, so it must not be retried after (or alongside) the newer job. Only
343
+ // attempts change, so its worker still owns it, and a retry gets its full maxAttempts.
344
+ // If the job finished, was replaced or lost its lease meanwhile, this changes nothing, and
345
+ // the next round inserts or replaces.
346
+ await target.execute(sql `
347
+ update ${table} as j set dedupe_key = null, attempts = greatest(j.attempts, j.max_attempts),
348
+ updated_at = ${now()}
349
+ where ${mine} and j.status = 'running' and j.locked_until > ${current()}`);
350
+ }
351
+ // Other callers kept taking the key between the two statements.
352
+ throw new GroundworkError("conflict", "enqueue with replace kept colliding with other enqueues of the same key; try again.");
353
+ }
354
+ /**
355
+ * Enqueues jobs of one type in one statement. Every job is checked first, so a bad one
356
+ * enqueues nothing. Ids are generated here, so each result can be matched to its job whatever
357
+ * order Postgres inserts them in. Of the jobs that share a `dedupeKey`, only the first is
358
+ * inserted, as if they'd been enqueued one after another.
359
+ */
360
+ async function enqueueMany(handler, items, manyOptions = {}) {
361
+ if (!Array.isArray(items)) {
362
+ throw new GroundworkError("invalid_argument", "enqueueMany needs a list of jobs, such as [{ payload }, { payload, dedupeKey }].");
363
+ }
364
+ if (items.length > MAX_ENQUEUE_MANY) {
365
+ throw new GroundworkError("invalid_argument", `enqueueMany takes at most ${MAX_ENQUEUE_MANY} jobs at a time; split larger batches.`);
366
+ }
367
+ if (typeof manyOptions !== "object" || manyOptions === null) {
368
+ throw new GroundworkError("invalid_argument", "enqueueMany's options must be an object.");
369
+ }
370
+ if (items.length === 0)
371
+ return [];
372
+ const prepared = await Promise.all(items.map(async (item, index) => {
373
+ try {
374
+ // Without this, a bare payload would be read as options and enqueue no payload at all.
375
+ if (typeof item !== "object" || item === null || !("payload" in item)) {
376
+ throw new GroundworkError("invalid_argument", "each job needs a payload: { payload, dedupeKey?, delay?, … }.");
377
+ }
378
+ if ("replace" in item && item.replace !== undefined) {
379
+ throw new GroundworkError("invalid_argument", "enqueueMany doesn't take replace; use enqueue for each job you want to replace.");
380
+ }
381
+ if ("tx" in item && item.tx !== undefined) {
382
+ throw new GroundworkError("invalid_argument", "tx goes on the call, not on a job: enqueueMany(jobs, { tx }).");
383
+ }
384
+ return await prepare(handler, item.payload, item);
385
+ }
386
+ catch (error) {
387
+ if (!isGroundworkError(error))
388
+ throw error;
389
+ throw new GroundworkError(error.code, `jobs[${index}]: ${error.message}`, {
390
+ cause: error,
391
+ });
392
+ }
393
+ }));
394
+ const records = prepared.map((job, i) => ({
395
+ i,
396
+ id: randomUUID(),
397
+ // As text, so a null payload is stored as JSON null, as enqueue() stores it.
398
+ payload: JSON.stringify(job.json),
399
+ priority: job.priority,
400
+ max_attempts: job.maxAttempts,
401
+ run_at: job.runAt?.toISOString() ?? null,
402
+ delay_ms: job.delayMs,
403
+ dedupe_key: job.dedupeKey,
404
+ }));
405
+ const target = manyOptions.tx ?? db;
406
+ const insertBatch = async (batch) => rowsOf(await target.execute(sql `
214
407
  with input as materialized (select ${now()} as now),
408
+ items as (
409
+ select * from jsonb_to_recordset(${jsonbParam(JSON.stringify(batch))}) as t(
410
+ i int, id uuid, payload text, priority int, max_attempts int, run_at timestamptz,
411
+ delay_ms float8, dedupe_key text)
412
+ ),
413
+ firsts as (
414
+ select * from items where dedupe_key is null
415
+ union all
416
+ (select distinct on (dedupe_key) * from items where dedupe_key is not null
417
+ order by dedupe_key, i)
418
+ ),
215
419
  inserted as (
216
- insert into ${table} as j (type, payload, priority, max_attempts, run_at, dedupe_key, created_at, updated_at)
217
- select ${handler.type}::text, ${jsonbParam(JSON.stringify(json))}, ${priority}::int, ${maxAttempts}::int,
218
- ${runAt}, ${dedupeKey}::text, input.now, input.now
219
- from input
420
+ insert into ${table} as j (id, type, payload, priority, max_attempts, run_at, dedupe_key, created_at, updated_at)
421
+ select f.id, ${handler.type}::text, f.payload::jsonb, f.priority, f.max_attempts,
422
+ coalesce(f.run_at, input.now + coalesce(f.delay_ms, 0) * interval '1 millisecond'),
423
+ f.dedupe_key, input.now, input.now
424
+ from firsts as f, input
425
+ -- In key order, so concurrent calls that share keys wait for each other's keys in the
426
+ -- same order and can't deadlock. Ids were made in the app, so results keep the caller's.
427
+ order by f.dedupe_key nulls last, f.i
220
428
  on conflict (type, dedupe_key) where dedupe_key is not null and status in ('pending', 'running') do nothing
221
- returning j.id::text as id
429
+ returning j.id::text as id, j.dedupe_key
222
430
  )
223
- select id, true as created from inserted
431
+ select 'inserted' as kind, id, dedupe_key from inserted
224
432
  union all
225
- select j.id::text, false from ${table} j
226
- where ${dedupeKey}::text is not null and j.type = ${handler.type}::text and j.dedupe_key = ${dedupeKey}::text
227
- and j.status in ('pending', 'running') and not exists (select 1 from inserted)
228
- limit 1`));
229
- const row = rows[0];
230
- if (row)
231
- return { id: row.id, created: row.created === true };
232
- // The duplicate committed after this statement's snapshot was taken: look it up again.
233
- const [existing] = rowsOf(await target.execute(sql `select id::text as id from ${table} where type = ${handler.type}::text and dedupe_key = ${dedupeKey}::text and status in ('pending', 'running') limit 1`));
234
- if (!existing)
235
- throw new Error("enqueue found neither a new job nor the duplicate it collided with");
236
- return { id: existing.id, created: false };
433
+ -- The snapshot can still show a job that finished while the insert waited for it, so a
434
+ -- key this statement inserted isn't reported as existing too.
435
+ select 'existing', j.id::text, j.dedupe_key from ${table} as j
436
+ where j.type = ${handler.type}::text and j.status in ('pending', 'running')
437
+ and j.dedupe_key in (select dedupe_key from items where dedupe_key is not null)
438
+ and j.dedupe_key not in (select dedupe_key from inserted where dedupe_key is not null)`));
439
+ const inserted = new Set();
440
+ const byKey = new Map();
441
+ const unresolved = (batch) => batch.filter((record) => !inserted.has(record.id) && record.dedupe_key !== null && !byKey.has(record.dedupe_key));
442
+ // Every job goes in the first round. A later round only has keyed jobs whose duplicate
443
+ // vanished (see below), and stops once each has a job.
444
+ let batch = records;
445
+ for (let round = 0; round < 3 && batch.length > 0; round++) {
446
+ const rows = await insertBatch(batch);
447
+ // A job this call created wins over anything else with its key.
448
+ for (const row of rows) {
449
+ if (row.kind !== "inserted")
450
+ continue;
451
+ inserted.add(row.id);
452
+ if (row.dedupe_key !== null)
453
+ byKey.set(row.dedupe_key, row.id);
454
+ }
455
+ for (const row of rows) {
456
+ if (row.kind === "existing" && row.dedupe_key !== null && !byKey.has(row.dedupe_key)) {
457
+ byKey.set(row.dedupe_key, row.id);
458
+ }
459
+ }
460
+ // A duplicate that committed after this statement's snapshot was taken: look for those
461
+ // again. The rest of the batch is committed, so throwing would strand it.
462
+ const unknownKeys = [
463
+ ...new Set(unresolved(batch).flatMap((record) => record.dedupe_key ?? [])),
464
+ ];
465
+ if (unknownKeys.length > 0) {
466
+ const found = rowsOf(await target.execute(sql `
467
+ select id::text as id, dedupe_key from ${table}
468
+ where type = ${handler.type}::text and status in ('pending', 'running')
469
+ and dedupe_key in (${sql.join(unknownKeys.map((key) => sql `${key}::text`), sql `, `)})`));
470
+ for (const row of found)
471
+ byKey.set(row.dedupe_key, row.id);
472
+ }
473
+ // A key no live job has any more: the duplicate finished, or a replace took its key. The
474
+ // key is free, so those jobs go in again.
475
+ batch = unresolved(batch);
476
+ }
477
+ return records.map((record) => {
478
+ if (inserted.has(record.id))
479
+ return { id: record.id, created: true };
480
+ const existing = record.dedupe_key === null ? undefined : byKey.get(record.dedupe_key);
481
+ if (existing === undefined) {
482
+ throw new Error("enqueueMany found neither a new job nor the duplicate it collided with");
483
+ }
484
+ return { id: existing, created: false };
485
+ });
237
486
  }
238
487
  // ── Schedules ──────────────────────────────────────────────────────────────
239
488
  const scheduleValues = () => sql.join([...schedules.values()].map((s) => sql `(${s.name}::text, ${s.every}::text, ${s.everyMs}::float8, ${s.maxAttempts}::int)`), sql `, `);
@@ -296,7 +545,8 @@ export function createJobs(options) {
296
545
  const types = [...handlers.keys()];
297
546
  if (types.length === 0 || limit < 1)
298
547
  return [];
299
- const rows = rowsOf(await db.execute(sql `
548
+ // Every worker claims first, so a table without a column this version uses shows up here.
549
+ return selectRecords(sql `
300
550
  with input as materialized (select ${now()} as now),
301
551
  candidates as (
302
552
  select c.id from ${table} c, input
@@ -307,16 +557,33 @@ export function createJobs(options) {
307
557
  for update of c skip locked
308
558
  )
309
559
  update ${table} as j
310
- set status = 'running', attempts = j.attempts + 1, locked_by = ${workerId}::text,
560
+ set status = 'running', attempts = least(j.attempts::bigint + 1, ${MAX_INT}::bigint)::int,
561
+ claims = j.claims + 1,
562
+ locked_by = ${workerId}::text,
311
563
  locked_until = input.now + ${lease}, run_at = input.now + ${lease},
312
564
  started_at = coalesce(j.started_at, input.now), updated_at = input.now
313
565
  from candidates, input
314
566
  where j.id = candidates.id
315
- returning ${RECORD} as record`));
316
- return rows.map((row) => JSON.parse(row.record));
567
+ returning ${RECORD} as record`);
568
+ }
569
+ /**
570
+ * Runs a statement that selects `RECORD`s. If a column is missing, the app hasn't applied a
571
+ * migration this version needs: the error says so, instead of "column does not exist".
572
+ */
573
+ async function selectRecords(statement) {
574
+ let result;
575
+ try {
576
+ result = await db.execute(statement);
577
+ }
578
+ catch (error) {
579
+ if (pgCode(error) !== "42703")
580
+ throw error;
581
+ throw new GroundworkError("invalid_config", `The jobs table is missing a column this version of groundwork uses (${pgMessage(error)}). Generate a migration with drizzle-kit and apply it: 0.4.0 added "claims".`, { cause: error });
582
+ }
583
+ return rowsOf(result).map((row) => JSON.parse(row.record));
317
584
  }
318
- /** Only the worker holding the latest attempt may change a running job. */
319
- const owned = (job) => sql `j.id = ${job.id}::uuid and j.status = 'running' and j.locked_by = ${workerId}::text and j.attempts = ${job.attempts}::int`;
585
+ /** Only the worker holding the latest claim may change a running job. */
586
+ const owned = (job) => sql `j.id = ${job.id}::uuid and j.status = 'running' and j.locked_by = ${workerId}::text and j.claims = ${job.claims}::int`;
320
587
  async function extendLease(job) {
321
588
  const rows = rowsOf(await db.execute(sql `
322
589
  update ${table} as j set locked_until = ${now()} + ${lease}, run_at = ${now()} + ${lease}, updated_at = ${now()}
@@ -340,7 +607,7 @@ export function createJobs(options) {
340
607
  }
341
608
  async function fail(job, handler, error, permanent) {
342
609
  const { name, message } = errorText(error);
343
- const lastError = `${name}: ${message}`.slice(0, MAX_ERROR_LENGTH);
610
+ const lastError = storable(`${name}: ${message}`.slice(0, MAX_ERROR_LENGTH));
344
611
  const exhausted = permanent || job.attempts >= job.max_attempts;
345
612
  const delayMs = exhausted
346
613
  ? 0
@@ -352,26 +619,34 @@ export function createJobs(options) {
352
619
  update ${schedulesTable} set last_failure_at = ${now()}, last_error = ${lastError}::text, updated_at = ${now()}
353
620
  where name = ${handler.schedule}::text and exists (select 1 from done))`
354
621
  : sql ``;
622
+ // Decided against the row, not the claimed copy: giving up its key to a replace makes the
623
+ // running attempt the last one after the job was claimed.
624
+ const final = sql `(${exhausted}::boolean or j.attempts >= j.max_attempts)`;
355
625
  const [row] = rowsOf(await db.execute(sql `
356
626
  with done as (
357
627
  update ${table} as j set
358
- status = ${exhausted ? "failed" : "pending"}::text,
359
- run_at = ${exhausted ? sql `j.run_at` : sql `${now()} + ${delayMs}::float8 * interval '1 millisecond'`},
360
- completed_at = ${exhausted ? now() : sql `null`},
628
+ status = case when ${final} then 'failed' else 'pending' end,
629
+ run_at = case when ${final} then j.run_at
630
+ else ${now()} + ${delayMs}::float8 * interval '1 millisecond' end,
631
+ completed_at = case when ${final} then ${now()} else null end,
361
632
  last_error = ${lastError}::text, locked_by = null, locked_until = null, updated_at = ${now()}
362
- where ${owned(job)} returning 1
633
+ where ${owned(job)} returning j.status
363
634
  )${scheduleUpdate}
364
- select count(*)::int as done from done`));
365
- if (!row || toNumber(row.done) !== 1)
635
+ select status from done`));
636
+ if (!row)
366
637
  return "lost";
638
+ const failed = row.status === "failed";
367
639
  const context = { type: job.type, id: job.id, attempt: job.attempts, error: { name, message } };
368
- if (exhausted) {
640
+ if (failed && !exhausted) {
641
+ logger.warn(`Job "${job.type}" failed and isn't retried: a newer job with its dedupe key replaced it.`, context);
642
+ }
643
+ else if (failed) {
369
644
  logger.error(`Job "${job.type}" failed for good after ${job.attempts} attempt(s).`, context);
370
645
  }
371
646
  else {
372
647
  logger.warn(`Job "${job.type}" failed; retrying in ${Math.ceil(delayMs / 1000)}s.`, context);
373
648
  }
374
- return exhausted ? "failed" : "retried";
649
+ return failed ? "failed" : "retried";
375
650
  }
376
651
  async function execute(job, counters) {
377
652
  const handler = handlers.get(job.type);
@@ -424,7 +699,12 @@ export function createJobs(options) {
424
699
  }
425
700
  let payload = job.payload;
426
701
  if (handler.schema) {
427
- const checked = await validateWith(handler.schema, job.payload);
702
+ // A schema that throws (a transform calling new Date(x).toISOString(), say) is as final as
703
+ // one that rejects: the same payload would make it throw again.
704
+ const checked = await validateWith(handler.schema, job.payload).catch((thrown) => {
705
+ const { name, message } = errorText(thrown);
706
+ return { ok: false, message: `the schema threw ${name}: ${message}` };
707
+ });
428
708
  if (!checked.ok) {
429
709
  // A payload that doesn't validate never will: fail now instead of retrying.
430
710
  const error = new GroundworkError("invalid_argument", `Invalid payload: ${checked.message}`);
@@ -468,39 +748,80 @@ export function createJobs(options) {
468
748
  });
469
749
  });
470
750
  aborted.catch(() => { });
471
- const result = await Promise.race([running, aborted]);
472
- if (await complete(job, handler, result))
751
+ let result;
752
+ try {
753
+ result = await Promise.race([running, aborted]);
754
+ }
755
+ catch (error) {
756
+ const outcome = await fail(job, handler, error, false);
757
+ record(outcome);
758
+ if (outcome === "failed")
759
+ await runExhausted(payload, error);
760
+ return;
761
+ }
762
+ // The handler succeeded. Nothing after this counts as a failed attempt: retrying would
763
+ // repeat its side effects, and onExhausted would report work that was done.
764
+ if (await completeSucceeded(job, handler, result))
473
765
  counters.completed++;
474
766
  else
475
767
  record("lost");
476
768
  }
477
- catch (error) {
478
- const outcome = await fail(job, handler, error, false);
479
- record(outcome);
480
- if (outcome === "failed")
481
- await runExhausted(payload, error);
482
- }
483
769
  finally {
484
770
  clearTimeout(timer);
485
771
  clearInterval(heartbeat);
486
772
  }
487
773
  }
774
+ /**
775
+ * Marks a job whose handler succeeded as completed. A result that can't be stored (a `toJSON`
776
+ * that throws, or JSON beyond what `jsonb` holds) is stored as `null` instead, with an error
777
+ * logged. Any other error, a lost connection say, propagates: the job stays running until its
778
+ * lease runs out and then runs again, as after a crash.
779
+ */
780
+ async function completeSucceeded(job, handler, result) {
781
+ let stored;
782
+ try {
783
+ stored = toJsonValue(result);
784
+ JSON.stringify(stored);
785
+ }
786
+ catch (error) {
787
+ return completeWithoutResult(job, handler, error);
788
+ }
789
+ try {
790
+ return await complete(job, handler, stored);
791
+ }
792
+ catch (error) {
793
+ if (!UNSTORABLE.has(pgCode(error) ?? ""))
794
+ throw error;
795
+ return completeWithoutResult(job, handler, error);
796
+ }
797
+ }
798
+ async function completeWithoutResult(job, handler, error) {
799
+ logger.error(`Job "${job.type}" succeeded, but its result can't be stored; it's stored as null.`, {
800
+ id: job.id,
801
+ error: errorText(error),
802
+ });
803
+ return complete(job, handler, null);
804
+ }
488
805
  async function loop(settings) {
489
806
  const started = performance.now();
490
807
  const counters = { claimed: 0, completed: 0, retried: 0, failed: 0, scheduled: 0 };
491
808
  const inFlight = new Set();
809
+ // Called once when the next job finishes. One set of listeners instead of a `.then` on every
810
+ // running job each time round, which piled up on long jobs.
811
+ const onFinish = new Set();
812
+ const nextFinish = () => new Promise((resolve) => onFinish.add(resolve));
492
813
  const stopping = () => settings.signal?.aborted === true ||
493
814
  (settings.deadline !== null && performance.now() >= settings.deadline);
494
815
  let lastTick = Number.NEGATIVE_INFINITY;
495
816
  const wait = (msToWait) => new Promise((resolve) => {
496
817
  const timer = setTimeout(done, msToWait);
497
818
  settings.signal?.addEventListener("abort", done, { once: true });
498
- for (const promise of inFlight)
499
- promise.then(done, done);
819
+ onFinish.add(done);
500
820
  function done() {
501
821
  clearTimeout(timer);
502
822
  // Without this, every idle poll of a long-running worker would leave a listener behind.
503
823
  settings.signal?.removeEventListener("abort", done);
824
+ onFinish.delete(done);
504
825
  resolve();
505
826
  }
506
827
  });
@@ -517,18 +838,30 @@ export function createJobs(options) {
517
838
  once.reset("claim");
518
839
  counters.claimed += claimed.length;
519
840
  for (const job of claimed) {
520
- const promise = execute(job, counters).finally(() => inFlight.delete(promise));
841
+ const promise = execute(job, counters)
842
+ .catch((error) => {
843
+ // Only the database calls that record the outcome get here. The job stays
844
+ // running until its lease runs out, then runs again; the other jobs go on.
845
+ logger.error(`Job "${job.type}" ran, but its outcome couldn't be recorded; it runs again after its lease.`, { id: job.id, error: errorText(error) });
846
+ })
847
+ .finally(() => {
848
+ inFlight.delete(promise);
849
+ const listeners = [...onFinish];
850
+ onFinish.clear();
851
+ for (const listener of listeners)
852
+ listener();
853
+ });
521
854
  inFlight.add(promise);
522
855
  }
523
856
  if (inFlight.size >= settings.concurrency) {
524
- await Promise.race(inFlight);
857
+ await nextFinish();
525
858
  }
526
859
  else if (claimed.length < free) {
527
860
  // Nothing more is due right now.
528
861
  if (settings.mode === "once") {
529
862
  if (inFlight.size === 0)
530
863
  break;
531
- await Promise.race(inFlight); // a finishing job may have enqueued another
864
+ await nextFinish(); // a finishing job may have enqueued another
532
865
  }
533
866
  else {
534
867
  await wait(settings.pollMs);
@@ -538,7 +871,10 @@ export function createJobs(options) {
538
871
  catch (error) {
539
872
  if (settings.mode === "once")
540
873
  throw error;
541
- once.once("error", "claim", "The job worker could not reach the database; it keeps retrying.", {
874
+ // A table that needs a migration isn't an outage, so its own message leads the log.
875
+ once.once("error", "claim", isGroundworkError(error) && error.code === "invalid_config"
876
+ ? `${error.message} The job worker keeps retrying.`
877
+ : "The job worker could not reach the database; it keeps retrying.", {
542
878
  error: errorText(error),
543
879
  });
544
880
  await wait(settings.pollMs);
@@ -571,6 +907,7 @@ export function createJobs(options) {
571
907
  return {
572
908
  type,
573
909
  enqueue: (payload, enqueueOptions) => enqueue(handler, payload, enqueueOptions),
910
+ enqueueMany: (items, manyOptions) => enqueueMany(handler, items, manyOptions),
574
911
  };
575
912
  },
576
913
  schedule(name, scheduleOptions, run) {
@@ -607,10 +944,12 @@ export function createJobs(options) {
607
944
  return rows.length > 0;
608
945
  },
609
946
  runOnce(runOptions = {}) {
610
- const budgetMs = runOptions.budgetMs ?? 10_000;
611
- if (typeof budgetMs !== "number" || !Number.isFinite(budgetMs) || budgetMs <= 0) {
612
- throw new GroundworkError("invalid_argument", "budgetMs must be a positive number of milliseconds.");
947
+ if (runOptions.budgetMs !== undefined) {
948
+ throw new GroundworkError("invalid_argument", 'runOnce takes budget, a duration such as "10s"; budgetMs was removed in 1.0.');
613
949
  }
950
+ const budgetMs = runOptions.budget === undefined
951
+ ? 10_000
952
+ : parseDuration(runOptions.budget, { label: "budget", minMs: 1 });
614
953
  return loop({
615
954
  concurrency: validConcurrency(runOptions.concurrency),
616
955
  deadline: performance.now() + budgetMs,
@@ -635,8 +974,8 @@ export function createJobs(options) {
635
974
  async get(id) {
636
975
  if (!validId(id))
637
976
  return null;
638
- const [row] = rowsOf(await db.execute(sql `select ${RECORD} as record from ${table} j where j.id = ${id}::uuid`));
639
- return row ? toRecord(JSON.parse(row.record)) : null;
977
+ const [job] = await selectRecords(sql `select ${RECORD} as record from ${table} j where j.id = ${id}::uuid`);
978
+ return job ? toRecord(job) : null;
640
979
  },
641
980
  async list(filter = {}) {
642
981
  const limit = filter.limit ?? 100;
@@ -663,8 +1002,8 @@ export function createJobs(options) {
663
1002
  conditions.push(sql `j.created_at >= ${filter.since.toISOString()}::timestamptz`);
664
1003
  }
665
1004
  const where = conditions.length === 0 ? sql `` : sql `where ${sql.join(conditions, sql ` and `)}`;
666
- const rows = rowsOf(await db.execute(sql `select ${RECORD} as record from ${table} j ${where} order by j.created_at desc, j.id desc limit ${limit}`));
667
- return rows.map((row) => toRecord(JSON.parse(row.record)));
1005
+ const jobs = await selectRecords(sql `select ${RECORD} as record from ${table} j ${where} order by j.created_at desc, j.id desc limit ${limit}`);
1006
+ return jobs.map(toRecord);
668
1007
  },
669
1008
  async retry(id) {
670
1009
  if (!validId(id))
@@ -678,9 +1017,7 @@ export function createJobs(options) {
678
1017
  }
679
1018
  catch (error) {
680
1019
  // Another job with the same dedupe key is already pending or running.
681
- const code = error?.code ??
682
- error?.cause?.code;
683
- if (code === "23505")
1020
+ if (pgCode(error) === "23505")
684
1021
  return false;
685
1022
  throw error;
686
1023
  }
@@ -729,7 +1066,7 @@ export function createJobs(options) {
729
1066
  select j.type,
730
1067
  count(*) filter (where j.status = 'pending')::int as pending,
731
1068
  count(*) filter (where j.status = 'running')::int as running,
732
- count(*) filter (where j.status = 'failed' and j.completed_at > input.now - interval '24 hours')::int as failed_24h,
1069
+ count(*) filter (where j.status = 'failed' and j.completed_at > input.now - interval '24 hours')::int as failed_last_day,
733
1070
  ${sql.raw(ms("input.now"))} - ${sql.raw(ms("min(j.run_at) filter (where j.status = 'pending' and j.run_at <= input.now)"))} as oldest_pending_age_ms,
734
1071
  ${sql.raw(ms("max(j.completed_at) filter (where j.status = 'completed')"))} as last_success
735
1072
  from ${table} j, input
@@ -743,7 +1080,7 @@ export function createJobs(options) {
743
1080
  type,
744
1081
  pending: number(row?.pending),
745
1082
  running: number(row?.running),
746
- failedLast24h: number(row?.failed_24h),
1083
+ failedLast24h: number(row?.failed_last_day),
747
1084
  oldestPendingAgeMs: row?.oldest_pending_age_ms === null || row?.oldest_pending_age_ms === undefined
748
1085
  ? null
749
1086
  : Math.max(0, Math.round(toNumber(row.oldest_pending_age_ms))),