@gmitch215/folio 0.0.0-stage → 1.0.1
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 +541 -2
- package/dist/bake.d.ts +179 -0
- package/dist/bake.js +704 -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 +79 -0
- package/dist/compiler.js +620 -0
- package/dist/context.d.ts +33 -0
- package/dist/context.js +93 -0
- package/dist/coordinator.d.ts +27 -0
- package/dist/coordinator.js +191 -0
- package/dist/extract.d.ts +165 -0
- package/dist/extract.js +1817 -0
- package/dist/frames.d.ts +33 -0
- package/dist/frames.js +159 -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/inline.d.ts +68 -0
- package/dist/inline.js +503 -0
- package/dist/iteration-admission.d.ts +76 -0
- package/dist/iteration-admission.js +72 -0
- package/dist/iteration-layout.d.ts +75 -0
- package/dist/iteration-layout.js +118 -0
- package/dist/iteration-owner.d.ts +32 -0
- package/dist/iteration-owner.js +223 -0
- package/dist/iteration-worker.d.ts +1 -0
- package/dist/iteration-worker.js +150 -0
- package/dist/iteration.d.ts +163 -0
- package/dist/iteration.js +435 -0
- package/dist/managed.d.ts +92 -0
- package/dist/managed.js +421 -0
- package/dist/memory.d.ts +10 -0
- package/dist/memory.js +89 -0
- package/dist/node.d.ts +138 -0
- package/dist/node.js +1153 -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 +330 -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 +130 -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
package/dist/inline.d.ts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/** Names of the exported mutable i32 globals the inline lowering adds, plus the stack export. */
|
|
2
|
+
export declare const inlineGlobals: {
|
|
3
|
+
readonly readBitmap: "__folio_rb";
|
|
4
|
+
readonly writeBitmap: "__folio_wb";
|
|
5
|
+
readonly logPointer: "__folio_lp";
|
|
6
|
+
readonly logLimit: "__folio_ll";
|
|
7
|
+
readonly stampAddress: "__folio_sa";
|
|
8
|
+
readonly stackPointer: "__folio_sp";
|
|
9
|
+
readonly frameLow: "__folio_fl";
|
|
10
|
+
readonly frameSize: "__folio_fn";
|
|
11
|
+
readonly frameShadow: "__folio_fs";
|
|
12
|
+
};
|
|
13
|
+
/** Bytes of one undo entry: the granule address, the stamp, then the prior bytes of the granule. */
|
|
14
|
+
export declare const inlineEntryBytes: (writeGranule?: number) => number;
|
|
15
|
+
/** Options for `lowerInline`. */
|
|
16
|
+
export interface InlineOptions {
|
|
17
|
+
/** Read granule in bytes, a power of two from 16 to 4096. Default 64. */
|
|
18
|
+
readGranule?: number;
|
|
19
|
+
/** Write and undo granule in bytes, a power of two from 16 to 256. Default 32. */
|
|
20
|
+
writeGranule?: number;
|
|
21
|
+
/** Refuse a memory that is not shared. Pass false to lower a module for one thread. Default true. */
|
|
22
|
+
requireShared?: boolean;
|
|
23
|
+
/** The mutable i32 global exported as `__folio_sp`. Default: the one `stackRoute` names, if any. */
|
|
24
|
+
stack?: string;
|
|
25
|
+
/** Track exposed reads of one frame region (see `lowerInline`). Default off. */
|
|
26
|
+
frame?: boolean;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* A second lowering, next to the host-call one in `prepare`: it marks memory accesses inline, with
|
|
30
|
+
* no host call and no added import, so a region can be validated after it ran. Nothing in
|
|
31
|
+
* `prepare` calls it yet and its output is not a `PreparedProgram` field.
|
|
32
|
+
*
|
|
33
|
+
* State lives in mutable i32 globals the owner exports and sets before each region; all start at
|
|
34
|
+
* 0, which traps on the first access. `__folio_rb` and `__folio_wb` are the bases of the read and
|
|
35
|
+
* write bitmaps, `__folio_lp` and `__folio_ll` the undo log pointer and limit, `__folio_sa` the
|
|
36
|
+
* address of a shared i32 stamp counter (4-byte aligned). The stack pointer global is exported as
|
|
37
|
+
* `__folio_sp` when the module has one. A bitmap has one bit per granule: granule `g`, with
|
|
38
|
+
* `g = address >> log2(granule)`, is bit `g & 7` of byte `base + (g >> 3)`. The bitmaps are
|
|
39
|
+
* private to a region and the owner clears them between regions.
|
|
40
|
+
*
|
|
41
|
+
* Every load, store, atomic access and SIMD load marks its read granule, and an access that
|
|
42
|
+
* crosses a boundary marks both. A store, a SIMD lane store and the destination of `memory.copy`,
|
|
43
|
+
* `memory.fill` and `memory.init` mark write granules; atomic accesses mark both sets; the source
|
|
44
|
+
* of `memory.copy` marks read granules. The first write to a write granule appends an undo entry
|
|
45
|
+
* at `__folio_lp`: the granule address (u32), a stamp from an atomic add on `__folio_sa` taken
|
|
46
|
+
* after the prior bytes were copied and before the write, then the prior bytes of the granule.
|
|
47
|
+
* `__folio_lp` then advances by `inlineEntryBytes(writeGranule)`; an entry that would pass
|
|
48
|
+
* `__folio_ll` traps with `unreachable`. The start function is not lowered.
|
|
49
|
+
*
|
|
50
|
+
* With `frame: true` the module also tracks one frame region, for a stack frame whose bytes an
|
|
51
|
+
* iteration may read after an earlier iteration wrote them. The owner sets `__folio_fl` (low
|
|
52
|
+
* address), `__folio_fn` (size in bytes) and `__folio_fs` (shadow base) before a region; with
|
|
53
|
+
* `__folio_fn` at 0 nothing is tracked. An access that overlaps the region is checked against a
|
|
54
|
+
* shadow of one written bit per frame byte, `4 * ceil(size / 32)` bytes with the bits of frame
|
|
55
|
+
* granule `g` (32 bytes) in the i32 at `__folio_fs + 4 * g`, then 4 pad bytes, then the exposed
|
|
56
|
+
* bits laid out the same way, then 4 more pad bytes. A store sets written bits after its value is
|
|
57
|
+
* computed; a load sets the exposed bit of each byte it reads whose written bit is clear, so a
|
|
58
|
+
* region reports exactly the frame bytes it read before it wrote them.
|
|
59
|
+
* `memory.copy`, `memory.fill` and `memory.init` set or check the exact byte range, an atomic
|
|
60
|
+
* read-modify-write checks then sets, and any other atomic access or SIMD load checks. The owner
|
|
61
|
+
* zeroes the shadow before each region. Accesses outside the region pay one compare. Stack below
|
|
62
|
+
* the region is not tracked.
|
|
63
|
+
*
|
|
64
|
+
* Throws for a module without exactly one memory, a 64-bit memory, an unshared memory when
|
|
65
|
+
* `requireShared` is set, a start function that calls, a reserved name or an expression it does
|
|
66
|
+
* not know. An imported host function that touches memory is not seen.
|
|
67
|
+
*/
|
|
68
|
+
export declare function lowerInline(bytes: Uint8Array, options?: InlineOptions): Uint8Array;
|