cairnq 0.5.0 → 0.6.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
@@ -66,8 +66,9 @@ Opt-in: every API still accepts a plain name string (cross-language callers use
66
66
 
67
67
  ```ts
68
68
  const worker = Worker.sqlite("tasks.db", {
69
- concurrency: 4,
70
- retryBackoffMs: 1_000, // doubles per attempt, capped by retryBackoffMaxMs (30s); 0 disables
69
+ concurrency: 4, // handler calls at once; use maxInFlightBytes to bound memory
70
+ retryBackoffMs: 1_000, // window doubles per attempt, capped at retryBackoffMaxMs (30s),
71
+ // jittered over its upper half; 0 disables
71
72
  onError: (err, info) => log.warn({ err, ...info }), // claims/writes the loop survived
72
73
  });
73
74
 
@@ -0,0 +1,25 @@
1
+ -- Serves the per-name claim: claim_one_name.sql and claim_one_queue_one_name.sql,
2
+ -- which a worker uses to draw a separate quota for each task name that sizes
3
+ -- itself (a `batch`, or its own concurrency). See "Batch delivery" in PROTOCOL.md.
4
+ --
5
+ -- cairnq_tasks_claim_idx does not cover it: `name` is not in that index, so a
6
+ -- name filter is a residual applied while walking the queue in claim order. The
7
+ -- cost lands hardest on a name with *nothing* queued — the claim walks every
8
+ -- claimable row in the queue looking for `limit` matches and finds none — and a
9
+ -- worker makes one such draw per registered name, per poll, inside the claim's
10
+ -- transaction, holding its FOR UPDATE row locks for the whole of it.
11
+ --
12
+ -- Both indexes are needed. `name` sits before the ORDER BY columns here, so this
13
+ -- one can only be read in claim order when `name` is an equality — exactly the
14
+ -- per-name draws. A claim with no name filter, or an array-valued one, still
15
+ -- reads cairnq_tasks_claim_idx and is unaffected.
16
+ --
17
+ -- NOT built CONCURRENTLY: migrations run inside a transaction (see the runner's
18
+ -- `lock table cairnq_migrations`), and CREATE INDEX CONCURRENTLY cannot. On an
19
+ -- existing large cairnq_tasks this takes a write lock for the build. Deploying
20
+ -- into a busy database is the case to watch; build it by hand with CONCURRENTLY
21
+ -- first if that matters, and this statement then becomes a no-op.
22
+ create index if not exists cairnq_tasks_claim_name_idx
23
+ on cairnq_tasks (queue, status, name, priority desc, created_at_ms);
24
+
25
+ update cairnq_meta set value = '6' where key = 'schema_version';
@@ -0,0 +1,26 @@
1
+ -- Serves the per-name claim: claim_one_name.sql and claim_one_queue_one_name.sql,
2
+ -- which a worker uses to draw a separate quota for each task name that sizes
3
+ -- itself (a `batch`, or its own concurrency). See "Batch delivery" in PROTOCOL.md.
4
+ --
5
+ -- cairnq_tasks_claim_idx does not cover it: `name` is not in that index, so a
6
+ -- name filter is a residual applied while walking the queue in claim order. The
7
+ -- cost lands hardest on a name with *nothing* queued — the claim walks every
8
+ -- claimable row in the queue looking for `limit` matches and finds none — and a
9
+ -- worker makes one such draw per registered name, per poll, inside the claim's
10
+ -- write transaction. Measured on a 20k backlog: 1116us for an empty name's draw
11
+ -- against cairnq_tasks_claim_idx, 8.8us against this one.
12
+ --
13
+ -- Both indexes are needed. `name` sits before the ORDER BY columns here, so this
14
+ -- one can only be read in claim order when `name` is an equality — exactly the
15
+ -- per-name draws. A claim with no name filter, or a list-valued one, still reads
16
+ -- cairnq_tasks_claim_idx and is unaffected (measured flat at ~13-16us either way).
17
+ --
18
+ -- The equality is what makes it usable: `name in (select value from json_each(?))`
19
+ -- does NOT reach this index even for a single-element list — SQLite builds a
20
+ -- bloom filter over the subquery and falls back to cairnq_tasks_claim_idx
21
+ -- (measured 1446us, i.e. no improvement at all). That is why the per-name
22
+ -- statements exist as separate files rather than the shared one being reused.
23
+ create index if not exists cairnq_tasks_claim_name_idx
24
+ on cairnq_tasks (queue, status, name, priority desc, created_at_ms);
25
+
26
+ update cairnq_meta set value = '6' where key = 'schema_version';
@@ -0,0 +1,37 @@
1
+ -- claim, for a caller drawing exactly ONE task name (Postgres dialect).
2
+ -- Byte-for-byte claim.sql except that the name filter is an equality on :name
3
+ -- instead of `= any(:names)` — a drift-guard test asserts precisely that, so
4
+ -- treat claim.sql as the source and re-derive this file when it changes.
5
+ --
6
+ -- It exists so the draw can reach cairnq_tasks_claim_name_idx, whose leading
7
+ -- columns are (queue, status, name): an array-valued name filter cannot be read
8
+ -- in claim order against it, so the name falls back to a residual on
9
+ -- cairnq_tasks_claim_idx and a draw for a name with nothing queued scans the
10
+ -- whole claimable backlog — inside the transaction, holding its row locks. See
11
+ -- migration 0006.
12
+ --
13
+ -- Used for the per-name quotas a worker draws for names that size themselves —
14
+ -- a `batch`, or their own concurrency. See "Batch delivery" in PROTOCOL.md.
15
+ -- params: queues (text[]), name, worker_id, lease_ms, limit
16
+ update cairnq_tasks t
17
+ set
18
+ status = 'running',
19
+ worker_id = :worker_id,
20
+ lease_until_ms = (extract(epoch from clock_timestamp()) * 1000)::bigint + :lease_ms,
21
+ attempt = attempt + 1,
22
+ updated_at_ms = (extract(epoch from clock_timestamp()) * 1000)::bigint
23
+ from (
24
+ select id from cairnq_tasks
25
+ where status = 'queued'
26
+ and queue = any(:queues::text[])
27
+ and name = :name
28
+ and run_at_ms <= (extract(epoch from clock_timestamp()) * 1000)::bigint
29
+ -- id breaks created_at_ms ties (same-millisecond submits), so claim order
30
+ -- is deterministic: FIFO at millisecond granularity; within one millisecond
31
+ -- the id's random half decides, stably but not in submit order.
32
+ order by priority desc, created_at_ms asc, id asc
33
+ limit :limit
34
+ for update skip locked
35
+ ) sel
36
+ where t.id = sel.id
37
+ returning t.*;
@@ -0,0 +1,34 @@
1
+ -- claim, for a caller watching ONE queue and drawing ONE task name (Postgres
2
+ -- dialect) — the common shape for a batched worker. Byte-for-byte claim.sql
3
+ -- except that both the queue and the name filters are equalities; a drift-guard
4
+ -- test asserts precisely that, so treat claim.sql as the source and re-derive
5
+ -- this file when it changes.
6
+ --
7
+ -- It is the combination of claim_one_queue.sql's queue equality and
8
+ -- claim_one_name.sql's name equality, and each is there for the reason that file
9
+ -- gives. Together they pin both leading columns of cairnq_tasks_claim_name_idx,
10
+ -- so the draw is an index scan in claim order that stops at :limit rows however
11
+ -- deep the backlog is.
12
+ -- params: queue, name, worker_id, lease_ms, limit
13
+ update cairnq_tasks t
14
+ set
15
+ status = 'running',
16
+ worker_id = :worker_id,
17
+ lease_until_ms = (extract(epoch from clock_timestamp()) * 1000)::bigint + :lease_ms,
18
+ attempt = attempt + 1,
19
+ updated_at_ms = (extract(epoch from clock_timestamp()) * 1000)::bigint
20
+ from (
21
+ select id from cairnq_tasks
22
+ where status = 'queued'
23
+ and queue = :queue
24
+ and name = :name
25
+ and run_at_ms <= (extract(epoch from clock_timestamp()) * 1000)::bigint
26
+ -- id breaks created_at_ms ties (same-millisecond submits), so claim order
27
+ -- is deterministic: FIFO at millisecond granularity; within one millisecond
28
+ -- the id's random half decides, stably but not in submit order.
29
+ order by priority desc, created_at_ms asc, id asc
30
+ limit :limit
31
+ for update skip locked
32
+ ) sel
33
+ where t.id = sel.id
34
+ returning t.*;
@@ -0,0 +1,24 @@
1
+ -- Extend the lease on several tasks at once (Postgres dialect) — the heartbeat
2
+ -- for batch delivery. Ownership-checked per row, exactly as heartbeat.sql: a task
3
+ -- whose lease this worker no longer holds simply does not come back, so the
4
+ -- caller learns which ones it lost by which ids are absent from the result rather
5
+ -- than by an error. One statement per beat replaces one round trip per leased
6
+ -- task, which for a 256-task batch is the difference between one write and 256.
7
+ --
8
+ -- Returns only what the beat needs, unlike heartbeat.sql's `returning *`: the
9
+ -- singular statement hands its row to the caller as `ctx.heartbeat()`'s public
10
+ -- return value, while this one's rows never leave the worker — they answer "still
11
+ -- mine?" (presence) and "cancelled?" (the one column). Whole rows here would pull
12
+ -- every payload back on every beat: 256 tasks * 4KB is a megabyte re-read every
13
+ -- lease/3 for the life of the call, and a JSON parse per row to discard it.
14
+ --
15
+ -- New lease (now + :lease_ms) and time come from the DB clock.
16
+ -- params: ids (text[]), worker_id, lease_ms
17
+ update cairnq_tasks
18
+ set lease_until_ms = (extract(epoch from now()) * 1000)::bigint + :lease_ms,
19
+ updated_at_ms = (extract(epoch from now()) * 1000)::bigint
20
+ where id = any(:ids::text[])
21
+ and status = 'running'
22
+ and worker_id = :worker_id
23
+ and lease_until_ms > (extract(epoch from now()) * 1000)::bigint
24
+ returning id, cancel_requested_at_ms;
@@ -0,0 +1,36 @@
1
+ -- claim, for a caller drawing exactly ONE task name. Byte-for-byte claim.sql
2
+ -- except that the name filter is an equality on :name instead of an IN over
3
+ -- :names — a drift-guard test asserts precisely that, so treat claim.sql as the
4
+ -- source and re-derive this file when it changes.
5
+ --
6
+ -- It exists because `name in (select value from json_each(:names))` cannot reach
7
+ -- cairnq_tasks_claim_name_idx, even for a single-element list: SQLite builds a
8
+ -- bloom filter over the subquery and falls back to cairnq_tasks_claim_idx, where
9
+ -- the name is a residual and a draw for a name with nothing queued walks the
10
+ -- whole claimable backlog. Measured on a 20k backlog: 1446us for the json_each
11
+ -- form, 8.8us for this one. See migration 0006.
12
+ --
13
+ -- Used for the per-name quotas a worker draws for names that size themselves —
14
+ -- a `batch`, or their own concurrency. See "Batch delivery" in PROTOCOL.md.
15
+ -- params: queues (JSON array text), name, now_ms, worker_id, lease_until_ms,
16
+ -- limit
17
+ update cairnq_tasks
18
+ set
19
+ status = 'running',
20
+ worker_id = :worker_id,
21
+ lease_until_ms = :lease_until_ms,
22
+ attempt = attempt + 1,
23
+ updated_at_ms = :now_ms
24
+ where id in (
25
+ select id from cairnq_tasks
26
+ where status = 'queued'
27
+ and queue in (select value from json_each(:queues))
28
+ and name = :name
29
+ and run_at_ms <= :now_ms
30
+ -- id breaks created_at_ms ties (same-millisecond submits), so claim order
31
+ -- is deterministic: FIFO at millisecond granularity; within one millisecond
32
+ -- the id's random half decides, stably but not in submit order.
33
+ order by priority desc, created_at_ms asc, id asc
34
+ limit :limit
35
+ )
36
+ returning *;
@@ -0,0 +1,31 @@
1
+ -- claim, for a caller watching ONE queue and drawing ONE task name — the common
2
+ -- shape for a batched worker. Byte-for-byte claim.sql except that both the queue
3
+ -- and the name filters are equalities; a drift-guard test asserts precisely that,
4
+ -- so treat claim.sql as the source and re-derive this file when it changes.
5
+ --
6
+ -- It is the combination of claim_one_queue.sql's queue equality and
7
+ -- claim_one_name.sql's name equality, and each is there for the reason that file
8
+ -- gives. Together they let cairnq_tasks_claim_name_idx be read in claim order
9
+ -- with both leading columns pinned, so the draw is a seek that terminates at
10
+ -- :limit rows however deep the backlog is.
11
+ -- params: queue, name, now_ms, worker_id, lease_until_ms, limit
12
+ update cairnq_tasks
13
+ set
14
+ status = 'running',
15
+ worker_id = :worker_id,
16
+ lease_until_ms = :lease_until_ms,
17
+ attempt = attempt + 1,
18
+ updated_at_ms = :now_ms
19
+ where id in (
20
+ select id from cairnq_tasks
21
+ where status = 'queued'
22
+ and queue = :queue
23
+ and name = :name
24
+ and run_at_ms <= :now_ms
25
+ -- id breaks created_at_ms ties (same-millisecond submits), so claim order
26
+ -- is deterministic: FIFO at millisecond granularity; within one millisecond
27
+ -- the id's random half decides, stably but not in submit order.
28
+ order by priority desc, created_at_ms asc, id asc
29
+ limit :limit
30
+ )
31
+ returning *;
@@ -0,0 +1,29 @@
1
+ -- Extend the lease on several tasks at once — the heartbeat for batch delivery.
2
+ -- Ownership-checked per row, exactly as heartbeat.sql: a task whose lease this
3
+ -- worker no longer holds simply does not come back, so the caller learns which
4
+ -- ones it lost by which ids are absent from the result rather than by an error.
5
+ -- One statement per beat is the point: a batch handler holding 256 leases would
6
+ -- otherwise write 256 rows every heartbeat interval, which on SQLite means 256
7
+ -- turns of the single write lock for work nobody is waiting on.
8
+ --
9
+ -- Returns only what the beat needs, unlike heartbeat.sql's `returning *`: the
10
+ -- singular statement hands its row to the caller as `ctx.heartbeat()`'s public
11
+ -- return value, while this one's rows never leave the worker — they answer "still
12
+ -- mine?" (presence) and "cancelled?" (the one column). Whole rows here would pull
13
+ -- every payload back on every beat: 256 tasks * 4KB is a megabyte re-read every
14
+ -- lease/3 for the life of the call, and a JSON parse per row to discard it.
15
+ -- Unlike heartbeat.sql, this one's plan depends on statistics: json_each() hides
16
+ -- the id list's length, so without sqlite_stat1 the planner drives the update off
17
+ -- cairnq_tasks_status_idx and walks every 'running' row in the database per beat
18
+ -- instead of doing primary-key lookups. Both SDKs ANALYZE on open and revisit
19
+ -- once a minute per connection (see "Planner statistics" in PROTOCOL.md), so this
20
+ -- is a warm-up window rather than a standing cost — but the statement it replaced
21
+ -- had no such dependency, which is why it is called out here.
22
+ -- params: ids (JSON array text), worker_id, now_ms, lease_until_ms
23
+ update cairnq_tasks
24
+ set lease_until_ms = :lease_until_ms, updated_at_ms = :now_ms
25
+ where id in (select value from json_each(:ids))
26
+ and status = 'running'
27
+ and worker_id = :worker_id
28
+ and lease_until_ms > :now_ms
29
+ returning id, cancel_requested_at_ms;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Retry backoff, in its own module because two callers need it.
3
+ *
4
+ * The worker computes it when a handler's failure ends an attempt; TaskContext
5
+ * computes it when a handler fails one task of a batch itself. Keeping it in
6
+ * worker.ts would make context.ts import the module that imports it.
7
+ */
8
+ export declare const DEFAULT_RETRY_BACKOFF_MS = 1000;
9
+ export declare const DEFAULT_RETRY_BACKOFF_MAX_MS = 30000;
10
+ /**
11
+ * Exponential backoff with equal jitter: the window doubles per attempt up to
12
+ * `maxMs`, and the delay lands uniformly in its upper half, `[w/2, w)`.
13
+ *
14
+ * The jitter is what keeps a fleet from retrying in lockstep. Failures align
15
+ * when the downstream fails fast enough that a whole concurrency batch raises
16
+ * at once (connection refused, DNS gone), and capped exponential backoff then
17
+ * *preserves* that alignment — once every task sits at `maxMs`, they all retry
18
+ * on the same beat forever. Spreading over half the window breaks it; keeping
19
+ * the lower half as a floor means jitter never shortens the wait to less than
20
+ * half of what plain exponential backoff would have asked for.
21
+ *
22
+ * `rand` is injected so tests can pin an exact delay.
23
+ */
24
+ export declare function retryDelayMs(attempt: number, baseMs: number, maxMs: number, rand?: () => number): number;
25
+ /**
26
+ * The delay a `fail` write should carry. Not just the backoff: a permanent
27
+ * failure is never re-run, so it always delays 0. Both settlement paths — the
28
+ * worker's and a handler's `ctx.fail` — go through this, so they cannot end up
29
+ * backing off differently.
30
+ */
31
+ export declare function failDelayMs(attempt: number, retryable: boolean, baseMs: number, maxMs: number, rand?: () => number): number;
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Retry backoff, in its own module because two callers need it.
3
+ *
4
+ * The worker computes it when a handler's failure ends an attempt; TaskContext
5
+ * computes it when a handler fails one task of a batch itself. Keeping it in
6
+ * worker.ts would make context.ts import the module that imports it.
7
+ */
8
+ export const DEFAULT_RETRY_BACKOFF_MS = 1_000;
9
+ export const DEFAULT_RETRY_BACKOFF_MAX_MS = 30_000;
10
+ /**
11
+ * Exponential backoff with equal jitter: the window doubles per attempt up to
12
+ * `maxMs`, and the delay lands uniformly in its upper half, `[w/2, w)`.
13
+ *
14
+ * The jitter is what keeps a fleet from retrying in lockstep. Failures align
15
+ * when the downstream fails fast enough that a whole concurrency batch raises
16
+ * at once (connection refused, DNS gone), and capped exponential backoff then
17
+ * *preserves* that alignment — once every task sits at `maxMs`, they all retry
18
+ * on the same beat forever. Spreading over half the window breaks it; keeping
19
+ * the lower half as a floor means jitter never shortens the wait to less than
20
+ * half of what plain exponential backoff would have asked for.
21
+ *
22
+ * `rand` is injected so tests can pin an exact delay.
23
+ */
24
+ export function retryDelayMs(attempt, baseMs, maxMs, rand = Math.random) {
25
+ if (baseMs <= 0)
26
+ return 0;
27
+ const exponent = Math.max(0, attempt - 1);
28
+ const window = Math.min(maxMs, baseMs * 2 ** exponent);
29
+ const floor = Math.floor(window / 2);
30
+ return floor + Math.floor(rand() * (window - floor));
31
+ }
32
+ /**
33
+ * The delay a `fail` write should carry. Not just the backoff: a permanent
34
+ * failure is never re-run, so it always delays 0. Both settlement paths — the
35
+ * worker's and a handler's `ctx.fail` — go through this, so they cannot end up
36
+ * backing off differently.
37
+ */
38
+ export function failDelayMs(attempt, retryable, baseMs, maxMs, rand = Math.random) {
39
+ return retryable ? retryDelayMs(attempt, baseMs, maxMs, rand) : 0;
40
+ }
package/dist/context.d.ts CHANGED
@@ -1,8 +1,20 @@
1
+ import { type FailReason } from "./errors.js";
1
2
  import { type Task } from "./models.js";
2
3
  import type { SubmitOptions } from "./client.js";
3
4
  import type { TaskStore } from "./store/base.js";
4
5
  import { type TaskDef } from "./task.js";
5
- /** Handed to a task handler. Worker-side capabilities mirror the Python SDK. */
6
+ export interface TaskContextOptions {
7
+ retryBackoffMs?: number;
8
+ retryBackoffMaxMs?: number;
9
+ }
10
+ /**
11
+ * Handed to a task handler. Worker-side capabilities mirror the Python SDK.
12
+ *
13
+ * One of these per task, whether a handler is delivered one task or a batch: a
14
+ * batch handler receives a `TaskContext[]`, so a single-task handler's `ctx` is
15
+ * literally the batch-of-one element. Lease, cancellation and settlement are per
16
+ * task, which is why they live here rather than on anything batch-shaped.
17
+ */
6
18
  export declare class TaskContext {
7
19
  private readonly store;
8
20
  private readonly task;
@@ -11,7 +23,10 @@ export declare class TaskContext {
11
23
  private readonly abort;
12
24
  private leaseLost;
13
25
  private cancelSeen;
14
- constructor(store: TaskStore, task: Task, workerId: string, leaseMs: number);
26
+ private isSettled;
27
+ private readonly backoffMs;
28
+ private readonly backoffMaxMs;
29
+ constructor(store: TaskStore, task: Task, workerId: string, leaseMs: number, opts?: TaskContextOptions);
15
30
  get taskId(): string;
16
31
  get name(): string;
17
32
  get queue(): string;
@@ -20,6 +35,14 @@ export declare class TaskContext {
20
35
  get rootId(): string | null;
21
36
  get correlationId(): string | null;
22
37
  get payload(): any;
38
+ /**
39
+ * True once this task reached a terminal state — whether the handler settled
40
+ * it with succeed()/fail() or the worker settled it on the handler's behalf.
41
+ * The heartbeat and the settlement paths both read it.
42
+ */
43
+ get settled(): boolean;
44
+ /** @internal Called by the worker when it finalizes this task itself. */
45
+ markSettled(): void;
23
46
  /**
24
47
  * True once this worker has lost the task's lease — it expired and another
25
48
  * worker reclaimed it. Nothing this handler writes will be recorded any more
@@ -32,11 +55,34 @@ export declare class TaskContext {
32
55
  /** @internal Called by the worker when an owned write reports a lost lease. */
33
56
  markLeaseLost(): void;
34
57
  private observe;
58
+ /**
59
+ * @internal The same observation from just the flag, for a caller that read it
60
+ * without materializing a Task — the shared heartbeat, whose statement returns
61
+ * only the id and the cancel column precisely so it does not have to drag
62
+ * every payload back on every beat.
63
+ */
64
+ observeCancel(cancelRequested: boolean): void;
35
65
  private owned;
36
66
  progress(value: number | null, message?: string | null): Promise<Task>;
37
67
  heartbeat(): Promise<Task>;
38
68
  /** Cooperative cancel check. Free once a heartbeat has already seen the flag. */
39
69
  canceled(): Promise<boolean>;
70
+ /**
71
+ * Finalize this task as succeeded, now, without waiting for the handler to
72
+ * return. `complete` semantics: a cancel requested while it ran wins and the
73
+ * task finalizes as canceled instead, its result discarded. Returns null if
74
+ * this task was already settled.
75
+ */
76
+ succeed(result?: unknown): Promise<Task | null>;
77
+ /**
78
+ * Finalize this task as failed, now. `error` may be a string reason, an Error,
79
+ * a TaskError (which carries its own retryability), or a ready envelope.
80
+ * Retryable failures get the worker's backoff and are re-queued while attempts
81
+ * remain, exactly as a thrown error would be. Returns null if already settled.
82
+ */
83
+ fail(error?: FailReason, opts?: {
84
+ retryable?: boolean;
85
+ }): Promise<Task | null>;
40
86
  /** Submit a child task; parent/root/correlation are wired automatically. */
41
87
  submit(name: string, payload?: unknown, opts?: SubmitOptions): Promise<Task>;
42
88
  submit<P, R>(task: TaskDef<P, R>, payload?: P, opts?: SubmitOptions): Promise<Task>;
package/dist/context.js CHANGED
@@ -1,8 +1,16 @@
1
- import { LostLease } from "./errors.js";
1
+ import { DEFAULT_RETRY_BACKOFF_MAX_MS, DEFAULT_RETRY_BACKOFF_MS, failDelayMs } from "./backoff.js";
2
+ import { asEnvelope, LostLease } from "./errors.js";
2
3
  import { cancelRequested } from "./models.js";
3
4
  import { taskName } from "./task.js";
4
5
  import { pollWait } from "./wait.js";
5
- /** Handed to a task handler. Worker-side capabilities mirror the Python SDK. */
6
+ /**
7
+ * Handed to a task handler. Worker-side capabilities mirror the Python SDK.
8
+ *
9
+ * One of these per task, whether a handler is delivered one task or a batch: a
10
+ * batch handler receives a `TaskContext[]`, so a single-task handler's `ctx` is
11
+ * literally the batch-of-one element. Lease, cancellation and settlement are per
12
+ * task, which is why they live here rather than on anything batch-shaped.
13
+ */
6
14
  export class TaskContext {
7
15
  store;
8
16
  task;
@@ -13,11 +21,20 @@ export class TaskContext {
13
21
  // Cancellation is monotonic: once the DB has told us a cancel was requested it
14
22
  // can't be taken back, so canceled() can answer from this without a re-read.
15
23
  cancelSeen = false;
16
- constructor(store, task, workerId, leaseMs) {
24
+ // Set once this task reached a terminal state through succeed()/fail(). The
25
+ // worker reads it to know which tasks a batch handler already decided, so it
26
+ // neither settles them twice nor keeps renewing their leases — the bookkeeping
27
+ // every ack/nack-style handler otherwise has to carry itself.
28
+ isSettled = false;
29
+ backoffMs;
30
+ backoffMaxMs;
31
+ constructor(store, task, workerId, leaseMs, opts = {}) {
17
32
  this.store = store;
18
33
  this.task = task;
19
34
  this.workerId = workerId;
20
35
  this.leaseMs = leaseMs;
36
+ this.backoffMs = opts.retryBackoffMs ?? DEFAULT_RETRY_BACKOFF_MS;
37
+ this.backoffMaxMs = opts.retryBackoffMaxMs ?? DEFAULT_RETRY_BACKOFF_MAX_MS;
21
38
  }
22
39
  get taskId() {
23
40
  return this.task.id;
@@ -43,6 +60,18 @@ export class TaskContext {
43
60
  get payload() {
44
61
  return this.task.payload;
45
62
  }
63
+ /**
64
+ * True once this task reached a terminal state — whether the handler settled
65
+ * it with succeed()/fail() or the worker settled it on the handler's behalf.
66
+ * The heartbeat and the settlement paths both read it.
67
+ */
68
+ get settled() {
69
+ return this.isSettled;
70
+ }
71
+ /** @internal Called by the worker when it finalizes this task itself. */
72
+ markSettled() {
73
+ this.isSettled = true;
74
+ }
46
75
  /**
47
76
  * True once this worker has lost the task's lease — it expired and another
48
77
  * worker reclaimed it. Nothing this handler writes will be recorded any more
@@ -66,18 +95,37 @@ export class TaskContext {
66
95
  // Every owned write returns the current row, so cancellation and lease loss
67
96
  // ride along on writes the handler was making anyway.
68
97
  observe(task) {
69
- if (cancelRequested(task))
70
- this.cancelSeen = true;
98
+ this.observeCancel(cancelRequested(task));
71
99
  return task;
72
100
  }
101
+ /**
102
+ * @internal The same observation from just the flag, for a caller that read it
103
+ * without materializing a Task — the shared heartbeat, whose statement returns
104
+ * only the id and the cancel column precisely so it does not have to drag
105
+ * every payload back on every beat.
106
+ */
107
+ observeCancel(cancelRequested) {
108
+ if (cancelRequested)
109
+ this.cancelSeen = true;
110
+ }
73
111
  async owned(write) {
74
- // Short-circuit once the lease is known lost: nothing this context writes
75
- // may be recorded any more. Locally, not just via the store's ownership
76
- // check — after an abandoned (timed-out) attempt the same worker may
77
- // re-claim this task under the same workerId, and a zombie handler's write
78
- // would then pass ownership against the NEW attempt.
112
+ // One gate for every write through this context, so "may I still write?" is
113
+ // answered in one place rather than at each call site.
114
+ //
115
+ // Lease lost: nothing this context writes may be recorded any more. Checked
116
+ // locally, not just via the store's ownership check after an abandoned
117
+ // (timed-out) attempt the same worker may re-claim this task under the same
118
+ // workerId, and a zombie handler's write would then pass ownership against
119
+ // the NEW attempt.
79
120
  if (this.leaseLost)
80
121
  throw new LostLease(this.task.id);
122
+ // Settled: the task is terminal, so the statement would match no row and come
123
+ // back as a lost lease — telling the handler "another worker took this" when
124
+ // the truth is "you already finished it", and flipping lostLease on the way.
125
+ // Refuse here instead, without the round trip and without corrupting the
126
+ // lease state.
127
+ if (this.isSettled)
128
+ throw new LostLease(this.task.id);
81
129
  try {
82
130
  return this.observe(await write());
83
131
  }
@@ -113,6 +161,49 @@ export class TaskContext {
113
161
  this.cancelSeen = true;
114
162
  return this.cancelSeen || t.status === "canceled";
115
163
  }
164
+ // ------------------------------------------------------------- settlement
165
+ // Finalizing a task is normally the worker's job, decided by whether the
166
+ // handler returned or threw. These two let a handler decide one task itself,
167
+ // which is what a batch needs: four of 256 tasks failing for four different
168
+ // reasons is the ordinary case, not the edge one, and it cannot be expressed
169
+ // by a single return value or a single throw.
170
+ //
171
+ // Settling twice is a no-op rather than an error. Handlers built on ack/nack
172
+ // queues all end up carrying a `finalizedIds` set to guarantee exactly that;
173
+ // holding it here instead is the point.
174
+ /**
175
+ * Finalize this task as succeeded, now, without waiting for the handler to
176
+ * return. `complete` semantics: a cancel requested while it ran wins and the
177
+ * task finalizes as canceled instead, its result discarded. Returns null if
178
+ * this task was already settled.
179
+ */
180
+ async succeed(result = null) {
181
+ if (this.isSettled)
182
+ return null;
183
+ const task = await this.owned(() => this.store.complete({ taskId: this.task.id, workerId: this.workerId, result }));
184
+ this.markSettled();
185
+ return task;
186
+ }
187
+ /**
188
+ * Finalize this task as failed, now. `error` may be a string reason, an Error,
189
+ * a TaskError (which carries its own retryability), or a ready envelope.
190
+ * Retryable failures get the worker's backoff and are re-queued while attempts
191
+ * remain, exactly as a thrown error would be. Returns null if already settled.
192
+ */
193
+ async fail(error = "task failed", opts = {}) {
194
+ if (this.isSettled)
195
+ return null;
196
+ const [envelope, retryable] = asEnvelope(error, opts.retryable ?? true);
197
+ const task = await this.owned(() => this.store.fail({
198
+ taskId: this.task.id,
199
+ workerId: this.workerId,
200
+ error: envelope,
201
+ retryable,
202
+ delayMs: failDelayMs(this.task.attempt, retryable, this.backoffMs, this.backoffMaxMs),
203
+ }));
204
+ this.markSettled();
205
+ return task;
206
+ }
116
207
  async submit(task, payload, opts = {}) {
117
208
  return this.store.submit({
118
209
  name: taskName(task),
package/dist/errors.d.ts CHANGED
@@ -9,6 +9,15 @@ export declare function errorEnvelope(e: {
9
9
  retryable: boolean;
10
10
  details?: Record<string, unknown>;
11
11
  }): Record<string, unknown>;
12
+ /**
13
+ * How an arbitrary thrown value becomes an envelope. Split out from `asEnvelope`
14
+ * below because the worker also reaches it directly, for a thrown plain object —
15
+ * which `asEnvelope` reads as a ready envelope, the right call for `ctx.fail` and
16
+ * the wrong one for something that was thrown. Both must agree on `code` and on
17
+ * deriving `type` from the error's name, or the same error reads differently
18
+ * depending on which way it was recorded.
19
+ */
20
+ export declare function exceptionEnvelope(err: unknown, retryable?: boolean): Record<string, unknown>;
12
21
  export declare class CairnQError extends Error {
13
22
  constructor(message?: string);
14
23
  }
@@ -84,3 +93,21 @@ export declare class TaskError extends CairnQError {
84
93
  });
85
94
  envelope(): Record<string, unknown>;
86
95
  }
96
+ /** What a handler may pass to `ctx.fail`. */
97
+ export type FailReason = string | Error | TaskError | Record<string, unknown>;
98
+ /**
99
+ * Normalize anything that can end a task into [envelope, retryable].
100
+ *
101
+ * Shared by both ways a failure is recorded — a handler passing a reason to
102
+ * `ctx.fail`, and the worker classifying an error that ended an attempt — so the
103
+ * two cannot disagree about what a given error means. It lives here, beside the
104
+ * envelope constructors it dispatches to, rather than in the module that happens
105
+ * to expose it to handlers.
106
+ *
107
+ * A handler failing one task of a batch has a reason, not an exception object:
108
+ * `item.fail("no source records", { retryable: false })` is the shape the real
109
+ * code wants. A TaskError carries its own retryability and wins over the option;
110
+ * everything else takes the caller's. A ready envelope passes through, which is
111
+ * how the worker hands in the ones it composes itself.
112
+ */
113
+ export declare function asEnvelope(error: FailReason, retryable: boolean): [Record<string, unknown>, boolean];