@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,310 @@
1
+ import { TaskTable } from "./tasks.js";
2
+ /** A pool that cannot finish. `code` is `failed` (a task failed), `unfinished` or `stalled` (no lane claims). */
3
+ export class LanePoolError extends Error {
4
+ /** Why the pool could not finish. */
5
+ code;
6
+ constructor(code, detail, cause) {
7
+ super(`lane pool ${code}: ${detail}`, cause === undefined ? undefined : { cause });
8
+ this.name = 'LanePoolError';
9
+ this.code = code;
10
+ }
11
+ }
12
+ const minLeaseMs = 5000;
13
+ // lane calls in a row that claim nothing while work is ready
14
+ const stallLimit = 3;
15
+ const systemClock = {
16
+ now: () => Date.now(),
17
+ sleep: (ms, signal) => new Promise((resolve) => {
18
+ const timer = setTimeout(resolve, ms);
19
+ signal?.addEventListener('abort', () => {
20
+ clearTimeout(timer);
21
+ resolve();
22
+ }, { once: true });
23
+ })
24
+ };
25
+ const isValue = (value) => typeof value === 'string' || value instanceof Uint8Array;
26
+ const decode = (value) => typeof value === 'string' ? value : new TextDecoder().decode(value);
27
+ function resultOf(row) {
28
+ const finished = () => {
29
+ if (row.state !== 'done' || row.result === null)
30
+ throw new LanePoolError('failed', `task ${row.id} is ${row.state}: ${row.error ?? ''}`);
31
+ return decode(row.result);
32
+ };
33
+ return {
34
+ id: row.id,
35
+ name: row.name,
36
+ state: row.state,
37
+ attempt: row.attempt,
38
+ ...(row.result === null ? {} : { value: row.result }),
39
+ ...(row.error === null ? {} : { error: row.error }),
40
+ text: finished,
41
+ json: () => JSON.parse(finished())
42
+ };
43
+ }
44
+ /**
45
+ * The coordinator side of a durable lane pool. Tasks are rows in the object's own SQLite, lanes
46
+ * on other objects claim them by RPC, and a lane that resets loses only the tasks it was
47
+ * running: their leases end and the next claim replays them. A coordinator that resets loses
48
+ * only the transitions since its last flush; build a new pool over the same storage and call
49
+ * `run` or `resume`.
50
+ *
51
+ * A write is durable once an await or a flush has passed it, so the pool flushes after the three
52
+ * transitions that must survive (enqueue, claim, complete) and before anything depends on them.
53
+ * A failure report, a lease renewal and the expiry of a lease are not flushed: losing one only
54
+ * brings the same replay that a lane reset brings.
55
+ *
56
+ * Each id's result is written once. A task body runs at least once, so the result is exactly
57
+ * once in the table and effectively once for a task whose body is deterministic or idempotent.
58
+ */
59
+ export class LanePool {
60
+ /** The task table, for callers that read rows directly. */
61
+ table;
62
+ #transport;
63
+ #width;
64
+ #leaseMs;
65
+ #batch;
66
+ #clock;
67
+ #flush;
68
+ #claims = 0;
69
+ #kicks = 0;
70
+ #laneErrors = 0;
71
+ #lastError;
72
+ constructor(sql, options) {
73
+ const { width, leaseMs = 15000, claimBatch = 1 } = options;
74
+ if (!Number.isInteger(width) || width < 1)
75
+ throw new RangeError('width must be a positive integer');
76
+ if (!Number.isInteger(leaseMs) || leaseMs < minLeaseMs)
77
+ throw new RangeError(`leaseMs must be an integer of at least ${minLeaseMs}`);
78
+ if (!Number.isInteger(claimBatch) || claimBatch < 1)
79
+ throw new RangeError('claimBatch must be a positive integer');
80
+ this.table = new TaskTable(sql, { table: options.table, maxAttempts: options.maxAttempts });
81
+ this.#transport = options.transport;
82
+ this.#width = width;
83
+ this.#leaseMs = leaseMs;
84
+ this.#batch = claimBatch;
85
+ this.#clock = options.clock ?? systemClock;
86
+ this.#flush = options.flush ?? (async () => { });
87
+ }
88
+ /**
89
+ * Adds tasks and returns how many were new, once they are flushed. An id that exists is
90
+ * ignored, so repeating a submit that failed is safe.
91
+ */
92
+ async submit(tasks) {
93
+ let added = 0;
94
+ for (const task of tasks) {
95
+ if (typeof task.id !== 'string' || !task.id)
96
+ throw new TypeError('a task needs an id');
97
+ if (typeof task.name !== 'string' || !task.name)
98
+ throw new TypeError(`task ${task.id} needs a name`);
99
+ if (task.args !== undefined && task.argsJson !== undefined)
100
+ throw new TypeError('pass args or argsJson, not both');
101
+ const args = task.argsJson === undefined ? (task.args ?? '') : JSON.stringify(task.argsJson);
102
+ if (!isValue(args))
103
+ throw new TypeError(`args of task ${task.id} must be a string or bytes`);
104
+ if (this.table.enqueue(task.id, task.name, args))
105
+ added++;
106
+ }
107
+ await this.#flush();
108
+ return added;
109
+ }
110
+ /**
111
+ * Claims up to `claimBatch` tasks for a lane and flushes the claim before it returns, so a
112
+ * lane never runs a task whose claim a reset could still take back. Settles poison tasks first.
113
+ */
114
+ async claim() {
115
+ const rows = this.table.claim(this.#clock.now(), this.#leaseMs, this.#batch);
116
+ await this.#flush();
117
+ if (rows.length)
118
+ this.#claims++;
119
+ return rows.map((row) => ({
120
+ id: row.id,
121
+ name: row.name,
122
+ args: row.args,
123
+ attempt: row.attempt,
124
+ leaseMs: this.#leaseMs
125
+ }));
126
+ }
127
+ /** Writes a task's result unless the task is already final, and flushes before it answers. */
128
+ async complete(id, attempt, result) {
129
+ if (!isValue(result))
130
+ throw new TypeError('a task result must be a string or bytes');
131
+ const outcome = this.table.complete(id, attempt, result);
132
+ await this.#flush();
133
+ return outcome;
134
+ }
135
+ /** Records an error from an attempt; the task retries until `maxAttempts`. */
136
+ async fail(id, attempt, error) {
137
+ return this.table.fail(id, attempt, String(error));
138
+ }
139
+ /** Extends the lease of each hold that is still the task's current attempt. */
140
+ async renew(holds) {
141
+ const now = this.#clock.now();
142
+ return holds.map((hold) => this.table.renew(hold.id, hold.attempt, now, this.#leaseMs));
143
+ }
144
+ /**
145
+ * Calls lanes until every task is `done` or `failed`. Lanes that reset or return late are
146
+ * replayed after their leases end, so this can wait a lease length. Throws `stalled` when
147
+ * lanes keep returning without claiming work that is ready. Failed tasks do not throw here;
148
+ * read `failed` in the report, or let `fold` throw.
149
+ */
150
+ async run() {
151
+ const busy = new Map();
152
+ let fruitless = 0;
153
+ for (;;) {
154
+ const now = this.#clock.now();
155
+ this.table.expire(now);
156
+ const open = this.table.pending(now);
157
+ if (open.open === 0)
158
+ return this.#report(now);
159
+ if (fruitless >= stallLimit)
160
+ throw new LanePoolError('stalled', `${stallLimit} lane calls in a row claimed nothing while ${open.claimable} tasks were ready`, this.#lastError);
161
+ let wanted = Math.min(this.#width - busy.size, Math.ceil(open.claimable / this.#batch));
162
+ for (let lane = 0; wanted > 0 && lane < this.#width; lane++) {
163
+ if (busy.has(lane))
164
+ continue;
165
+ wanted--;
166
+ const before = this.#claims;
167
+ busy.set(lane, this.#kick(lane).then(() => {
168
+ fruitless = this.#claims === before ? fruitless + 1 : 0;
169
+ busy.delete(lane);
170
+ }));
171
+ }
172
+ const wake = new AbortController();
173
+ const waits = [...busy.values()];
174
+ if (open.nextExpiry !== undefined)
175
+ waits.push(this.#clock.sleep(open.nextExpiry - now, wake.signal));
176
+ if (!waits.length)
177
+ throw new LanePoolError('stalled', 'no lane is working and no lease is pending');
178
+ await Promise.race(waits);
179
+ wake.abort();
180
+ }
181
+ }
182
+ /**
183
+ * One pass for an alarm: settles poison tasks, calls lanes for the work that is ready, waits
184
+ * for those calls and reports. `wake` says when to call again.
185
+ */
186
+ async resume() {
187
+ const now = this.#clock.now();
188
+ this.table.expire(now);
189
+ const open = this.table.pending(now);
190
+ const lanes = Math.min(this.#width, Math.ceil(open.claimable / this.#batch));
191
+ await Promise.all(Array.from({ length: lanes }, (_, lane) => this.#kick(lane)));
192
+ const after = this.#clock.now();
193
+ this.table.expire(after);
194
+ return this.#report(after);
195
+ }
196
+ /** Every task in id order, whatever its state. */
197
+ results() {
198
+ return this.table.snapshot().map(resultOf);
199
+ }
200
+ /**
201
+ * Folds the results in id order, whatever order the tasks finished in. Throws `unfinished`
202
+ * while a task is open and `failed` when one failed.
203
+ */
204
+ fold(combine, init) {
205
+ const all = this.results();
206
+ const failed = all.filter((result) => result.state === 'failed');
207
+ if (failed.length)
208
+ throw new LanePoolError('failed', `${failed.length} tasks failed, first ${failed[0].id}: ${failed[0].error ?? ''}`);
209
+ const open = all.filter((result) => result.state !== 'done');
210
+ if (open.length)
211
+ throw new LanePoolError('unfinished', `${open.length} tasks are not done`);
212
+ return all.reduce((acc, result, index) => combine(acc, result, index), init);
213
+ }
214
+ /** Closes the transport. */
215
+ close() {
216
+ return Promise.resolve(this.#transport.close?.());
217
+ }
218
+ async #kick(lane) {
219
+ this.#kicks++;
220
+ try {
221
+ await this.#transport.work(lane);
222
+ }
223
+ catch (error) {
224
+ this.#laneErrors++;
225
+ this.#lastError = error;
226
+ }
227
+ }
228
+ #report(now) {
229
+ const counts = this.table.counts();
230
+ const wake = counts.queued + counts.running === 0
231
+ ? undefined
232
+ : Math.max(this.table.pending(now).nextExpiry ?? 0, now + minLeaseMs);
233
+ return {
234
+ ...counts,
235
+ kicks: this.#kicks,
236
+ laneErrors: this.#laneErrors,
237
+ ...(wake === undefined ? {} : { wake })
238
+ };
239
+ }
240
+ }
241
+ const message = (error) => (error instanceof Error ? error.message : String(error)).slice(0, 1000);
242
+ /**
243
+ * The lane side. Returns the methods of a lane object: `work(coordinator)` claims tasks from the
244
+ * coordinator, runs `registry[name](args)` for each and reports the result, until a claim comes
245
+ * back empty. A task that returns a promise has its lease renewed while it runs; between the tasks
246
+ * of one claimed batch the lane renews the ones it still holds and skips any that are no longer
247
+ * its own. A task that throws, or names nothing in the registry, is reported as failed, and the
248
+ * pool retries it up to `maxAttempts`. A lane that resets mid-task reports nothing, and the lease
249
+ * ends the claim.
250
+ */
251
+ export function serveLane(registry) {
252
+ return {
253
+ async work(coordinator) {
254
+ const worked = { claimed: 0, completed: 0, failed: 0 };
255
+ for (;;) {
256
+ const batch = await coordinator.claim();
257
+ if (!batch.length)
258
+ return worked;
259
+ worked.claimed += batch.length;
260
+ const held = new Map(batch.map((task) => [task.id, task]));
261
+ const holds = () => [...held.values()].map(({ id, attempt }) => ({ id, attempt }));
262
+ for (const [index, task] of batch.entries()) {
263
+ if (index > 0 && held.size) {
264
+ const before = holds();
265
+ const kept = await coordinator.renew(before);
266
+ before.forEach((hold, at) => {
267
+ if (!kept[at])
268
+ held.delete(hold.id);
269
+ });
270
+ }
271
+ if (!held.has(task.id))
272
+ continue;
273
+ let timer;
274
+ let outcome;
275
+ try {
276
+ const fn = Object.hasOwn(registry, task.name)
277
+ ? registry[task.name]
278
+ : undefined;
279
+ if (!fn)
280
+ throw new Error(`no task named ${task.name}`);
281
+ const pending = fn(task.args, task);
282
+ let value = pending;
283
+ if (typeof pending?.then === 'function') {
284
+ timer = setInterval(() => void coordinator.renew(holds()).catch(() => { }), Math.max(1000, Math.floor(task.leaseMs / 3)));
285
+ value = await pending;
286
+ }
287
+ if (!isValue(value))
288
+ throw new TypeError(`task ${task.name} returned neither a string nor bytes`);
289
+ outcome = { value };
290
+ }
291
+ catch (error) {
292
+ outcome = { error: message(error) };
293
+ }
294
+ finally {
295
+ clearInterval(timer);
296
+ }
297
+ held.delete(task.id);
298
+ if ('value' in outcome) {
299
+ await coordinator.complete(task.id, task.attempt, outcome.value);
300
+ worked.completed++;
301
+ }
302
+ else {
303
+ await coordinator.fail(task.id, task.attempt, outcome.error);
304
+ worked.failed++;
305
+ }
306
+ }
307
+ }
308
+ }
309
+ };
310
+ }
@@ -0,0 +1,154 @@
1
+ import type { SqlStorage } from '../memory/continuation.ts';
2
+ /** A task argument or result. Structured data travels as JSON text. */
3
+ export type TaskValue = string | Uint8Array;
4
+ /** Where a task is in its life. `done` and `failed` are final. */
5
+ export type TaskState = 'queued' | 'running' | 'done' | 'failed';
6
+ /**
7
+ * What a successor does with a running row whose lease ended, when the earlier attempt may have
8
+ * run its effect. `resend` runs the effect again (at least once). `report` ends the row as
9
+ * `failed` and never runs the effect again (at most once).
10
+ */
11
+ export type ReplayPolicy = 'resend' | 'report';
12
+ /** The replay policy of each kind. A kind that is not listed, and a row with no kind, is `report`. */
13
+ export type ReplayPolicies = Readonly<Record<string, ReplayPolicy>>;
14
+ /** One row of the task table. */
15
+ export interface TaskRow {
16
+ /** The task id, unique in the table. */
17
+ id: string;
18
+ /** The registry key a lane runs. */
19
+ name: string;
20
+ /** The kind of effect the row carries, or null for a row with none. */
21
+ kind: string | null;
22
+ /** The arguments as submitted. */
23
+ args: TaskValue;
24
+ /** Where the row is in its life. */
25
+ state: TaskState;
26
+ /** Claims so far; a running row is on this attempt. */
27
+ attempt: number;
28
+ /** The time a running row's lease ends, in the units of the clock the caller passes. */
29
+ leaseUntil: number | null;
30
+ /** The result, once the row is done. */
31
+ result: TaskValue | null;
32
+ /** The last error, from a failed attempt or an expired last lease. */
33
+ error: string | null;
34
+ /** Submission order, which `claim` follows. */
35
+ seq: number;
36
+ }
37
+ /** A row a `claim` moved to running. */
38
+ export interface ClaimedRow {
39
+ /** The task id. */
40
+ id: string;
41
+ /** The registry key to run. */
42
+ name: string;
43
+ /** The kind of effect the row carries, or null for a row with none. */
44
+ kind: string | null;
45
+ /** The arguments as submitted. */
46
+ args: TaskValue;
47
+ /** The new attempt number. */
48
+ attempt: number;
49
+ /** When the new lease ends. */
50
+ leaseUntil: number;
51
+ /** Submission order. */
52
+ seq: number;
53
+ }
54
+ /** What `complete` did: wrote the result of the current attempt, of a superseded one, or nothing. */
55
+ export type CompletionOutcome = 'done' | 'late' | 'ignored';
56
+ /** What `fail` did: put the row back in the queue, ended it, or nothing. */
57
+ export type FailureOutcome = 'retry' | 'failed' | 'ignored';
58
+ /** Rows still open at a moment in time. */
59
+ export interface OpenTasks {
60
+ /** Queued rows and running rows, whatever their lease says. */
61
+ open: number;
62
+ /** Rows a `claim` at that time would take: queued, or running with an expired lease. */
63
+ claimable: number;
64
+ /** The soonest lease end after that time among running rows, if any. */
65
+ nextExpiry?: number;
66
+ }
67
+ /** Options for `TaskTable`. */
68
+ export interface TaskTableOptions {
69
+ /** SQL identifier of the table, `folio_tasks` by default. */
70
+ table?: string;
71
+ /** Executions a task may start before it fails, 3 by default. */
72
+ maxAttempts?: number;
73
+ }
74
+ /** Options for `TaskTable.claim`. */
75
+ export interface ClaimOptions {
76
+ /**
77
+ * Replay policy by kind. Without it every expired running row is claimed again. With it an
78
+ * expired running row is claimed again only when its kind is `resend`, and any other kind,
79
+ * including a row with none, is ended as `failed` instead.
80
+ */
81
+ policies?: ReplayPolicies;
82
+ /** Ids this claim must leave alone, such as rows the caller failed a moment ago. */
83
+ skip?: readonly string[];
84
+ }
85
+ /**
86
+ * A queue of named tasks in SQL with leases and attempt counts. Every method is one transition
87
+ * with no I/O, and the clock is an argument, so a caller controls time and a test can replay it.
88
+ *
89
+ * The table has no I/O, so it cannot flush: a caller that needs a transition to survive a reset
90
+ * awaits the storage's flush after it. Until then the transition can be lost, and no statement
91
+ * depends on the order of the others.
92
+ *
93
+ * Each statement reads and writes only the row it names and moves it along one way: queued to
94
+ * running, running back to queued or on to done or failed, never out of done or failed. A reset
95
+ * that keeps any subset of the statements of an event, in any order, leaves every row in a state
96
+ * that the next `claim` handles: a lost claim leaves the row queued, a lost `complete` or `fail`
97
+ * leaves it running until its lease ends, and a lost lease renewal shortens a lease that the next
98
+ * `renew` or a replay corrects.
99
+ *
100
+ * One rule changes when `claim` gets `policies`: a running row whose lease ended is claimed again
101
+ * only if its kind is `resend`. The `claim` statement itself carries that test, so it holds even
102
+ * when the statement that ends `report` rows was lost, and a `report` row is never claimed twice.
103
+ */
104
+ export declare class TaskTable {
105
+ #private;
106
+ constructor(sql: SqlStorage, options?: TaskTableOptions);
107
+ /** Executions a task may start before it fails. */
108
+ get maxAttempts(): number;
109
+ /**
110
+ * Adds a queued task, with the kind of effect it carries if any. Returns false and changes
111
+ * nothing when the id exists.
112
+ */
113
+ enqueue(id: string, name: string, args?: TaskValue, kind?: string): boolean;
114
+ /**
115
+ * Ends the running rows whose lease ended and whose kind is not `resend`, so that no later
116
+ * claim runs their effect again, and returns how many. The error names the policy and the
117
+ * attempt that was lost. `expire` and `claim` do this when they get policies.
118
+ */
119
+ reportLost(now: number, policies: ReplayPolicies): number;
120
+ /**
121
+ * Fails the running rows whose lease ended after their last allowed attempt and returns how
122
+ * many. `claim` does this first; call it alone to settle poison rows when nothing will claim.
123
+ * With `policies` it also ends the rows `reportLost` names, and counts them.
124
+ */
125
+ expire(now: number, policies?: ReplayPolicies): number;
126
+ /**
127
+ * Starts up to `limit` rows, oldest `seq` first: queued rows and running rows whose lease ended.
128
+ * Each gets the next attempt number and a lease of `leaseMs` from `now`. A running row whose
129
+ * lease ended on its last allowed attempt becomes `failed` instead, and so does one whose kind
130
+ * is not `resend` when `options.policies` is given.
131
+ */
132
+ claim(now: number, leaseMs: number, limit: number, options?: ClaimOptions): ClaimedRow[];
133
+ /**
134
+ * Writes the result of any attempt unless the row is already final, so the first completion
135
+ * wins and a second one changes nothing. `done` means the attempt was the row's current one,
136
+ * `late` that a superseded attempt finished first. The result is the same for a task whose
137
+ * body is deterministic.
138
+ */
139
+ complete(id: string, attempt: number, result: TaskValue): CompletionOutcome;
140
+ /**
141
+ * Records an error from the row's current attempt: back to `queued` while attempts remain,
142
+ * `failed` on the last one, or at once when `final` is true. A failure from a superseded
143
+ * attempt changes nothing.
144
+ */
145
+ fail(id: string, attempt: number, error: string, final?: boolean): FailureOutcome;
146
+ /** Moves a running row's lease to `leaseMs` after `now`, never earlier. False for any other row or attempt. */
147
+ renew(id: string, attempt: number, now: number, leaseMs: number): boolean;
148
+ /** Counts the rows that are not final at `now`. */
149
+ pending(now: number): OpenTasks;
150
+ /** Rows per state. */
151
+ counts(): Record<TaskState, number>;
152
+ /** Every row in id order, which is the byte order of the id. */
153
+ snapshot(): TaskRow[];
154
+ }
@@ -0,0 +1,183 @@
1
+ // the kinds that may be sent again, as JSON text for json_each
2
+ function resendKinds(policies) {
3
+ const kinds = [];
4
+ for (const [kind, policy] of Object.entries(policies)) {
5
+ if (policy !== 'resend' && policy !== 'report')
6
+ throw new TypeError(`the policy of ${kind} must be resend or report`);
7
+ if (policy === 'resend')
8
+ kinds.push(kind);
9
+ }
10
+ return JSON.stringify(kinds);
11
+ }
12
+ const bytesOf = (value) => typeof value === 'string'
13
+ ? value
14
+ : value instanceof Uint8Array
15
+ ? value.slice()
16
+ : new Uint8Array(value).slice();
17
+ const bind = (value) => typeof value === 'string' ? value : new Uint8Array(value).buffer;
18
+ function rowOf(row) {
19
+ return {
20
+ id: String(row.id),
21
+ name: String(row.name),
22
+ kind: row.kind === null ? null : String(row.kind),
23
+ args: bytesOf(row.args),
24
+ state: String(row.state),
25
+ attempt: Number(row.attempt),
26
+ leaseUntil: row.lease_until === null ? null : Number(row.lease_until),
27
+ result: row.result === null ? null : bytesOf(row.result),
28
+ error: row.error === null ? null : String(row.error),
29
+ seq: Number(row.seq)
30
+ };
31
+ }
32
+ /**
33
+ * A queue of named tasks in SQL with leases and attempt counts. Every method is one transition
34
+ * with no I/O, and the clock is an argument, so a caller controls time and a test can replay it.
35
+ *
36
+ * The table has no I/O, so it cannot flush: a caller that needs a transition to survive a reset
37
+ * awaits the storage's flush after it. Until then the transition can be lost, and no statement
38
+ * depends on the order of the others.
39
+ *
40
+ * Each statement reads and writes only the row it names and moves it along one way: queued to
41
+ * running, running back to queued or on to done or failed, never out of done or failed. A reset
42
+ * that keeps any subset of the statements of an event, in any order, leaves every row in a state
43
+ * that the next `claim` handles: a lost claim leaves the row queued, a lost `complete` or `fail`
44
+ * leaves it running until its lease ends, and a lost lease renewal shortens a lease that the next
45
+ * `renew` or a replay corrects.
46
+ *
47
+ * One rule changes when `claim` gets `policies`: a running row whose lease ended is claimed again
48
+ * only if its kind is `resend`. The `claim` statement itself carries that test, so it holds even
49
+ * when the statement that ends `report` rows was lost, and a `report` row is never claimed twice.
50
+ */
51
+ export class TaskTable {
52
+ #sql;
53
+ #table;
54
+ #maxAttempts;
55
+ constructor(sql, options = {}) {
56
+ const table = options.table ?? 'folio_tasks';
57
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table))
58
+ throw new TypeError('table must be a SQL identifier');
59
+ const maxAttempts = options.maxAttempts ?? 3;
60
+ if (!Number.isInteger(maxAttempts) || maxAttempts < 1)
61
+ throw new RangeError('maxAttempts must be a positive integer');
62
+ this.#sql = sql;
63
+ this.#table = table;
64
+ this.#maxAttempts = maxAttempts;
65
+ // args and result carry no type, so a string stays text and bytes stay a blob
66
+ this.#run(`CREATE TABLE IF NOT EXISTS ${table} (id TEXT PRIMARY KEY, name TEXT NOT NULL, kind TEXT, args, state TEXT NOT NULL, attempt INTEGER NOT NULL, lease_until INTEGER, result, error TEXT, seq INTEGER NOT NULL)`);
67
+ // a table made before the kind column existed keeps its rows
68
+ const columns = this.#run(`SELECT name FROM pragma_table_info(?)`, table);
69
+ if (!columns.some((column) => column.name === 'kind'))
70
+ this.#run(`ALTER TABLE ${table} ADD COLUMN kind TEXT`);
71
+ }
72
+ /** Executions a task may start before it fails. */
73
+ get maxAttempts() {
74
+ return this.#maxAttempts;
75
+ }
76
+ #run(query, ...bindings) {
77
+ return this.#sql.exec(query, ...bindings).toArray();
78
+ }
79
+ /**
80
+ * Adds a queued task, with the kind of effect it carries if any. Returns false and changes
81
+ * nothing when the id exists.
82
+ */
83
+ enqueue(id, name, args = '', kind) {
84
+ return (this.#run(`INSERT OR IGNORE INTO ${this.#table} (id, name, kind, args, state, attempt, lease_until, result, error, seq) VALUES (?, ?, ?, ?, 'queued', 0, NULL, NULL, NULL, (SELECT COALESCE(MAX(seq), 0) + 1 FROM ${this.#table})) RETURNING id`, id, name, kind ?? null, bind(args)).length === 1);
85
+ }
86
+ /**
87
+ * Ends the running rows whose lease ended and whose kind is not `resend`, so that no later
88
+ * claim runs their effect again, and returns how many. The error names the policy and the
89
+ * attempt that was lost. `expire` and `claim` do this when they get policies.
90
+ */
91
+ reportLost(now, policies) {
92
+ return this.#run(`UPDATE ${this.#table} SET state = 'failed', lease_until = NULL, error = 'lease expired on attempt ' || attempt || ' of ' || COALESCE('kind ' || kind, 'a row with no kind') || ': policy report, the effect may have run and is not run again' WHERE state = 'running' AND lease_until <= ? AND (kind IS NULL OR kind NOT IN (SELECT value FROM json_each(?))) RETURNING id`, now, resendKinds(policies)).length;
93
+ }
94
+ /**
95
+ * Fails the running rows whose lease ended after their last allowed attempt and returns how
96
+ * many. `claim` does this first; call it alone to settle poison rows when nothing will claim.
97
+ * With `policies` it also ends the rows `reportLost` names, and counts them.
98
+ */
99
+ expire(now, policies) {
100
+ const reported = policies ? this.reportLost(now, policies) : 0;
101
+ return (reported +
102
+ this.#run(`UPDATE ${this.#table} SET state = 'failed', lease_until = NULL, error = ? WHERE state = 'running' AND lease_until <= ? AND attempt >= ? RETURNING id`, `lease expired after ${this.#maxAttempts} attempts`, now, this.#maxAttempts).length);
103
+ }
104
+ /**
105
+ * Starts up to `limit` rows, oldest `seq` first: queued rows and running rows whose lease ended.
106
+ * Each gets the next attempt number and a lease of `leaseMs` from `now`. A running row whose
107
+ * lease ended on its last allowed attempt becomes `failed` instead, and so does one whose kind
108
+ * is not `resend` when `options.policies` is given.
109
+ */
110
+ claim(now, leaseMs, limit, options = {}) {
111
+ const { policies, skip } = options;
112
+ this.expire(now, policies);
113
+ const bindings = [now + leaseMs, this.#maxAttempts, now];
114
+ let expired = '';
115
+ if (policies) {
116
+ expired = ' AND kind IN (SELECT value FROM json_each(?))';
117
+ bindings.push(resendKinds(policies));
118
+ }
119
+ let skipped = '';
120
+ if (skip?.length) {
121
+ skipped = ' AND id NOT IN (SELECT value FROM json_each(?))';
122
+ bindings.push(JSON.stringify(skip));
123
+ }
124
+ return this.#run(`UPDATE ${this.#table} SET state = 'running', attempt = attempt + 1, lease_until = ? WHERE id IN (SELECT id FROM ${this.#table} WHERE attempt < ? AND (state = 'queued' OR (state = 'running' AND lease_until <= ?${expired}))${skipped} ORDER BY seq LIMIT ?) RETURNING id, name, kind, args, attempt, lease_until, seq`, ...bindings, limit)
125
+ .map((row) => ({
126
+ id: String(row.id),
127
+ name: String(row.name),
128
+ kind: row.kind === null ? null : String(row.kind),
129
+ args: bytesOf(row.args),
130
+ attempt: Number(row.attempt),
131
+ leaseUntil: Number(row.lease_until),
132
+ seq: Number(row.seq)
133
+ }))
134
+ .sort((a, b) => a.seq - b.seq);
135
+ }
136
+ /**
137
+ * Writes the result of any attempt unless the row is already final, so the first completion
138
+ * wins and a second one changes nothing. `done` means the attempt was the row's current one,
139
+ * `late` that a superseded attempt finished first. The result is the same for a task whose
140
+ * body is deterministic.
141
+ */
142
+ complete(id, attempt, result) {
143
+ const rows = this.#run(`UPDATE ${this.#table} SET state = 'done', result = ?, error = NULL, lease_until = NULL WHERE id = ? AND state IN ('queued', 'running') RETURNING attempt`, bind(result), id);
144
+ if (!rows.length)
145
+ return 'ignored';
146
+ return Number(rows[0].attempt) === attempt ? 'done' : 'late';
147
+ }
148
+ /**
149
+ * Records an error from the row's current attempt: back to `queued` while attempts remain,
150
+ * `failed` on the last one, or at once when `final` is true. A failure from a superseded
151
+ * attempt changes nothing.
152
+ */
153
+ fail(id, attempt, error, final = false) {
154
+ const rows = this.#run(`UPDATE ${this.#table} SET state = CASE WHEN ? OR attempt >= ? THEN 'failed' ELSE 'queued' END, error = ?, lease_until = NULL WHERE id = ? AND attempt = ? AND state = 'running' RETURNING state`, final ? 1 : 0, this.#maxAttempts, error, id, attempt);
155
+ if (!rows.length)
156
+ return 'ignored';
157
+ return rows[0].state === 'failed' ? 'failed' : 'retry';
158
+ }
159
+ /** Moves a running row's lease to `leaseMs` after `now`, never earlier. False for any other row or attempt. */
160
+ renew(id, attempt, now, leaseMs) {
161
+ return (this.#run(`UPDATE ${this.#table} SET lease_until = MAX(lease_until, ?) WHERE id = ? AND attempt = ? AND state = 'running' RETURNING id`, now + leaseMs, id, attempt).length === 1);
162
+ }
163
+ /** Counts the rows that are not final at `now`. */
164
+ pending(now) {
165
+ const row = this.#run(`SELECT COUNT(*) AS open, COALESCE(SUM((state = 'queued' OR lease_until <= ?) AND attempt < ?), 0) AS claimable, MIN(CASE WHEN state = 'running' AND lease_until > ? THEN lease_until END) AS next FROM ${this.#table} WHERE state IN ('queued', 'running')`, now, this.#maxAttempts, now)[0];
166
+ return {
167
+ open: Number(row.open),
168
+ claimable: Number(row.claimable),
169
+ ...(row.next === null ? {} : { nextExpiry: Number(row.next) })
170
+ };
171
+ }
172
+ /** Rows per state. */
173
+ counts() {
174
+ const counts = { queued: 0, running: 0, done: 0, failed: 0 };
175
+ for (const row of this.#run(`SELECT state, COUNT(*) AS n FROM ${this.#table} GROUP BY state`))
176
+ counts[String(row.state)] = Number(row.n);
177
+ return counts;
178
+ }
179
+ /** Every row in id order, which is the byte order of the id. */
180
+ snapshot() {
181
+ return this.#run(`SELECT * FROM ${this.#table} ORDER BY id`).map(rowOf);
182
+ }
183
+ }