cairnq 0.8.0 → 0.9.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.
package/README.md CHANGED
@@ -1,8 +1,12 @@
1
1
  # cairnq (TypeScript / Node)
2
2
 
3
3
  SQLite-first, cross-language, storage-centered durable task runtime. The
4
- TypeScript SDK (Node ≥ 20, `better-sqlite3`). API and worker processes coordinate
5
- only through a shared SQLite file.
4
+ TypeScript SDK (Node ≥ 20). API and worker processes coordinate only through a
5
+ shared SQLite file.
6
+
7
+ Both drivers are optional peers — install the one you use:
8
+ `npm i better-sqlite3` for the SQLite backend, `npm i pg` for Postgres. Importing
9
+ `cairnq` loads neither, so a Postgres-only deployment builds no native module.
6
10
 
7
11
  ```ts
8
12
  import { CairnQ, Worker } from "cairnq";
@@ -98,5 +102,64 @@ worker.task("long.job", async (ctx) => {
98
102
  Same code, Postgres instead of the file — `CairnQ.postgres(dsn)` /
99
103
  `Worker.postgres(dsn)`. Requires the optional `pg` peer dependency (`npm i pg`).
100
104
 
105
+ ### Sharing the application's connection
106
+
107
+ Given a `PgExecutor` instead of a DSN, cairnq runs inside a session the
108
+ application already has — no second driver, no second pool:
109
+
110
+ ```ts
111
+ import { CairnQ, type PgExecutor } from "cairnq";
112
+
113
+ const executor: PgExecutor = { /* ~30 lines over your driver */ };
114
+ const tasks = CairnQ.postgres(executor);
115
+ ```
116
+
117
+ `schema` (DSN form only) puts cairnq's tables in a schema of their own:
118
+ `CairnQ.postgres(dsn, { schema: "cairnq" })` creates it if absent and sets
119
+ `search_path` per connection. The protocol's SQL names no schema, so nothing else
120
+ changes. With your own executor, the search_path is yours to set.
121
+
122
+ Two things an adapter must get right: `int8` has to come back as a JS number
123
+ (every cairnq `*_ms` is an epoch or a counter, all inside the safe range), and
124
+ `jsonb` as an object rather than a string. An executor cairnq was handed is
125
+ never closed by cairnq.
126
+
127
+ That shared session is also what lets a task's settlement commit together with
128
+ the rows the task produced:
129
+
130
+ ```ts
131
+ worker.task("render.document", async (ctx, payload) => {
132
+ const rendered = await render(payload);
133
+ return ctx.succeedIn(async (session) => {
134
+ await db.withSession(session).insert(pages).values(rendered);
135
+ return { pages: rendered.length }; // becomes the task's result
136
+ });
137
+ });
138
+ ```
139
+
140
+ Without it the two are separate transactions, and a crash between them leaves
141
+ work durable while the task still reads as running — on retry, recomputed. If
142
+ the lease turns out to be gone, the settlement matches no row and the caller's
143
+ writes roll back with it.
144
+
145
+ ## Watching
146
+
147
+ `watch` calls back when the tasks on a queue may have changed — for a dashboard
148
+ that would otherwise poll:
149
+
150
+ ```ts
151
+ const stop = tasks.watch({ queues: ["render"] }, async (signal) => {
152
+ if (signal.reason === "done") return refreshOne(signal.taskId!);
153
+ setCounts(await tasks.stats());
154
+ });
155
+ ```
156
+
157
+ It is notify-accelerated polling, not an event log. On Postgres an idle watch
158
+ costs nothing and a signal lands within milliseconds; where LISTEN is
159
+ unavailable — a transaction-mode pooler, or SQLite, which has no channel — the
160
+ timer alone still delivers `poll` signals. So the same consumer is correct either
161
+ way, and only its promptness differs. Treat a signal as "re-read now"; the truth
162
+ is in `stats()` / `list()` / `get()`.
163
+
101
164
  The protocol (schema + canonical SQL) lives in `../cairnq-protocol` and is shared
102
165
  verbatim with the Python SDK. See `../cairnq-protocol/PROTOCOL.md`.
package/dist/client.d.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import type { BackpressureOptions } from "./backpressure.js";
2
2
  import { type RetentionOptions } from "./retention.js";
3
3
  import { type Task, type TaskRef, type TaskStatus } from "./models.js";
4
- import type { ListInput, PurgeInput, SubmitInput, TaskStore } from "./store/base.js";
4
+ import type { PgExecutor } from "./store/pg-executor.js";
5
+ import type { ListInput, PurgeInput, SubmitInput, TaskStore, WatchOptions, WatchSignal } from "./store/base.js";
5
6
  import { type TaskDef } from "./task.js";
6
7
  import { type PollOptions } from "./wait.js";
7
8
  export type SubmitOptions = Omit<SubmitInput, "name" | "payload">;
@@ -28,10 +29,13 @@ export declare class CairnQ {
28
29
  static sqlite(path: string, opts?: {
29
30
  busyTimeoutMs?: number;
30
31
  } & ClientOptions): CairnQ;
31
- /** Multi-host backend. `dsn` is a libpq connection string; requires the
32
- * optional `pg` package. */
33
- static postgres(dsn: string, opts?: {
32
+ /** Multi-host backend. `source` is a libpq connection string — which requires
33
+ * the optional `pg` package — or a PgExecutor over a driver the application
34
+ * already runs (an ORM's pool, say), which cairnq then shares instead of
35
+ * opening a second one. */
36
+ static postgres(source: string | PgExecutor, opts?: {
34
37
  max?: number;
38
+ schema?: string;
35
39
  } & ClientOptions): CairnQ;
36
40
  get store(): TaskStore;
37
41
  connect(): Promise<void>;
@@ -73,6 +77,17 @@ export declare class CairnQ {
73
77
  /** Task counts per queue, keyed by status and zero-filled across all statuses
74
78
  * — `(await stats()).default.queued` is the backlog of a queue. */
75
79
  stats(): Promise<Record<string, Record<TaskStatus, number>>>;
80
+ /**
81
+ * Call `onSignal` when the tasks on `queues` may have changed. Returns an
82
+ * unsubscribe.
83
+ *
84
+ * Notify-accelerated polling, not an event log: a signal means "re-read now",
85
+ * and `stats()` / `list()` / `get()` are where the truth is. On Postgres an
86
+ * idle watch costs nothing and signals land in milliseconds; everywhere else
87
+ * the timer alone still delivers, so the same consumer code is correct either
88
+ * way. See TaskStore.watch for the full contract.
89
+ */
90
+ watch(opts: WatchOptions, onSignal: (signal: WatchSignal) => void): () => void;
76
91
  /** Wait for a task to finish. Resolves with the terminal Task (any status);
77
92
  * throws TaskTimeout without stopping the task, so `wait(err.taskId)` picks the
78
93
  * same wait back up — from another process, or after a longer deadline. */
package/dist/client.js CHANGED
@@ -29,11 +29,13 @@ export class CairnQ {
29
29
  const { busyTimeoutMs, ...client } = opts;
30
30
  return new CairnQ(new SQLiteStore(path, { busyTimeoutMs }), client);
31
31
  }
32
- /** Multi-host backend. `dsn` is a libpq connection string; requires the
33
- * optional `pg` package. */
34
- static postgres(dsn, opts = {}) {
35
- const { max, ...client } = opts;
36
- return new CairnQ(new PostgresStore(dsn, { max }), client);
32
+ /** Multi-host backend. `source` is a libpq connection string — which requires
33
+ * the optional `pg` package — or a PgExecutor over a driver the application
34
+ * already runs (an ORM's pool, say), which cairnq then shares instead of
35
+ * opening a second one. */
36
+ static postgres(source, opts = {}) {
37
+ const { max, schema, ...client } = opts;
38
+ return new CairnQ(new PostgresStore(source, { max, schema }), client);
37
39
  }
38
40
  get store() {
39
41
  return this._store;
@@ -99,6 +101,19 @@ export class CairnQ {
99
101
  stats() {
100
102
  return this._store.stats();
101
103
  }
104
+ /**
105
+ * Call `onSignal` when the tasks on `queues` may have changed. Returns an
106
+ * unsubscribe.
107
+ *
108
+ * Notify-accelerated polling, not an event log: a signal means "re-read now",
109
+ * and `stats()` / `list()` / `get()` are where the truth is. On Postgres an
110
+ * idle watch costs nothing and signals land in milliseconds; everywhere else
111
+ * the timer alone still delivers, so the same consumer code is correct either
112
+ * way. See TaskStore.watch for the full contract.
113
+ */
114
+ watch(opts, onSignal) {
115
+ return this._store.watch(opts, onSignal);
116
+ }
102
117
  /** Wait for a task to finish. Resolves with the terminal Task (any status);
103
118
  * throws TaskTimeout without stopping the task, so `wait(err.taskId)` picks the
104
119
  * same wait back up — from another process, or after a longer deadline. */
package/dist/context.d.ts CHANGED
@@ -2,6 +2,7 @@ import { type FailReason } from "./errors.js";
2
2
  import { type Task } from "./models.js";
3
3
  import type { SubmitOptions } from "./client.js";
4
4
  import type { TaskStore } from "./store/base.js";
5
+ import type { PgSession } from "./store/pg-executor.js";
5
6
  import { type TaskDef } from "./task.js";
6
7
  export interface TaskContextOptions {
7
8
  retryBackoffMs?: number;
@@ -74,6 +75,30 @@ export declare class TaskContext {
74
75
  * this task was already settled.
75
76
  */
76
77
  succeed(result?: unknown): Promise<Task | null>;
78
+ /**
79
+ * Finalize this task as succeeded, committing the caller's own writes in the
80
+ * SAME transaction as the settlement. Whatever `write` returns becomes the
81
+ * task's result.
82
+ *
83
+ * await ctx.succeedIn(async (session) => {
84
+ * await db.withSession(session).insert(pages).values(rendered)
85
+ * return { pages: rendered.length }
86
+ * })
87
+ *
88
+ * The alternative — write the rows, then settle — has a window between the two
89
+ * commits where the work is durable but the task still reads as running. A
90
+ * crash there re-runs the whole task, which for a render or an ingest means
91
+ * recomputing it, and for non-idempotent work means doing it twice.
92
+ *
93
+ * `session` is the driver's, so this needs a Postgres store built on a
94
+ * PgExecutor the application shares with its own driver; anything else throws.
95
+ * If the settlement finds the lease gone, `write`'s work is rolled back with
96
+ * it and LostLease is raised. Returns null if this task was already settled.
97
+ *
98
+ * `write` may be replayed if the backend retries the transaction — derive
99
+ * nothing inside it that cannot be derived twice.
100
+ */
101
+ succeedIn<T>(write: (session: PgSession) => Promise<T>): Promise<Task | null>;
77
102
  /**
78
103
  * Finalize this task as failed, now. `error` may be a string reason, an Error,
79
104
  * a TaskError (which carries its own retryability), or a ready envelope.
package/dist/context.js CHANGED
@@ -184,6 +184,39 @@ export class TaskContext {
184
184
  this.markSettled();
185
185
  return task;
186
186
  }
187
+ /**
188
+ * Finalize this task as succeeded, committing the caller's own writes in the
189
+ * SAME transaction as the settlement. Whatever `write` returns becomes the
190
+ * task's result.
191
+ *
192
+ * await ctx.succeedIn(async (session) => {
193
+ * await db.withSession(session).insert(pages).values(rendered)
194
+ * return { pages: rendered.length }
195
+ * })
196
+ *
197
+ * The alternative — write the rows, then settle — has a window between the two
198
+ * commits where the work is durable but the task still reads as running. A
199
+ * crash there re-runs the whole task, which for a render or an ingest means
200
+ * recomputing it, and for non-idempotent work means doing it twice.
201
+ *
202
+ * `session` is the driver's, so this needs a Postgres store built on a
203
+ * PgExecutor the application shares with its own driver; anything else throws.
204
+ * If the settlement finds the lease gone, `write`'s work is rolled back with
205
+ * it and LostLease is raised. Returns null if this task was already settled.
206
+ *
207
+ * `write` may be replayed if the backend retries the transaction — derive
208
+ * nothing inside it that cannot be derived twice.
209
+ */
210
+ async succeedIn(write) {
211
+ if (this.isSettled)
212
+ return null;
213
+ const task = await this.owned(async () => {
214
+ const { task } = await this.store.completeIn({ taskId: this.task.id, workerId: this.workerId }, write);
215
+ return task;
216
+ });
217
+ this.markSettled();
218
+ return task;
219
+ }
187
220
  /**
188
221
  * Finalize this task as failed, now. `error` may be a string reason, an Error,
189
222
  * a TaskError (which carries its own retryability), or a ready envelope.
package/dist/index.d.ts CHANGED
@@ -12,8 +12,12 @@ export { defineTask } from "./task.js";
12
12
  export type { TaskDef } from "./task.js";
13
13
  export { SQLiteStore } from "./store/sqlite.js";
14
14
  export { PostgresStore } from "./store/postgres.js";
15
+ export { ListenUnavailable } from "./store/pg-executor.js";
16
+ export type { PgExecutor, PgSession, Row } from "./store/pg-executor.js";
17
+ export { createPoolExecutor } from "./store/pg-pool.js";
15
18
  export { TaskStore } from "./store/base.js";
16
- export type { ListInput, PurgeInput, SubmitInput, Conflict } from "./store/base.js";
19
+ export type { ListInput, PurgeInput, SubmitInput, Conflict, WatchOptions, WatchSignal, } from "./store/base.js";
20
+ export { DEFAULT_WATCH_POLL_MS } from "./store/base.js";
17
21
  export type { Task, TaskRef, TaskStatus, TerminalStatus } from "./models.js";
18
22
  export { STATUSES, isTerminal, isTerminalStatus, cancelRequested, isQueued, isRunning, isSucceeded, isFailed, isCanceled, } from "./models.js";
19
23
  export { CairnQError, AlreadyExists, QueueFull, TaskTimeout, TaskFailed, TaskCanceled, TaskError, LostLease, EventLoopBlocked, ProtocolVersionMismatch, SerializationError, } from "./errors.js";
package/dist/index.js CHANGED
@@ -6,6 +6,9 @@ export { TaskContext } from "./context.js";
6
6
  export { defineTask } from "./task.js";
7
7
  export { SQLiteStore } from "./store/sqlite.js";
8
8
  export { PostgresStore } from "./store/postgres.js";
9
+ export { ListenUnavailable } from "./store/pg-executor.js";
10
+ export { createPoolExecutor } from "./store/pg-pool.js";
9
11
  export { TaskStore } from "./store/base.js";
12
+ export { DEFAULT_WATCH_POLL_MS } from "./store/base.js";
10
13
  export { STATUSES, isTerminal, isTerminalStatus, cancelRequested, isQueued, isRunning, isSucceeded, isFailed, isCanceled, } from "./models.js";
11
14
  export { CairnQError, AlreadyExists, QueueFull, TaskTimeout, TaskFailed, TaskCanceled, TaskError, LostLease, EventLoopBlocked, ProtocolVersionMismatch, SerializationError, } from "./errors.js";
@@ -83,6 +83,32 @@ export declare function statementParams(sql: string): readonly string[];
83
83
  * them in one place is what stops SQLite and Postgres from drifting apart in
84
84
  * behavior; the shared SQL already stops them from drifting in wording.
85
85
  */
86
+ /**
87
+ * Why `watch` is calling back.
88
+ *
89
+ * `queued` / `done` come from the store's push channel and name what moved;
90
+ * `poll` is the timer saying the watch cannot rule out a change. None of them
91
+ * carries state — the row is the truth.
92
+ */
93
+ export interface WatchSignal {
94
+ reason: "queued" | "done" | "poll";
95
+ /** The queue a task was queued on. Only on `queued`. */
96
+ queue?: string;
97
+ /** The task that reached a terminal status. Only on `done`. */
98
+ taskId?: string;
99
+ }
100
+ export interface WatchOptions {
101
+ /** Restrict `queued` signals to these queues. Unset watches every queue. */
102
+ queues?: string[];
103
+ /**
104
+ * How often to signal in the absence of a push channel — and, where there is
105
+ * one, how long a dropped listener can go unnoticed. The default trades a
106
+ * dashboard's idle query rate against how stale it may look.
107
+ */
108
+ pollMs?: number;
109
+ }
110
+ /** See WatchOptions.pollMs. */
111
+ export declare const DEFAULT_WATCH_POLL_MS = 2000;
86
112
  export declare abstract class TaskStore {
87
113
  /** Set by useBackpressure; null means submit is ungated. */
88
114
  private gate;
@@ -100,6 +126,34 @@ export declare abstract class TaskStore {
100
126
  * build ids and payloads before opening the transaction, not within it.
101
127
  */
102
128
  protected abstract tx<T>(fn: (fetch: Fetch) => Promise<T>): Promise<T>;
129
+ /**
130
+ * `tx`, but also handing `fn` the driver's own session so the CALLER can run
131
+ * their statements in the same transaction as the protocol's.
132
+ *
133
+ * This is what lets a task's settlement and the rows that task produced commit
134
+ * together. Without it the two are separate transactions and there is a window
135
+ * where the work is durable but the task still reads as unfinished — a crash
136
+ * there costs a full recomputation on retry, and for non-idempotent work costs
137
+ * more than that.
138
+ *
139
+ * Optional, because the session type is the driver's, not the protocol's: a
140
+ * store that has no session worth handing out simply does not implement it and
141
+ * `completeIn` reports that. Postgres implements it; SQLite does not.
142
+ */
143
+ protected txWithSession?<T>(fn: (fetch: Fetch, session: unknown) => Promise<T>): Promise<T>;
144
+ /**
145
+ * Register for this store's push channel, if it has one; returns an
146
+ * unsubscribe. A store without a push channel does not implement this, and
147
+ * `watch` degrades to its timer alone.
148
+ */
149
+ protected subscribePush?(onSignal: (signal: WatchSignal) => void): () => void;
150
+ /**
151
+ * Nudge the push channel back up if it has dropped. Called from `watch`'s
152
+ * timer, which is the only thing keeping a client-side subscriber alive: a
153
+ * process that never claims never calls claimWake, so without this a listener
154
+ * that died once would never come back there.
155
+ */
156
+ protected warmPush?(): void;
103
157
  /**
104
158
  * Whether it is worth opening the claim transaction at all. SQLite gates its
105
159
  * single write lock behind a read-only probe; Postgres readers don't block
@@ -169,6 +223,28 @@ export declare abstract class TaskStore {
169
223
  * them.
170
224
  */
171
225
  stats(): Promise<Record<string, Record<TaskStatus, number>>>;
226
+ /**
227
+ * Call `onSignal` when the tasks on `queues` may have changed — something was
228
+ * queued, or something finished.
229
+ *
230
+ * This is notify-ACCELERATED POLLING, not an event log, and the difference is
231
+ * the whole contract. Where a push channel is available (Postgres LISTEN) an
232
+ * idle watch costs nothing and a signal arrives within milliseconds of the
233
+ * event. Where it is not — a transaction-mode pooler refuses LISTEN, SQLite has
234
+ * no channel at all — the timer alone still delivers `poll` signals, so a
235
+ * consumer that re-reads on every signal is correct in both cases and merely
236
+ * less prompt in one.
237
+ *
238
+ * What it will NOT do is promise that a signal means something happened, or
239
+ * that every event produces its own signal. Treat a signal as "re-read now"
240
+ * and take the truth from `stats()` / `list()` / `get()`, which is where it
241
+ * lives. `reason` is a hint for reading less: a `done` signal names the task,
242
+ * so a dashboard can refresh that row instead of the list.
243
+ *
244
+ * Returns an unsubscribe. The timer is unref'd — watching does not hold a
245
+ * process open.
246
+ */
247
+ watch(opts: WatchOptions, onSignal: (signal: WatchSignal) => void): () => void;
172
248
  /**
173
249
  * How many more tasks fit on `queue` under `maxDepth` — 0 once it is full.
174
250
  *
@@ -262,6 +338,29 @@ export declare abstract class TaskStore {
262
338
  workerId: string;
263
339
  result: unknown;
264
340
  }): Promise<Task>;
341
+ /**
342
+ * `complete`, with the caller's own writes committed in the same transaction.
343
+ *
344
+ * `fn` runs first and whatever it returns becomes the task's result; the
345
+ * settlement is the last statement in the transaction. So a lost lease — the
346
+ * settlement matching no row — rolls the caller's writes back with it, and
347
+ * there is no ordering in which the work is recorded but the task is not.
348
+ *
349
+ * The settlement runs LAST rather than checking ownership up front on purpose:
350
+ * the ownership predicate lives in the protocol's complete.sql, and a
351
+ * fail-fast pre-check here would be a second copy of it, free to drift. The
352
+ * cost of that choice is that a doomed attempt does its work before finding
353
+ * out, which is the rare path.
354
+ *
355
+ * `fn` must be replayable for the same reason `tx`'s callback must be.
356
+ */
357
+ completeIn<S, T>(input: {
358
+ taskId: string;
359
+ workerId: string;
360
+ }, fn: (session: S) => Promise<T>): Promise<{
361
+ task: Task;
362
+ value: T;
363
+ }>;
265
364
  fail(input: {
266
365
  taskId: string;
267
366
  workerId: string;
@@ -122,17 +122,8 @@ export function statementParams(sql) {
122
122
  }
123
123
  return names;
124
124
  }
125
- /**
126
- * The storage seam.
127
- *
128
- * A backend supplies three things: how to run one protocol statement, how to run
129
- * several inside a transaction, and how its dialect binds parameters. Everything
130
- * above that — the submit conflict branches, the *_by_key lookups, the
131
- * recover-then-claim sequence, the ownership-checked writes — lives here once,
132
- * because those are protocol decisions rather than storage decisions. Keeping
133
- * them in one place is what stops SQLite and Postgres from drifting apart in
134
- * behavior; the shared SQL already stops them from drifting in wording.
135
- */
125
+ /** See WatchOptions.pollMs. */
126
+ export const DEFAULT_WATCH_POLL_MS = 2_000;
136
127
  export class TaskStore {
137
128
  /** Set by useBackpressure; null means submit is ungated. */
138
129
  gate = null;
@@ -354,6 +345,57 @@ export class TaskStore {
354
345
  }
355
346
  return out;
356
347
  }
348
+ /**
349
+ * Call `onSignal` when the tasks on `queues` may have changed — something was
350
+ * queued, or something finished.
351
+ *
352
+ * This is notify-ACCELERATED POLLING, not an event log, and the difference is
353
+ * the whole contract. Where a push channel is available (Postgres LISTEN) an
354
+ * idle watch costs nothing and a signal arrives within milliseconds of the
355
+ * event. Where it is not — a transaction-mode pooler refuses LISTEN, SQLite has
356
+ * no channel at all — the timer alone still delivers `poll` signals, so a
357
+ * consumer that re-reads on every signal is correct in both cases and merely
358
+ * less prompt in one.
359
+ *
360
+ * What it will NOT do is promise that a signal means something happened, or
361
+ * that every event produces its own signal. Treat a signal as "re-read now"
362
+ * and take the truth from `stats()` / `list()` / `get()`, which is where it
363
+ * lives. `reason` is a hint for reading less: a `done` signal names the task,
364
+ * so a dashboard can refresh that row instead of the list.
365
+ *
366
+ * Returns an unsubscribe. The timer is unref'd — watching does not hold a
367
+ * process open.
368
+ */
369
+ watch(opts, onSignal) {
370
+ const pollMs = Math.max(1, opts.pollMs ?? DEFAULT_WATCH_POLL_MS);
371
+ const queues = opts.queues ?? null;
372
+ let live = true;
373
+ const emit = (signal) => {
374
+ // A signal delivered after unsubscribe would have the consumer re-reading
375
+ // a store it has stopped caring about, possibly a closed one.
376
+ if (live)
377
+ onSignal(signal);
378
+ };
379
+ const unsubscribe = this.subscribePush?.((signal) => {
380
+ // A queued signal names its queue, so a watch scoped to some queues can
381
+ // drop the rest. A done signal names only the task — which queue it was on
382
+ // is not in the notification, so it is never filtered out.
383
+ if (signal.reason === "queued" && queues && signal.queue && !queues.includes(signal.queue)) {
384
+ return;
385
+ }
386
+ emit(signal);
387
+ });
388
+ const timer = setInterval(() => {
389
+ this.warmPush?.();
390
+ emit({ reason: "poll" });
391
+ }, pollMs);
392
+ timer.unref?.();
393
+ return () => {
394
+ live = false;
395
+ unsubscribe?.();
396
+ clearInterval(timer);
397
+ };
398
+ }
357
399
  /**
358
400
  * How many more tasks fit on `queue` under `maxDepth` — 0 once it is full.
359
401
  *
@@ -504,6 +546,40 @@ export class TaskStore {
504
546
  result: input.result == null ? null : dumpJson(input.result),
505
547
  });
506
548
  }
549
+ /**
550
+ * `complete`, with the caller's own writes committed in the same transaction.
551
+ *
552
+ * `fn` runs first and whatever it returns becomes the task's result; the
553
+ * settlement is the last statement in the transaction. So a lost lease — the
554
+ * settlement matching no row — rolls the caller's writes back with it, and
555
+ * there is no ordering in which the work is recorded but the task is not.
556
+ *
557
+ * The settlement runs LAST rather than checking ownership up front on purpose:
558
+ * the ownership predicate lives in the protocol's complete.sql, and a
559
+ * fail-fast pre-check here would be a second copy of it, free to drift. The
560
+ * cost of that choice is that a doomed attempt does its work before finding
561
+ * out, which is the rare path.
562
+ *
563
+ * `fn` must be replayable for the same reason `tx`'s callback must be.
564
+ */
565
+ async completeIn(input, fn) {
566
+ if (!this.txWithSession) {
567
+ throw new Error("this store cannot share a transaction with the caller — " +
568
+ "completeIn requires a Postgres store (see PgExecutor)");
569
+ }
570
+ return this.txWithSession(async (fetch, session) => {
571
+ const value = await fn(session);
572
+ const rows = await fetch("complete", {
573
+ id: input.taskId,
574
+ worker_id: input.workerId,
575
+ result: value == null ? null : dumpJson(value),
576
+ });
577
+ // Rolls back `fn`'s writes along with the settlement that did not land.
578
+ if (!rows.length)
579
+ throw new LostLease(input.taskId);
580
+ return { task: rowToTask(rows[0]), value };
581
+ });
582
+ }
507
583
  async fail(input) {
508
584
  let error;
509
585
  try {
@@ -0,0 +1,77 @@
1
+ /**
2
+ * The seam between PostgresStore and whatever actually talks to Postgres.
3
+ *
4
+ * PostgresStore owns the *dialect* — the protocol's named-parameter SQL rewritten
5
+ * to `$n`, the migration ledger, the LISTEN policy. It does not own the
6
+ * *connection*. Applications that already run a Postgres driver (an ORM, a pool
7
+ * they size themselves) pass their own executor and cairnq joins that session
8
+ * instead of opening a second one, which is what makes a task's settlement
9
+ * commit in the same transaction as the rows the task produced.
10
+ *
11
+ * Implementing one is small — see `createPoolExecutor` below for the reference
12
+ * implementation over `pg`, and PROTOCOL.md for the two things an adapter must
13
+ * get right that are easy to miss: int8 must come back as a JS number (every
14
+ * cairnq bigint is an epoch-ms or a counter, all inside the safe range), and
15
+ * jsonb must come back as an object, not a string.
16
+ */
17
+ /** A row as the driver hands it back: column name -> value. */
18
+ export type Row = Record<string, unknown>;
19
+ /**
20
+ * Somewhere statements can run. The same shape whether it is a pool (each call
21
+ * on some connection) or one transaction's dedicated connection — the store's
22
+ * statements do not care, and this is what lets `tx` hand the same interface to
23
+ * its callback.
24
+ */
25
+ export interface PgSession {
26
+ /**
27
+ * One parameterised statement, `$1`-style. `values` is positional and may
28
+ * legitimately contain nulls — a null parameter is "this filter is off" in
29
+ * several protocol statements, not a missing argument.
30
+ */
31
+ query(text: string, values: readonly unknown[]): Promise<Row[]>;
32
+ /**
33
+ * Parameterless SQL that may hold several statements, for migration DDL.
34
+ * Separate from `query` because it must go over the simple query protocol:
35
+ * the extended protocol a parameterised call uses accepts only one statement,
36
+ * and every migration is a script.
37
+ */
38
+ exec(sql: string): Promise<void>;
39
+ }
40
+ /** A session that can also open transactions, listen, and be shut down. */
41
+ export interface PgExecutor extends PgSession {
42
+ /**
43
+ * Run `fn` inside one transaction on one dedicated connection, committing if
44
+ * it returns and rolling back if it throws. The store relies on both halves:
45
+ * a claim that cannot see its own `recover_leases` is a double-dispatch, and a
46
+ * keyed submit that commits half way poisons the key.
47
+ */
48
+ tx<T>(fn: (session: PgSession) => Promise<T>): Promise<T>;
49
+ /**
50
+ * Subscribe a dedicated connection to `channels`. Optional: an executor that
51
+ * omits it (or a Postgres that refuses LISTEN) costs latency, never
52
+ * correctness — the store falls back to plain polling, which is the contract
53
+ * PROTOCOL.md gives for push wakeups.
54
+ *
55
+ * Resolves with a function that stops listening. `onClose` reports a
56
+ * connection that dropped on its own, so the store can degrade and retry.
57
+ *
58
+ * Throw `ListenUnavailable` when this Postgres will never accept LISTEN — a
59
+ * transaction-mode pooler, say. Any other rejection is read as transient and
60
+ * retried with backoff, so a permanent condition raised as a plain Error
61
+ * becomes a reconnect loop that cannot succeed.
62
+ */
63
+ listen?(channels: readonly string[], onNotify: (channel: string, payload: string | undefined) => void, onClose: () => void): Promise<() => void>;
64
+ /**
65
+ * Release this executor's resources. Called by PostgresStore.close() ONLY for
66
+ * an executor the store created itself: an injected one belongs to the caller,
67
+ * whose other work would not survive cairnq closing it.
68
+ */
69
+ close(): Promise<void>;
70
+ }
71
+ /**
72
+ * LISTEN will not work on this connection, and retrying cannot change that.
73
+ * See `PgExecutor.listen`.
74
+ */
75
+ export declare class ListenUnavailable extends Error {
76
+ constructor(message?: string);
77
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The seam between PostgresStore and whatever actually talks to Postgres.
3
+ *
4
+ * PostgresStore owns the *dialect* — the protocol's named-parameter SQL rewritten
5
+ * to `$n`, the migration ledger, the LISTEN policy. It does not own the
6
+ * *connection*. Applications that already run a Postgres driver (an ORM, a pool
7
+ * they size themselves) pass their own executor and cairnq joins that session
8
+ * instead of opening a second one, which is what makes a task's settlement
9
+ * commit in the same transaction as the rows the task produced.
10
+ *
11
+ * Implementing one is small — see `createPoolExecutor` below for the reference
12
+ * implementation over `pg`, and PROTOCOL.md for the two things an adapter must
13
+ * get right that are easy to miss: int8 must come back as a JS number (every
14
+ * cairnq bigint is an epoch-ms or a counter, all inside the safe range), and
15
+ * jsonb must come back as an object, not a string.
16
+ */
17
+ /**
18
+ * LISTEN will not work on this connection, and retrying cannot change that.
19
+ * See `PgExecutor.listen`.
20
+ */
21
+ export class ListenUnavailable extends Error {
22
+ constructor(message = "LISTEN is not available on this connection") {
23
+ super(message);
24
+ this.name = "ListenUnavailable";
25
+ }
26
+ }
@@ -0,0 +1,16 @@
1
+ import { type PgExecutor } from "./pg-executor.js";
2
+ /**
3
+ * The built-in executor: a `pg.Pool` over a libpq DSN. What `CairnQ.postgres(dsn)`
4
+ * uses, and the reference for what an adapter over another driver must do.
5
+ *
6
+ * Creating it does not connect — `pg.Pool` is lazy, and the store's first
7
+ * statement (the migration ledger) is what proves the database is reachable.
8
+ *
9
+ * `schema` puts cairnq's tables in a schema of their own rather than in whatever
10
+ * the connection's search_path leads with. The protocol's SQL names no schema, so
11
+ * this is a per-connection `search_path` and not one statement changes.
12
+ */
13
+ export declare function createPoolExecutor(dsn: string, opts?: {
14
+ max?: number;
15
+ schema?: string;
16
+ }): Promise<PgExecutor>;