@vantedev/groundwork 0.3.2 → 0.4.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 (47) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +7 -6
  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 +36 -32
  6. package/dist/api-keys/api-keys.js.map +1 -1
  7. package/dist/idempotency/idempotency.d.ts +7 -1
  8. package/dist/idempotency/idempotency.d.ts.map +1 -1
  9. package/dist/idempotency/idempotency.js +169 -47
  10. package/dist/idempotency/idempotency.js.map +1 -1
  11. package/dist/index.d.ts +13 -3
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +7 -2
  14. package/dist/index.js.map +1 -1
  15. package/dist/internal/cidr.d.ts +6 -0
  16. package/dist/internal/cidr.d.ts.map +1 -1
  17. package/dist/internal/cidr.js +14 -0
  18. package/dist/internal/cidr.js.map +1 -1
  19. package/dist/internal/crypto.d.ts +14 -1
  20. package/dist/internal/crypto.d.ts.map +1 -1
  21. package/dist/internal/crypto.js +37 -5
  22. package/dist/internal/crypto.js.map +1 -1
  23. package/dist/internal/db.d.ts +4 -0
  24. package/dist/internal/db.d.ts.map +1 -1
  25. package/dist/internal/db.js +14 -0
  26. package/dist/internal/db.js.map +1 -1
  27. package/dist/jobs/index.d.ts +1 -1
  28. package/dist/jobs/index.d.ts.map +1 -1
  29. package/dist/jobs/jobs.d.ts +4 -1
  30. package/dist/jobs/jobs.d.ts.map +1 -1
  31. package/dist/jobs/jobs.js +318 -52
  32. package/dist/jobs/jobs.js.map +1 -1
  33. package/dist/jobs/types.d.ts +29 -0
  34. package/dist/jobs/types.d.ts.map +1 -1
  35. package/dist/rate-limit/index.d.ts +1 -0
  36. package/dist/rate-limit/index.d.ts.map +1 -1
  37. package/dist/rate-limit/index.js +1 -0
  38. package/dist/rate-limit/index.js.map +1 -1
  39. package/dist/rate-limit/ip-subject.d.ts +26 -0
  40. package/dist/rate-limit/ip-subject.d.ts.map +1 -0
  41. package/dist/rate-limit/ip-subject.js +21 -0
  42. package/dist/rate-limit/ip-subject.js.map +1 -0
  43. package/dist/schema/jobs.d.ts +23 -3
  44. package/dist/schema/jobs.d.ts.map +1 -1
  45. package/dist/schema/jobs.js +7 -2
  46. package/dist/schema/jobs.js.map +1 -1
  47. package/package.json +1 -1
package/dist/jobs/jobs.js CHANGED
@@ -1,10 +1,10 @@
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";
@@ -14,15 +14,23 @@ import { backoffDelayMs, ladderDelayMs } from "./backoff.js";
14
14
  const NAME_PATTERN = /^[A-Za-z0-9_.:-]{1,100}$/;
15
15
  const SCHEDULE_PREFIX = "schedule:";
16
16
  const MAX_LIST = 1_000;
17
+ const MAX_ENQUEUE_MANY = 1_000;
17
18
  const PRUNE_BATCH = 5_000;
18
19
  const MAX_ERROR_LENGTH = 2_000;
19
20
  const MAX_BACKOFF_STEPS = 100;
21
+ /**
22
+ * The largest `maxAttempts`: one less than Postgres's `integer`, which `attempts` and
23
+ * `max_attempts` are, because a claim can take `attempts` one past `max_attempts`.
24
+ */
25
+ const MAX_ATTEMPTS = 2_147_483_646;
26
+ /** Postgres's largest `integer`. */
27
+ const MAX_INT = 2_147_483_647;
20
28
  /** A schedule's tick may run this early at most (and never more than a tenth of `every`). */
21
29
  const SCHEDULE_EARLY_MAX_MS = 5_000;
22
30
  const ms = (column) => `(extract(epoch from ${column}) * 1000)::float8`;
23
31
  const RECORD = sql.raw(`jsonb_build_object(
24
32
  '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")},
33
+ 'attempts', j.attempts, 'max_attempts', j.max_attempts, 'claims', j.claims, 'run_at', ${ms("j.run_at")},
26
34
  'locked_until', ${ms("j.locked_until")}, 'locked_by', j.locked_by, 'dedupe_key', j.dedupe_key,
27
35
  'last_error', j.last_error, 'result', j.result, 'created_at', ${ms("j.created_at")},
28
36
  'started_at', ${ms("j.started_at")}, 'completed_at', ${ms("j.completed_at")}, 'updated_at', ${ms("j.updated_at")}
@@ -44,6 +52,7 @@ function toRecord(row) {
44
52
  priority: row.priority,
45
53
  attempts: row.attempts,
46
54
  maxAttempts: row.max_attempts,
55
+ claims: row.claims,
47
56
  runAt: new Date(row.run_at),
48
57
  lockedUntil: toDate(row.locked_until),
49
58
  lockedBy: row.locked_by,
@@ -68,6 +77,12 @@ function positiveInt(value, label, code) {
68
77
  }
69
78
  return value;
70
79
  }
80
+ function attemptsLimit(value, label, code) {
81
+ if (!Number.isSafeInteger(value) || value < 1 || value > MAX_ATTEMPTS) {
82
+ throw new GroundworkError(code, `${label} must be an integer from 1 to 2,147,483,646.`);
83
+ }
84
+ return value;
85
+ }
71
86
  function integer(value, label, code) {
72
87
  if (!Number.isSafeInteger(value) || Math.abs(value) > 1_000_000) {
73
88
  throw new GroundworkError(code, `${label} must be an integer between -1,000,000 and 1,000,000.`);
@@ -114,6 +129,11 @@ export function createJobs(options) {
114
129
  let schedulesSynced = false;
115
130
  /** The time a statement works with: the injected clock, else Postgres's `now()`. */
116
131
  const now = () => (clock ? sql `${clock.now().toISOString()}::timestamptz` : sql `now()`);
132
+ /**
133
+ * The time to judge a lease by. `now()` is when the transaction began, which inside a caller's
134
+ * long transaction can be well before the lease ran out.
135
+ */
136
+ const current = () => clock ? sql `${clock.now().toISOString()}::timestamptz` : sql `statement_timestamp()`;
117
137
  const lease = sql `${leaseMs}::float8 * interval '1 millisecond'`;
118
138
  function addHandler(type, definition, defaults, schedule) {
119
139
  if (handlers.has(type)) {
@@ -150,7 +170,7 @@ export function createJobs(options) {
150
170
  onExhausted: definition.onExhausted,
151
171
  maxAttempts: definition.maxAttempts === undefined
152
172
  ? defaults.maxAttempts
153
- : positiveInt(definition.maxAttempts, `maxAttempts of "${type}"`, "invalid_config"),
173
+ : attemptsLimit(definition.maxAttempts, `maxAttempts of "${type}"`, "invalid_config"),
154
174
  backoffBaseMs: parseDuration((backoff.base ?? defaults.base), {
155
175
  label: `backoff.base of "${type}"`,
156
176
  }),
@@ -182,14 +202,15 @@ export function createJobs(options) {
182
202
  }
183
203
  return toJsonValue(payload);
184
204
  }
185
- async function enqueue(handler, payload, enqueueOptions = {}) {
205
+ /** Validates one job's payload and options, as `enqueue` and `enqueueMany` both need. */
206
+ async function prepare(handler, payload, enqueueOptions) {
186
207
  const json = await payloadFor(handler, payload);
187
208
  const priority = enqueueOptions.priority === undefined
188
209
  ? handler.priority
189
210
  : integer(enqueueOptions.priority, "priority", "invalid_argument");
190
211
  const maxAttempts = enqueueOptions.maxAttempts === undefined
191
212
  ? handler.maxAttempts
192
- : positiveInt(enqueueOptions.maxAttempts, "maxAttempts", "invalid_argument");
213
+ : attemptsLimit(enqueueOptions.maxAttempts, "maxAttempts", "invalid_argument");
193
214
  const dedupeKey = enqueueOptions.dedupeKey ?? null;
194
215
  if (dedupeKey !== null &&
195
216
  (typeof dedupeKey !== "string" || dedupeKey === "" || dedupeKey.length > 500)) {
@@ -198,42 +219,259 @@ export function createJobs(options) {
198
219
  if (enqueueOptions.runAt !== undefined && enqueueOptions.delay !== undefined) {
199
220
  throw new GroundworkError("invalid_argument", "Pass runAt or delay, not both.");
200
221
  }
201
- let runAt = sql `input.now`;
222
+ let runAt = null;
223
+ let delayMs = null;
202
224
  if (enqueueOptions.runAt !== undefined) {
203
225
  if (!(enqueueOptions.runAt instanceof Date) || Number.isNaN(enqueueOptions.runAt.getTime())) {
204
226
  throw new GroundworkError("invalid_argument", "runAt must be a valid Date.");
205
227
  }
206
- runAt = sql `${enqueueOptions.runAt.toISOString()}::timestamptz`;
228
+ runAt = enqueueOptions.runAt;
207
229
  }
208
230
  else if (enqueueOptions.delay !== undefined) {
209
- const delayMs = parseDuration(enqueueOptions.delay, { label: "delay" });
210
- runAt = sql `input.now + ${delayMs}::float8 * interval '1 millisecond'`;
231
+ delayMs = parseDuration(enqueueOptions.delay, { label: "delay" });
232
+ }
233
+ return { json, priority, maxAttempts, dedupeKey, runAt, delayMs };
234
+ }
235
+ async function enqueue(handler, payload, enqueueOptions = {}) {
236
+ const replace = enqueueOptions.replace ?? false;
237
+ if (typeof replace !== "boolean") {
238
+ throw new GroundworkError("invalid_argument", "replace must be true or false.");
211
239
  }
240
+ const prepared = await prepare(handler, payload, enqueueOptions);
241
+ const { json, priority, maxAttempts, dedupeKey, ...when } = prepared;
242
+ const runAt = when.runAt !== null
243
+ ? sql `${when.runAt.toISOString()}::timestamptz`
244
+ : when.delayMs !== null
245
+ ? sql `input.now + ${when.delayMs}::float8 * interval '1 millisecond'`
246
+ : sql `input.now`;
212
247
  const target = enqueueOptions.tx ?? db;
213
- const rows = rowsOf(await target.execute(sql `
248
+ if (replace) {
249
+ if (dedupeKey === null) {
250
+ throw new GroundworkError("invalid_argument", "replace needs a dedupeKey: it replaces the pending job with that key.");
251
+ }
252
+ return enqueueReplacing(handler, prepared, dedupeKey, runAt, target);
253
+ }
254
+ for (let round = 0; round < 3; round++) {
255
+ const rows = rowsOf(await target.execute(sql `
256
+ with input as materialized (select ${now()} as now),
257
+ inserted as (
258
+ insert into ${table} as j (type, payload, priority, max_attempts, run_at, dedupe_key, created_at, updated_at)
259
+ select ${handler.type}::text, ${jsonbParam(JSON.stringify(json))}, ${priority}::int, ${maxAttempts}::int,
260
+ ${runAt}, ${dedupeKey}::text, input.now, input.now
261
+ from input
262
+ on conflict (type, dedupe_key) where dedupe_key is not null and status in ('pending', 'running') do nothing
263
+ returning j.id::text as id
264
+ )
265
+ select id, true as created from inserted
266
+ union all
267
+ select j.id::text, false from ${table} j
268
+ where ${dedupeKey}::text is not null and j.type = ${handler.type}::text and j.dedupe_key = ${dedupeKey}::text
269
+ and j.status in ('pending', 'running') and not exists (select 1 from inserted)
270
+ limit 1`));
271
+ const row = rows[0];
272
+ if (row)
273
+ return { id: row.id, created: row.created === true };
274
+ // The duplicate committed after this statement's snapshot was taken: look for it again.
275
+ const [existing] = rowsOf(await target.execute(sql `select id::text as id from ${table} where type = ${handler.type}::text and dedupe_key = ${dedupeKey}::text
276
+ and status in ('pending', 'running') limit 1`));
277
+ if (existing)
278
+ return { id: existing.id, created: false };
279
+ // No live job has the key any more: the duplicate finished, or a replace took its key. The
280
+ // key is free, as if this call had come a moment later, so try again. A finished job with
281
+ // the key isn't the answer: it may be any earlier job that had it.
282
+ }
283
+ throw new Error("enqueue found neither a new job nor the duplicate it collided with");
284
+ }
285
+ /**
286
+ * `enqueue` with `replace`, to debounce, as graphile-worker's "replace" mode does:
287
+ *
288
+ * - A pending job with the key gets this call's payload, timing, priority and maxAttempts, and
289
+ * keeps its id. Its attempts start again from 0; its claims don't, since they fence workers.
290
+ * - So does a running job whose lease ran out (its worker is gone): it goes back to pending,
291
+ * so the old worker can no longer finish it.
292
+ * - A running job that's alive keeps running, but gives up the key, and a new job is enqueued.
293
+ * Its payload may be out of date, and dropping this call would lose the latest one.
294
+ *
295
+ * The first statement replaces or inserts. If it does neither, a live running job holds the
296
+ * key: the second statement takes the key from it, and the first runs again.
297
+ */
298
+ async function enqueueReplacing(handler, job, dedupeKey, runAt, target) {
299
+ const payload = jsonbParam(JSON.stringify(job.json));
300
+ const mine = sql `j.type = ${handler.type}::text and j.dedupe_key = ${dedupeKey}::text`;
301
+ for (let attempt = 0; attempt < 5; attempt++) {
302
+ const [row] = rowsOf(await target.execute(sql `
303
+ with input as materialized (select ${now()} as now, ${current()} as current),
304
+ replaced as (
305
+ update ${table} as j set payload = ${payload}, run_at = ${runAt},
306
+ priority = ${job.priority}::int,
307
+ -- The new payload's tries start from 0. Claims fence workers, so they stay.
308
+ attempts = 0, max_attempts = ${job.maxAttempts}::int, last_error = null,
309
+ status = 'pending', locked_by = null, locked_until = null, updated_at = input.now
310
+ from input
311
+ where ${mine}
312
+ and (j.status = 'pending' or (j.status = 'running' and j.locked_until <= input.current))
313
+ returning j.id::text as id
314
+ ),
315
+ inserted as (
316
+ insert into ${table} as j (type, payload, priority, max_attempts, run_at, dedupe_key, created_at, updated_at)
317
+ select ${handler.type}::text, ${payload}, ${job.priority}::int, ${job.maxAttempts}::int,
318
+ ${runAt}, ${dedupeKey}::text, input.now, input.now
319
+ from input
320
+ where not exists (select 1 from replaced)
321
+ on conflict (type, dedupe_key) where dedupe_key is not null and status in ('pending', 'running') do nothing
322
+ returning j.id::text as id
323
+ )
324
+ select id, false as created from replaced
325
+ union all
326
+ select id, true from inserted`));
327
+ if (row)
328
+ return { id: row.id, created: row.created === true };
329
+ // A live running job holds the key. It keeps running without it, and the loop enqueues
330
+ // this one. Its current attempt becomes its last, as graphile-worker does it: its payload
331
+ // is out of date, so it must not be retried after (or alongside) the newer job. Only
332
+ // attempts change, so its worker still owns it, and a retry gets its full maxAttempts.
333
+ // If the job finished, was replaced or lost its lease meanwhile, this changes nothing, and
334
+ // the next round inserts or replaces.
335
+ await target.execute(sql `
336
+ update ${table} as j set dedupe_key = null, attempts = greatest(j.attempts, j.max_attempts),
337
+ updated_at = ${now()}
338
+ where ${mine} and j.status = 'running' and j.locked_until > ${current()}`);
339
+ }
340
+ // Other callers kept taking the key between the two statements.
341
+ throw new Error("enqueue with replace kept colliding with other enqueues of the same key");
342
+ }
343
+ /**
344
+ * Enqueues jobs of one type in one statement. Every job is checked first, so a bad one
345
+ * enqueues nothing. Ids are generated here, so each result can be matched to its job whatever
346
+ * order Postgres inserts them in. Of the jobs that share a `dedupeKey`, only the first is
347
+ * inserted, as if they'd been enqueued one after another.
348
+ */
349
+ async function enqueueMany(handler, items, manyOptions = {}) {
350
+ if (!Array.isArray(items)) {
351
+ throw new GroundworkError("invalid_argument", "enqueueMany needs a list of jobs, such as [{ payload }, { payload, dedupeKey }].");
352
+ }
353
+ if (items.length > MAX_ENQUEUE_MANY) {
354
+ throw new GroundworkError("invalid_argument", `enqueueMany takes at most ${MAX_ENQUEUE_MANY} jobs at a time; split larger batches.`);
355
+ }
356
+ if (typeof manyOptions !== "object" || manyOptions === null) {
357
+ throw new GroundworkError("invalid_argument", "enqueueMany's options must be an object.");
358
+ }
359
+ if (items.length === 0)
360
+ return [];
361
+ const prepared = await Promise.all(items.map(async (item, index) => {
362
+ try {
363
+ // Without this, a bare payload would be read as options and enqueue no payload at all.
364
+ if (typeof item !== "object" || item === null || !("payload" in item)) {
365
+ throw new GroundworkError("invalid_argument", "each job needs a payload: { payload, dedupeKey?, delay?, … }.");
366
+ }
367
+ if ("replace" in item && item.replace !== undefined) {
368
+ throw new GroundworkError("invalid_argument", "enqueueMany doesn't take replace; use enqueue for each job you want to replace.");
369
+ }
370
+ if ("tx" in item && item.tx !== undefined) {
371
+ throw new GroundworkError("invalid_argument", "tx goes on the call, not on a job: enqueueMany(jobs, { tx }).");
372
+ }
373
+ return await prepare(handler, item.payload, item);
374
+ }
375
+ catch (error) {
376
+ if (!isGroundworkError(error))
377
+ throw error;
378
+ throw new GroundworkError(error.code, `jobs[${index}]: ${error.message}`, {
379
+ cause: error,
380
+ });
381
+ }
382
+ }));
383
+ const records = prepared.map((job, i) => ({
384
+ i,
385
+ id: randomUUID(),
386
+ // As text, so a null payload is stored as JSON null, as enqueue() stores it.
387
+ payload: JSON.stringify(job.json),
388
+ priority: job.priority,
389
+ max_attempts: job.maxAttempts,
390
+ run_at: job.runAt?.toISOString() ?? null,
391
+ delay_ms: job.delayMs,
392
+ dedupe_key: job.dedupeKey,
393
+ }));
394
+ const target = manyOptions.tx ?? db;
395
+ const insertBatch = async (batch) => rowsOf(await target.execute(sql `
214
396
  with input as materialized (select ${now()} as now),
397
+ items as (
398
+ select * from jsonb_to_recordset(${jsonbParam(JSON.stringify(batch))}) as t(
399
+ i int, id uuid, payload text, priority int, max_attempts int, run_at timestamptz,
400
+ delay_ms float8, dedupe_key text)
401
+ ),
402
+ firsts as (
403
+ select * from items where dedupe_key is null
404
+ union all
405
+ (select distinct on (dedupe_key) * from items where dedupe_key is not null
406
+ order by dedupe_key, i)
407
+ ),
215
408
  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
409
+ insert into ${table} as j (id, type, payload, priority, max_attempts, run_at, dedupe_key, created_at, updated_at)
410
+ select f.id, ${handler.type}::text, f.payload::jsonb, f.priority, f.max_attempts,
411
+ coalesce(f.run_at, input.now + coalesce(f.delay_ms, 0) * interval '1 millisecond'),
412
+ f.dedupe_key, input.now, input.now
413
+ from firsts as f, input
414
+ -- In key order, so concurrent calls that share keys wait for each other's keys in the
415
+ -- same order and can't deadlock. Ids were made in the app, so results keep the caller's.
416
+ order by f.dedupe_key nulls last, f.i
220
417
  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
418
+ returning j.id::text as id, j.dedupe_key
222
419
  )
223
- select id, true as created from inserted
420
+ select 'inserted' as kind, id, dedupe_key from inserted
224
421
  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 };
422
+ -- The snapshot can still show a job that finished while the insert waited for it, so a
423
+ -- key this statement inserted isn't reported as existing too.
424
+ select 'existing', j.id::text, j.dedupe_key from ${table} as j
425
+ where j.type = ${handler.type}::text and j.status in ('pending', 'running')
426
+ and j.dedupe_key in (select dedupe_key from items where dedupe_key is not null)
427
+ and j.dedupe_key not in (select dedupe_key from inserted where dedupe_key is not null)`));
428
+ const inserted = new Set();
429
+ const byKey = new Map();
430
+ const unresolved = (batch) => batch.filter((record) => !inserted.has(record.id) && record.dedupe_key !== null && !byKey.has(record.dedupe_key));
431
+ // Every job goes in the first round. A later round only has keyed jobs whose duplicate
432
+ // vanished (see below), and stops once each has a job.
433
+ let batch = records;
434
+ for (let round = 0; round < 3 && batch.length > 0; round++) {
435
+ const rows = await insertBatch(batch);
436
+ // A job this call created wins over anything else with its key.
437
+ for (const row of rows) {
438
+ if (row.kind !== "inserted")
439
+ continue;
440
+ inserted.add(row.id);
441
+ if (row.dedupe_key !== null)
442
+ byKey.set(row.dedupe_key, row.id);
443
+ }
444
+ for (const row of rows) {
445
+ if (row.kind === "existing" && row.dedupe_key !== null && !byKey.has(row.dedupe_key)) {
446
+ byKey.set(row.dedupe_key, row.id);
447
+ }
448
+ }
449
+ // A duplicate that committed after this statement's snapshot was taken: look for those
450
+ // again. The rest of the batch is committed, so throwing would strand it.
451
+ const unknownKeys = [
452
+ ...new Set(unresolved(batch).flatMap((record) => record.dedupe_key ?? [])),
453
+ ];
454
+ if (unknownKeys.length > 0) {
455
+ const found = rowsOf(await target.execute(sql `
456
+ select id::text as id, dedupe_key from ${table}
457
+ where type = ${handler.type}::text and status in ('pending', 'running')
458
+ and dedupe_key in (${sql.join(unknownKeys.map((key) => sql `${key}::text`), sql `, `)})`));
459
+ for (const row of found)
460
+ byKey.set(row.dedupe_key, row.id);
461
+ }
462
+ // A key no live job has any more: the duplicate finished, or a replace took its key. The
463
+ // key is free, so those jobs go in again.
464
+ batch = unresolved(batch);
465
+ }
466
+ return records.map((record) => {
467
+ if (inserted.has(record.id))
468
+ return { id: record.id, created: true };
469
+ const existing = record.dedupe_key === null ? undefined : byKey.get(record.dedupe_key);
470
+ if (existing === undefined) {
471
+ throw new Error("enqueueMany found neither a new job nor the duplicate it collided with");
472
+ }
473
+ return { id: existing, created: false };
474
+ });
237
475
  }
238
476
  // ── Schedules ──────────────────────────────────────────────────────────────
239
477
  const scheduleValues = () => sql.join([...schedules.values()].map((s) => sql `(${s.name}::text, ${s.every}::text, ${s.everyMs}::float8, ${s.maxAttempts}::int)`), sql `, `);
@@ -296,7 +534,8 @@ export function createJobs(options) {
296
534
  const types = [...handlers.keys()];
297
535
  if (types.length === 0 || limit < 1)
298
536
  return [];
299
- const rows = rowsOf(await db.execute(sql `
537
+ // Every worker claims first, so a table without a column this version uses shows up here.
538
+ return selectRecords(sql `
300
539
  with input as materialized (select ${now()} as now),
301
540
  candidates as (
302
541
  select c.id from ${table} c, input
@@ -307,16 +546,33 @@ export function createJobs(options) {
307
546
  for update of c skip locked
308
547
  )
309
548
  update ${table} as j
310
- set status = 'running', attempts = j.attempts + 1, locked_by = ${workerId}::text,
549
+ set status = 'running', attempts = least(j.attempts::bigint + 1, ${MAX_INT}::bigint)::int,
550
+ claims = j.claims + 1,
551
+ locked_by = ${workerId}::text,
311
552
  locked_until = input.now + ${lease}, run_at = input.now + ${lease},
312
553
  started_at = coalesce(j.started_at, input.now), updated_at = input.now
313
554
  from candidates, input
314
555
  where j.id = candidates.id
315
- returning ${RECORD} as record`));
316
- return rows.map((row) => JSON.parse(row.record));
556
+ returning ${RECORD} as record`);
557
+ }
558
+ /**
559
+ * Runs a statement that selects `RECORD`s. If a column is missing, the app hasn't applied a
560
+ * migration this version needs: the error says so, instead of "column does not exist".
561
+ */
562
+ async function selectRecords(statement) {
563
+ let result;
564
+ try {
565
+ result = await db.execute(statement);
566
+ }
567
+ catch (error) {
568
+ if (pgCode(error) !== "42703")
569
+ throw error;
570
+ 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 });
571
+ }
572
+ return rowsOf(result).map((row) => JSON.parse(row.record));
317
573
  }
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`;
574
+ /** Only the worker holding the latest claim may change a running job. */
575
+ 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
576
  async function extendLease(job) {
321
577
  const rows = rowsOf(await db.execute(sql `
322
578
  update ${table} as j set locked_until = ${now()} + ${lease}, run_at = ${now()} + ${lease}, updated_at = ${now()}
@@ -352,26 +608,34 @@ export function createJobs(options) {
352
608
  update ${schedulesTable} set last_failure_at = ${now()}, last_error = ${lastError}::text, updated_at = ${now()}
353
609
  where name = ${handler.schedule}::text and exists (select 1 from done))`
354
610
  : sql ``;
611
+ // Decided against the row, not the claimed copy: giving up its key to a replace makes the
612
+ // running attempt the last one after the job was claimed.
613
+ const final = sql `(${exhausted}::boolean or j.attempts >= j.max_attempts)`;
355
614
  const [row] = rowsOf(await db.execute(sql `
356
615
  with done as (
357
616
  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`},
617
+ status = case when ${final} then 'failed' else 'pending' end,
618
+ run_at = case when ${final} then j.run_at
619
+ else ${now()} + ${delayMs}::float8 * interval '1 millisecond' end,
620
+ completed_at = case when ${final} then ${now()} else null end,
361
621
  last_error = ${lastError}::text, locked_by = null, locked_until = null, updated_at = ${now()}
362
- where ${owned(job)} returning 1
622
+ where ${owned(job)} returning j.status
363
623
  )${scheduleUpdate}
364
- select count(*)::int as done from done`));
365
- if (!row || toNumber(row.done) !== 1)
624
+ select status from done`));
625
+ if (!row)
366
626
  return "lost";
627
+ const failed = row.status === "failed";
367
628
  const context = { type: job.type, id: job.id, attempt: job.attempts, error: { name, message } };
368
- if (exhausted) {
629
+ if (failed && !exhausted) {
630
+ logger.warn(`Job "${job.type}" failed and isn't retried: a newer job with its dedupe key replaced it.`, context);
631
+ }
632
+ else if (failed) {
369
633
  logger.error(`Job "${job.type}" failed for good after ${job.attempts} attempt(s).`, context);
370
634
  }
371
635
  else {
372
636
  logger.warn(`Job "${job.type}" failed; retrying in ${Math.ceil(delayMs / 1000)}s.`, context);
373
637
  }
374
- return exhausted ? "failed" : "retried";
638
+ return failed ? "failed" : "retried";
375
639
  }
376
640
  async function execute(job, counters) {
377
641
  const handler = handlers.get(job.type);
@@ -538,7 +802,10 @@ export function createJobs(options) {
538
802
  catch (error) {
539
803
  if (settings.mode === "once")
540
804
  throw error;
541
- once.once("error", "claim", "The job worker could not reach the database; it keeps retrying.", {
805
+ // A table that needs a migration isn't an outage, so its own message leads the log.
806
+ once.once("error", "claim", isGroundworkError(error) && error.code === "invalid_config"
807
+ ? `${error.message} The job worker keeps retrying.`
808
+ : "The job worker could not reach the database; it keeps retrying.", {
542
809
  error: errorText(error),
543
810
  });
544
811
  await wait(settings.pollMs);
@@ -571,6 +838,7 @@ export function createJobs(options) {
571
838
  return {
572
839
  type,
573
840
  enqueue: (payload, enqueueOptions) => enqueue(handler, payload, enqueueOptions),
841
+ enqueueMany: (items, manyOptions) => enqueueMany(handler, items, manyOptions),
574
842
  };
575
843
  },
576
844
  schedule(name, scheduleOptions, run) {
@@ -635,8 +903,8 @@ export function createJobs(options) {
635
903
  async get(id) {
636
904
  if (!validId(id))
637
905
  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;
906
+ const [job] = await selectRecords(sql `select ${RECORD} as record from ${table} j where j.id = ${id}::uuid`);
907
+ return job ? toRecord(job) : null;
640
908
  },
641
909
  async list(filter = {}) {
642
910
  const limit = filter.limit ?? 100;
@@ -663,8 +931,8 @@ export function createJobs(options) {
663
931
  conditions.push(sql `j.created_at >= ${filter.since.toISOString()}::timestamptz`);
664
932
  }
665
933
  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)));
934
+ const jobs = await selectRecords(sql `select ${RECORD} as record from ${table} j ${where} order by j.created_at desc, j.id desc limit ${limit}`);
935
+ return jobs.map(toRecord);
668
936
  },
669
937
  async retry(id) {
670
938
  if (!validId(id))
@@ -678,9 +946,7 @@ export function createJobs(options) {
678
946
  }
679
947
  catch (error) {
680
948
  // 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")
949
+ if (pgCode(error) === "23505")
684
950
  return false;
685
951
  throw error;
686
952
  }