@gmitch215/folio 1.0.1 → 1.2.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 (130) hide show
  1. package/README.md +98 -460
  2. package/dist/boot.d.ts +1 -0
  3. package/dist/boot.js +1 -0
  4. package/dist/browser/index.d.ts +73 -0
  5. package/dist/browser/index.js +277 -0
  6. package/dist/browser.d.ts +1 -68
  7. package/dist/browser.js +1 -274
  8. package/dist/continuation.d.ts +1 -0
  9. package/dist/continuation.js +1 -0
  10. package/dist/{compiler.d.ts → execution/compiler.d.ts} +1 -1
  11. package/dist/{compiler.js → execution/compiler.js} +5 -12
  12. package/dist/{coordinator.d.ts → execution/coordinator.d.ts} +1 -1
  13. package/dist/{coordinator.js → execution/coordinator.js} +55 -8
  14. package/dist/{extract.d.ts → execution/extract.d.ts} +22 -13
  15. package/dist/{extract.js → execution/extract.js} +137 -10
  16. package/dist/execution/fold.d.ts +44 -0
  17. package/dist/execution/fold.js +105 -0
  18. package/dist/{guards.d.ts → execution/guards.d.ts} +2 -1
  19. package/dist/execution/runs.d.ts +44 -0
  20. package/dist/execution/runs.js +182 -0
  21. package/dist/{transaction.d.ts → execution/transaction.d.ts} +10 -0
  22. package/dist/execution/types.d.ts +221 -0
  23. package/dist/folds/affine-state.d.ts +142 -0
  24. package/dist/folds/affine-state.js +737 -0
  25. package/dist/folds/affine.d.ts +148 -0
  26. package/dist/folds/affine.js +562 -0
  27. package/dist/folds/boundaries.d.ts +48 -0
  28. package/dist/folds/boundaries.js +119 -0
  29. package/dist/folds/certified.d.ts +55 -0
  30. package/dist/folds/certified.js +178 -0
  31. package/dist/folds/certify.d.ts +87 -0
  32. package/dist/folds/certify.js +2611 -0
  33. package/dist/footprints/memo.d.ts +74 -0
  34. package/dist/footprints/memo.js +256 -0
  35. package/dist/footprints/ranges.d.ts +78 -0
  36. package/dist/footprints/ranges.js +263 -0
  37. package/dist/footprints/read-scan.d.ts +18 -0
  38. package/dist/footprints/read-scan.js +94 -0
  39. package/dist/footprints/read-windows.d.ts +77 -0
  40. package/dist/footprints/read-windows.js +245 -0
  41. package/dist/index.d.ts +16 -4
  42. package/dist/index.js +14 -2
  43. package/dist/iteration/admission.d.ts +149 -0
  44. package/dist/iteration/admission.js +201 -0
  45. package/dist/iteration/index.d.ts +239 -0
  46. package/dist/iteration/index.js +1210 -0
  47. package/dist/iteration/inline.d.ts +182 -0
  48. package/dist/{inline.js → iteration/inline.js} +277 -21
  49. package/dist/{iteration-owner.d.ts → iteration/owner.d.ts} +16 -3
  50. package/dist/{iteration-owner.js → iteration/owner.js} +6 -5
  51. package/dist/iteration/worker.js +216 -0
  52. package/dist/{managed.d.ts → managed/index.d.ts} +75 -3
  53. package/dist/managed/index.js +817 -0
  54. package/dist/managed/outbox.d.ts +128 -0
  55. package/dist/managed/outbox.js +156 -0
  56. package/dist/managed/pool.d.ts +221 -0
  57. package/dist/managed/pool.js +310 -0
  58. package/dist/managed/tasks.d.ts +154 -0
  59. package/dist/managed/tasks.js +183 -0
  60. package/dist/{bake.d.ts → memory/bake.d.ts} +12 -6
  61. package/dist/{bake.js → memory/bake.js} +9 -7
  62. package/dist/memory/continuation.d.ts +141 -0
  63. package/dist/memory/continuation.js +495 -0
  64. package/dist/memory/elastic-peer.d.ts +20 -0
  65. package/dist/memory/elastic-peer.js +39 -0
  66. package/dist/memory/elastic-sql.d.ts +11 -0
  67. package/dist/memory/elastic-sql.js +35 -0
  68. package/dist/memory/elastic.d.ts +130 -0
  69. package/dist/memory/elastic.js +475 -0
  70. package/dist/memory/growth-governor.d.ts +16 -0
  71. package/dist/memory/growth-governor.js +42 -0
  72. package/dist/memory/imports.d.ts +10 -0
  73. package/dist/memory/imports.js +89 -0
  74. package/dist/{iteration-layout.d.ts → memory/iteration-layout.d.ts} +61 -1
  75. package/dist/{iteration-layout.js → memory/iteration-layout.js} +54 -3
  76. package/dist/memory/lease.d.ts +45 -0
  77. package/dist/memory/lease.js +274 -0
  78. package/dist/{pages.d.ts → memory/pages.d.ts} +3 -3
  79. package/dist/memory.d.ts +5 -10
  80. package/dist/memory.js +5 -89
  81. package/dist/{context.d.ts → node/context.d.ts} +17 -3
  82. package/dist/{context.js → node/context.js} +60 -14
  83. package/dist/{host.d.ts → node/host.d.ts} +1 -1
  84. package/dist/{host.js → node/host.js} +2 -2
  85. package/dist/{node.d.ts → node/index.d.ts} +46 -49
  86. package/dist/{node.js → node/index.js} +101 -26
  87. package/dist/{tasks.d.ts → node/tasks.d.ts} +16 -17
  88. package/dist/{tasks.js → node/tasks.js} +12 -11
  89. package/dist/node/worker.d.ts +1 -0
  90. package/dist/{worker.js → node/worker.js} +2 -2
  91. package/dist/ownership/index.d.ts +161 -0
  92. package/dist/ownership/index.js +6565 -0
  93. package/dist/ownership/redirect.d.ts +30 -0
  94. package/dist/ownership/redirect.js +179 -0
  95. package/dist/ownership/slices.d.ts +44 -0
  96. package/dist/ownership/slices.js +72 -0
  97. package/dist/{frames.d.ts → remote/frames.d.ts} +6 -2
  98. package/dist/remote/frames.js +306 -0
  99. package/dist/{remote.d.ts → remote/index.d.ts} +7 -2
  100. package/dist/{remote.js → remote/index.js} +7 -2
  101. package/dist/routing/index.d.ts +203 -0
  102. package/dist/routing/index.js +671 -0
  103. package/dist/routing/worker.d.ts +1 -0
  104. package/dist/routing/worker.js +4 -0
  105. package/dist/slices/index.d.ts +126 -0
  106. package/dist/slices/index.js +441 -0
  107. package/dist/slices/worker.d.ts +1 -0
  108. package/dist/slices/worker.js +38 -0
  109. package/dist/workers.d.ts +5 -0
  110. package/dist/workers.js +5 -0
  111. package/package.json +32 -46
  112. package/dist/frames.js +0 -159
  113. package/dist/inline.d.ts +0 -68
  114. package/dist/iteration-admission.d.ts +0 -76
  115. package/dist/iteration-admission.js +0 -72
  116. package/dist/iteration-worker.js +0 -150
  117. package/dist/iteration.d.ts +0 -163
  118. package/dist/iteration.js +0 -435
  119. package/dist/managed.js +0 -421
  120. /package/dist/{browser-worker.d.ts → browser/worker.d.ts} +0 -0
  121. /package/dist/{browser-worker.js → browser/worker.js} +0 -0
  122. /package/dist/{guards.js → execution/guards.js} +0 -0
  123. /package/dist/{import-order.d.ts → execution/import-order.d.ts} +0 -0
  124. /package/dist/{import-order.js → execution/import-order.js} +0 -0
  125. /package/dist/{transaction.js → execution/transaction.js} +0 -0
  126. /package/dist/{iteration-worker.d.ts → execution/types.js} +0 -0
  127. /package/dist/{worker.d.ts → iteration/worker.d.ts} +0 -0
  128. /package/dist/{pages.js → memory/pages.js} +0 -0
  129. /package/dist/{values.d.ts → remote/values.d.ts} +0 -0
  130. /package/dist/{values.js → remote/values.js} +0 -0
@@ -0,0 +1,128 @@
1
+ import type { SqlStorage } from '../memory/continuation.ts';
2
+ import type { ReplayPolicies, TaskRow, TaskValue } from './tasks.ts';
3
+ import { TaskTable } from './tasks.ts';
4
+ /** Thrown by an effect to end its row as `failed` with no retry. */
5
+ export declare class PermanentError extends Error {
6
+ constructor(message: string, options?: {
7
+ cause?: unknown;
8
+ });
9
+ }
10
+ /** What an effect receives for one attempt. */
11
+ export interface OutboxContext {
12
+ /** The row id. */
13
+ id: string;
14
+ /** The kind the row was enqueued with. */
15
+ kind: string;
16
+ /** The claim number of this attempt; a replay gets the next one. */
17
+ attempt: number;
18
+ /**
19
+ * The idempotency key. It is the row id and is the same on every attempt, so use it as the
20
+ * `Message-ID` of a mail or the `Idempotency-Key` header of a request.
21
+ */
22
+ key: string;
23
+ /** The arguments as enqueued, text or bytes. */
24
+ args: TaskValue;
25
+ }
26
+ /**
27
+ * Runs the effect of one row. Return its result, or nothing, or a promise of either. Throw a
28
+ * `PermanentError` when it can never succeed, and any other error when it did not happen and
29
+ * trying again is safe.
30
+ */
31
+ export type OutboxEffect = (context: OutboxContext) => void | TaskValue | Promise<void | TaskValue>;
32
+ /** A row to enqueue. Pass `args` or `argsJson`, not both. */
33
+ export interface OutboxItem {
34
+ /** Unique id, which is also the idempotency key. Rows run in the byte order of the id. */
35
+ id: string;
36
+ /** The kind of effect, such as `mail` or `http`. It picks the replay policy. */
37
+ kind: string;
38
+ /** The arguments, text or bytes. */
39
+ args?: TaskValue;
40
+ /** Serialized with `JSON.stringify` into `args`. */
41
+ argsJson?: unknown;
42
+ }
43
+ /** Time for the outbox. */
44
+ export interface OutboxClock {
45
+ /** Milliseconds on any clock the outbox and its readers agree on. */
46
+ now(): number;
47
+ }
48
+ /** What one `drain` did. */
49
+ export interface OutboxReport {
50
+ /** Rows whose effect finished and whose result was written. */
51
+ done: number;
52
+ /** Rows ended as `failed` by a `PermanentError`, by their last attempt or by an exhausted lease. */
53
+ failed: number;
54
+ /** Rows whose effect threw and that wait for another attempt. */
55
+ retried: number;
56
+ /** Rows ended as `failed` because their lease ended and their kind is `report`. */
57
+ reported: number;
58
+ }
59
+ /** What `resume` returns. */
60
+ export interface OutboxResume extends OutboxReport {
61
+ /** When to call `resume` again, at least 5 s ahead. Unset when no row is open. */
62
+ wake?: number;
63
+ }
64
+ /** Options for `Outbox`. */
65
+ export interface OutboxOptions {
66
+ /** Runs the effect of a row. */
67
+ effect: OutboxEffect;
68
+ /**
69
+ * What to do with a row whose lease ended while it ran, by kind. `resend` runs the effect
70
+ * again. `report` ends the row as `failed` and never runs it again. A kind that is not listed
71
+ * is `report`.
72
+ */
73
+ policies?: ReplayPolicies;
74
+ /**
75
+ * Resolves once every earlier write survives a reset; pass `() => ctx.storage.sync()` inside a
76
+ * Durable Object. Awaited after an enqueue, after a claim before the effect, after a
77
+ * completion and after a failure. Without it the outbox trusts the storage to be durable at
78
+ * each await.
79
+ */
80
+ flush?: () => Promise<void>;
81
+ /** Time source. Defaults to `Date.now`. */
82
+ clock?: OutboxClock;
83
+ /** Lease of a claim, in milliseconds. Default 15,000, minimum 5,000. An effect that awaits renews it. */
84
+ leaseMs?: number;
85
+ /** Executions a row may start before it fails. Default 3. */
86
+ maxAttempts?: number;
87
+ /** Rows run at once by `drain`. Default 1. */
88
+ width?: number;
89
+ /** SQL identifier of the table. Default `folio_tasks`. */
90
+ table?: string;
91
+ }
92
+ /**
93
+ * A durable outbox for effects that must not be lost or repeated without notice: mail, outbound
94
+ * requests, Redis commands, cron units. Rows live in the task table of the object's own SQLite.
95
+ *
96
+ * Each row goes through four steps in this order: claim, flush, effect, complete, flush. The
97
+ * flush after the claim is what gives `report` its meaning. A reset after it leaves a running
98
+ * row that a successor knows may have run its effect, and the successor ends it as `failed`
99
+ * instead of running it again. A reset before it loses the claim, and nothing ran. The flush
100
+ * after the completion keeps a finished effect from being replayed after a reset.
101
+ *
102
+ * So a `resend` kind runs its effect at least once and a `report` kind at most once. A reported
103
+ * row is the operator's: it is final, and sending the effect again means a new id.
104
+ */
105
+ export declare class Outbox {
106
+ #private;
107
+ /** The task table, for callers that read rows directly. */
108
+ readonly table: TaskTable;
109
+ constructor(sql: SqlStorage, options: OutboxOptions);
110
+ /**
111
+ * Adds rows and returns how many were new, once they are flushed. An id that exists is
112
+ * ignored, so repeating an enqueue that failed is safe.
113
+ */
114
+ enqueue(items: readonly OutboxItem[]): Promise<number>;
115
+ /**
116
+ * Runs every row that is ready, `width` at a time, and returns what happened. A row whose
117
+ * effect threw waits for the next `drain` instead of running again at once. Rows whose lease
118
+ * ended are replayed or reported by their kind first.
119
+ */
120
+ drain(): Promise<OutboxReport>;
121
+ /**
122
+ * One pass for an alarm: `drain`, then when to call again. `wake` is at least 5 s ahead and
123
+ * never before the soonest lease ends, and it is unset when no row is open.
124
+ */
125
+ resume(): Promise<OutboxResume>;
126
+ /** Every row in id order, whatever its state. */
127
+ results(): TaskRow[];
128
+ }
@@ -0,0 +1,156 @@
1
+ import { TaskTable } from "./tasks.js";
2
+ /** Thrown by an effect to end its row as `failed` with no retry. */
3
+ export class PermanentError extends Error {
4
+ constructor(message, options) {
5
+ super(message, options);
6
+ this.name = 'PermanentError';
7
+ }
8
+ }
9
+ const minLeaseMs = 5000;
10
+ const isValue = (value) => typeof value === 'string' || value instanceof Uint8Array;
11
+ const message = (error) => (error instanceof Error ? error.message : String(error)).slice(0, 1000);
12
+ /**
13
+ * A durable outbox for effects that must not be lost or repeated without notice: mail, outbound
14
+ * requests, Redis commands, cron units. Rows live in the task table of the object's own SQLite.
15
+ *
16
+ * Each row goes through four steps in this order: claim, flush, effect, complete, flush. The
17
+ * flush after the claim is what gives `report` its meaning. A reset after it leaves a running
18
+ * row that a successor knows may have run its effect, and the successor ends it as `failed`
19
+ * instead of running it again. A reset before it loses the claim, and nothing ran. The flush
20
+ * after the completion keeps a finished effect from being replayed after a reset.
21
+ *
22
+ * So a `resend` kind runs its effect at least once and a `report` kind at most once. A reported
23
+ * row is the operator's: it is final, and sending the effect again means a new id.
24
+ */
25
+ export class Outbox {
26
+ /** The task table, for callers that read rows directly. */
27
+ table;
28
+ #effect;
29
+ #policies;
30
+ #flush;
31
+ #clock;
32
+ #leaseMs;
33
+ #width;
34
+ constructor(sql, options) {
35
+ const { leaseMs = 15000, width = 1 } = options;
36
+ if (typeof options.effect !== 'function')
37
+ throw new TypeError('effect must be a function');
38
+ if (!Number.isInteger(leaseMs) || leaseMs < minLeaseMs)
39
+ throw new RangeError(`leaseMs must be an integer of at least ${minLeaseMs}`);
40
+ if (!Number.isInteger(width) || width < 1)
41
+ throw new RangeError('width must be a positive integer');
42
+ for (const [kind, policy] of Object.entries(options.policies ?? {}))
43
+ if (policy !== 'resend' && policy !== 'report')
44
+ throw new TypeError(`the policy of ${kind} must be resend or report`);
45
+ this.#policies = { ...options.policies };
46
+ this.table = new TaskTable(sql, { table: options.table, maxAttempts: options.maxAttempts });
47
+ this.#effect = options.effect;
48
+ this.#flush = options.flush ?? (async () => { });
49
+ this.#clock = options.clock ?? { now: () => Date.now() };
50
+ this.#leaseMs = leaseMs;
51
+ this.#width = width;
52
+ }
53
+ /**
54
+ * Adds rows and returns how many were new, once they are flushed. An id that exists is
55
+ * ignored, so repeating an enqueue that failed is safe.
56
+ */
57
+ async enqueue(items) {
58
+ let added = 0;
59
+ for (const item of items) {
60
+ if (typeof item.id !== 'string' || !item.id)
61
+ throw new TypeError('a row needs an id');
62
+ if (typeof item.kind !== 'string' || !item.kind)
63
+ throw new TypeError(`row ${item.id} needs a kind`);
64
+ if (item.args !== undefined && item.argsJson !== undefined)
65
+ throw new TypeError('pass args or argsJson, not both');
66
+ const args = item.argsJson === undefined ? (item.args ?? '') : JSON.stringify(item.argsJson);
67
+ if (!isValue(args))
68
+ throw new TypeError(`args of row ${item.id} must be a string or bytes`);
69
+ if (this.table.enqueue(item.id, item.kind, args, item.kind))
70
+ added++;
71
+ }
72
+ await this.#flush();
73
+ return added;
74
+ }
75
+ /**
76
+ * Runs every row that is ready, `width` at a time, and returns what happened. A row whose
77
+ * effect threw waits for the next `drain` instead of running again at once. Rows whose lease
78
+ * ended are replayed or reported by their kind first.
79
+ */
80
+ async drain() {
81
+ const report = { done: 0, failed: 0, retried: 0, reported: 0 };
82
+ const attempted = [];
83
+ for (;;) {
84
+ const now = this.#clock.now();
85
+ report.reported += this.table.reportLost(now, this.#policies);
86
+ report.failed += this.table.expire(now);
87
+ const rows = this.table.claim(now, this.#leaseMs, this.#width, {
88
+ policies: this.#policies,
89
+ skip: attempted
90
+ });
91
+ await this.#flush();
92
+ if (!rows.length)
93
+ return report;
94
+ attempted.push(...rows.map((row) => row.id));
95
+ await Promise.all(rows.map((row) => this.#run(row, report)));
96
+ }
97
+ }
98
+ /**
99
+ * One pass for an alarm: `drain`, then when to call again. `wake` is at least 5 s ahead and
100
+ * never before the soonest lease ends, and it is unset when no row is open.
101
+ */
102
+ async resume() {
103
+ const report = await this.drain();
104
+ const now = this.#clock.now();
105
+ const open = this.table.pending(now);
106
+ return {
107
+ ...report,
108
+ ...(open.open === 0 ? {} : { wake: Math.max(open.nextExpiry ?? 0, now + minLeaseMs) })
109
+ };
110
+ }
111
+ /** Every row in id order, whatever its state. */
112
+ results() {
113
+ return this.table.snapshot();
114
+ }
115
+ async #run(row, report) {
116
+ let timer;
117
+ let outcome;
118
+ try {
119
+ const pending = this.#effect({
120
+ id: row.id,
121
+ kind: row.kind ?? '',
122
+ attempt: row.attempt,
123
+ key: row.id,
124
+ args: row.args
125
+ });
126
+ let value = pending;
127
+ if (typeof pending?.then === 'function') {
128
+ timer = setInterval(() => this.table.renew(row.id, row.attempt, this.#clock.now(), this.#leaseMs), Math.max(1000, Math.floor(this.#leaseMs / 3)));
129
+ value = await pending;
130
+ }
131
+ // a result of the wrong type is a bug in the effect, and running it again would repeat the effect
132
+ if (value !== undefined && !isValue(value))
133
+ throw new PermanentError(`effect of kind ${row.kind} returned neither text, bytes nor nothing`);
134
+ outcome = { value: value ?? '' };
135
+ }
136
+ catch (error) {
137
+ outcome = { error };
138
+ }
139
+ finally {
140
+ clearInterval(timer);
141
+ }
142
+ if ('value' in outcome) {
143
+ const completion = this.table.complete(row.id, row.attempt, outcome.value);
144
+ await this.#flush();
145
+ if (completion !== 'ignored')
146
+ report.done++;
147
+ return;
148
+ }
149
+ const failure = this.table.fail(row.id, row.attempt, message(outcome.error), outcome.error instanceof PermanentError);
150
+ await this.#flush();
151
+ if (failure === 'retry')
152
+ report.retried++;
153
+ else if (failure === 'failed')
154
+ report.failed++;
155
+ }
156
+ }
@@ -0,0 +1,221 @@
1
+ import type { SqlStorage } from '../memory/continuation.ts';
2
+ import type { CompletionOutcome, FailureOutcome, TaskState, TaskValue } from './tasks.ts';
3
+ import { TaskTable } from './tasks.ts';
4
+ /** A task a lane claimed. */
5
+ export interface LaneTask {
6
+ /** The task id. */
7
+ id: string;
8
+ /** The registry key to run. */
9
+ name: string;
10
+ /** The arguments as submitted, text or bytes. */
11
+ args: TaskValue;
12
+ /** The claim number of this task; a replay gets the next one. */
13
+ attempt: number;
14
+ /** The lease the claim granted, in milliseconds. */
15
+ leaseMs: number;
16
+ }
17
+ /** A claimed task named by id and attempt. */
18
+ export interface LaneHold {
19
+ /** The task id. */
20
+ id: string;
21
+ /** The claim number the lane holds. */
22
+ attempt: number;
23
+ }
24
+ /**
25
+ * What a lane calls on the coordinator. `LanePool` implements it, and a Durable Object stub that
26
+ * forwards the four methods to a pool satisfies it.
27
+ */
28
+ export interface LaneCoordinator {
29
+ /** Claims up to `claimBatch` tasks, or none when nothing is ready. */
30
+ claim(): Promise<LaneTask[]>;
31
+ /** Writes a result. The first completion of an id wins. */
32
+ complete(id: string, attempt: number, result: TaskValue): Promise<CompletionOutcome>;
33
+ /** Records an error from an attempt. */
34
+ fail(id: string, attempt: number, error: string): Promise<FailureOutcome>;
35
+ /** Extends the leases of tasks the lane still holds; false marks a task that is no longer its own. */
36
+ renew(holds: readonly LaneHold[]): Promise<boolean[]>;
37
+ }
38
+ /** Runs one named task. Return the result, or a promise of it; a throw fails the attempt. */
39
+ export type TaskFunction = (args: TaskValue, task: LaneTask) => TaskValue | Promise<TaskValue>;
40
+ /** The tasks a lane can run, by name. */
41
+ export type TaskRegistry = Record<string, TaskFunction>;
42
+ /** What one `work` call did. */
43
+ export interface LaneWorked {
44
+ /** Tasks the lane claimed. */
45
+ claimed: number;
46
+ /** Tasks it finished and reported done. */
47
+ completed: number;
48
+ /** Tasks it reported as failed. */
49
+ failed: number;
50
+ }
51
+ /** How the coordinator reaches a lane. */
52
+ export interface LaneTransport {
53
+ /**
54
+ * Asks lane `lane` (0 up to `width - 1`) to work the queue. Resolves when the lane's claim
55
+ * comes back empty. Reject, or time out, when the lane stops answering: a call that never
56
+ * settles keeps its lane busy for the life of the pool.
57
+ */
58
+ work(lane: number): Promise<unknown>;
59
+ /** Releases the lanes' connections or objects. */
60
+ close?(): Promise<void>;
61
+ }
62
+ /** Time for the pool. `sleep` resolves after `ms`, or as soon as the signal aborts. */
63
+ export interface LaneClock {
64
+ /** Milliseconds on any clock the pool and its lanes agree on. */
65
+ now(): number;
66
+ /** Resolves after `ms`, or when `signal` aborts. */
67
+ sleep(ms: number, signal?: AbortSignal): Promise<void>;
68
+ }
69
+ /** A task to submit. Pass `args` or `argsJson`, not both. */
70
+ export interface TaskSpec {
71
+ /** Unique id. Results come back in the byte order of the id. */
72
+ id: string;
73
+ /** Key into the lane's registry. */
74
+ name: string;
75
+ /** The arguments, text or bytes. */
76
+ args?: TaskValue;
77
+ /** Serialized with `JSON.stringify` into `args`. */
78
+ argsJson?: unknown;
79
+ }
80
+ /** One task's outcome. */
81
+ export interface LaneResult {
82
+ /** The task id. */
83
+ id: string;
84
+ /** The registry key that ran. */
85
+ name: string;
86
+ /** Where the task ended up. */
87
+ state: TaskState;
88
+ /** Claims the task took. */
89
+ attempt: number;
90
+ /** The raw result, once the task is done. */
91
+ value?: TaskValue;
92
+ /** The last error, for a failed task. */
93
+ error?: string;
94
+ /** The result as text. Throws unless the task is done. */
95
+ text(): string;
96
+ /** The result parsed as JSON. Throws unless the task is done. */
97
+ json<T = unknown>(): T;
98
+ }
99
+ /** The state of the pool after a `run` or a `resume`. */
100
+ export interface LaneReport {
101
+ /** Tasks waiting to be claimed. */
102
+ queued: number;
103
+ /** Tasks claimed and not yet reported. */
104
+ running: number;
105
+ /** Tasks with a result. */
106
+ done: number;
107
+ /** Tasks that ran out of attempts. */
108
+ failed: number;
109
+ /** Lane calls made since the pool was built. */
110
+ kicks: number;
111
+ /** Lane calls that rejected. */
112
+ laneErrors: number;
113
+ /** When to call `resume` again, in clock time, at least the 5 s alarm floor ahead. Unset when nothing is open. */
114
+ wake?: number;
115
+ }
116
+ /** Options for `LanePool`. */
117
+ export interface LanePoolOptions {
118
+ /** How lanes are called. */
119
+ transport: LaneTransport;
120
+ /** Lanes to use at once. */
121
+ width: number;
122
+ /**
123
+ * Lease granted to a claim, in milliseconds. Default 15,000, minimum 5,000. The alarm that
124
+ * calls `resume` cannot be set closer than 5 s, so a shorter lease could not be enforced
125
+ * sooner than that anyway. Only a task that awaits renews its lease; a synchronous task has to
126
+ * finish inside it.
127
+ */
128
+ leaseMs?: number;
129
+ /** Executions a task may start before it fails. Default 3. */
130
+ maxAttempts?: number;
131
+ /** Tasks a lane claims per call. Default 1. */
132
+ claimBatch?: number;
133
+ /** Time source. Defaults to `Date.now` and timers. */
134
+ clock?: LaneClock;
135
+ /** SQL identifier of the task table. Default `folio_tasks`. */
136
+ table?: string;
137
+ /**
138
+ * Resolves once every earlier write survives a reset; pass `() => ctx.storage.sync()` inside a
139
+ * Durable Object. The pool awaits it after `submit`, after a claim before the tasks reach the
140
+ * lane, and after a completion before it is acknowledged. Without it the pool trusts the
141
+ * storage to be durable at each await.
142
+ */
143
+ flush?: () => Promise<void>;
144
+ }
145
+ /** A pool that cannot finish. `code` is `failed` (a task failed), `unfinished` or `stalled` (no lane claims). */
146
+ export declare class LanePoolError extends Error {
147
+ /** Why the pool could not finish. */
148
+ readonly code: 'failed' | 'unfinished' | 'stalled';
149
+ constructor(code: 'failed' | 'unfinished' | 'stalled', detail: string, cause?: unknown);
150
+ }
151
+ /**
152
+ * The coordinator side of a durable lane pool. Tasks are rows in the object's own SQLite, lanes
153
+ * on other objects claim them by RPC, and a lane that resets loses only the tasks it was
154
+ * running: their leases end and the next claim replays them. A coordinator that resets loses
155
+ * only the transitions since its last flush; build a new pool over the same storage and call
156
+ * `run` or `resume`.
157
+ *
158
+ * A write is durable once an await or a flush has passed it, so the pool flushes after the three
159
+ * transitions that must survive (enqueue, claim, complete) and before anything depends on them.
160
+ * A failure report, a lease renewal and the expiry of a lease are not flushed: losing one only
161
+ * brings the same replay that a lane reset brings.
162
+ *
163
+ * Each id's result is written once. A task body runs at least once, so the result is exactly
164
+ * once in the table and effectively once for a task whose body is deterministic or idempotent.
165
+ */
166
+ export declare class LanePool implements LaneCoordinator {
167
+ #private;
168
+ /** The task table, for callers that read rows directly. */
169
+ readonly table: TaskTable;
170
+ constructor(sql: SqlStorage, options: LanePoolOptions);
171
+ /**
172
+ * Adds tasks and returns how many were new, once they are flushed. An id that exists is
173
+ * ignored, so repeating a submit that failed is safe.
174
+ */
175
+ submit(tasks: readonly TaskSpec[]): Promise<number>;
176
+ /**
177
+ * Claims up to `claimBatch` tasks for a lane and flushes the claim before it returns, so a
178
+ * lane never runs a task whose claim a reset could still take back. Settles poison tasks first.
179
+ */
180
+ claim(): Promise<LaneTask[]>;
181
+ /** Writes a task's result unless the task is already final, and flushes before it answers. */
182
+ complete(id: string, attempt: number, result: TaskValue): Promise<CompletionOutcome>;
183
+ /** Records an error from an attempt; the task retries until `maxAttempts`. */
184
+ fail(id: string, attempt: number, error: string): Promise<FailureOutcome>;
185
+ /** Extends the lease of each hold that is still the task's current attempt. */
186
+ renew(holds: readonly LaneHold[]): Promise<boolean[]>;
187
+ /**
188
+ * Calls lanes until every task is `done` or `failed`. Lanes that reset or return late are
189
+ * replayed after their leases end, so this can wait a lease length. Throws `stalled` when
190
+ * lanes keep returning without claiming work that is ready. Failed tasks do not throw here;
191
+ * read `failed` in the report, or let `fold` throw.
192
+ */
193
+ run(): Promise<LaneReport>;
194
+ /**
195
+ * One pass for an alarm: settles poison tasks, calls lanes for the work that is ready, waits
196
+ * for those calls and reports. `wake` says when to call again.
197
+ */
198
+ resume(): Promise<LaneReport>;
199
+ /** Every task in id order, whatever its state. */
200
+ results(): LaneResult[];
201
+ /**
202
+ * Folds the results in id order, whatever order the tasks finished in. Throws `unfinished`
203
+ * while a task is open and `failed` when one failed.
204
+ */
205
+ fold<T>(combine: (acc: T, result: LaneResult, index: number) => T, init: T): T;
206
+ /** Closes the transport. */
207
+ close(): Promise<void>;
208
+ }
209
+ /**
210
+ * The lane side. Returns the methods of a lane object: `work(coordinator)` claims tasks from the
211
+ * coordinator, runs `registry[name](args)` for each and reports the result, until a claim comes
212
+ * back empty. A task that returns a promise has its lease renewed while it runs; between the tasks
213
+ * of one claimed batch the lane renews the ones it still holds and skips any that are no longer
214
+ * its own. A task that throws, or names nothing in the registry, is reported as failed, and the
215
+ * pool retries it up to `maxAttempts`. A lane that resets mid-task reports nothing, and the lease
216
+ * ends the claim.
217
+ */
218
+ export declare function serveLane(registry: TaskRegistry): {
219
+ /** Works the queue through `coordinator` until a claim comes back empty. */
220
+ work(coordinator: LaneCoordinator): Promise<LaneWorked>;
221
+ };