cairnq 0.1.0 → 0.3.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 (68) hide show
  1. package/README.md +28 -0
  2. package/dist/_protocol/migrations/postgres/0001_init.sql +3 -1
  3. package/dist/_protocol/migrations/postgres/0002_purge_index.sql +6 -0
  4. package/dist/_protocol/migrations/postgres/0003_notify.sql +38 -0
  5. package/dist/_protocol/migrations/postgres/0004_lease_index.sql +16 -0
  6. package/dist/_protocol/migrations/postgres/0005_clear_terminal_lease.sql +17 -0
  7. package/dist/_protocol/migrations/sqlite/0001_init.sql +3 -1
  8. package/dist/_protocol/migrations/sqlite/0002_purge_index.sql +6 -0
  9. package/dist/_protocol/migrations/sqlite/0004_lease_index.sql +22 -0
  10. package/dist/_protocol/migrations/sqlite/0005_clear_terminal_lease.sql +17 -0
  11. package/dist/_protocol/sql/postgres/claim.sql +18 -5
  12. package/dist/_protocol/sql/postgres/claim_one_queue.sql +35 -0
  13. package/dist/_protocol/sql/postgres/complete.sql +3 -0
  14. package/dist/_protocol/sql/postgres/fail.sql +30 -8
  15. package/dist/_protocol/sql/postgres/insert_task.sql +6 -3
  16. package/dist/_protocol/sql/postgres/list.sql +3 -1
  17. package/dist/_protocol/sql/postgres/lock_key.sql +9 -0
  18. package/dist/_protocol/sql/postgres/progress.sql +4 -3
  19. package/dist/_protocol/sql/postgres/protocol_version.sql +4 -0
  20. package/dist/_protocol/sql/postgres/purge.sql +25 -0
  21. package/dist/_protocol/sql/postgres/recover_leases.sql +49 -14
  22. package/dist/_protocol/sql/postgres/retry.sql +3 -0
  23. package/dist/_protocol/sql/postgres/stats.sql +8 -0
  24. package/dist/_protocol/sql/postgres/succeed.sql +4 -0
  25. package/dist/_protocol/sql/sqlite/claim.sql +13 -2
  26. package/dist/_protocol/sql/sqlite/claim_one_queue.sql +36 -0
  27. package/dist/_protocol/sql/sqlite/claimable_probe.sql +6 -2
  28. package/dist/_protocol/sql/sqlite/complete.sql +3 -0
  29. package/dist/_protocol/sql/sqlite/fail.sql +32 -8
  30. package/dist/_protocol/sql/sqlite/list.sql +3 -1
  31. package/dist/_protocol/sql/sqlite/lock_key.sql +5 -0
  32. package/dist/_protocol/sql/sqlite/progress.sql +6 -2
  33. package/dist/_protocol/sql/sqlite/protocol_version.sql +4 -0
  34. package/dist/_protocol/sql/sqlite/purge.sql +18 -0
  35. package/dist/_protocol/sql/sqlite/recover_leases.sql +25 -7
  36. package/dist/_protocol/sql/sqlite/retry.sql +3 -0
  37. package/dist/_protocol/sql/sqlite/stats.sql +8 -0
  38. package/dist/_protocol/sql/sqlite/succeed.sql +4 -0
  39. package/dist/client.d.ts +10 -2
  40. package/dist/client.js +12 -0
  41. package/dist/context.d.ts +17 -1
  42. package/dist/context.js +60 -6
  43. package/dist/errors.d.ts +18 -2
  44. package/dist/errors.js +49 -3
  45. package/dist/index.d.ts +3 -2
  46. package/dist/index.js +2 -1
  47. package/dist/sql.js +16 -9
  48. package/dist/store/base.d.ts +114 -9
  49. package/dist/store/base.js +376 -1
  50. package/dist/store/postgres.d.ts +62 -63
  51. package/dist/store/postgres.js +245 -222
  52. package/dist/store/sqlite.d.ts +83 -60
  53. package/dist/store/sqlite.js +370 -234
  54. package/dist/wait.d.ts +15 -2
  55. package/dist/wait.js +23 -5
  56. package/dist/worker.d.ts +53 -1
  57. package/dist/worker.js +202 -42
  58. package/package.json +9 -2
  59. package/src/client.ts +16 -2
  60. package/src/context.ts +70 -13
  61. package/src/errors.ts +59 -4
  62. package/src/index.ts +3 -1
  63. package/src/sql.ts +15 -8
  64. package/src/store/base.ts +443 -27
  65. package/src/store/postgres.ts +243 -267
  66. package/src/store/sqlite.ts +378 -263
  67. package/src/wait.ts +28 -5
  68. package/src/worker.ts +242 -42
@@ -1,5 +1,17 @@
1
- import type { Task } from "../models.js";
2
- export type Conflict = "reuse" | "reject" | "replace";
1
+ import { type Task, type TaskStatus } from "../models.js";
2
+ /** Encode a value for a protocol JSON column, raising SerializationError on
3
+ * anything JSON cannot represent. Refuses what JSON.stringify would silently
4
+ * mangle into `null`: NaN/Infinity anywhere, undefined/function/symbol inside an
5
+ * array, and a top-level undefined that disappears entirely — either way the
6
+ * twin SDK reads back something other than what the caller meant (the Python
7
+ * SDK rejects the same values, via allow_nan=False). */
8
+ export declare function dumpJson(value: unknown): string;
9
+ /** Refuse to run against a store whose protocol major this SDK does not speak.
10
+ * The supported major is a protocol fact, not a dialect one — every backend
11
+ * checks it here so the constant can't fork per store. */
12
+ export declare function checkProtocolVersion(version: number): void;
13
+ declare const CONFLICTS: readonly ["reuse", "reject", "replace"];
14
+ export type Conflict = (typeof CONFLICTS)[number];
3
15
  export interface SubmitInput {
4
16
  name: string;
5
17
  payload: unknown;
@@ -15,7 +27,7 @@ export interface SubmitInput {
15
27
  runAtDelayMs?: number;
16
28
  }
17
29
  export interface ListInput {
18
- status?: string | null;
30
+ status?: TaskStatus | null;
19
31
  queue?: string | null;
20
32
  name?: string | null;
21
33
  rootId?: string | null;
@@ -23,28 +35,120 @@ export interface ListInput {
23
35
  limit?: number;
24
36
  offset?: number;
25
37
  }
26
- /** The storage seam. SQLiteStore is the only MVP implementation. */
27
- export interface TaskStore {
28
- connect(): Promise<void>;
29
- close(): Promise<void>;
30
- protocolVersion(): Promise<number>;
38
+ export interface PurgeInput {
39
+ olderThanMs?: number;
40
+ limit?: number;
41
+ }
42
+ export type Params = Record<string, unknown>;
43
+ /** Runs one named protocol statement and returns its rows. */
44
+ export type Fetch = (name: string, params: Params) => Promise<any[]>;
45
+ export declare const LEASE_EXPIRED_ERROR_JSON: string;
46
+ /** Strips SQL line comments, so a `:name` in a header comment isn't a parameter. */
47
+ export declare const COMMENT: RegExp;
48
+ /** A `:name` placeholder. The lookbehind spares Postgres `::type` casts. */
49
+ export declare const NAMED: RegExp;
50
+ /**
51
+ * The parameter names a statement binds, in first-appearance order.
52
+ *
53
+ * Callers pass a superset of parameters and each dialect takes what its own SQL
54
+ * asks for — that is what lets one call site serve both dialects even though e.g.
55
+ * SQLite binds `:lease_until_ms` where Postgres binds `:lease_ms`. This is the one
56
+ * place that decides what counts as a parameter; both dialects' binding goes
57
+ * through it.
58
+ */
59
+ export declare function statementParams(sql: string): readonly string[];
60
+ /**
61
+ * The storage seam.
62
+ *
63
+ * A backend supplies three things: how to run one protocol statement, how to run
64
+ * several inside a transaction, and how its dialect binds parameters. Everything
65
+ * above that — the submit conflict branches, the *_by_key lookups, the
66
+ * recover-then-claim sequence, the ownership-checked writes — lives here once,
67
+ * because those are protocol decisions rather than storage decisions. Keeping
68
+ * them in one place is what stops SQLite and Postgres from drifting apart in
69
+ * behavior; the shared SQL already stops them from drifting in wording.
70
+ */
71
+ export declare abstract class TaskStore {
72
+ abstract connect(): Promise<void>;
73
+ abstract close(): Promise<void>;
74
+ abstract protocolVersion(): Promise<number>;
75
+ /** Run one protocol statement outside a transaction, connecting if needed. */
76
+ protected abstract fetch(name: string, params: Params): Promise<any[]>;
77
+ /**
78
+ * Run several statements atomically; `fn` receives a Fetch bound to the txn.
79
+ *
80
+ * A backend may invoke `fn` more than once, retrying the transaction after a
81
+ * transient failure (SQLite does, on write-lock contention). So `fn` must be
82
+ * replayable: derive nothing inside it that the caller cannot derive twice —
83
+ * build ids and payloads before opening the transaction, not within it.
84
+ */
85
+ protected abstract tx<T>(fn: (fetch: Fetch) => Promise<T>): Promise<T>;
86
+ /**
87
+ * Whether it is worth opening the claim transaction at all. SQLite gates its
88
+ * single write lock behind a read-only probe; Postgres readers don't block
89
+ * writers, so it just says yes.
90
+ */
91
+ protected hasClaimableWork(_params: Params): Promise<boolean>;
92
+ /** Resolves when a task may have become claimable on one of `queues`. The
93
+ * timer is unref'd: the worker races this against its own stop-aware, ref'd
94
+ * sleep, so it must neither hold the process open nor need clearing. */
95
+ claimWake(_queues: string[], timeoutMs: number): Promise<void>;
96
+ /** Resolves when `taskId` may have gone terminal. Plain ref'd sleep —
97
+ * pollWait awaits it directly, so it is what keeps the process alive. */
98
+ taskDoneWake(_taskId: string, timeoutMs: number): Promise<void>;
99
+ /**
100
+ * An ownership-checked worker write (heartbeat/progress/succeed/complete/fail).
101
+ * Each statement's WHERE pins worker_id + a live lease, so 0 rows back means
102
+ * the lease was lost — every such write reports it the same way.
103
+ */
104
+ private ownedWrite;
105
+ private static one;
31
106
  submit(input: SubmitInput): Promise<Task>;
32
107
  get(taskId: string): Promise<Task | null>;
33
108
  getByKey(key: string): Promise<Task | null>;
34
109
  list(input?: ListInput): Promise<Task[]>;
35
110
  cancel(taskId: string): Promise<Task | null>;
36
- cancelByKey(key: string): Promise<Task | null>;
37
111
  retry(taskId: string, opts?: {
38
112
  resetAttempt?: boolean;
39
113
  }): Promise<Task | null>;
114
+ cancelByKey(key: string): Promise<Task | null>;
40
115
  retryByKey(key: string, opts?: {
41
116
  resetAttempt?: boolean;
42
117
  }): Promise<Task | null>;
118
+ /**
119
+ * Resolve a key to the task it currently points at, then act on that task —
120
+ * under the key's lock, so a concurrent `replace` can't repoint the key
121
+ * between the lookup and the write (the transaction alone is not enough on
122
+ * Postgres; see lock_key.sql).
123
+ */
124
+ private byKey;
125
+ /**
126
+ * Delete terminal tasks that completed more than `olderThanMs` ago and return
127
+ * their ids. Nothing else removes rows, so a long-lived database needs this
128
+ * called periodically. Bounded by `limit` to keep each sweep a short write;
129
+ * call it in a loop until it returns fewer than `limit`.
130
+ */
131
+ purge(input?: PurgeInput): Promise<string[]>;
132
+ /**
133
+ * Task counts per queue, keyed by status and zero-filled across all statuses —
134
+ * `(await stats()).default.queued` is the backlog of a queue. A queue appears
135
+ * only while it has rows; terminal tasks keep counting until `purge` removes
136
+ * them.
137
+ */
138
+ stats(): Promise<Record<string, Record<TaskStatus, number>>>;
139
+ /**
140
+ * Take up to `limit` claimable tasks. `names` restricts the claim to task names
141
+ * this caller can actually run — a worker passes its registered handlers.
142
+ * Queues alone do not partition work, so without it a worker claims a task it
143
+ * cannot run and fails it permanently. Undefined means no filter; an empty
144
+ * array claims nothing.
145
+ */
43
146
  claim(input: {
44
147
  queues: string[];
45
148
  workerId: string;
46
149
  leaseMs?: number;
47
150
  limit?: number;
151
+ names?: string[];
48
152
  }): Promise<Task[]>;
49
153
  heartbeat(input: {
50
154
  taskId: string;
@@ -75,3 +179,4 @@ export interface TaskStore {
75
179
  delayMs?: number;
76
180
  }): Promise<Task>;
77
181
  }
182
+ export {};
@@ -1 +1,376 @@
1
- export {};
1
+ import { newId } from "../ids.js";
2
+ import { AlreadyExists, errorEnvelope, LostLease, ProtocolVersionMismatch, SerializationError, } from "../errors.js";
3
+ import { rowToTask, STATUSES } from "../models.js";
4
+ const rejectMangled = function (_key, v) {
5
+ if (typeof v === "number" && !Number.isFinite(v)) {
6
+ throw new SerializationError(`non-finite number ${v} is not JSON-serializable`);
7
+ }
8
+ // In an array these become the literal `null` (in an object they are merely
9
+ // omitted, the JS idiom for "absent") — the twin SDK would read back a null
10
+ // the caller never wrote.
11
+ if (Array.isArray(this) && (v === undefined || typeof v === "function" || typeof v === "symbol")) {
12
+ throw new SerializationError(`${typeof v} inside an array is not JSON-serializable`);
13
+ }
14
+ return v;
15
+ };
16
+ /** Encode a value for a protocol JSON column, raising SerializationError on
17
+ * anything JSON cannot represent. Refuses what JSON.stringify would silently
18
+ * mangle into `null`: NaN/Infinity anywhere, undefined/function/symbol inside an
19
+ * array, and a top-level undefined that disappears entirely — either way the
20
+ * twin SDK reads back something other than what the caller meant (the Python
21
+ * SDK rejects the same values, via allow_nan=False). */
22
+ export function dumpJson(value) {
23
+ let text;
24
+ try {
25
+ text = JSON.stringify(value);
26
+ }
27
+ catch (err) {
28
+ // BigInt or a circular structure.
29
+ throw new SerializationError(err instanceof Error ? err.message : String(err));
30
+ }
31
+ if (text === undefined) {
32
+ throw new SerializationError(`value of type ${typeof value} is not JSON-serializable`);
33
+ }
34
+ // Every mangled value reaches the output as the literal `null`, so a
35
+ // null-free result needs no strict pass — this keeps the replacer (which
36
+ // forfeits V8's native stringifier) off the hot path.
37
+ if (text.includes("null"))
38
+ JSON.stringify(value, rejectMangled);
39
+ return text;
40
+ }
41
+ const SUPPORTED_PROTOCOL_MAJOR = 1;
42
+ /** Refuse to run against a store whose protocol major this SDK does not speak.
43
+ * The supported major is a protocol fact, not a dialect one — every backend
44
+ * checks it here so the constant can't fork per store. */
45
+ export function checkProtocolVersion(version) {
46
+ if (version !== SUPPORTED_PROTOCOL_MAJOR) {
47
+ throw new ProtocolVersionMismatch(`storage protocol_version=${version}, SDK supports ${SUPPORTED_PROTOCOL_MAJOR}`);
48
+ }
49
+ }
50
+ // CONFLICTS is the canonical declaration; the type derives from it so the
51
+ // runtime guard in submit() and the type can't drift apart (same pattern as
52
+ // STATUSES/TaskStatus in models.ts).
53
+ const CONFLICTS = ["reuse", "reject", "replace"];
54
+ export const LEASE_EXPIRED_ERROR_JSON = dumpJson(errorEnvelope({
55
+ type: "LeaseExpired",
56
+ code: "lease_expired",
57
+ message: "task lease expired and max attempts reached",
58
+ retryable: false,
59
+ }));
60
+ /** Strips SQL line comments, so a `:name` in a header comment isn't a parameter. */
61
+ export const COMMENT = /--[^\n]*/g;
62
+ /** A `:name` placeholder. The lookbehind spares Postgres `::type` casts. */
63
+ export const NAMED = /(?<!:):(\w+)/g;
64
+ // Statement text is loaded once at construction and never varies, so the parse is
65
+ // memoized on it: every dialect's binding path runs on each query, and re-scanning
66
+ // the SQL each time would put a regex sweep on the worker's poll loop.
67
+ const paramCache = new Map();
68
+ /**
69
+ * The parameter names a statement binds, in first-appearance order.
70
+ *
71
+ * Callers pass a superset of parameters and each dialect takes what its own SQL
72
+ * asks for — that is what lets one call site serve both dialects even though e.g.
73
+ * SQLite binds `:lease_until_ms` where Postgres binds `:lease_ms`. This is the one
74
+ * place that decides what counts as a parameter; both dialects' binding goes
75
+ * through it.
76
+ */
77
+ export function statementParams(sql) {
78
+ let names = paramCache.get(sql);
79
+ if (!names) {
80
+ const seen = new Set();
81
+ for (const m of sql.replace(COMMENT, "").matchAll(NAMED))
82
+ seen.add(m[1]);
83
+ names = [...seen];
84
+ paramCache.set(sql, names);
85
+ }
86
+ return names;
87
+ }
88
+ /**
89
+ * The storage seam.
90
+ *
91
+ * A backend supplies three things: how to run one protocol statement, how to run
92
+ * several inside a transaction, and how its dialect binds parameters. Everything
93
+ * above that — the submit conflict branches, the *_by_key lookups, the
94
+ * recover-then-claim sequence, the ownership-checked writes — lives here once,
95
+ * because those are protocol decisions rather than storage decisions. Keeping
96
+ * them in one place is what stops SQLite and Postgres from drifting apart in
97
+ * behavior; the shared SQL already stops them from drifting in wording.
98
+ */
99
+ export class TaskStore {
100
+ /**
101
+ * Whether it is worth opening the claim transaction at all. SQLite gates its
102
+ * single write lock behind a read-only probe; Postgres readers don't block
103
+ * writers, so it just says yes.
104
+ */
105
+ async hasClaimableWork(_params) {
106
+ return true;
107
+ }
108
+ // ------------------------------------------------------------ wake channel
109
+ // Wake-or-timeout contract (PROTOCOL.md "Push wakeups"): resolve when the
110
+ // watched event may have happened, or after timeoutMs at the latest. The
111
+ // default is a plain sleep — polling IS the wake mechanism; a dialect with a
112
+ // push channel (PostgresStore, LISTEN/NOTIFY) resolves earlier.
113
+ /** Resolves when a task may have become claimable on one of `queues`. The
114
+ * timer is unref'd: the worker races this against its own stop-aware, ref'd
115
+ * sleep, so it must neither hold the process open nor need clearing. */
116
+ claimWake(_queues, timeoutMs) {
117
+ return new Promise((resolve) => setTimeout(resolve, timeoutMs).unref?.());
118
+ }
119
+ /** Resolves when `taskId` may have gone terminal. Plain ref'd sleep —
120
+ * pollWait awaits it directly, so it is what keeps the process alive. */
121
+ taskDoneWake(_taskId, timeoutMs) {
122
+ return new Promise((resolve) => setTimeout(resolve, timeoutMs));
123
+ }
124
+ // --------------------------------------------------------------- internals
125
+ /**
126
+ * An ownership-checked worker write (heartbeat/progress/succeed/complete/fail).
127
+ * Each statement's WHERE pins worker_id + a live lease, so 0 rows back means
128
+ * the lease was lost — every such write reports it the same way.
129
+ */
130
+ async ownedWrite(name, taskId, params) {
131
+ const rows = await this.fetch(name, params);
132
+ if (!rows.length)
133
+ throw new LostLease(taskId);
134
+ return rowToTask(rows[0]);
135
+ }
136
+ static one(rows) {
137
+ return rows.length ? rowToTask(rows[0]) : null;
138
+ }
139
+ // ------------------------------------------------------------- client side
140
+ async submit(input) {
141
+ const id = newId("task");
142
+ const ins = {
143
+ id,
144
+ name: input.name,
145
+ queue: input.queue ?? "default",
146
+ payload: dumpJson(input.payload ?? {}),
147
+ metadata: dumpJson(input.metadata ?? {}),
148
+ max_attempts: input.maxAttempts ?? 3,
149
+ priority: input.priority ?? 0,
150
+ delay_ms: input.runAtDelayMs ?? 0,
151
+ parent_id: input.parentId ?? null,
152
+ root_id: input.rootId ?? id,
153
+ correlation_id: input.correlationId ?? null,
154
+ };
155
+ const key = input.key ?? null;
156
+ const conflict = input.conflict ?? "reuse";
157
+ // Validate up front: untyped callers otherwise only hit the strategy branch
158
+ // on the second submit of a key, deep inside the transaction.
159
+ if (!CONFLICTS.includes(conflict)) {
160
+ throw new Error(`unknown conflict strategy: ${conflict}`);
161
+ }
162
+ // maxAttempts < 1 would still run once (claim increments before the check),
163
+ // a silently different meaning than the number says; a negative delay is
164
+ // always a mistake. Both fail loudly instead. Only supplied values are
165
+ // checked — the defaults live in the params object alone.
166
+ if (input.maxAttempts != null && input.maxAttempts < 1) {
167
+ throw new Error(`maxAttempts must be >= 1, got ${input.maxAttempts}`);
168
+ }
169
+ if (input.runAtDelayMs != null && input.runAtDelayMs < 0) {
170
+ throw new Error(`runAtDelayMs must be >= 0, got ${input.runAtDelayMs}`);
171
+ }
172
+ if (key === null)
173
+ return rowToTask((await this.fetch("insert_task", ins))[0]);
174
+ // A key makes submit a read-then-write, so it has to be one transaction —
175
+ // opened by taking the key's lock, because on Postgres the transaction alone
176
+ // is not enough: concurrent same-key submits must not both see "no existing
177
+ // task" (see lock_key.sql; on SQLite it is a no-op).
178
+ return this.tx(async (fetch) => {
179
+ await fetch("lock_key", { key });
180
+ const existing = (await fetch("get_key", { key }));
181
+ if (existing.length) {
182
+ // Read the task itself before branching: a concurrent purge (which
183
+ // takes no key lock) may have deleted it — cascading the key row away —
184
+ // between our statements' snapshots. A vanished task means the key is
185
+ // free after all, whatever the strategy.
186
+ const current = (await fetch("get", { id: existing[0].task_id }))[0];
187
+ if (current) {
188
+ if (conflict === "reuse")
189
+ return rowToTask(current);
190
+ if (conflict === "reject")
191
+ throw new AlreadyExists(key);
192
+ // "replace": cancel the recorded task, then repoint the key below.
193
+ await fetch("cancel", { id: existing[0].task_id });
194
+ }
195
+ }
196
+ const row = (await fetch("insert_task", ins))[0];
197
+ await fetch("upsert_key", { key, task_id: id });
198
+ return rowToTask(row);
199
+ });
200
+ }
201
+ async get(taskId) {
202
+ return TaskStore.one(await this.fetch("get", { id: taskId }));
203
+ }
204
+ async getByKey(key) {
205
+ return TaskStore.one(await this.fetch("get_by_key", { key }));
206
+ }
207
+ async list(input = {}) {
208
+ // Validate up front, like submit's conflict guard: a typo'd status otherwise
209
+ // matches nothing and returns [] indistinguishably from "no such tasks".
210
+ if (input.status != null && !STATUSES.includes(input.status)) {
211
+ throw new Error(`unknown status filter: ${input.status}`);
212
+ }
213
+ if ((input.limit != null && input.limit < 0) || (input.offset != null && input.offset < 0)) {
214
+ throw new Error(`limit/offset must be >= 0, got limit=${input.limit} offset=${input.offset}`);
215
+ }
216
+ const rows = await this.fetch("list", {
217
+ status: input.status ?? null,
218
+ queue: input.queue ?? null,
219
+ name: input.name ?? null,
220
+ root_id: input.rootId ?? null,
221
+ correlation_id: input.correlationId ?? null,
222
+ limit: input.limit ?? 100,
223
+ offset: input.offset ?? 0,
224
+ });
225
+ return rows.map(rowToTask);
226
+ }
227
+ async cancel(taskId) {
228
+ return TaskStore.one(await this.fetch("cancel", { id: taskId }));
229
+ }
230
+ async retry(taskId, opts = {}) {
231
+ return TaskStore.one(await this.fetch("retry", { id: taskId, reset_attempt: opts.resetAttempt ?? false }));
232
+ }
233
+ async cancelByKey(key) {
234
+ return this.byKey("cancel", key, {});
235
+ }
236
+ async retryByKey(key, opts = {}) {
237
+ return this.byKey("retry", key, { reset_attempt: opts.resetAttempt ?? false });
238
+ }
239
+ /**
240
+ * Resolve a key to the task it currently points at, then act on that task —
241
+ * under the key's lock, so a concurrent `replace` can't repoint the key
242
+ * between the lookup and the write (the transaction alone is not enough on
243
+ * Postgres; see lock_key.sql).
244
+ */
245
+ async byKey(name, key, params) {
246
+ return this.tx(async (fetch) => {
247
+ await fetch("lock_key", { key });
248
+ const existing = (await fetch("get_key", { key }));
249
+ if (!existing.length)
250
+ return null;
251
+ return TaskStore.one(await fetch(name, { id: existing[0].task_id, ...params }));
252
+ });
253
+ }
254
+ /**
255
+ * Delete terminal tasks that completed more than `olderThanMs` ago and return
256
+ * their ids. Nothing else removes rows, so a long-lived database needs this
257
+ * called periodically. Bounded by `limit` to keep each sweep a short write;
258
+ * call it in a loop until it returns fewer than `limit`.
259
+ */
260
+ async purge(input = {}) {
261
+ if (input.olderThanMs != null && input.olderThanMs < 0) {
262
+ throw new Error(`olderThanMs must be >= 0, got ${input.olderThanMs}`);
263
+ }
264
+ if (input.limit != null && input.limit < 1) {
265
+ throw new Error(`limit must be >= 1, got ${input.limit}`);
266
+ }
267
+ const rows = await this.fetch("purge", {
268
+ older_than_ms: input.olderThanMs ?? 0,
269
+ limit: input.limit ?? 1_000,
270
+ });
271
+ return rows.map((r) => r.id);
272
+ }
273
+ /**
274
+ * Task counts per queue, keyed by status and zero-filled across all statuses —
275
+ * `(await stats()).default.queued` is the backlog of a queue. A queue appears
276
+ * only while it has rows; terminal tasks keep counting until `purge` removes
277
+ * them.
278
+ */
279
+ async stats() {
280
+ const out = {};
281
+ for (const row of await this.fetch("stats", {})) {
282
+ const per = (out[row.queue] ??= Object.fromEntries(STATUSES.map((s) => [s, 0])));
283
+ per[row.status] = Number(row.count);
284
+ }
285
+ return out;
286
+ }
287
+ // ------------------------------------------------------------- worker side
288
+ /**
289
+ * Take up to `limit` claimable tasks. `names` restricts the claim to task names
290
+ * this caller can actually run — a worker passes its registered handlers.
291
+ * Queues alone do not partition work, so without it a worker claims a task it
292
+ * cannot run and fails it permanently. Undefined means no filter; an empty
293
+ * array claims nothing.
294
+ */
295
+ async claim(input) {
296
+ // One queue is the common case and gets its own statement: a list-valued queue
297
+ // filter cannot be read in claim order, so the planner sorts every claimable
298
+ // row to take LIMIT of them, and claim's cost grows with the queued backlog
299
+ // while it holds the claim transaction. See claim_one_queue.sql.
300
+ const oneQueue = input.queues.length === 1;
301
+ const params = {
302
+ queues: input.queues,
303
+ queue: oneQueue ? input.queues[0] : null,
304
+ names: input.names ?? null,
305
+ worker_id: input.workerId,
306
+ lease_ms: input.leaseMs ?? 30_000,
307
+ limit: input.limit ?? 1,
308
+ lease_expired_error: LEASE_EXPIRED_ERROR_JSON,
309
+ };
310
+ if (!(await this.hasClaimableWork(params)))
311
+ return [];
312
+ // Recovery must share the claim's transaction: a lease reclaimed here has to
313
+ // be visible to the claim that follows, and to nobody in between.
314
+ return this.tx(async (fetch) => {
315
+ await fetch("recover_leases", params);
316
+ return (await fetch(oneQueue ? "claim_one_queue" : "claim", params)).map(rowToTask);
317
+ });
318
+ }
319
+ async heartbeat(input) {
320
+ return this.ownedWrite("heartbeat", input.taskId, {
321
+ id: input.taskId,
322
+ worker_id: input.workerId,
323
+ lease_ms: input.leaseMs ?? 30_000,
324
+ });
325
+ }
326
+ async progress(input) {
327
+ return this.ownedWrite("progress", input.taskId, {
328
+ id: input.taskId,
329
+ worker_id: input.workerId,
330
+ progress: input.progress,
331
+ message: input.message,
332
+ });
333
+ }
334
+ async succeed(input) {
335
+ return this.ownedWrite("succeed", input.taskId, {
336
+ id: input.taskId,
337
+ worker_id: input.workerId,
338
+ result: input.result == null ? null : dumpJson(input.result),
339
+ message: null,
340
+ });
341
+ }
342
+ async complete(input) {
343
+ return this.ownedWrite("complete", input.taskId, {
344
+ id: input.taskId,
345
+ worker_id: input.workerId,
346
+ result: input.result == null ? null : dumpJson(input.result),
347
+ });
348
+ }
349
+ async fail(input) {
350
+ let error;
351
+ try {
352
+ error = dumpJson(input.error ?? {});
353
+ }
354
+ catch (err) {
355
+ if (!(err instanceof SerializationError))
356
+ throw err;
357
+ // A failure record must never itself fail to serialize (a TaskError
358
+ // carrying exotic details would otherwise strand the task until lease
359
+ // expiry). Strip the envelope to its string fields and record that.
360
+ const e = (input.error ?? {});
361
+ error = dumpJson(errorEnvelope({
362
+ type: String(e.type ?? "TaskError"),
363
+ code: String(e.code ?? "task_error"),
364
+ message: String(e.message ?? ""),
365
+ retryable: input.retryable !== false,
366
+ }));
367
+ }
368
+ return this.ownedWrite("fail", input.taskId, {
369
+ id: input.taskId,
370
+ worker_id: input.workerId,
371
+ error,
372
+ retryable: input.retryable !== false,
373
+ delay_ms: input.delayMs ?? 0,
374
+ });
375
+ }
376
+ }