@gmitch215/folio 1.1.0 → 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 (122) hide show
  1. package/README.md +78 -810
  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} +5 -5
  14. package/dist/{extract.d.ts → execution/extract.d.ts} +3 -13
  15. package/dist/{extract.js → execution/extract.js} +7 -8
  16. package/dist/{fold.d.ts → execution/fold.d.ts} +15 -3
  17. package/dist/{guards.d.ts → execution/guards.d.ts} +2 -1
  18. package/dist/execution/types.d.ts +221 -0
  19. package/dist/{affine-state.d.ts → folds/affine-state.d.ts} +18 -47
  20. package/dist/{affine-state.js → folds/affine-state.js} +18 -44
  21. package/dist/{affine.d.ts → folds/affine.d.ts} +12 -24
  22. package/dist/{affine.js → folds/affine.js} +8 -17
  23. package/dist/{boundaries.d.ts → folds/boundaries.d.ts} +7 -18
  24. package/dist/{boundaries.js → folds/boundaries.js} +5 -13
  25. package/dist/{certified.d.ts → folds/certified.d.ts} +13 -24
  26. package/dist/{certified.js → folds/certified.js} +12 -26
  27. package/dist/{certify.d.ts → folds/certify.d.ts} +11 -22
  28. package/dist/{certify.js → folds/certify.js} +24 -41
  29. package/dist/{memo.d.ts → footprints/memo.d.ts} +8 -33
  30. package/dist/{memo.js → footprints/memo.js} +8 -2
  31. package/dist/{ranges.js → footprints/ranges.js} +1 -1
  32. package/dist/{read-scan.js → footprints/read-scan.js} +1 -1
  33. package/dist/{read-windows.d.ts → footprints/read-windows.d.ts} +6 -32
  34. package/dist/{read-windows.js → footprints/read-windows.js} +8 -7
  35. package/dist/index.d.ts +16 -4
  36. package/dist/index.js +14 -2
  37. package/dist/{iteration-admission.d.ts → iteration/admission.d.ts} +2 -38
  38. package/dist/{iteration.d.ts → iteration/index.d.ts} +8 -98
  39. package/dist/{iteration.js → iteration/index.js} +28 -28
  40. package/dist/{inline.js → iteration/inline.js} +2 -9
  41. package/dist/{iteration-owner.d.ts → iteration/owner.d.ts} +3 -3
  42. package/dist/{iteration-owner.js → iteration/owner.js} +4 -3
  43. package/dist/{iteration-worker.js → iteration/worker.js} +3 -3
  44. package/dist/{managed.d.ts → managed/index.d.ts} +3 -3
  45. package/dist/{managed.js → managed/index.js} +7 -9
  46. package/dist/managed/outbox.d.ts +128 -0
  47. package/dist/managed/outbox.js +156 -0
  48. package/dist/managed/pool.d.ts +221 -0
  49. package/dist/managed/pool.js +310 -0
  50. package/dist/managed/tasks.d.ts +154 -0
  51. package/dist/managed/tasks.js +183 -0
  52. package/dist/{bake.d.ts → memory/bake.d.ts} +12 -6
  53. package/dist/{bake.js → memory/bake.js} +9 -7
  54. package/dist/memory/continuation.d.ts +141 -0
  55. package/dist/memory/continuation.js +495 -0
  56. package/dist/memory/elastic-peer.d.ts +20 -0
  57. package/dist/memory/elastic-peer.js +39 -0
  58. package/dist/memory/elastic-sql.d.ts +11 -0
  59. package/dist/memory/elastic-sql.js +35 -0
  60. package/dist/memory/elastic.d.ts +130 -0
  61. package/dist/memory/elastic.js +475 -0
  62. package/dist/memory/growth-governor.d.ts +16 -0
  63. package/dist/memory/growth-governor.js +42 -0
  64. package/dist/memory/imports.d.ts +10 -0
  65. package/dist/memory/imports.js +89 -0
  66. package/dist/{iteration-layout.d.ts → memory/iteration-layout.d.ts} +1 -1
  67. package/dist/{pages.d.ts → memory/pages.d.ts} +3 -3
  68. package/dist/memory.d.ts +5 -10
  69. package/dist/memory.js +5 -89
  70. package/dist/{context.d.ts → node/context.d.ts} +1 -1
  71. package/dist/{host.d.ts → node/host.d.ts} +1 -1
  72. package/dist/{host.js → node/host.js} +2 -2
  73. package/dist/{node.d.ts → node/index.d.ts} +4 -49
  74. package/dist/{node.js → node/index.js} +16 -17
  75. package/dist/{tasks.d.ts → node/tasks.d.ts} +2 -13
  76. package/dist/{worker.js → node/worker.js} +2 -2
  77. package/dist/{ownership.js → ownership/index.js} +7 -10
  78. package/dist/{ownership-redirect.d.ts → ownership/redirect.d.ts} +2 -2
  79. package/dist/{ownership-redirect.js → ownership/redirect.js} +2 -2
  80. package/dist/{ownership-slices.d.ts → ownership/slices.d.ts} +3 -3
  81. package/dist/{ownership-slices.js → ownership/slices.js} +3 -3
  82. package/dist/{frames.d.ts → remote/frames.d.ts} +1 -1
  83. package/dist/{frames.js → remote/frames.js} +2 -2
  84. package/dist/{remote.d.ts → remote/index.d.ts} +7 -2
  85. package/dist/{remote.js → remote/index.js} +7 -2
  86. package/dist/{router.d.ts → routing/index.d.ts} +3 -3
  87. package/dist/{router.js → routing/index.js} +19 -15
  88. package/dist/{router-worker.js → routing/worker.js} +1 -1
  89. package/dist/{slices.d.ts → slices/index.d.ts} +2 -2
  90. package/dist/{slices.js → slices/index.js} +5 -5
  91. package/dist/slices/worker.d.ts +1 -0
  92. package/dist/{slices-worker.js → slices/worker.js} +2 -2
  93. package/dist/workers.d.ts +5 -0
  94. package/dist/workers.js +5 -0
  95. package/package.json +30 -80
  96. /package/dist/{browser-worker.d.ts → browser/worker.d.ts} +0 -0
  97. /package/dist/{browser-worker.js → browser/worker.js} +0 -0
  98. /package/dist/{fold.js → execution/fold.js} +0 -0
  99. /package/dist/{guards.js → execution/guards.js} +0 -0
  100. /package/dist/{import-order.d.ts → execution/import-order.d.ts} +0 -0
  101. /package/dist/{import-order.js → execution/import-order.js} +0 -0
  102. /package/dist/{runs.d.ts → execution/runs.d.ts} +0 -0
  103. /package/dist/{runs.js → execution/runs.js} +0 -0
  104. /package/dist/{transaction.d.ts → execution/transaction.d.ts} +0 -0
  105. /package/dist/{transaction.js → execution/transaction.js} +0 -0
  106. /package/dist/{iteration-worker.d.ts → execution/types.js} +0 -0
  107. /package/dist/{ranges.d.ts → footprints/ranges.d.ts} +0 -0
  108. /package/dist/{read-scan.d.ts → footprints/read-scan.d.ts} +0 -0
  109. /package/dist/{iteration-admission.js → iteration/admission.js} +0 -0
  110. /package/dist/{inline.d.ts → iteration/inline.d.ts} +0 -0
  111. /package/dist/{worker.d.ts → iteration/worker.d.ts} +0 -0
  112. /package/dist/{iteration-layout.js → memory/iteration-layout.js} +0 -0
  113. /package/dist/{lease.d.ts → memory/lease.d.ts} +0 -0
  114. /package/dist/{lease.js → memory/lease.js} +0 -0
  115. /package/dist/{pages.js → memory/pages.js} +0 -0
  116. /package/dist/{context.js → node/context.js} +0 -0
  117. /package/dist/{tasks.js → node/tasks.js} +0 -0
  118. /package/dist/{router-worker.d.ts → node/worker.d.ts} +0 -0
  119. /package/dist/{ownership.d.ts → ownership/index.d.ts} +0 -0
  120. /package/dist/{values.d.ts → remote/values.d.ts} +0 -0
  121. /package/dist/{values.js → remote/values.js} +0 -0
  122. /package/dist/{slices-worker.d.ts → routing/worker.d.ts} +0 -0
@@ -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
+ }
@@ -61,7 +61,10 @@ export interface BakeOptions {
61
61
  /** Bake an image that reports changed table slots; the caller then restores them itself. */
62
62
  allowTableChanges?: boolean;
63
63
  }
64
- /** What `applyImage` requires of an image; a value the image does not carry or differs in is refused. */
64
+ /**
65
+ * What `applyImage` requires of an image. A value the image does not carry, or one that differs,
66
+ * is refused.
67
+ */
65
68
  export interface ApplyExpectation {
66
69
  /** sha256 hex of the module bytes the memory belongs to. */
67
70
  module?: string;
@@ -97,7 +100,10 @@ export declare class ImageMismatchError extends Error {
97
100
  readonly code: ImageMismatchCode;
98
101
  constructor(code: ImageMismatchCode, detail: string);
99
102
  }
100
- /** Why bytes are not an image: a wrong `magic` or `version`, `truncated` input, or `invalid` contents. */
103
+ /**
104
+ * Why bytes are not an image: a wrong `magic` or `version`, `truncated` input, or `invalid`
105
+ * contents.
106
+ */
101
107
  export type ImageFormatCode = 'magic' | 'version' | 'truncated' | 'invalid';
102
108
  /** Bytes are not an encoded image, or an image object is inconsistent. */
103
109
  export declare class ImageFormatError extends Error {
@@ -105,7 +111,7 @@ export declare class ImageFormatError extends Error {
105
111
  readonly code: ImageFormatCode;
106
112
  constructor(code: ImageFormatCode, detail: string);
107
113
  }
108
- /** Default cap on one data segment (64 MiB); it bounds the string and heap copy made per segment. */
114
+ /** Default cap on one data segment (64 MiB). It bounds the string and heap copy made per segment. */
109
115
  export declare const maxSegmentBytes: number;
110
116
  /** Lowercase sha256 hex of module bytes, the form `MemoryImage.module` holds. */
111
117
  export declare function moduleDigest(bytes: Uint8Array): Promise<string>;
@@ -172,8 +178,8 @@ export declare function findInImage(image: MemoryImage, needles: Uint8Array[]):
172
178
  * flag and memory64 flag stay as they are, and one already large enough is untouched.
173
179
  *
174
180
  * Throws `ImageMismatchError` for a wrong module digest (taken over `bytes` as passed), a module
175
- * with no memory or with more than one, an image over the memory maximum, a global that cannot be rewritten and changed
176
- * table slots (unless `allowTableChanges`). A start function is refused because it would run
177
- * again over the captured state.
181
+ * with no memory or with more than one, an image over the memory maximum, a global that cannot be
182
+ * rewritten, and changed table slots (unless `allowTableChanges`). A start function is refused
183
+ * because it would run again over the captured state.
178
184
  */
179
185
  export declare function bakeModule(bytes: Uint8Array, image: MemoryImage, options?: BakeOptions): Promise<Uint8Array>;
@@ -1,4 +1,4 @@
1
- import { memoryImports } from "./memory.js";
1
+ import { memoryImports } from "./imports.js";
2
2
  import { pageBytes } from "./pages.js";
3
3
  /** The image cannot be baked into this module. */
4
4
  export class ImageMismatchError extends Error {
@@ -20,7 +20,7 @@ export class ImageFormatError extends Error {
20
20
  this.code = code;
21
21
  }
22
22
  }
23
- /** Default cap on one data segment (64 MiB); it bounds the string and heap copy made per segment. */
23
+ /** Default cap on one data segment (64 MiB). It bounds the string and heap copy made per segment. */
24
24
  export const maxSegmentBytes = 64 * 1024 * 1024;
25
25
  const zeroPage = new Uint8Array(pageBytes);
26
26
  const hexDigest = /^[0-9a-f]{64}$/;
@@ -390,7 +390,9 @@ function name(c) {
390
390
  c.at += length;
391
391
  return value;
392
392
  }
393
- /** Calls `visit` with a section's id, a cursor at its body, its end and its start; stops on `false`. */
393
+ /**
394
+ * Calls `visit` with a section's id, a cursor at its body, its end and its start. Stops on `false`.
395
+ */
394
396
  function eachSection(bytes, visit) {
395
397
  const header = [0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00];
396
398
  if (bytes.length < 8 || !header.every((value, i) => bytes[i] === value))
@@ -597,7 +599,7 @@ const latin1 = (data) => {
597
599
  text += String.fromCharCode(...data.subarray(at, at + 8192));
598
600
  return text;
599
601
  };
600
- /** appends one active segment through the C entry point; setMemory drops the module's own segments */
602
+ // appends through the C entry point; setMemory drops the module's own segments
601
603
  function addSegment(binaryen, mod, segment, memory, offset, data, memory64) {
602
604
  const api = binaryen;
603
605
  const pointers = [];
@@ -646,9 +648,9 @@ function setGlobal(binaryen, mod, index, value) {
646
648
  * flag and memory64 flag stay as they are, and one already large enough is untouched.
647
649
  *
648
650
  * Throws `ImageMismatchError` for a wrong module digest (taken over `bytes` as passed), a module
649
- * with no memory or with more than one, an image over the memory maximum, a global that cannot be rewritten and changed
650
- * table slots (unless `allowTableChanges`). A start function is refused because it would run
651
- * again over the captured state.
651
+ * with no memory or with more than one, an image over the memory maximum, a global that cannot be
652
+ * rewritten, and changed table slots (unless `allowTableChanges`). A start function is refused
653
+ * because it would run again over the captured state.
652
654
  */
653
655
  export async function bakeModule(bytes, image, options = {}) {
654
656
  assertImage(image);
@@ -0,0 +1,141 @@
1
+ /** The subset of a Durable Object SQL handle this module uses. */
2
+ export interface SqlStorage {
3
+ exec(query: string, ...bindings: (string | number | null | ArrayBuffer)[]): {
4
+ toArray(): Record<string, unknown>[];
5
+ };
6
+ }
7
+ /** The subset of a Durable Object storage handle this module uses. */
8
+ export interface DurableObjectStorage {
9
+ readonly sql: SqlStorage;
10
+ transactionSync<T>(closure: () => T): T;
11
+ sync(): Promise<void>;
12
+ setAlarm(scheduledTime: number | Date): Promise<void>;
13
+ }
14
+ /** The platform CPU warning, read from the `__instance_signal` word of a guest. */
15
+ export interface CpuSignal {
16
+ /** Byte address of the u32 word in the guest memory. */
17
+ readonly address: number;
18
+ /** True when the word is nonzero. */
19
+ readonly raised: boolean;
20
+ /** Writes 0 to the word. */
21
+ clear(): void;
22
+ }
23
+ /** The CPU warning of an instance, or undefined when it does not export `__instance_signal`. */
24
+ export declare function cpuSignal(instance: WebAssembly.Instance, memory?: WebAssembly.Memory): CpuSignal | undefined;
25
+ /**
26
+ * Hashes each 64 KiB page into two u32 words (low, high). A change detector, not a security hash;
27
+ * the words are read little-endian, as every supported host is.
28
+ */
29
+ export declare function hashPages(memory: WebAssembly.Memory | Uint8Array): Uint32Array;
30
+ /** Page indexes whose hash differs from the previous checkpoint, or all pages when there is none. */
31
+ export declare function changedPages(current: Uint32Array, previous: Uint32Array | undefined): number[];
32
+ /** One committed checkpoint. */
33
+ export interface CheckpointManifest {
34
+ epoch: number;
35
+ byteLength: number;
36
+ hashes: Uint32Array;
37
+ globals: Record<string, number | bigint>;
38
+ state?: string;
39
+ }
40
+ /**
41
+ * Storage behind a checkpoint. `commit` is all or nothing; `pages` returns the newest copy at or
42
+ * below `epoch`. `flush`, when the store has one, resolves once every earlier write survives a
43
+ * killed invocation.
44
+ */
45
+ export interface CheckpointStore {
46
+ latest(): CheckpointManifest | undefined;
47
+ pages(epoch: number, indexes: number[]): Map<number, Uint8Array>;
48
+ commit(manifest: CheckpointManifest, pages: Map<number, Uint8Array>): void;
49
+ flush?(): Promise<void>;
50
+ }
51
+ /** A checkpoint that cannot be loaded: a `hash`, `size`, `global` or `manifest` mismatch. */
52
+ export declare class CheckpointError extends Error {
53
+ readonly code: 'hash' | 'size' | 'global' | 'manifest';
54
+ constructor(code: 'hash' | 'size' | 'global' | 'manifest', detail: string);
55
+ }
56
+ /** In-process store for tests and Node. Keeps the newest copy of each page. */
57
+ export declare function memoryCheckpointStore(): CheckpointStore;
58
+ interface SqlStoreOptions {
59
+ prefix?: string;
60
+ groupPages?: number;
61
+ /** Becomes the store's `flush`; pass `() => storage.sync()` inside a Durable Object. */
62
+ sync?: () => Promise<void>;
63
+ }
64
+ /**
65
+ * DO SQLite store with one row per group of `groupPages` pages (default 16, 1 MiB). Keep one value
66
+ * of `groupPages` per prefix. Commit must run in one synchronous span.
67
+ */
68
+ export declare function sqlCheckpointStore(sql: SqlStorage, options?: SqlStoreOptions): CheckpointStore;
69
+ /** Options for `saveCheckpoint`. */
70
+ export interface SaveOptions {
71
+ globals?: Record<string, WebAssembly.Global>;
72
+ state?: string;
73
+ stateJson?: unknown;
74
+ }
75
+ /** Writes the pages that changed since the last manifest, with the globals and host state. */
76
+ export declare function saveCheckpoint(store: CheckpointStore, memory: WebAssembly.Memory, options?: SaveOptions): {
77
+ epoch: number;
78
+ pagesWritten: number;
79
+ bytesWritten: number;
80
+ };
81
+ /**
82
+ * Restores the newest checkpoint into the memory, growing it as needed. Every page is verified
83
+ * before anything is written. Returns undefined when the store is empty. For a runSlice checkpoint,
84
+ * `json()` returns `{budget, measured, steps, host}`.
85
+ */
86
+ export declare function loadCheckpoint(store: CheckpointStore, memory: WebAssembly.Memory, options?: {
87
+ globals?: Record<string, WebAssembly.Global>;
88
+ }): {
89
+ epoch: number;
90
+ state?: string;
91
+ json<T>(): T;
92
+ } | undefined;
93
+ /** Why a slice ended. */
94
+ export type StopReason = 'finished' | 'signal' | 'budget';
95
+ /** Options for `runSlice`. */
96
+ export interface SliceOptions {
97
+ storage: DurableObjectStorage;
98
+ memory: WebAssembly.Memory;
99
+ globals?: Record<string, WebAssembly.Global>;
100
+ /** From `cpuSignal()`; cleared at the start of each slice. */
101
+ signal?: CpuSignal;
102
+ /** Runs up to `budgetSteps` guest steps and returns at a quiescent point. */
103
+ run(budgetSteps: number): StopReason | Promise<StopReason>;
104
+ /** The guest's monotonic step counter. */
105
+ steps(): number;
106
+ /** Step budget of the first slice, default 2000. */
107
+ initialBudget?: number;
108
+ /** Host state saved with each checkpoint. */
109
+ state?(): string | undefined;
110
+ /** Called after a restore and before `run`. */
111
+ restore?(state: string | undefined): void;
112
+ }
113
+ /** A slice whose previous attempt died before it committed. */
114
+ export interface SliceLoss {
115
+ /** The event number, which the retry keeps. */
116
+ k: number;
117
+ /** Budget of the attempt that died. */
118
+ from: number;
119
+ /** Budget the retry runs with. */
120
+ to: number;
121
+ }
122
+ /**
123
+ * Runs one alarm event of a guest: restores or commits as needed, runs the guest with the event
124
+ * budget, and commits at a budget stop. A signal stop writes nothing before it re-arms.
125
+ * The manifest state holds a runSlice record (budget, step count, host state), so
126
+ * `loadCheckpoint(...).json()` returns that record for checkpoints written here.
127
+ * Before the guest runs, an attempt row with the event number and budget is written and flushed.
128
+ * An event that starts in a new isolate and finds an attempt with no commit after it knows the
129
+ * previous attempt was killed: it halves that budget (never below `initialBudget`), stops doubling
130
+ * and reports the halving in `lost`.
131
+ * Call it from alarm().
132
+ */
133
+ export declare function runSlice(options: SliceOptions): Promise<{
134
+ finished: boolean;
135
+ restored: boolean;
136
+ stop: StopReason | 'cut';
137
+ epoch: number;
138
+ budget: number;
139
+ lost?: SliceLoss;
140
+ }>;
141
+ export {};