@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,126 @@
1
+ import type { OwnershipPlan } from '../execution/extract.ts';
2
+ import { type TaskRecord } from '../node/tasks.ts';
3
+ /** Options for `SlicePool.open`. */
4
+ export interface SlicePoolOptions {
5
+ /**
6
+ * The shared memory every worker runs on. It must be a shared memory with a declared maximum
7
+ * that leaves room for one private stack per worker. The pool grows it by that much at open.
8
+ */
9
+ memory: WebAssembly.Memory;
10
+ /** Worker count. The default is the available parallelism, at most 8. */
11
+ workers?: number;
12
+ /**
13
+ * Bytes of private stack per worker, a multiple of 65,536. Only a module that keeps a stack
14
+ * pointer global gets stacks. The default is 65,536.
15
+ */
16
+ stackBytes?: number;
17
+ /**
18
+ * A module specifier or URL whose default export returns the imports the module needs besides
19
+ * its memory. Each worker loads it, because functions do not cross threads.
20
+ */
21
+ imports?: string | URL;
22
+ /**
23
+ * The plan of a module that `redirectOwnership` rewrote. Each worker gets a private copy of every
24
+ * window next to its stack, the owner copies the last record's bytes back after a clean run, and
25
+ * a trap in any slice restores `writes` and runs the calls serially in place.
26
+ */
27
+ ownership?: OwnershipPlan;
28
+ }
29
+ /** Options for one `SlicePool.run`. */
30
+ export interface SliceRunOptions {
31
+ /** Calls per slice. The default splits the range evenly over the workers. */
32
+ grain?: number;
33
+ /**
34
+ * Byte ranges the calls write outside the windows, such as the output slots. A pool opened with
35
+ * `ownership` needs them: they are copied before the run and put back when a slice traps. The
36
+ * list must name every range the calls write: a range left out keeps the writes of the calls
37
+ * after the trap, and the serial replay does not undo them.
38
+ */
39
+ writes?: [number, number][];
40
+ /** Largest copy of `writes` in bytes. Past it the calls run serially in place. Default 64 MiB. */
41
+ snapshotLimit?: number;
42
+ /**
43
+ * Runs the same slices serially on a copy of the memory taken before the run and compares the
44
+ * result and every byte below the stacks. A difference throws `SliceConflictError`. It costs
45
+ * a serial execution and a memory copy, and is meant for tests and canaries.
46
+ */
47
+ audit?: boolean;
48
+ }
49
+ /** What an ownership pool did around the slices of one run. */
50
+ export interface OwnedSliceReport {
51
+ snapshotBytes: number;
52
+ snapshotMs: number;
53
+ copyOutMs: number;
54
+ restoreMs: number;
55
+ /** A slice trapped, so the calls ran again serially in place and that run decided the result. */
56
+ replayed: boolean;
57
+ /** `snapshot` when `writes` was past the limit and the calls ran serially in place. */
58
+ refused?: 'snapshot';
59
+ /** First line of the failure of the first failed slice. */
60
+ trap?: string;
61
+ tasks: TaskRecord[];
62
+ }
63
+ /** What one `run` did. */
64
+ export interface SliceReport {
65
+ slices: number;
66
+ workers: number;
67
+ wallMs: number;
68
+ /** The value each slice's last call returned, in slice order. */
69
+ results: (number | bigint | undefined)[];
70
+ audited: boolean;
71
+ ownership?: OwnedSliceReport;
72
+ }
73
+ /** The audit found the parallel run differs from the serial one. */
74
+ export declare class SliceConflictError extends Error {
75
+ readonly kind: 'memory' | 'result';
76
+ /** First differing byte for `memory`, the slice index for `result`. */
77
+ readonly at: number;
78
+ constructor(kind: 'memory' | 'result', at: number);
79
+ }
80
+ /** @internal */
81
+ export declare const encodeValues: (values: unknown) => string;
82
+ /** @internal */
83
+ export declare const decodeValues: (text: string) => unknown;
84
+ /**
85
+ * Marks the imported memory of a module as shared by setting its limits flag. The module has to
86
+ * declare a maximum already.
87
+ * @internal
88
+ */
89
+ export declare function sharedMemoryImport(bytes: Uint8Array): Uint8Array<ArrayBuffer>;
90
+ /**
91
+ * Runs slices of a call range on several threads over one shared memory, in place. The caller
92
+ * declares that the calls are independent and nothing tracks reads or writes, so a program that
93
+ * touches state the serial program would share returns a different result; `audit` finds that.
94
+ * Nothing is copied into a private context, which is why a bandwidth-bound kernel can win here
95
+ * while a route that copies its input first cannot. The module runs unmodified except for its
96
+ * memory import, which is marked shared. A module that keeps a stack pointer global gets one
97
+ * private stack per worker; any other mutable global, a start function or a data segment that
98
+ * is dropped refuses the module.
99
+ * @since 1.1.0
100
+ */
101
+ export declare class SlicePool {
102
+ #private;
103
+ private constructor();
104
+ /** The shared memory. Write the records into it after `open`, and read the results from it. */
105
+ get memory(): WebAssembly.Memory;
106
+ /** Worker count. */
107
+ get size(): number;
108
+ /** First byte of the private stacks and window copies, or undefined when there are none. */
109
+ get privateBase(): number | undefined;
110
+ /** First byte of the private stacks, or undefined when the module has no stack pointer. */
111
+ get stackBase(): number | undefined;
112
+ /**
113
+ * Compiles the module, grows the memory by one stack per worker when the module has a stack
114
+ * pointer, and starts the workers. Opening applies the module's data segments to the memory,
115
+ * so write the records after it returns.
116
+ */
117
+ static open(bytes: Uint8Array, options: SlicePoolOptions): Promise<SlicePool>;
118
+ /**
119
+ * Calls the exported function `entry` for the range `[0, count)` in slices, one slice per task.
120
+ * `args(from, to)` returns the i32 (or i64 as bigint) arguments of the call for a slice, in the
121
+ * owner thread. The caller guarantees the slices are independent.
122
+ */
123
+ run(entry: string, count: number, args: (from: number, to: number) => (number | bigint)[], options?: SliceRunOptions): Promise<SliceReport>;
124
+ /** Stops the workers. */
125
+ close(): Promise<void>;
126
+ }
@@ -0,0 +1,441 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { availableParallelism } from 'node:os';
10
+ import { Worker } from 'node:worker_threads';
11
+ import { prepareContext } from "../execution/compiler.js";
12
+ import { TaskPool } from "../node/tasks.js";
13
+ const PAGE = 65536;
14
+ const SNAPSHOT_LIMIT = 1 << 26;
15
+ /** The audit found the parallel run differs from the serial one. */
16
+ export class SliceConflictError extends Error {
17
+ kind;
18
+ /** First differing byte for `memory`, the slice index for `result`. */
19
+ at;
20
+ constructor(kind, at) {
21
+ super(kind === 'memory'
22
+ ? `slices differ from the serial run at byte ${at}; the calls are not independent`
23
+ : `slice ${at} returned a different value than the serial run`);
24
+ this.name = 'SliceConflictError';
25
+ this.kind = kind;
26
+ this.at = at;
27
+ }
28
+ }
29
+ const encoder = (_, value) => typeof value === 'bigint' ? { $bigint: value.toString() } : value;
30
+ const decoder = (_, value) => value && typeof value === 'object' && '$bigint' in value
31
+ ? BigInt(value.$bigint)
32
+ : value;
33
+ const decodeAll = (done) => done.map((item) => {
34
+ const text = item.text();
35
+ return (text ? decodeValues(text) : undefined);
36
+ });
37
+ /** @internal */
38
+ export const encodeValues = (values) => JSON.stringify(values, encoder);
39
+ /** @internal */
40
+ export const decodeValues = (text) => JSON.parse(text, decoder);
41
+ /**
42
+ * Marks the imported memory of a module as shared by setting its limits flag. The module has to
43
+ * declare a maximum already.
44
+ * @internal
45
+ */
46
+ export function sharedMemoryImport(bytes) {
47
+ const out = new Uint8Array(bytes.length);
48
+ out.set(bytes);
49
+ let at = 8;
50
+ const leb = () => {
51
+ let value = 0, shift = 0, byte;
52
+ do {
53
+ byte = out[at++];
54
+ value |= (byte & 0x7f) << shift;
55
+ shift += 7;
56
+ } while (byte & 0x80);
57
+ return value;
58
+ };
59
+ const skip = (length) => (at += length);
60
+ while (at < out.length) {
61
+ const id = out[at++];
62
+ const size = leb();
63
+ const end = at + size;
64
+ if (id === 2) {
65
+ for (let count = leb(); count > 0; count--) {
66
+ skip(leb());
67
+ skip(leb());
68
+ const kind = out[at++];
69
+ if (kind === 2) {
70
+ if (out[at] === 1)
71
+ out[at] = 3;
72
+ else if (out[at] !== 3)
73
+ throw new Error('the memory import needs a maximum');
74
+ return out;
75
+ }
76
+ if (kind === 0)
77
+ leb();
78
+ else if (kind === 1) {
79
+ at++;
80
+ const flags = out[at++];
81
+ leb();
82
+ if (flags & 1)
83
+ leb();
84
+ }
85
+ else if (kind === 3)
86
+ at += 2;
87
+ }
88
+ }
89
+ at = end;
90
+ }
91
+ throw new Error('the module imports no memory');
92
+ }
93
+ /**
94
+ * Runs slices of a call range on several threads over one shared memory, in place. The caller
95
+ * declares that the calls are independent and nothing tracks reads or writes, so a program that
96
+ * touches state the serial program would share returns a different result; `audit` finds that.
97
+ * Nothing is copied into a private context, which is why a bandwidth-bound kernel can win here
98
+ * while a route that copies its input first cannot. The module runs unmodified except for its
99
+ * memory import, which is marked shared. A module that keeps a stack pointer global gets one
100
+ * private stack per worker; any other mutable global, a start function or a data segment that
101
+ * is dropped refuses the module.
102
+ * @since 1.1.0
103
+ */
104
+ export class SlicePool {
105
+ #memory;
106
+ #module;
107
+ #tasks;
108
+ #workers;
109
+ #stack;
110
+ #importSlot;
111
+ #extra;
112
+ #exports;
113
+ #own;
114
+ #grown;
115
+ #closed = false;
116
+ constructor(memory, module, tasks, workers, stack, slot, extra, grown, own) {
117
+ this.#memory = memory;
118
+ this.#module = module;
119
+ this.#tasks = tasks;
120
+ this.#workers = workers;
121
+ this.#stack = stack;
122
+ this.#importSlot = slot;
123
+ this.#extra = extra;
124
+ this.#grown = grown;
125
+ this.#own = own;
126
+ this.#exports = new Set(WebAssembly.Module.exports(module)
127
+ .filter((item) => item.kind === 'function')
128
+ .map((item) => item.name));
129
+ }
130
+ /** The shared memory. Write the records into it after `open`, and read the results from it. */
131
+ get memory() {
132
+ return this.#memory;
133
+ }
134
+ /** Worker count. */
135
+ get size() {
136
+ return this.#workers.length;
137
+ }
138
+ /** First byte of the private stacks and window copies, or undefined when there are none. */
139
+ get privateBase() {
140
+ return this.#grown;
141
+ }
142
+ /** First byte of the private stacks, or undefined when the module has no stack pointer. */
143
+ get stackBase() {
144
+ return this.#stack?.base;
145
+ }
146
+ /**
147
+ * Compiles the module, grows the memory by one stack per worker when the module has a stack
148
+ * pointer, and starts the workers. Opening applies the module's data segments to the memory,
149
+ * so write the records after it returns.
150
+ */
151
+ static async open(bytes, options) {
152
+ const { memory } = options;
153
+ if (Object.prototype.toString.call(memory.buffer) !== '[object SharedArrayBuffer]')
154
+ throw new TypeError('slices need a shared memory');
155
+ const plan = prepareContext(bytes);
156
+ if (plan.reasons.length)
157
+ throw new TypeError(`module cannot run on slices: ${plan.reasons.join('; ')}`);
158
+ const ownership = options.ownership;
159
+ const deltas = ownership?.windows.length ?? 0;
160
+ if (plan.globals.length - deltas > 1)
161
+ throw new TypeError(`module keeps ${plan.globals.length - deltas} mutable globals; slices handle at most a stack pointer`);
162
+ const hasStack = plan.globals.length > deltas;
163
+ let patched;
164
+ try {
165
+ patched = sharedMemoryImport(Uint8Array.from(plan.bytes));
166
+ }
167
+ catch (error) {
168
+ throw new TypeError(`module cannot take a shared memory: ${error.message}`);
169
+ }
170
+ const module = new WebAssembly.Module(patched);
171
+ const slot = WebAssembly.Module.imports(module).find((item) => item.kind === 'memory');
172
+ if (!slot)
173
+ throw new TypeError('module must import its memory');
174
+ const width = options.workers ?? Math.max(1, Math.min(availableParallelism(), 8));
175
+ if (!Number.isSafeInteger(width) || width < 1)
176
+ throw new RangeError('invalid worker count');
177
+ let stack;
178
+ let grown;
179
+ let copies;
180
+ if (ownership) {
181
+ const names = new Set(WebAssembly.Module.exports(module)
182
+ .filter((item) => item.kind === 'global')
183
+ .map((item) => item.name));
184
+ const sorted = [...ownership.windows].sort((a, b) => a.low - b.low);
185
+ sorted.forEach((w, at) => {
186
+ if (!names.has(w.delta))
187
+ throw new TypeError(`module does not export the delta global ${w.delta}`);
188
+ if (w.low % 64 ||
189
+ w.end % 64 ||
190
+ w.end <= w.low ||
191
+ (at && w.low < sorted[at - 1].end))
192
+ throw new TypeError('ownership windows must be disjoint, 64-aligned and not empty');
193
+ });
194
+ if (!ownership.windows.length)
195
+ throw new TypeError('ownership plan has no window');
196
+ for (const [from, to] of ownership.copyOut)
197
+ if (!ownership.windows.some((w) => w.low <= from && from <= to && to <= w.end))
198
+ throw new TypeError('a copy-out range lies outside every window');
199
+ }
200
+ const shadowBytes = ownership
201
+ ? ownership.windows.reduce((sum, w) => sum + w.end - w.low, 0)
202
+ : 0;
203
+ if (hasStack || ownership) {
204
+ const bytesPerStack = hasStack ? (options.stackBytes ?? PAGE) : 0;
205
+ if (hasStack &&
206
+ (!Number.isSafeInteger(bytesPerStack) ||
207
+ bytesPerStack < PAGE ||
208
+ bytesPerStack % PAGE))
209
+ throw new RangeError('stackBytes must be a positive multiple of 65536');
210
+ const each = bytesPerStack + Math.ceil(shadowBytes / PAGE) * PAGE;
211
+ const base = memory.buffer.byteLength;
212
+ if (ownership?.windows.some((w) => w.end > base))
213
+ throw new RangeError('an ownership window lies past the memory');
214
+ try {
215
+ memory.grow((width * each) / PAGE);
216
+ }
217
+ catch (error) {
218
+ if (!(error instanceof RangeError))
219
+ throw error;
220
+ throw new RangeError(`the memory maximum leaves no room for ${width} stacks of ${each} bytes`);
221
+ }
222
+ grown = base;
223
+ // each worker's region: the stack grows down from the copies at its top
224
+ const top = (index) => base + (index + 1) * each - shadowBytes;
225
+ if (hasStack)
226
+ stack = {
227
+ name: plan.globals[0],
228
+ base,
229
+ tops: Array.from({ length: width }, (_, index) => top(index))
230
+ };
231
+ if (ownership)
232
+ copies = Array.from({ length: width }, (_, index) => {
233
+ let at = top(index);
234
+ return ownership.windows.map((w) => {
235
+ const copy = at;
236
+ at += w.end - w.low;
237
+ return copy;
238
+ });
239
+ });
240
+ }
241
+ const extra = options.imports
242
+ ? (await import(__rewriteRelativeImportExtension(String(options.imports)))).default()
243
+ : {};
244
+ let own;
245
+ if (ownership) {
246
+ const owner = new WebAssembly.Instance(module, {
247
+ ...extra,
248
+ [slot.module]: { ...(extra[slot.module] ?? {}), [slot.name]: memory }
249
+ });
250
+ const global = stack && owner.exports[stack.name];
251
+ own = {
252
+ plan: ownership,
253
+ copies: copies,
254
+ owner,
255
+ stack: global && { global, home: global.value }
256
+ };
257
+ }
258
+ const tasks = new TaskPool(width);
259
+ const workers = [];
260
+ const extension = import.meta.url.endsWith('.ts') ? 'ts' : 'js';
261
+ try {
262
+ await Promise.all(Array.from({ length: width }, (_, index) => {
263
+ const link = tasks.link(index);
264
+ return new Promise((resolve, reject) => {
265
+ const worker = new Worker(new URL(`./worker.${extension}`, import.meta.url), {
266
+ workerData: {
267
+ module,
268
+ memory,
269
+ link,
270
+ slot,
271
+ stack: stack && { name: stack.name, top: stack.tops[index] },
272
+ windows: ownership &&
273
+ ownership.windows.map((w, at) => ({
274
+ low: w.low,
275
+ end: w.end,
276
+ delta: w.delta,
277
+ copy: copies[index][at]
278
+ })),
279
+ imports: options.imports && String(options.imports)
280
+ },
281
+ transferList: [link.port]
282
+ });
283
+ workers.push(worker);
284
+ worker.once('message', () => resolve());
285
+ worker.once('error', reject);
286
+ });
287
+ }));
288
+ }
289
+ catch (error) {
290
+ tasks.close();
291
+ await Promise.all(workers.map((worker) => worker.terminate()));
292
+ throw error;
293
+ }
294
+ return new SlicePool(memory, module, tasks, workers, stack, slot, extra, grown, own);
295
+ }
296
+ /**
297
+ * Calls the exported function `entry` for the range `[0, count)` in slices, one slice per task.
298
+ * `args(from, to)` returns the i32 (or i64 as bigint) arguments of the call for a slice, in the
299
+ * owner thread. The caller guarantees the slices are independent.
300
+ */
301
+ async run(entry, count, args, options = {}) {
302
+ if (this.#closed)
303
+ throw new Error('slice pool is closed');
304
+ if (!this.#exports.has(entry))
305
+ throw new TypeError(`module exports no function ${entry}`);
306
+ if (!Number.isSafeInteger(count) || count < 0)
307
+ throw new RangeError('invalid count');
308
+ const width = this.#workers.length;
309
+ const grain = options.grain ?? Math.max(1, Math.ceil(count / width));
310
+ if (!Number.isSafeInteger(grain) || grain < 1)
311
+ throw new RangeError('invalid grain');
312
+ const slices = [];
313
+ for (let from = 0; from < count; from += grain)
314
+ slices.push([from, Math.min(from + grain, count)]);
315
+ const before = options.audit ? new Uint8Array(this.#memory.buffer).slice() : undefined;
316
+ const calls = slices.map(([from, to]) => encodeValues(args(from, to)));
317
+ if (this.#own && !options.writes)
318
+ throw new TypeError('an ownership pool needs the byte ranges the calls write');
319
+ const start = performance.now();
320
+ let results;
321
+ let owned;
322
+ if (this.#own)
323
+ ({ results, owned } = await this.#runOwned(this.#own, entry, calls, options));
324
+ else {
325
+ const done = await this.#tasks.run(calls.map((call) => [entry, call]));
326
+ results = decodeAll(done);
327
+ }
328
+ const wallMs = performance.now() - start;
329
+ if (before)
330
+ this.#audit(entry, calls, results, before);
331
+ return {
332
+ slices: slices.length,
333
+ workers: width,
334
+ wallMs,
335
+ results,
336
+ audited: Boolean(before),
337
+ ownership: owned
338
+ };
339
+ }
340
+ // a trap leaves the writes of later records in place, so the serial run decides: put them back
341
+ // (the other writers are private windows and stacks) and run in place
342
+ async #runOwned(own, entry, calls, options) {
343
+ const writes = options.writes;
344
+ const bytes = new Uint8Array(this.#memory.buffer);
345
+ for (const [from, to] of writes)
346
+ if (!Number.isSafeInteger(from) || from < 0 || from > to || to > this.#grown)
347
+ throw new RangeError('a write range lies outside the memory below the private regions');
348
+ const owned = {
349
+ snapshotBytes: writes.reduce((sum, [from, to]) => sum + to - from, 0),
350
+ snapshotMs: 0,
351
+ copyOutMs: 0,
352
+ restoreMs: 0,
353
+ replayed: false,
354
+ tasks: []
355
+ };
356
+ if (!calls.length)
357
+ return { results: [], owned };
358
+ if (owned.snapshotBytes > (options.snapshotLimit ?? SNAPSHOT_LIMIT)) {
359
+ owned.refused = 'snapshot';
360
+ return { results: this.#replay(own, entry, calls), owned };
361
+ }
362
+ let at = performance.now();
363
+ const saved = writes.map(([from, to]) => bytes.slice(from, to));
364
+ owned.snapshotMs = performance.now() - at;
365
+ const handles = calls.map((call) => this.#tasks.submit(entry, call));
366
+ // every task has to finish before the memory is touched again
367
+ const done = [];
368
+ let failure;
369
+ for (const handle of handles) {
370
+ try {
371
+ done.push(await this.#tasks.joinAsync(handle));
372
+ }
373
+ catch (error) {
374
+ failure ??= error;
375
+ done.push(undefined);
376
+ }
377
+ }
378
+ if (failure === undefined) {
379
+ const finished = done;
380
+ owned.tasks = finished.map((item) => item.record);
381
+ at = performance.now();
382
+ const copies = own.copies[finished[finished.length - 1].record.worker];
383
+ for (const [from, to] of own.plan.copyOut) {
384
+ const index = own.plan.windows.findIndex((w) => w.low <= from && to <= w.end);
385
+ const source = copies[index] + from - own.plan.windows[index].low;
386
+ bytes.copyWithin(from, source, source + to - from);
387
+ }
388
+ owned.copyOutMs = performance.now() - at;
389
+ return { results: decodeAll(finished), owned };
390
+ }
391
+ at = performance.now();
392
+ writes.forEach(([from], index) => bytes.set(saved[index], from));
393
+ owned.restoreMs = performance.now() - at;
394
+ owned.replayed = true;
395
+ owned.trap = String(failure?.message ?? failure).split('\n')[0];
396
+ return { results: this.#replay(own, entry, calls), owned };
397
+ }
398
+ #replay(own, entry, calls) {
399
+ if (own.stack)
400
+ own.stack.global.value = own.stack.home;
401
+ const run = own.owner.exports[entry];
402
+ return calls.map((call) => run(...decodeValues(call)));
403
+ }
404
+ #audit(entry, calls, results, before) {
405
+ const after = new Uint8Array(this.#memory.buffer).slice();
406
+ const copy = new WebAssembly.Memory({
407
+ initial: before.length / PAGE,
408
+ maximum: before.length / PAGE,
409
+ shared: true
410
+ });
411
+ const { module: moduleName, name } = this.#importSlot;
412
+ const imports = {
413
+ ...this.#extra,
414
+ [moduleName]: { ...(this.#extra[moduleName] ?? {}), [name]: copy }
415
+ };
416
+ const instance = new WebAssembly.Instance(this.#module, imports);
417
+ // instantiating applied the data segments over the copy; put the snapshot back
418
+ new Uint8Array(copy.buffer).set(before);
419
+ if (this.#stack)
420
+ instance.exports[this.#stack.name].value = this.#stack.tops[0];
421
+ const run = instance.exports[entry];
422
+ calls.forEach((call, index) => {
423
+ const serial = run(...decodeValues(call));
424
+ if (serial !== results[index])
425
+ throw new SliceConflictError('result', index);
426
+ });
427
+ const limit = this.#grown ?? Math.min(before.length, after.length);
428
+ const reference = new Uint8Array(copy.buffer);
429
+ for (let at = 0; at < limit; at++)
430
+ if (after[at] !== reference[at])
431
+ throw new SliceConflictError('memory', at);
432
+ }
433
+ /** Stops the workers. */
434
+ async close() {
435
+ if (this.#closed)
436
+ return;
437
+ this.#closed = true;
438
+ this.#tasks.close();
439
+ await Promise.all(this.#workers.map((worker) => worker.terminate()));
440
+ }
441
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,38 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { parentPort, workerData } from 'node:worker_threads';
10
+ import { serveTasks } from "../node/tasks.js";
11
+ import { decodeValues, encodeValues } from "./index.js";
12
+ const data = workerData;
13
+ (async () => {
14
+ const extra = data.imports ? (await import(__rewriteRelativeImportExtension(data.imports))).default() : {};
15
+ const imports = {
16
+ ...extra,
17
+ [data.slot.module]: { ...(extra[data.slot.module] ?? {}), [data.slot.name]: data.memory }
18
+ };
19
+ const instance = new WebAssembly.Instance(data.module, imports);
20
+ const stack = data.stack && instance.exports[data.stack.name];
21
+ if (stack)
22
+ stack.value = data.stack.top;
23
+ for (const w of data.windows ?? [])
24
+ instance.exports[w.delta].value = w.copy - w.low;
25
+ serveTasks(data.link, (name, input) => {
26
+ if (data.windows) {
27
+ // a trap leaves the stack pointer deep, and the last slice left its own bytes in the copies
28
+ if (stack)
29
+ stack.value = data.stack.top;
30
+ const bytes = new Uint8Array(data.memory.buffer);
31
+ for (const w of data.windows)
32
+ bytes.copyWithin(w.copy, w.low, w.end);
33
+ }
34
+ const result = instance.exports[name](...decodeValues(String(input)));
35
+ return result === undefined ? '' : encodeValues(result);
36
+ });
37
+ parentPort.postMessage({ ready: true });
38
+ })();
@@ -0,0 +1,5 @@
1
+ export * from './managed/index.ts';
2
+ export * from './managed/outbox.ts';
3
+ export * from './managed/pool.ts';
4
+ export * from './managed/tasks.ts';
5
+ export * from './remote/index.ts';
@@ -0,0 +1,5 @@
1
+ export * from "./managed/index.js";
2
+ export * from "./managed/outbox.js";
3
+ export * from "./managed/pool.js";
4
+ export * from "./managed/tasks.js";
5
+ export * from "./remote/index.js";