@gmitch215/folio 0.0.0-stage → 1.0.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.
- package/LICENSE +21 -0
- package/README.md +482 -2
- package/dist/bake.d.ts +174 -0
- package/dist/bake.js +701 -0
- package/dist/browser-worker.d.ts +9 -0
- package/dist/browser-worker.js +37 -0
- package/dist/browser.d.ts +68 -0
- package/dist/browser.js +274 -0
- package/dist/compiler.d.ts +43 -0
- package/dist/compiler.js +505 -0
- package/dist/coordinator.d.ts +27 -0
- package/dist/coordinator.js +189 -0
- package/dist/extract.d.ts +71 -0
- package/dist/extract.js +1176 -0
- package/dist/frames.d.ts +19 -0
- package/dist/frames.js +111 -0
- package/dist/guards.d.ts +12 -0
- package/dist/guards.js +202 -0
- package/dist/host.d.ts +60 -0
- package/dist/host.js +374 -0
- package/dist/import-order.d.ts +2 -0
- package/dist/import-order.js +114 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +2 -0
- package/dist/managed.d.ts +86 -0
- package/dist/managed.js +398 -0
- package/dist/memory.d.ts +10 -0
- package/dist/memory.js +89 -0
- package/dist/node.d.ts +124 -0
- package/dist/node.js +831 -0
- package/dist/pages.d.ts +109 -0
- package/dist/pages.js +339 -0
- package/dist/remote.d.ts +86 -0
- package/dist/remote.js +255 -0
- package/dist/tasks.d.ts +107 -0
- package/dist/tasks.js +317 -0
- package/dist/transaction.d.ts +23 -0
- package/dist/transaction.js +93 -0
- package/dist/values.d.ts +3 -0
- package/dist/values.js +25 -0
- package/dist/worker.d.ts +1 -0
- package/dist/worker.js +86 -0
- package/package.json +126 -5
package/dist/host.js
ADDED
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
import { Folio } from "./node.js";
|
|
2
|
+
import { decodeBytes, decodeValue, encodeBytes, encodeValue } from "./remote.js";
|
|
3
|
+
class ProtocolError extends Error {
|
|
4
|
+
status;
|
|
5
|
+
constructor(message, status = 400) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.status = status;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
const defaults = {
|
|
11
|
+
liveGroups: 4,
|
|
12
|
+
workersPerGroup: 8,
|
|
13
|
+
memoryBytesPerGroup: 64 * 1024 * 1024,
|
|
14
|
+
requestBytes: 2 * 1024 * 1024,
|
|
15
|
+
responseBytes: 2 * 1024 * 1024,
|
|
16
|
+
readBytes: 512 * 1024,
|
|
17
|
+
writeBytes: 512 * 1024,
|
|
18
|
+
argumentsPerCall: 64,
|
|
19
|
+
idleMilliseconds: 5 * 60_000,
|
|
20
|
+
retainedSessions: 64
|
|
21
|
+
};
|
|
22
|
+
function integer(value, maximum = Number.MAX_SAFE_INTEGER) {
|
|
23
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0 || value > maximum)
|
|
24
|
+
throw new ProtocolError('invalid integer or exceeded admission limit');
|
|
25
|
+
return value;
|
|
26
|
+
}
|
|
27
|
+
/** Same-process execution behind an authenticated fetch handler, with no public code upload. */
|
|
28
|
+
export class FolioHost {
|
|
29
|
+
#artifacts;
|
|
30
|
+
#sessions = new Map();
|
|
31
|
+
#authorize;
|
|
32
|
+
#limits;
|
|
33
|
+
#path;
|
|
34
|
+
#timer;
|
|
35
|
+
#opening = 0;
|
|
36
|
+
#closed = false;
|
|
37
|
+
#closing;
|
|
38
|
+
#opens = new Set();
|
|
39
|
+
constructor(options) {
|
|
40
|
+
this.#artifacts = new Map(Object.entries(options.artifacts));
|
|
41
|
+
this.#authorize = options.authorize;
|
|
42
|
+
this.#limits = { ...defaults, ...options.limits };
|
|
43
|
+
for (const value of Object.values(this.#limits))
|
|
44
|
+
if (!Number.isSafeInteger(value) || value < 1)
|
|
45
|
+
throw new RangeError('invalid host limit');
|
|
46
|
+
if (this.#limits.responseBytes < 512)
|
|
47
|
+
throw new RangeError('response limit must reserve at least 512 bytes for errors');
|
|
48
|
+
this.#path = options.path ?? '/folio';
|
|
49
|
+
if (!/^\/[a-zA-Z0-9/_-]*[a-zA-Z0-9_-]$/.test(this.#path))
|
|
50
|
+
throw new TypeError('invalid host path');
|
|
51
|
+
this.#timer = setInterval(() => {
|
|
52
|
+
const now = Date.now();
|
|
53
|
+
for (const [key, session] of this.#sessions) {
|
|
54
|
+
if (session.operations)
|
|
55
|
+
continue;
|
|
56
|
+
if (now - session.touched < this.#limits.idleMilliseconds)
|
|
57
|
+
continue;
|
|
58
|
+
if (session.released)
|
|
59
|
+
this.#sessions.delete(key);
|
|
60
|
+
else if (!session.closed)
|
|
61
|
+
void this.#enqueue(session, () => this.#closeSession(session)).catch(() => { });
|
|
62
|
+
}
|
|
63
|
+
}, Math.min(this.#limits.idleMilliseconds, 60_000));
|
|
64
|
+
this.#timer.unref();
|
|
65
|
+
}
|
|
66
|
+
/** Groups open or opening, counting those still joining their workers. */
|
|
67
|
+
get activeGroups() {
|
|
68
|
+
return (this.#opening +
|
|
69
|
+
[...this.#sessions.values()].filter((session) => !session.released).length);
|
|
70
|
+
}
|
|
71
|
+
#response(value, status = 200) {
|
|
72
|
+
return new Response(this.#serialize(value), {
|
|
73
|
+
status,
|
|
74
|
+
headers: { 'content-type': 'application/json', 'cache-control': 'no-store' }
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
#serialize(value) {
|
|
78
|
+
const body = JSON.stringify(encodeValue(value));
|
|
79
|
+
if (new TextEncoder().encode(body).length > this.#limits.responseBytes)
|
|
80
|
+
throw new ProtocolError('response exceeds transport byte limit', 413);
|
|
81
|
+
return body;
|
|
82
|
+
}
|
|
83
|
+
#error(error) {
|
|
84
|
+
return {
|
|
85
|
+
body: {
|
|
86
|
+
kind: (error instanceof Error ? error.name : 'Error').slice(0, 32),
|
|
87
|
+
message: (error instanceof Error
|
|
88
|
+
? error.message
|
|
89
|
+
: 'execution threw a non-error value').slice(0, Math.min(1024, Math.floor(this.#limits.responseBytes / 32)))
|
|
90
|
+
},
|
|
91
|
+
status: error instanceof ProtocolError ? error.status : 422
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
async #body(request) {
|
|
95
|
+
const maximum = this.#limits.requestBytes;
|
|
96
|
+
const reader = request.body?.getReader();
|
|
97
|
+
if (!reader)
|
|
98
|
+
throw new ProtocolError('request body is required');
|
|
99
|
+
const chunks = [];
|
|
100
|
+
let size = 0;
|
|
101
|
+
try {
|
|
102
|
+
for (;;) {
|
|
103
|
+
const { done, value } = await reader.read();
|
|
104
|
+
if (done)
|
|
105
|
+
break;
|
|
106
|
+
size += value.length;
|
|
107
|
+
if (size > maximum)
|
|
108
|
+
throw new ProtocolError('request exceeds transport byte limit', 413);
|
|
109
|
+
chunks.push(value);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
catch (error) {
|
|
113
|
+
await reader.cancel().catch(() => { });
|
|
114
|
+
throw error;
|
|
115
|
+
}
|
|
116
|
+
finally {
|
|
117
|
+
reader.releaseLock();
|
|
118
|
+
}
|
|
119
|
+
const bytes = new Uint8Array(size);
|
|
120
|
+
let offset = 0;
|
|
121
|
+
for (const chunk of chunks) {
|
|
122
|
+
bytes.set(chunk, offset);
|
|
123
|
+
offset += chunk.length;
|
|
124
|
+
}
|
|
125
|
+
return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
126
|
+
}
|
|
127
|
+
#enqueue(session, operation) {
|
|
128
|
+
session.operations++;
|
|
129
|
+
const result = session.tail.then(operation).finally(() => {
|
|
130
|
+
session.operations--;
|
|
131
|
+
session.touched = Date.now();
|
|
132
|
+
});
|
|
133
|
+
session.tail = result.catch(() => { });
|
|
134
|
+
return result;
|
|
135
|
+
}
|
|
136
|
+
#closeSession(session) {
|
|
137
|
+
if (session.closing)
|
|
138
|
+
return session.closing;
|
|
139
|
+
session.closed = true;
|
|
140
|
+
session.closing = (async () => {
|
|
141
|
+
try {
|
|
142
|
+
await session.pool.close();
|
|
143
|
+
}
|
|
144
|
+
finally {
|
|
145
|
+
try {
|
|
146
|
+
await session.dispose?.();
|
|
147
|
+
}
|
|
148
|
+
finally {
|
|
149
|
+
session.released = true;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
})();
|
|
153
|
+
return session.closing;
|
|
154
|
+
}
|
|
155
|
+
async #open(value) {
|
|
156
|
+
if (this.#closed)
|
|
157
|
+
throw new ProtocolError('execution host is closed', 503);
|
|
158
|
+
if (typeof value.artifact !== 'string' || !this.#artifacts.has(value.artifact))
|
|
159
|
+
throw new ProtocolError('unknown registered artifact', 404);
|
|
160
|
+
if (this.activeGroups >= this.#limits.liveGroups)
|
|
161
|
+
throw new ProtocolError('live group admission limit reached', 429);
|
|
162
|
+
while (this.#sessions.size + this.#opening >= this.#limits.retainedSessions) {
|
|
163
|
+
const oldest = [...this.#sessions].find(([, session]) => session.released);
|
|
164
|
+
if (!oldest)
|
|
165
|
+
throw new ProtocolError('retained session admission limit reached', 429);
|
|
166
|
+
this.#sessions.delete(oldest[0]);
|
|
167
|
+
}
|
|
168
|
+
const workers = value.workers === undefined
|
|
169
|
+
? Math.min(4, this.#limits.workersPerGroup)
|
|
170
|
+
: integer(value.workers, this.#limits.workersPerGroup);
|
|
171
|
+
if (!workers)
|
|
172
|
+
throw new ProtocolError('at least one worker is required');
|
|
173
|
+
this.#opening++;
|
|
174
|
+
let binding;
|
|
175
|
+
let pool;
|
|
176
|
+
try {
|
|
177
|
+
const artifact = this.#artifacts.get(value.artifact);
|
|
178
|
+
binding = await artifact.create?.();
|
|
179
|
+
pool = await Folio.open(artifact.program, { ...binding?.options, workers });
|
|
180
|
+
const memories = new Set(Object.values(pool.memories));
|
|
181
|
+
try {
|
|
182
|
+
memories.add(pool.memory);
|
|
183
|
+
}
|
|
184
|
+
catch { }
|
|
185
|
+
const totalBytes = [...memories].reduce((sum, memory) => sum + memory.buffer.byteLength, 0);
|
|
186
|
+
if (totalBytes > this.#limits.memoryBytesPerGroup)
|
|
187
|
+
throw new ProtocolError('artifact exceeds memory admission limit', 413);
|
|
188
|
+
if (this.#closed)
|
|
189
|
+
throw new ProtocolError('execution host is closed', 503);
|
|
190
|
+
const capability = crypto.randomUUID() + crypto.randomUUID();
|
|
191
|
+
const session = {
|
|
192
|
+
pool,
|
|
193
|
+
artifact,
|
|
194
|
+
dispose: binding?.dispose,
|
|
195
|
+
sequence: 0,
|
|
196
|
+
tail: Promise.resolve(),
|
|
197
|
+
operations: 0,
|
|
198
|
+
touched: Date.now(),
|
|
199
|
+
closed: false,
|
|
200
|
+
released: false
|
|
201
|
+
};
|
|
202
|
+
const response = this.#response({
|
|
203
|
+
capability,
|
|
204
|
+
threadIds: [...pool.threadIds],
|
|
205
|
+
capabilities: pool.capabilities
|
|
206
|
+
});
|
|
207
|
+
this.#sessions.set(capability, session);
|
|
208
|
+
return response;
|
|
209
|
+
}
|
|
210
|
+
catch (error) {
|
|
211
|
+
try {
|
|
212
|
+
await pool?.close();
|
|
213
|
+
}
|
|
214
|
+
finally {
|
|
215
|
+
await binding?.dispose?.();
|
|
216
|
+
}
|
|
217
|
+
throw error;
|
|
218
|
+
}
|
|
219
|
+
finally {
|
|
220
|
+
this.#opening--;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
#memory(session, key) {
|
|
224
|
+
if (key === undefined)
|
|
225
|
+
return session.pool.memory;
|
|
226
|
+
if (typeof key !== 'string' || !Object.hasOwn(session.pool.memories, key))
|
|
227
|
+
throw new ProtocolError('unknown memory');
|
|
228
|
+
return session.pool.memories[key];
|
|
229
|
+
}
|
|
230
|
+
async #operation(session, value) {
|
|
231
|
+
if (value.operation === 'close') {
|
|
232
|
+
await this.#closeSession(session);
|
|
233
|
+
return undefined;
|
|
234
|
+
}
|
|
235
|
+
if (value.operation === 'read' || value.operation === 'write') {
|
|
236
|
+
const memory = this.#memory(session, value.memory);
|
|
237
|
+
const offset = integer(value.offset);
|
|
238
|
+
let bytes;
|
|
239
|
+
if (value.operation === 'write') {
|
|
240
|
+
if (typeof value.bytes !== 'string' ||
|
|
241
|
+
value.bytes.length > this.#limits.writeBytes * 2)
|
|
242
|
+
throw new ProtocolError('write exceeds transport byte limit', 413);
|
|
243
|
+
bytes = decodeBytes(value.bytes);
|
|
244
|
+
}
|
|
245
|
+
const length = bytes?.length ?? integer(value.length, this.#limits.readBytes);
|
|
246
|
+
if (offset > memory.buffer.byteLength || length > memory.buffer.byteLength - offset)
|
|
247
|
+
throw new ProtocolError('memory range is out of bounds');
|
|
248
|
+
if (bytes) {
|
|
249
|
+
new Uint8Array(memory.buffer, offset, length).set(bytes);
|
|
250
|
+
return undefined;
|
|
251
|
+
}
|
|
252
|
+
return encodeBytes(new Uint8Array(memory.buffer, offset, length));
|
|
253
|
+
}
|
|
254
|
+
if (value.operation === 'run') {
|
|
255
|
+
if (typeof value.entry !== 'string' || !session.artifact.exports.includes(value.entry))
|
|
256
|
+
throw new ProtocolError('export is not authorized', 403);
|
|
257
|
+
if (!Array.isArray(value.args) ||
|
|
258
|
+
value.args.length > this.#limits.argumentsPerCall ||
|
|
259
|
+
value.args.some((arg) => !['number', 'bigint'].includes(typeof arg)))
|
|
260
|
+
throw new ProtocolError('arguments must be bounded numeric Wasm values');
|
|
261
|
+
const options = value.options ?? {};
|
|
262
|
+
if (options.parallel !== undefined &&
|
|
263
|
+
!['auto', 'off', 'speculate'].includes(options.parallel))
|
|
264
|
+
throw new ProtocolError('invalid parallel option');
|
|
265
|
+
const maximumWorkers = options.maximumWorkers === undefined
|
|
266
|
+
? undefined
|
|
267
|
+
: integer(options.maximumWorkers, this.#limits.workersPerGroup);
|
|
268
|
+
if (maximumWorkers === 0)
|
|
269
|
+
throw new ProtocolError('at least one worker is required');
|
|
270
|
+
return session.pool.run(value.entry, value.args, {
|
|
271
|
+
parallel: options.parallel,
|
|
272
|
+
maximumWorkers
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
throw new ProtocolError('unknown operation');
|
|
276
|
+
}
|
|
277
|
+
async #session(session, text, value) {
|
|
278
|
+
return this.#enqueue(session, async () => {
|
|
279
|
+
session.touched = Date.now();
|
|
280
|
+
const sequence = integer(value.sequence);
|
|
281
|
+
if (sequence === session.sequence - 1 && session.last) {
|
|
282
|
+
if (text !== session.last.body)
|
|
283
|
+
throw new ProtocolError('sequence was reused with different input', 409);
|
|
284
|
+
return new Response(session.last.response, {
|
|
285
|
+
status: session.last.status,
|
|
286
|
+
headers: {
|
|
287
|
+
'content-type': 'application/json',
|
|
288
|
+
'cache-control': 'no-store',
|
|
289
|
+
'x-folio-sequence': String(sequence)
|
|
290
|
+
}
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
if (sequence !== session.sequence)
|
|
294
|
+
throw new ProtocolError('out of order session request', 409);
|
|
295
|
+
if (session.closed)
|
|
296
|
+
throw new ProtocolError('session is closed', 410);
|
|
297
|
+
let response, status = 200;
|
|
298
|
+
try {
|
|
299
|
+
response = this.#serialize(await this.#operation(session, value));
|
|
300
|
+
}
|
|
301
|
+
catch (error) {
|
|
302
|
+
const failure = this.#error(error);
|
|
303
|
+
status = failure.status;
|
|
304
|
+
response = this.#serialize(failure.body);
|
|
305
|
+
}
|
|
306
|
+
session.last = { body: text, response, status };
|
|
307
|
+
session.sequence++;
|
|
308
|
+
return new Response(response, {
|
|
309
|
+
status,
|
|
310
|
+
headers: {
|
|
311
|
+
'content-type': 'application/json',
|
|
312
|
+
'cache-control': 'no-store',
|
|
313
|
+
'x-folio-sequence': String(sequence)
|
|
314
|
+
}
|
|
315
|
+
});
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
/** The authenticated handler to mount behind a service binding or an HTTP server. */
|
|
319
|
+
fetch = async (request) => {
|
|
320
|
+
try {
|
|
321
|
+
if (!(await this.#authorize(request)))
|
|
322
|
+
throw new ProtocolError('authorization required', 401);
|
|
323
|
+
if (request.method !== 'POST')
|
|
324
|
+
throw new ProtocolError('POST is required', 405);
|
|
325
|
+
if (this.#closed)
|
|
326
|
+
throw new ProtocolError('execution host is closed', 503);
|
|
327
|
+
const path = new URL(request.url).pathname;
|
|
328
|
+
if (path !== this.#path && !path.startsWith(`${this.#path}/`))
|
|
329
|
+
throw new ProtocolError('unknown host route', 404);
|
|
330
|
+
const text = await this.#body(request);
|
|
331
|
+
const value = decodeValue(JSON.parse(text));
|
|
332
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
333
|
+
throw new ProtocolError('request must be a record');
|
|
334
|
+
if (path === this.#path) {
|
|
335
|
+
const pending = this.#open(value);
|
|
336
|
+
this.#opens.add(pending);
|
|
337
|
+
try {
|
|
338
|
+
return await pending;
|
|
339
|
+
}
|
|
340
|
+
finally {
|
|
341
|
+
this.#opens.delete(pending);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
const session = this.#sessions.get(path.slice(this.#path.length + 1));
|
|
345
|
+
if (!session)
|
|
346
|
+
throw new ProtocolError('unknown session', 404);
|
|
347
|
+
return await this.#session(session, text, value);
|
|
348
|
+
}
|
|
349
|
+
catch (error) {
|
|
350
|
+
const failure = this.#error(error);
|
|
351
|
+
return this.#response(failure.body, failure.status);
|
|
352
|
+
}
|
|
353
|
+
};
|
|
354
|
+
/** Refuses new sessions, then joins every group's workers and pending effects. */
|
|
355
|
+
close() {
|
|
356
|
+
if (this.#closing)
|
|
357
|
+
return this.#closing;
|
|
358
|
+
this.#closed = true;
|
|
359
|
+
clearInterval(this.#timer);
|
|
360
|
+
this.#closing = (async () => {
|
|
361
|
+
await Promise.allSettled([...this.#opens]);
|
|
362
|
+
const closed = await Promise.allSettled([...this.#sessions.values()].map((session) => this.#enqueue(session, () => this.#closeSession(session))));
|
|
363
|
+
this.#sessions.clear();
|
|
364
|
+
const failure = closed.find((result) => result.status === 'rejected');
|
|
365
|
+
if (failure?.status === 'rejected')
|
|
366
|
+
throw failure.reason;
|
|
367
|
+
})();
|
|
368
|
+
return this.#closing;
|
|
369
|
+
}
|
|
370
|
+
/** `await using` support; equivalent to `close()`. */
|
|
371
|
+
[Symbol.asyncDispose]() {
|
|
372
|
+
return this.close();
|
|
373
|
+
}
|
|
374
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/** Restores observable import lookup order without changing any Wasm index space. */
|
|
2
|
+
export function restoreImportOrder(bytes, original) {
|
|
3
|
+
const descriptors = WebAssembly.Module.imports(new WebAssembly.Module(Uint8Array.from(bytes)));
|
|
4
|
+
let cursor = 8;
|
|
5
|
+
const uint = () => {
|
|
6
|
+
let value = 0, shift = 0, byte;
|
|
7
|
+
do {
|
|
8
|
+
byte = bytes[cursor++];
|
|
9
|
+
value += (byte & 127) * 2 ** shift;
|
|
10
|
+
shift += 7;
|
|
11
|
+
} while (byte & 128);
|
|
12
|
+
return value;
|
|
13
|
+
};
|
|
14
|
+
const type = () => {
|
|
15
|
+
const code = bytes[cursor++];
|
|
16
|
+
if (code === 0x63 || code === 0x64)
|
|
17
|
+
uint();
|
|
18
|
+
};
|
|
19
|
+
const limits = () => {
|
|
20
|
+
const flags = uint();
|
|
21
|
+
uint();
|
|
22
|
+
if (flags & 1)
|
|
23
|
+
uint();
|
|
24
|
+
};
|
|
25
|
+
while (cursor < bytes.length) {
|
|
26
|
+
const id = bytes[cursor++], length = uint(), start = cursor, end = start + length;
|
|
27
|
+
if (id !== 2) {
|
|
28
|
+
cursor = end;
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
const count = uint(), prefix = cursor;
|
|
32
|
+
const records = [];
|
|
33
|
+
for (let index = 0; index < count; index++) {
|
|
34
|
+
const begin = cursor;
|
|
35
|
+
for (let name = 0; name < 2; name++) {
|
|
36
|
+
const size = uint();
|
|
37
|
+
cursor += size;
|
|
38
|
+
}
|
|
39
|
+
const kind = bytes[cursor++];
|
|
40
|
+
if (kind === 0)
|
|
41
|
+
uint();
|
|
42
|
+
else if (kind === 1) {
|
|
43
|
+
type();
|
|
44
|
+
limits();
|
|
45
|
+
}
|
|
46
|
+
else if (kind === 2)
|
|
47
|
+
limits();
|
|
48
|
+
else if (kind === 3) {
|
|
49
|
+
type();
|
|
50
|
+
cursor++;
|
|
51
|
+
}
|
|
52
|
+
else if (kind === 4) {
|
|
53
|
+
uint();
|
|
54
|
+
uint();
|
|
55
|
+
}
|
|
56
|
+
else
|
|
57
|
+
throw new Error('unsupported import descriptor');
|
|
58
|
+
records.push({
|
|
59
|
+
kind: descriptors[index].kind,
|
|
60
|
+
descriptor: descriptors[index],
|
|
61
|
+
bytes: bytes.subarray(begin, cursor)
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
if (cursor !== end || records.length !== descriptors.length)
|
|
65
|
+
throw new Error('invalid import census');
|
|
66
|
+
const key = (value) => JSON.stringify([value.kind, value.module, value.name]);
|
|
67
|
+
const occurrences = new Map();
|
|
68
|
+
const kinds = new Map();
|
|
69
|
+
for (let index = 0; index < records.length; index++) {
|
|
70
|
+
const name = key(records[index].descriptor);
|
|
71
|
+
for (const [map, identity] of [
|
|
72
|
+
[occurrences, name],
|
|
73
|
+
[kinds, records[index].kind]
|
|
74
|
+
]) {
|
|
75
|
+
const queue = map.get(identity) ?? { indices: [], next: 0 };
|
|
76
|
+
queue.indices.push(index);
|
|
77
|
+
map.set(identity, queue);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
const wanted = original.map((value) => {
|
|
81
|
+
const queue = occurrences.get(key(value));
|
|
82
|
+
const index = queue?.indices[queue.next++];
|
|
83
|
+
if (index === undefined)
|
|
84
|
+
throw new Error('extraction removed an original import');
|
|
85
|
+
return index;
|
|
86
|
+
});
|
|
87
|
+
const retained = new Set(wanted), emitted = new Set(), order = [];
|
|
88
|
+
for (const target of wanted) {
|
|
89
|
+
const queue = kinds.get(records[target].kind);
|
|
90
|
+
while (queue.next < queue.indices.length && queue.indices[queue.next] <= target) {
|
|
91
|
+
const index = queue.indices[queue.next++];
|
|
92
|
+
if (index !== target && retained.has(index))
|
|
93
|
+
throw new Error('extraction changed per-kind import order');
|
|
94
|
+
emitted.add(index);
|
|
95
|
+
order.push(index);
|
|
96
|
+
}
|
|
97
|
+
if (!emitted.has(target))
|
|
98
|
+
throw new Error('extraction changed per-kind import order');
|
|
99
|
+
}
|
|
100
|
+
for (let index = 0; index < records.length; index++)
|
|
101
|
+
if (!emitted.has(index))
|
|
102
|
+
order.push(index);
|
|
103
|
+
const result = Uint8Array.from(bytes);
|
|
104
|
+
let write = prefix;
|
|
105
|
+
for (const index of order) {
|
|
106
|
+
result.set(records[index].bytes, write);
|
|
107
|
+
write += records[index].bytes.length;
|
|
108
|
+
}
|
|
109
|
+
return result;
|
|
110
|
+
}
|
|
111
|
+
if (original.length)
|
|
112
|
+
throw new Error('extraction removed the import section');
|
|
113
|
+
return bytes;
|
|
114
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import type { ControlPlan } from './extract.ts';
|
|
2
|
+
import type { MemoryImport } from './memory.ts';
|
|
3
|
+
import type { ExecutionReport } from './node.ts';
|
|
4
|
+
/** Precompiled modules for the managed backend. Nothing is compiled at request time. */
|
|
5
|
+
export interface ManagedArtifact {
|
|
6
|
+
/** The source program; serial and fallback execution use it unchanged. */
|
|
7
|
+
original: WebAssembly.Module;
|
|
8
|
+
/** The JSPI coordinator that discovers and joins regions. */
|
|
9
|
+
coordinator?: WebAssembly.Module;
|
|
10
|
+
/** The tracked region module each lane runs. */
|
|
11
|
+
transactional?: WebAssembly.Module;
|
|
12
|
+
/** The control plan from `prepare`, minus the module bytes carried above. */
|
|
13
|
+
control?: Omit<ControlPlan, 'coordinator' | 'workerOriginal' | 'transactional'>;
|
|
14
|
+
/** Imported memory limits of the source module, from `memoryImports`. */
|
|
15
|
+
memories?: readonly MemoryImport[];
|
|
16
|
+
}
|
|
17
|
+
/** One lane: sends a binary frame to a lane runtime and returns its binary response. */
|
|
18
|
+
export interface ManagedLaneTransport {
|
|
19
|
+
/** Delivers a frame to a `FolioLane` and resolves with the response frame. */
|
|
20
|
+
execute(frame: Uint8Array): Promise<Uint8Array>;
|
|
21
|
+
/** Releases the lane's connection or object. */
|
|
22
|
+
close?(): Promise<void>;
|
|
23
|
+
}
|
|
24
|
+
/** An `ExecutionReport` for the managed backend, which always copies snapshots. */
|
|
25
|
+
export interface ManagedReport extends Omit<ExecutionReport, 'memoryMode'> {
|
|
26
|
+
/** Always `managed-coherent`. */
|
|
27
|
+
backend: 'managed-coherent';
|
|
28
|
+
/** Lanes read copied snapshots, never shared memory. */
|
|
29
|
+
memoryMode: 'copied';
|
|
30
|
+
/** Encoded frame bytes sent to and received from lanes; platform internal copies are not visible. */
|
|
31
|
+
transportBytes: {
|
|
32
|
+
sent: number;
|
|
33
|
+
received: number;
|
|
34
|
+
};
|
|
35
|
+
/** Batches that ran natively at the owner after a transport failure or malformed reply. */
|
|
36
|
+
transportFallbacks: number;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* The lane runtime: runs tracked regions from a binary frame against a private copy of the
|
|
40
|
+
* frozen snapshot and returns byte read and write sets. Holds no state between frames.
|
|
41
|
+
*/
|
|
42
|
+
export declare class FolioLane {
|
|
43
|
+
#private;
|
|
44
|
+
constructor(module: WebAssembly.Module, options: {
|
|
45
|
+
initial: number;
|
|
46
|
+
maximum: number;
|
|
47
|
+
maximumMemoryBytes?: number;
|
|
48
|
+
maximumFrameBytes?: number;
|
|
49
|
+
});
|
|
50
|
+
/** Validates the frame, runs its calls in order and returns the encoded results. */
|
|
51
|
+
execute(frame: Uint8Array): Uint8Array;
|
|
52
|
+
/** Drops the instance and its memory; a later frame builds them again. */
|
|
53
|
+
close(): void;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* The owner side of the managed backend. The original Wasm stack keeps control flow and host
|
|
57
|
+
* effects, and JSPI joins regions that lanes execute over copied snapshots.
|
|
58
|
+
*/
|
|
59
|
+
export declare class ManagedFolio {
|
|
60
|
+
#private;
|
|
61
|
+
/** The original native exports. */
|
|
62
|
+
readonly exports: WebAssembly.Exports;
|
|
63
|
+
/** Optimization refusals and fallbacks seen so far. */
|
|
64
|
+
readonly diagnostics: string[];
|
|
65
|
+
constructor(artifact: ManagedArtifact, options: {
|
|
66
|
+
lanes: readonly ManagedLaneTransport[];
|
|
67
|
+
imports?: WebAssembly.Imports;
|
|
68
|
+
memory?: WebAssembly.Memory;
|
|
69
|
+
fuel?: number;
|
|
70
|
+
maxTransactionBytes?: number;
|
|
71
|
+
maximumSnapshotBytes?: number;
|
|
72
|
+
maximumFrameBytes?: number;
|
|
73
|
+
promising?: readonly string[];
|
|
74
|
+
});
|
|
75
|
+
/** The canonical memory, which must fit the owner runtime. Throws when there is no unique one. */
|
|
76
|
+
get memory(): WebAssembly.Memory;
|
|
77
|
+
/** Runs one entry; regions go to lanes and results commit in order. One run at a time. */
|
|
78
|
+
run(name: string, args?: readonly unknown[], options?: {
|
|
79
|
+
maximumWorkers?: number;
|
|
80
|
+
parallel?: 'auto' | 'off';
|
|
81
|
+
}): Promise<ManagedReport>;
|
|
82
|
+
/** Waits for the active run, then closes every lane. A failed disposer does not skip the rest. */
|
|
83
|
+
close(): Promise<void>;
|
|
84
|
+
/** `await using` support; equivalent to `close()`. */
|
|
85
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
86
|
+
}
|