@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,495 @@
1
+ import { pageBytes } from "./pages.js";
2
+ /** The CPU warning of an instance, or undefined when it does not export `__instance_signal`. */
3
+ export function cpuSignal(instance, memory) {
4
+ const exported = instance.exports.__instance_signal;
5
+ if (!(exported instanceof WebAssembly.Global))
6
+ return undefined;
7
+ const target = memory ?? instance.exports.memory;
8
+ if (!(target instanceof WebAssembly.Memory))
9
+ throw new TypeError('cpuSignal needs the memory the instance uses');
10
+ const address = exported.value;
11
+ if (!Number.isInteger(address) || address < 0 || address + 4 > target.buffer.byteLength)
12
+ throw new RangeError(`__instance_signal ${address} lies outside the memory`);
13
+ const word = () => new DataView(target.buffer, address, 4);
14
+ return {
15
+ address,
16
+ get raised() {
17
+ return word().getUint32(0, true) !== 0;
18
+ },
19
+ clear() {
20
+ word().setUint32(0, 0, true);
21
+ }
22
+ };
23
+ }
24
+ const seedHi = 0x243f6a88;
25
+ const seedLo = 0x85a308d3;
26
+ const primeHi = 0x9e3779b9;
27
+ const primeLo = 0x7f4a7c15;
28
+ const pageWords = pageBytes / 4;
29
+ // high 32 bits of a uint32 times a uint32, from 16-bit halves
30
+ function mulHigh(a, b) {
31
+ const a0 = a & 0xffff;
32
+ const a1 = a >>> 16;
33
+ const b0 = b & 0xffff;
34
+ const b1 = b >>> 16;
35
+ const p01 = a0 * b1;
36
+ const p10 = a1 * b0;
37
+ const mid = ((a0 * b0) >>> 16) + (p01 & 0xffff) + (p10 & 0xffff);
38
+ return a1 * b1 + (p01 >>> 16) + (p10 >>> 16) + (mid >>> 16);
39
+ }
40
+ function wordsOf(bytes) {
41
+ if (bytes.byteOffset % 4 === 0)
42
+ return new Uint32Array(bytes.buffer, bytes.byteOffset, bytes.length / 4);
43
+ return new Uint32Array(bytes.slice().buffer);
44
+ }
45
+ /**
46
+ * Hashes each 64 KiB page into two u32 words (low, high). A change detector, not a security hash;
47
+ * the words are read little-endian, as every supported host is.
48
+ */
49
+ export function hashPages(memory) {
50
+ const bytes = memory instanceof WebAssembly.Memory ? new Uint8Array(memory.buffer) : memory;
51
+ if (bytes.length % pageBytes)
52
+ throw new RangeError(`hashPages needs whole ${pageBytes} byte pages, got ${bytes.length}`);
53
+ const words = wordsOf(bytes);
54
+ const pages = bytes.length / pageBytes;
55
+ const out = new Uint32Array(pages * 2);
56
+ for (let page = 0; page < pages; page++) {
57
+ let hi = seedHi;
58
+ let lo = seedLo;
59
+ for (let w = page * pageWords; w < (page + 1) * pageWords; w += 2) {
60
+ lo ^= words[w];
61
+ hi ^= words[w + 1];
62
+ // (hi:lo) * prime mod 2^64, then h ^= h >>> 32
63
+ const productLo = Math.imul(lo, primeLo);
64
+ const productHi = (mulHigh(lo >>> 0, primeLo) + Math.imul(lo, primeHi) + Math.imul(hi, primeLo)) >>>
65
+ 0;
66
+ lo = productLo ^ productHi;
67
+ hi = productHi;
68
+ }
69
+ out[page * 2] = lo;
70
+ out[page * 2 + 1] = hi;
71
+ }
72
+ return out;
73
+ }
74
+ /** Page indexes whose hash differs from the previous checkpoint, or all pages when there is none. */
75
+ export function changedPages(current, previous) {
76
+ if (current.length % 2 || (previous && previous.length % 2))
77
+ throw new RangeError('page hashes come in pairs of words');
78
+ const pages = current.length / 2;
79
+ const known = previous ? previous.length / 2 : 0;
80
+ const changed = [];
81
+ for (let page = 0; page < pages; page++) {
82
+ if (page >= known ||
83
+ current[page * 2] !== previous[page * 2] ||
84
+ current[page * 2 + 1] !== previous[page * 2 + 1])
85
+ changed.push(page);
86
+ }
87
+ return changed;
88
+ }
89
+ /** A checkpoint that cannot be loaded: a `hash`, `size`, `global` or `manifest` mismatch. */
90
+ export class CheckpointError extends Error {
91
+ code;
92
+ constructor(code, detail) {
93
+ super(`checkpoint refused (${code}): ${detail}`);
94
+ this.name = 'CheckpointError';
95
+ this.code = code;
96
+ }
97
+ }
98
+ /** In-process store for tests and Node. Keeps the newest copy of each page. */
99
+ export function memoryCheckpointStore() {
100
+ let latest;
101
+ const copies = new Map();
102
+ return {
103
+ latest: () => latest,
104
+ pages(epoch, indexes) {
105
+ const found = new Map();
106
+ for (const index of indexes) {
107
+ const copy = copies.get(index);
108
+ if (copy && copy.epoch <= epoch)
109
+ found.set(index, copy.bytes);
110
+ }
111
+ return found;
112
+ },
113
+ commit(manifest, pages) {
114
+ if (latest && manifest.epoch <= latest.epoch)
115
+ throw new RangeError(`checkpoint epoch ${manifest.epoch} does not follow ${latest.epoch}`);
116
+ for (const [index, bytes] of pages) {
117
+ if (bytes.length !== pageBytes)
118
+ throw new RangeError('page bytes must be 65,536 long');
119
+ copies.set(index, { epoch: manifest.epoch, bytes });
120
+ }
121
+ latest = manifest;
122
+ }
123
+ };
124
+ }
125
+ const blob = (value) => value instanceof Uint8Array ? value : new Uint8Array(value);
126
+ function encodeGlobals(globals) {
127
+ return JSON.stringify(Object.entries(globals).map(([name, value]) => [name, typeof value, String(value)]));
128
+ }
129
+ function decodeGlobals(text) {
130
+ const out = {};
131
+ for (const [name, kind, value] of JSON.parse(text))
132
+ out[name] = kind === 'bigint' ? BigInt(value) : Number(value);
133
+ return out;
134
+ }
135
+ // the commit writes group rows, then the manifest, then prunes; any prefix of that leaves the
136
+ // previous manifest whole, so the store needs no transaction of its own
137
+ function openSqlStore(sql, options = {}, guard) {
138
+ const prefix = options.prefix ?? 'continuation_';
139
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(prefix))
140
+ throw new TypeError('prefix must be a SQL identifier');
141
+ const groupPages = options.groupPages ?? 16;
142
+ if (!Number.isInteger(groupPages) || groupPages < 1)
143
+ throw new RangeError('groupPages must be a positive integer');
144
+ const groupBytes = groupPages * pageBytes;
145
+ const groups = `${prefix}groups`;
146
+ const manifests = `${prefix}manifest`;
147
+ const run = (query, ...bindings) => sql.exec(query, ...bindings).toArray();
148
+ run(`CREATE TABLE IF NOT EXISTS ${groups} (g INTEGER NOT NULL, epoch INTEGER NOT NULL, bytes BLOB NOT NULL, PRIMARY KEY (g, epoch))`);
149
+ run(`CREATE TABLE IF NOT EXISTS ${manifests} (epoch INTEGER PRIMARY KEY, byte_length INTEGER NOT NULL, hashes BLOB NOT NULL, globals TEXT NOT NULL, state TEXT)`);
150
+ const rowAt = (g, epoch) => {
151
+ const row = run(`SELECT bytes FROM ${groups} WHERE g = ? AND epoch <= ? ORDER BY epoch DESC LIMIT 1`, g, epoch)[0];
152
+ return row ? blob(row.bytes) : undefined;
153
+ };
154
+ const latestRow = () => run(`SELECT * FROM ${manifests} ORDER BY epoch DESC LIMIT 1`)[0];
155
+ return {
156
+ ...(options.sync ? { flush: options.sync } : {}),
157
+ latest() {
158
+ const row = latestRow();
159
+ if (!row)
160
+ return undefined;
161
+ return {
162
+ epoch: Number(row.epoch),
163
+ byteLength: Number(row.byte_length),
164
+ hashes: new Uint32Array(blob(row.hashes).slice().buffer),
165
+ globals: decodeGlobals(String(row.globals)),
166
+ state: row.state === null ? undefined : String(row.state)
167
+ };
168
+ },
169
+ pages(epoch, indexes) {
170
+ const found = new Map();
171
+ const rows = new Map();
172
+ for (const index of indexes) {
173
+ const g = Math.floor(index / groupPages);
174
+ if (!rows.has(g))
175
+ rows.set(g, rowAt(g, epoch));
176
+ const row = rows.get(g);
177
+ if (!row)
178
+ continue;
179
+ const at = (index - g * groupPages) * pageBytes;
180
+ found.set(index, row.slice(at, at + pageBytes));
181
+ }
182
+ return found;
183
+ },
184
+ commit(manifest, pages) {
185
+ const head = latestRow();
186
+ const last = head ? Number(head.epoch) : 0;
187
+ if (manifest.epoch <= last)
188
+ throw new RangeError(`checkpoint epoch ${manifest.epoch} does not follow ${last}`);
189
+ const byGroup = new Map();
190
+ for (const [index, bytes] of pages) {
191
+ if (bytes.length !== pageBytes)
192
+ throw new RangeError('page bytes must be 65,536 long');
193
+ const g = Math.floor(index / groupPages);
194
+ byGroup.set(g, [...(byGroup.get(g) ?? []), [index, bytes]]);
195
+ }
196
+ run(`DELETE FROM ${groups} WHERE epoch > ?`, last);
197
+ const changed = [...byGroup.keys()].sort((a, b) => a - b);
198
+ for (const g of changed) {
199
+ const row = new Uint8Array(groupBytes);
200
+ const base = rowAt(g, last);
201
+ if (base)
202
+ row.set(base);
203
+ for (const [index, bytes] of byGroup.get(g))
204
+ row.set(bytes, (index - g * groupPages) * pageBytes);
205
+ run(`INSERT INTO ${groups} (g, epoch, bytes) VALUES (?, ?, ?)`, g, manifest.epoch, row.buffer);
206
+ guard?.();
207
+ }
208
+ run(`INSERT INTO ${manifests} (epoch, byte_length, hashes, globals, state) VALUES (?, ?, ?, ?, ?)`, manifest.epoch, manifest.byteLength, manifest.hashes.slice().buffer, encodeGlobals(manifest.globals), manifest.state ?? null);
209
+ for (const g of changed)
210
+ run(`DELETE FROM ${groups} WHERE g = ? AND epoch < ?`, g, manifest.epoch);
211
+ run(`DELETE FROM ${manifests} WHERE epoch < ?`, manifest.epoch);
212
+ }
213
+ };
214
+ }
215
+ /**
216
+ * DO SQLite store with one row per group of `groupPages` pages (default 16, 1 MiB). Keep one value
217
+ * of `groupPages` per prefix. Commit must run in one synchronous span.
218
+ */
219
+ export function sqlCheckpointStore(sql, options) {
220
+ return openSqlStore(sql, options);
221
+ }
222
+ /** Writes the pages that changed since the last manifest, with the globals and host state. */
223
+ export function saveCheckpoint(store, memory, options = {}) {
224
+ if (options.state !== undefined && options.stateJson !== undefined)
225
+ throw new TypeError('pass state or stateJson, not both');
226
+ const hashes = hashPages(memory);
227
+ const previous = store.latest();
228
+ const changed = changedPages(hashes, previous?.hashes);
229
+ const view = new Uint8Array(memory.buffer);
230
+ const pages = new Map();
231
+ for (const page of changed)
232
+ pages.set(page, view.slice(page * pageBytes, (page + 1) * pageBytes));
233
+ const epoch = (previous?.epoch ?? 0) + 1;
234
+ const globals = {};
235
+ for (const [name, global] of Object.entries(options.globals ?? {}))
236
+ globals[name] = global.value;
237
+ store.commit({
238
+ epoch,
239
+ byteLength: memory.buffer.byteLength,
240
+ hashes,
241
+ globals,
242
+ state: options.state ??
243
+ (options.stateJson === undefined ? undefined : JSON.stringify(options.stateJson))
244
+ }, pages);
245
+ return { epoch, pagesWritten: changed.length, bytesWritten: changed.length * pageBytes };
246
+ }
247
+ /**
248
+ * Restores the newest checkpoint into the memory, growing it as needed. Every page is verified
249
+ * before anything is written. Returns undefined when the store is empty. For a runSlice checkpoint,
250
+ * `json()` returns `{budget, measured, steps, host}`.
251
+ */
252
+ export function loadCheckpoint(store, memory, options = {}) {
253
+ const manifest = store.latest();
254
+ if (!manifest)
255
+ return undefined;
256
+ if (manifest.byteLength % pageBytes)
257
+ throw new CheckpointError('manifest', `byte length ${manifest.byteLength} is not whole pages`);
258
+ const count = manifest.byteLength / pageBytes;
259
+ if (manifest.hashes.length !== count * 2)
260
+ throw new CheckpointError('manifest', `${manifest.hashes.length} hash words for ${count} pages`);
261
+ if (memory.buffer.byteLength > manifest.byteLength)
262
+ throw new CheckpointError('size', `memory holds ${memory.buffer.byteLength} bytes, checkpoint has ${manifest.byteLength}`);
263
+ const globals = options.globals ?? {};
264
+ const wanted = Object.keys(globals);
265
+ const recorded = Object.keys(manifest.globals);
266
+ const unmatched = [
267
+ ...wanted.filter((n) => !(n in manifest.globals)),
268
+ ...recorded.filter((n) => !(n in globals))
269
+ ];
270
+ if (unmatched.length)
271
+ throw new CheckpointError('global', `globals differ: ${unmatched.join(', ')}`);
272
+ const copies = store.pages(manifest.epoch, Array.from({ length: count }, (_, i) => i));
273
+ const bytes = [];
274
+ const bad = [];
275
+ for (let page = 0; page < count; page++) {
276
+ const copy = copies.get(page);
277
+ if (!copy || copy.length !== pageBytes)
278
+ throw new CheckpointError('manifest', `page ${page} has no copy at epoch ${manifest.epoch}`);
279
+ bytes.push(copy);
280
+ const [lo, hi] = hashPages(copy);
281
+ if (lo !== manifest.hashes[page * 2] || hi !== manifest.hashes[page * 2 + 1])
282
+ bad.push(page);
283
+ }
284
+ if (bad.length)
285
+ throw new CheckpointError('hash', `${bad.length} page(s) fail, first ${bad[0]}`);
286
+ for (const name of wanted) {
287
+ try {
288
+ globals[name].value = manifest.globals[name];
289
+ }
290
+ catch {
291
+ throw new CheckpointError('global', `global ${name} cannot take ${typeof manifest.globals[name]}`);
292
+ }
293
+ }
294
+ const have = memory.buffer.byteLength / pageBytes;
295
+ if (have < count) {
296
+ try {
297
+ memory.grow(count - have);
298
+ }
299
+ catch {
300
+ throw new CheckpointError('size', `memory cannot grow to ${count} pages`);
301
+ }
302
+ }
303
+ const view = new Uint8Array(memory.buffer);
304
+ bytes.forEach((page, index) => view.set(page, index * pageBytes));
305
+ const { epoch, state } = manifest;
306
+ return {
307
+ epoch,
308
+ state,
309
+ json() {
310
+ return (state === undefined ? undefined : JSON.parse(state));
311
+ }
312
+ };
313
+ }
314
+ // one row written and flushed before the guest runs; a commit moves the epoch past it
315
+ function openAttempts(sql) {
316
+ const run = (query, ...bindings) => sql.exec(query, ...bindings).toArray();
317
+ run('CREATE TABLE IF NOT EXISTS continuation_attempt (id INTEGER PRIMARY KEY, k INTEGER NOT NULL, epoch INTEGER NOT NULL, budget INTEGER NOT NULL, open INTEGER NOT NULL)');
318
+ return {
319
+ read() {
320
+ const row = run('SELECT k, epoch, budget, open FROM continuation_attempt WHERE id = 1')[0];
321
+ if (!row)
322
+ return undefined;
323
+ return {
324
+ k: Number(row.k),
325
+ epoch: Number(row.epoch),
326
+ budget: Number(row.budget),
327
+ open: Number(row.open) !== 0
328
+ };
329
+ },
330
+ mark(attempt) {
331
+ run('INSERT OR REPLACE INTO continuation_attempt (id, k, epoch, budget, open) VALUES (1, ?, ?, ?, 1)', attempt.k, attempt.epoch, attempt.budget);
332
+ },
333
+ close() {
334
+ run('UPDATE continuation_attempt SET open = 0 WHERE id = 1');
335
+ }
336
+ };
337
+ }
338
+ // per storage object: a module-scope entry exists only in the isolate that wrote it
339
+ const tracks = new WeakMap();
340
+ const CUT = new Error('signal raised during a commit');
341
+ function readEnvelope(state) {
342
+ let parsed = null;
343
+ try {
344
+ parsed = JSON.parse(state ?? 'null');
345
+ }
346
+ catch {
347
+ parsed = null;
348
+ }
349
+ if (!parsed ||
350
+ typeof parsed.budget !== 'number' ||
351
+ typeof parsed.measured !== 'boolean' ||
352
+ typeof parsed.steps !== 'number')
353
+ throw new CheckpointError('manifest', 'checkpoint state is not a runSlice record');
354
+ return {
355
+ budget: parsed.budget,
356
+ measured: parsed.measured,
357
+ steps: parsed.steps,
358
+ host: parsed.host
359
+ };
360
+ }
361
+ /**
362
+ * Runs one alarm event of a guest: restores or commits as needed, runs the guest with the event
363
+ * budget, and commits at a budget stop. A signal stop writes nothing before it re-arms.
364
+ * The manifest state holds a runSlice record (budget, step count, host state), so
365
+ * `loadCheckpoint(...).json()` returns that record for checkpoints written here.
366
+ * Before the guest runs, an attempt row with the event number and budget is written and flushed.
367
+ * An event that starts in a new isolate and finds an attempt with no commit after it knows the
368
+ * previous attempt was killed: it halves that budget (never below `initialBudget`), stops doubling
369
+ * and reports the halving in `lost`.
370
+ * Call it from alarm().
371
+ */
372
+ export async function runSlice(options) {
373
+ const { storage, memory, signal, run, steps, initialBudget = 2000 } = options;
374
+ if (!Number.isInteger(initialBudget) || initialBudget < 1)
375
+ throw new RangeError(`initialBudget must be a positive integer, got ${initialBudget}`);
376
+ const globals = options.globals ?? {};
377
+ const guard = signal
378
+ ? () => {
379
+ if (signal.raised)
380
+ throw CUT;
381
+ }
382
+ : undefined;
383
+ const store = openSqlStore(storage.sql, { sync: () => storage.sync() }, guard);
384
+ const attempts = openAttempts(storage.sql);
385
+ const commit = (budget, measured) => storage.transactionSync(() => saveCheckpoint(store, memory, {
386
+ globals,
387
+ state: JSON.stringify({
388
+ budget,
389
+ measured,
390
+ steps: steps(),
391
+ host: options.state?.()
392
+ })
393
+ }));
394
+ let lost;
395
+ const outcome = (finished, restored, stop, budget) => ({
396
+ finished,
397
+ restored,
398
+ stop,
399
+ epoch: store.latest()?.epoch ?? 0,
400
+ budget,
401
+ ...(lost ? { lost } : {})
402
+ });
403
+ const signalStop = async (track, ran, restored, stop) => {
404
+ track.budget = Math.max(initialBudget, Math.round(0.7 * ran));
405
+ track.measured = true;
406
+ await storage.setAlarm(Date.now());
407
+ // no commit follows this attempt, so close it after the re-arm
408
+ attempts.close();
409
+ return outcome(false, restored, stop, track.budget);
410
+ };
411
+ signal?.clear();
412
+ let track;
413
+ let restored = false;
414
+ const known = tracks.get(storage);
415
+ const attempt = attempts.read();
416
+ // a live track means the previous call ended in this isolate; only a kill removes the isolate
417
+ const live = known !== undefined && known.memory === memory;
418
+ if (!live && attempt?.open && attempt.epoch === (store.latest()?.epoch ?? 0))
419
+ lost = {
420
+ k: attempt.k,
421
+ from: attempt.budget,
422
+ to: Math.max(initialBudget, Math.floor(attempt.budget / 2))
423
+ };
424
+ const k = attempt ? (lost ? attempt.k : attempt.k + 1) : 1;
425
+ if (known && live) {
426
+ track = known;
427
+ if (steps() > track.committed) {
428
+ try {
429
+ commit(track.budget, track.measured);
430
+ }
431
+ catch (error) {
432
+ if (error !== CUT)
433
+ throw error;
434
+ return signalStop(track, 0, restored, 'cut');
435
+ }
436
+ track.committed = steps();
437
+ await storage.sync();
438
+ }
439
+ }
440
+ else {
441
+ let budget = initialBudget;
442
+ let measured = false;
443
+ let committed = 0;
444
+ const latest = store.latest();
445
+ if (latest) {
446
+ const envelope = readEnvelope(latest.state);
447
+ loadCheckpoint(store, memory, { globals });
448
+ options.restore?.(envelope.host);
449
+ restored = true;
450
+ budget = envelope.budget;
451
+ measured = envelope.measured;
452
+ committed = envelope.steps;
453
+ }
454
+ if (lost) {
455
+ budget = lost.to;
456
+ measured = true;
457
+ }
458
+ track = { memory, budget, measured, committed };
459
+ tracks.set(storage, track);
460
+ }
461
+ attempts.mark({ k, epoch: store.latest()?.epoch ?? 0, budget: track.budget });
462
+ await store.flush?.();
463
+ const before = steps();
464
+ const reason = await run(track.budget);
465
+ const ran = steps() - before;
466
+ if (reason === 'signal' || signal?.raised)
467
+ return signalStop(track, ran, restored, 'signal');
468
+ if (reason === 'finished') {
469
+ try {
470
+ commit(track.budget, track.measured);
471
+ }
472
+ catch (error) {
473
+ if (error !== CUT)
474
+ throw error;
475
+ return signalStop(track, ran, restored, 'cut');
476
+ }
477
+ track.committed = steps();
478
+ await storage.sync();
479
+ return outcome(true, restored, 'finished', track.budget);
480
+ }
481
+ const next = track.measured ? Math.round(1.02 * track.budget) : 2 * track.budget;
482
+ try {
483
+ commit(next, track.measured);
484
+ }
485
+ catch (error) {
486
+ if (error !== CUT)
487
+ throw error;
488
+ return signalStop(track, ran, restored, 'cut');
489
+ }
490
+ await storage.sync();
491
+ track.budget = next;
492
+ track.committed = steps();
493
+ await storage.setAlarm(Date.now());
494
+ return outcome(false, restored, 'budget', next);
495
+ }
@@ -0,0 +1,20 @@
1
+ import type { AsyncHolder } from './elastic.ts';
2
+ export interface PeerRecord {
3
+ version: number;
4
+ bytes: Uint8Array;
5
+ }
6
+ /** The two RPC methods a peer Durable Object exposes. */
7
+ export interface PeerStub {
8
+ get(index: number): Promise<PeerRecord | undefined>;
9
+ put(index: number, version: number, bytes: Uint8Array): Promise<void>;
10
+ }
11
+ /**
12
+ * An `AsyncHolder` that spreads chunks over peers: chunk `i` lives on `stubs[i % stubs.length]`.
13
+ */
14
+ export declare function peerHolder(stubs: readonly PeerStub[]): AsyncHolder;
15
+ /**
16
+ * The object a peer Durable Object exposes as a `PeerStub`, keeping chunks in memory.
17
+ * A peer may lose its chunks, so a peer holder alone suits data the owner can rebuild. A peer
18
+ * in front of storage needs the owner to keep the storage copy.
19
+ */
20
+ export declare function peerStore(): PeerStub;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * An `AsyncHolder` that spreads chunks over peers: chunk `i` lives on `stubs[i % stubs.length]`.
3
+ */
4
+ export function peerHolder(stubs) {
5
+ if (stubs.length === 0)
6
+ throw new RangeError('peerHolder needs at least one stub');
7
+ const stubOf = (index) => stubs[index % stubs.length];
8
+ return {
9
+ async read(index, into) {
10
+ const record = await stubOf(index).get(index);
11
+ if (record === undefined)
12
+ return undefined;
13
+ if (record.bytes.length !== into.length)
14
+ throw new RangeError(`chunk ${index} holds ${record.bytes.length} bytes, expected ${into.length}`);
15
+ into.set(record.bytes);
16
+ return record.version;
17
+ },
18
+ async write(index, version, bytes) {
19
+ // copy first: the view aliases the region buffer, and an RPC would clone the whole buffer
20
+ await stubOf(index).put(index, version, bytes.slice());
21
+ }
22
+ };
23
+ }
24
+ /**
25
+ * The object a peer Durable Object exposes as a `PeerStub`, keeping chunks in memory.
26
+ * A peer may lose its chunks, so a peer holder alone suits data the owner can rebuild. A peer
27
+ * in front of storage needs the owner to keep the storage copy.
28
+ */
29
+ export function peerStore() {
30
+ const chunks = new Map();
31
+ return {
32
+ async get(index) {
33
+ return chunks.get(index);
34
+ },
35
+ async put(index, version, bytes) {
36
+ chunks.set(index, { version, bytes });
37
+ }
38
+ };
39
+ }
@@ -0,0 +1,11 @@
1
+ import type { SyncHolder } from './elastic.ts';
2
+ /** The subset of a Durable Object SQL handle this module uses. */
3
+ export interface ElasticSql {
4
+ exec(query: string, ...bindings: (string | number | ArrayBuffer)[]): {
5
+ toArray(): Record<string, unknown>[];
6
+ };
7
+ }
8
+ /**
9
+ * A `SyncHolder` over one SQL table, one row per (region, chunk). The table is created on first use.
10
+ */
11
+ export declare function sqlHolder(sql: ElasticSql, table?: string, region?: string): SyncHolder;
@@ -0,0 +1,35 @@
1
+ /**
2
+ * A `SyncHolder` over one SQL table, one row per (region, chunk). The table is created on first use.
3
+ */
4
+ export function sqlHolder(sql, table = 'folio_elastic', region = 'default') {
5
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table))
6
+ throw new TypeError('table must be a SQL identifier');
7
+ let ready = false;
8
+ const ensure = () => {
9
+ if (ready)
10
+ return;
11
+ sql.exec(`CREATE TABLE IF NOT EXISTS ${table} (region TEXT NOT NULL, idx INTEGER NOT NULL, version INTEGER NOT NULL, bytes BLOB NOT NULL, PRIMARY KEY (region, idx))`).toArray();
12
+ ready = true;
13
+ };
14
+ return {
15
+ read(index, into) {
16
+ ensure();
17
+ const row = sql
18
+ .exec(`SELECT version, bytes FROM ${table} WHERE region = ? AND idx = ?`, region, index)
19
+ .toArray()[0];
20
+ if (!row)
21
+ return undefined;
22
+ const bytes = row.bytes instanceof Uint8Array
23
+ ? row.bytes
24
+ : new Uint8Array(row.bytes);
25
+ if (bytes.length !== into.length)
26
+ throw new RangeError(`chunk ${index} holds ${bytes.length} bytes, expected ${into.length}`);
27
+ into.set(bytes);
28
+ return Number(row.version);
29
+ },
30
+ write(index, version, bytes) {
31
+ ensure();
32
+ sql.exec(`INSERT INTO ${table} (region, idx, version, bytes) VALUES (?, ?, ?, ?) ON CONFLICT (region, idx) DO UPDATE SET version = excluded.version, bytes = excluded.bytes`, region, index, version, bytes.slice().buffer).toArray();
33
+ }
34
+ };
35
+ }