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