@iso4/sandbox 0.4.2 → 0.5.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/README.md +153 -13
- package/dist/index.d.mts +820 -74
- package/dist/index.mjs +2833 -814
- package/package.json +9 -6
package/dist/index.mjs
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
|
-
import { access,
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
1
|
+
import { access, mkdtemp, rm } from "node:fs/promises";
|
|
2
|
+
import { existsSync, rmSync } from "node:fs";
|
|
3
|
+
import { availableParallelism, tmpdir, totalmem } from "node:os";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
5
|
import process from "node:process";
|
|
6
6
|
import { spawn } from "node:child_process";
|
|
7
|
-
import {
|
|
7
|
+
import { randomBytes } from "node:crypto";
|
|
8
8
|
import { fileURLToPath } from "node:url";
|
|
9
9
|
import { createConnection } from "node:net";
|
|
10
10
|
import { Buffer } from "node:buffer";
|
|
11
|
+
import v8 from "node:v8";
|
|
11
12
|
//#region src/binary.ts
|
|
12
13
|
function resolveRuntimeBinary(options = {}) {
|
|
13
14
|
if (options.binaryPath) return options.binaryPath;
|
|
@@ -40,439 +41,564 @@ function platformBinaryPackage() {
|
|
|
40
41
|
};
|
|
41
42
|
throw new Error(`Unsupported platform: ${process.platform}/${process.arch}. @iso4/sandbox supports darwin/arm64, darwin/x64, linux/arm64, and linux/x64.`);
|
|
42
43
|
}
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
* `decodeRunCompletionPayload` only.
|
|
54
|
-
*/
|
|
55
|
-
const TAG_UNDEFINED = 0;
|
|
56
|
-
const TAG_NULL = 1;
|
|
57
|
-
const TAG_FALSE = 2;
|
|
58
|
-
const TAG_TRUE = 3;
|
|
59
|
-
const TAG_NUMBER = 4;
|
|
60
|
-
const TAG_STRING = 5;
|
|
61
|
-
const TAG_BIGINT = 6;
|
|
62
|
-
const TAG_BYTES = 7;
|
|
63
|
-
const TAG_ARRAY = 8;
|
|
64
|
-
const TAG_OBJECT = 9;
|
|
65
|
-
var WireDecodeError = class extends Error {
|
|
66
|
-
name = "WireDecodeError";
|
|
67
|
-
constructor(message) {
|
|
68
|
-
super(message);
|
|
44
|
+
function tagName(tag) {
|
|
45
|
+
switch (tag) {
|
|
46
|
+
case 1: return "Headers";
|
|
47
|
+
case 2: return "Request";
|
|
48
|
+
case 3: return "Response";
|
|
49
|
+
case 4: return "ReadableStream";
|
|
50
|
+
case 5: return "WritableStream";
|
|
51
|
+
case 6: return "WebSocket";
|
|
52
|
+
case 7: return "AbortSignal";
|
|
53
|
+
default: return `unknown type (tag ${tag})`;
|
|
69
54
|
}
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Mirrors `MAX_HEADER_ENTRIES` in `webcodec.rs`.
|
|
58
|
+
*/
|
|
59
|
+
const MAX_HEADER_ENTRIES = 1024;
|
|
60
|
+
/**
|
|
61
|
+
* Thrown when a value cannot cross in this position. Surfaces to callers as
|
|
62
|
+
* `ERR_TYPE_NOT_SERIALIZABLE`.
|
|
63
|
+
*/
|
|
64
|
+
var HostTypeError = class extends TypeError {
|
|
65
|
+
name = "HostTypeError";
|
|
70
66
|
};
|
|
71
67
|
/**
|
|
72
|
-
*
|
|
73
|
-
*
|
|
74
|
-
*
|
|
68
|
+
* Prefix of the property name marking a branded descriptor — a plain object
|
|
69
|
+
* standing in for a host type on the way into the sandbox, which the runtime
|
|
70
|
+
* swaps for a real instance. The full brand key is this prefix followed by the
|
|
71
|
+
* sandbox's random descriptor token in hex ({@link brandKeyForToken}), so the
|
|
72
|
+
* runtime rehydrates only descriptors this host actually stamped: inbound
|
|
73
|
+
* structured data that happens to carry a brand-shaped key passes through as
|
|
74
|
+
* the plain data it is. Wire contract: kept in sync with `BRAND_PREFIX` in
|
|
75
|
+
* `native/v8-runtime/src/webcodec.rs`.
|
|
75
76
|
*/
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
77
|
+
const BRAND_PREFIX = "__iso4_ht_";
|
|
78
|
+
/**
|
|
79
|
+
* Build the session brand key for a descriptor token.
|
|
80
|
+
* @param token the sandbox's random descriptor token
|
|
81
|
+
*/
|
|
82
|
+
function brandKeyForToken(token) {
|
|
83
|
+
return BRAND_PREFIX + Buffer.from(token.buffer, token.byteOffset, token.byteLength).toString("hex");
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* The per-run registry of body sources being streamed to the sandbox. Created
|
|
87
|
+
* by the run entry points, filled by {@link materializeHostTypes} when a body
|
|
88
|
+
* outgrows the probe, pumped by the client's frame loop.
|
|
89
|
+
*/
|
|
90
|
+
var StreamSourceRegistry = class {
|
|
91
|
+
nextId = 1;
|
|
92
|
+
sources = /* @__PURE__ */ new Map();
|
|
93
|
+
newIds = [];
|
|
94
|
+
/**
|
|
95
|
+
* Register a source and return its stream id.
|
|
96
|
+
* @param reader the body reader, positioned after the probe
|
|
97
|
+
* @param prefix probed chunks to send first
|
|
98
|
+
*/
|
|
99
|
+
register(reader, prefix) {
|
|
100
|
+
const id = this.nextId++;
|
|
101
|
+
this.sources.set(id, {
|
|
102
|
+
reader,
|
|
103
|
+
prefix,
|
|
104
|
+
credit: 0,
|
|
105
|
+
pumping: false,
|
|
106
|
+
done: false
|
|
107
|
+
});
|
|
108
|
+
this.newIds.push(id);
|
|
109
|
+
return id;
|
|
94
110
|
}
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
111
|
+
/**
|
|
112
|
+
* Stream ids registered since the last take — the client activates their
|
|
113
|
+
* pumps once the frame carrying the descriptors has been written.
|
|
114
|
+
*/
|
|
115
|
+
takeNewIds() {
|
|
116
|
+
return this.newIds.splice(0);
|
|
100
117
|
}
|
|
101
118
|
/**
|
|
102
|
-
*
|
|
103
|
-
* floating-point precision loss from DataView.getBigUint64 on older runtimes
|
|
104
|
-
* (though Node 18+ supports it; this is belt-and-suspenders).
|
|
119
|
+
* Release every remaining source (run over, or torn down).
|
|
105
120
|
*/
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
121
|
+
releaseAll() {
|
|
122
|
+
for (const source of this.sources.values()) {
|
|
123
|
+
source.done = true;
|
|
124
|
+
source.reader.cancel().catch(() => {});
|
|
125
|
+
}
|
|
126
|
+
this.sources.clear();
|
|
127
|
+
this.newIds.length = 0;
|
|
112
128
|
}
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
129
|
+
};
|
|
130
|
+
/**
|
|
131
|
+
* Per-run registry of OUTBOUND streamed bodies — result bodies the sandbox
|
|
132
|
+
* produces and the consumer reads as a `ReadableStream`. Chunks arriving
|
|
133
|
+
* before the Result is decoded (the runtime's eager initial window) buffer
|
|
134
|
+
* here, bounded by the credit window; the consumer's reads replenish the
|
|
135
|
+
* runtime's credit chunk by chunk, so a slow reader stops production at
|
|
136
|
+
* the guest source.
|
|
137
|
+
*/
|
|
138
|
+
var OutboundStreamRegistry = class {
|
|
139
|
+
states = /* @__PURE__ */ new Map();
|
|
140
|
+
transport;
|
|
141
|
+
constructor(transport) {
|
|
142
|
+
this.transport = transport;
|
|
143
|
+
}
|
|
144
|
+
state(streamId) {
|
|
145
|
+
let st = this.states.get(streamId);
|
|
146
|
+
if (st === void 0) {
|
|
147
|
+
st = {
|
|
148
|
+
buffered: [],
|
|
149
|
+
cancelled: false
|
|
150
|
+
};
|
|
151
|
+
this.states.set(streamId, st);
|
|
152
|
+
}
|
|
153
|
+
return st;
|
|
118
154
|
}
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
155
|
+
/**
|
|
156
|
+
* A `StreamChunk` frame arrived for this run.
|
|
157
|
+
* @param streamId
|
|
158
|
+
* @param data
|
|
159
|
+
*/
|
|
160
|
+
deliverChunk(streamId, data) {
|
|
161
|
+
const st = this.state(streamId);
|
|
162
|
+
if (st.cancelled) return;
|
|
163
|
+
st.buffered.push(data);
|
|
164
|
+
st.waiter?.();
|
|
123
165
|
}
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
166
|
+
/**
|
|
167
|
+
* A `StreamEnd` frame arrived: clean EOF, or a guest source failure.
|
|
168
|
+
* @param streamId
|
|
169
|
+
* @param error
|
|
170
|
+
*/
|
|
171
|
+
deliverEnd(streamId, error) {
|
|
172
|
+
const st = this.state(streamId);
|
|
173
|
+
st.ended = error === void 0 ? {} : { error };
|
|
174
|
+
st.waiter?.();
|
|
128
175
|
}
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
176
|
+
/**
|
|
177
|
+
* Connection-level failure (teardown, desync) or the run ending with a
|
|
178
|
+
* stream never terminated: error every stream that has no outcome yet,
|
|
179
|
+
* so no consumer read hangs.
|
|
180
|
+
* @param error
|
|
181
|
+
*/
|
|
182
|
+
failAll(error) {
|
|
183
|
+
for (const st of this.states.values()) if (st.ended === void 0 && !st.cancelled && st.failed === void 0) {
|
|
184
|
+
st.failed = error;
|
|
185
|
+
st.waiter?.();
|
|
186
|
+
}
|
|
134
187
|
}
|
|
135
|
-
|
|
136
|
-
|
|
188
|
+
/**
|
|
189
|
+
* Hydrate one stream handle into the consumer-facing `ReadableStream`.
|
|
190
|
+
* Called during Result decode (via the body-stream binder).
|
|
191
|
+
* @param streamId
|
|
192
|
+
*/
|
|
193
|
+
attach(streamId) {
|
|
194
|
+
const st = this.state(streamId);
|
|
195
|
+
const serve = (controller) => {
|
|
196
|
+
const chunk = st.buffered.shift();
|
|
197
|
+
if (chunk !== void 0) {
|
|
198
|
+
controller.enqueue(chunk);
|
|
199
|
+
this.transport.pull(streamId, chunk.byteLength);
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
if (st.failed !== void 0) {
|
|
203
|
+
controller.error(st.failed);
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
if (st.ended !== void 0) {
|
|
207
|
+
if (st.ended.error !== void 0) controller.error(/* @__PURE__ */ new Error(`[iso4] body stream failed: ${st.ended.error}`));
|
|
208
|
+
else controller.close();
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
return new Promise((resolve) => {
|
|
212
|
+
st.waiter = () => {
|
|
213
|
+
st.waiter = void 0;
|
|
214
|
+
resolve();
|
|
215
|
+
};
|
|
216
|
+
}).then(() => serve(controller));
|
|
217
|
+
};
|
|
218
|
+
return new ReadableStream({
|
|
219
|
+
pull: (controller) => serve(controller),
|
|
220
|
+
cancel: (reason) => {
|
|
221
|
+
st.cancelled = true;
|
|
222
|
+
st.buffered = [];
|
|
223
|
+
if (st.ended === void 0 && st.failed === void 0) this.transport.cancel(streamId, String(reason ?? "cancelled"));
|
|
224
|
+
}
|
|
225
|
+
});
|
|
137
226
|
}
|
|
138
227
|
};
|
|
139
|
-
function
|
|
140
|
-
const
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
228
|
+
function flatHeaders(headers) {
|
|
229
|
+
const out = [];
|
|
230
|
+
const setCookies = typeof headers.getSetCookie === "function" ? headers.getSetCookie() : [];
|
|
231
|
+
headers.forEach((value, name) => {
|
|
232
|
+
if (name === "set-cookie" && setCookies.length > 0) return;
|
|
233
|
+
out.push(name, value);
|
|
234
|
+
});
|
|
235
|
+
for (const cookie of setCookies) out.push("set-cookie", cookie);
|
|
236
|
+
if (out.length / 2 > MAX_HEADER_ENTRIES) throw new HostTypeError(`[iso4] Headers has ${out.length / 2} entries, exceeding the ${MAX_HEADER_ENTRIES} limit`);
|
|
237
|
+
return out;
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Ceiling on a host-supplied body, matching the default `maxBridgeCallBytes` /
|
|
241
|
+
* `maxExportBytes`. The frame layer enforces the configured limit downstream;
|
|
242
|
+
* this exists so an unbounded body cannot exhaust host memory *before* the
|
|
243
|
+
* payload is ever framed.
|
|
244
|
+
*/
|
|
245
|
+
const MAX_BODY_BYTES = 16 * 1024 * 1024;
|
|
246
|
+
async function materializeBody(source, streams) {
|
|
247
|
+
if (source.bodyUsed) throw new HostTypeError("[iso4] cannot serialize a Request/Response whose body was already read — pass a fresh instance (cache the bytes, not the object)");
|
|
248
|
+
const stream = source.body;
|
|
249
|
+
if (stream === null || stream === void 0) {
|
|
250
|
+
const buffer = await source.arrayBuffer();
|
|
251
|
+
return buffer.byteLength === 0 ? null : new Uint8Array(buffer);
|
|
252
|
+
}
|
|
253
|
+
const probeLimit = streams === void 0 ? MAX_BODY_BYTES : STREAM_PROBE_BYTES;
|
|
254
|
+
const reader = stream.getReader();
|
|
255
|
+
const chunks = [];
|
|
256
|
+
let total = 0;
|
|
257
|
+
for (;;) {
|
|
258
|
+
let result;
|
|
259
|
+
try {
|
|
260
|
+
result = await reader.read();
|
|
261
|
+
} catch (error) {
|
|
262
|
+
reader.releaseLock();
|
|
263
|
+
throw error;
|
|
164
264
|
}
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
obj[key] = val;
|
|
173
|
-
}
|
|
174
|
-
return obj;
|
|
265
|
+
if (result.done) break;
|
|
266
|
+
total += result.value.byteLength;
|
|
267
|
+
chunks.push(result.value);
|
|
268
|
+
if (total > probeLimit) {
|
|
269
|
+
if (streams !== void 0) return { streamId: streams.register(reader, chunks) };
|
|
270
|
+
reader.releaseLock();
|
|
271
|
+
throw new HostTypeError(`[iso4] body exceeds ${MAX_BODY_BYTES} bytes; a Request/Response crossing the boundary must be bounded — buffer and truncate it first`);
|
|
175
272
|
}
|
|
176
|
-
default: throw new WireDecodeError(`unknown WireValue tag: 0x${tag.toString(16).padStart(2, "0")}`);
|
|
177
273
|
}
|
|
274
|
+
reader.releaseLock();
|
|
275
|
+
if (total === 0) return null;
|
|
276
|
+
const out = new Uint8Array(total);
|
|
277
|
+
let offset = 0;
|
|
278
|
+
for (const chunk of chunks) {
|
|
279
|
+
out.set(chunk, offset);
|
|
280
|
+
offset += chunk.byteLength;
|
|
281
|
+
}
|
|
282
|
+
return out;
|
|
283
|
+
}
|
|
284
|
+
function bodyFields(body) {
|
|
285
|
+
if (body !== null && typeof body === "object" && "streamId" in body) return {
|
|
286
|
+
body: null,
|
|
287
|
+
bodyStream: body.streamId
|
|
288
|
+
};
|
|
289
|
+
return { body };
|
|
290
|
+
}
|
|
291
|
+
async function toDescriptor(value, brandKey, streams) {
|
|
292
|
+
if (value instanceof globalThis.Response) return {
|
|
293
|
+
[brandKey]: 3,
|
|
294
|
+
status: value.status,
|
|
295
|
+
statusText: value.statusText,
|
|
296
|
+
headers: flatHeaders(value.headers),
|
|
297
|
+
...bodyFields(await materializeBody(value, streams))
|
|
298
|
+
};
|
|
299
|
+
if (value instanceof globalThis.Request) return {
|
|
300
|
+
[brandKey]: 2,
|
|
301
|
+
url: value.url,
|
|
302
|
+
method: value.method,
|
|
303
|
+
headers: flatHeaders(value.headers),
|
|
304
|
+
...bodyFields(await materializeBody(value, streams))
|
|
305
|
+
};
|
|
306
|
+
if (value instanceof globalThis.Headers) return {
|
|
307
|
+
[brandKey]: 1,
|
|
308
|
+
headers: flatHeaders(value),
|
|
309
|
+
body: null
|
|
310
|
+
};
|
|
178
311
|
}
|
|
179
312
|
/**
|
|
180
|
-
*
|
|
181
|
-
*
|
|
313
|
+
* Depth cap, matching `MAX_DEPTH` in `webcodec.rs`. Cycles are handled by the
|
|
314
|
+
* `seen` map, so this only bounds pathologically deep graphs.
|
|
315
|
+
*/
|
|
316
|
+
const MAX_DEPTH = 32;
|
|
317
|
+
/**
|
|
318
|
+
* Replace every `Request`/`Response`/`Headers` anywhere in `value` with a
|
|
319
|
+
* branded plain object, returning a graph ordinary serialization can write.
|
|
182
320
|
*
|
|
183
|
-
*
|
|
184
|
-
*
|
|
185
|
-
*
|
|
321
|
+
* Structure is rebuilt rather than mutated, so the surrounding objects are
|
|
322
|
+
* untouched. A `Request`/`Response` body, however, is read into bytes here and
|
|
323
|
+
* is therefore consumed — one-shot, like any body read: pass an unread
|
|
324
|
+
* instance and do not reuse it afterwards (streams cannot cross the boundary,
|
|
325
|
+
* so the body must be buffered rather than forwarded). Object identity and
|
|
326
|
+
* cycles are preserved through `seen`. `Map`/`Set` are rebuilt because a host
|
|
327
|
+
* type can hide in either.
|
|
328
|
+
* @param value the value to transform
|
|
329
|
+
* @param brandKey the sandbox's session brand key ({@link brandKeyForToken});
|
|
330
|
+
* the runtime rehydrates only descriptors stamped with it
|
|
331
|
+
* @param streams
|
|
186
332
|
*/
|
|
187
|
-
function
|
|
188
|
-
|
|
189
|
-
|
|
333
|
+
async function materializeHostTypes(value, brandKey, streams) {
|
|
334
|
+
return transform(value, brandKey, streams, /* @__PURE__ */ new Map(), 0);
|
|
335
|
+
}
|
|
336
|
+
async function transform(value, brandKey, streams, seen, depth) {
|
|
337
|
+
if (value === null || typeof value !== "object") return value;
|
|
338
|
+
if (depth > MAX_DEPTH) throw new HostTypeError(`[iso4] value nests deeper than ${MAX_DEPTH} levels; cannot scan it for host types`);
|
|
339
|
+
const existing = seen.get(value);
|
|
340
|
+
if (existing !== void 0) return existing;
|
|
341
|
+
const descriptor = await toDescriptor(value, brandKey, streams);
|
|
342
|
+
if (descriptor !== void 0) {
|
|
343
|
+
seen.set(value, descriptor);
|
|
344
|
+
return descriptor;
|
|
345
|
+
}
|
|
346
|
+
if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer || value instanceof Date || value instanceof RegExp || value instanceof Error) return value;
|
|
347
|
+
if (Array.isArray(value)) {
|
|
348
|
+
const out = [];
|
|
349
|
+
seen.set(value, out);
|
|
350
|
+
for (const item of value) out.push(await transform(item, brandKey, streams, seen, depth + 1));
|
|
351
|
+
return out;
|
|
352
|
+
}
|
|
353
|
+
if (value instanceof Map) {
|
|
354
|
+
const out = /* @__PURE__ */ new Map();
|
|
355
|
+
seen.set(value, out);
|
|
356
|
+
for (const [k, v] of value) out.set(await transform(k, brandKey, streams, seen, depth + 1), await transform(v, brandKey, streams, seen, depth + 1));
|
|
357
|
+
return out;
|
|
358
|
+
}
|
|
359
|
+
if (value instanceof Set) {
|
|
360
|
+
const out = /* @__PURE__ */ new Set();
|
|
361
|
+
seen.set(value, out);
|
|
362
|
+
for (const v of value) out.add(await transform(v, brandKey, streams, seen, depth + 1));
|
|
363
|
+
return out;
|
|
364
|
+
}
|
|
365
|
+
const out = Object.create(null);
|
|
366
|
+
seen.set(value, out);
|
|
367
|
+
for (const [k, v] of Object.entries(value)) out[k] = await transform(v, brandKey, streams, seen, depth + 1);
|
|
368
|
+
return out;
|
|
369
|
+
}
|
|
370
|
+
function readStr(des) {
|
|
371
|
+
const len = des.readUint32();
|
|
372
|
+
return des.readRawBytes(len).toString("utf8");
|
|
373
|
+
}
|
|
374
|
+
function readHeaders(des) {
|
|
375
|
+
const flat = des.readValue();
|
|
376
|
+
if (!Array.isArray(flat) || flat.length % 2 !== 0) throw new HostTypeError("[iso4] Headers entry list is malformed");
|
|
377
|
+
if (flat.length / 2 > MAX_HEADER_ENTRIES) throw new HostTypeError(`[iso4] Headers payload declares ${flat.length / 2} entries, exceeding the ${MAX_HEADER_ENTRIES} limit`);
|
|
378
|
+
const out = [];
|
|
379
|
+
for (let i = 0; i < flat.length; i += 2) out.push([String(flat[i]), String(flat[i + 1])]);
|
|
380
|
+
return out;
|
|
381
|
+
}
|
|
382
|
+
function readBody(des) {
|
|
383
|
+
const body = des.readValue();
|
|
384
|
+
if (body === null || body === void 0) return null;
|
|
385
|
+
if (typeof body === "string" || body instanceof Uint8Array) return body;
|
|
386
|
+
throw new HostTypeError("[iso4] received a body that is neither bytes, a string, nor absent");
|
|
190
387
|
}
|
|
191
388
|
/**
|
|
192
|
-
*
|
|
193
|
-
*
|
|
194
|
-
*
|
|
195
|
-
*
|
|
196
|
-
*
|
|
197
|
-
* u8 ok
|
|
198
|
-
* u8 successPresent (1 when ok = 1)
|
|
199
|
-
* WireValue exports
|
|
200
|
-
* List<String> stdout
|
|
201
|
-
* List<String> stderr
|
|
202
|
-
* f64 durationMs
|
|
203
|
-
* f64 cpuTimeMs
|
|
204
|
-
* List<BridgeCallRecord> bridgeCalls
|
|
205
|
-
* u8 failurePresent (1 when ok = 0)
|
|
206
|
-
* String code
|
|
207
|
-
* String name
|
|
208
|
-
* String message
|
|
209
|
-
* Optional<String> stack
|
|
210
|
-
* Optional<WireValue> fields
|
|
211
|
-
* List<String> stdout
|
|
212
|
-
* List<String> stderr
|
|
213
|
-
* f64 durationMs
|
|
214
|
-
* f64 cpuTimeMs
|
|
215
|
-
* List<BridgeCallRecord> bridgeCalls
|
|
216
|
-
* ```
|
|
217
|
-
* @param buf
|
|
389
|
+
* Binder resolving an outbound stream handle (from a descriptor's extras)
|
|
390
|
+
* into the consumer-facing `ReadableStream`. Installed around a Result
|
|
391
|
+
* decode by {@link withBodyStreamBinder}; module-level because the
|
|
392
|
+
* deserializer hook chain has no context parameter — safe, the decode is
|
|
393
|
+
* synchronous.
|
|
218
394
|
*/
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
reader.assertDone();
|
|
232
|
-
return {
|
|
233
|
-
runId,
|
|
234
|
-
result: {
|
|
235
|
-
status: "completed",
|
|
236
|
-
ok: true,
|
|
237
|
-
exports: wireObjectToExports(exportsRaw),
|
|
238
|
-
stdout,
|
|
239
|
-
stderr,
|
|
240
|
-
durationMs,
|
|
241
|
-
cpuTimeMs,
|
|
242
|
-
bridgeCalls
|
|
243
|
-
}
|
|
244
|
-
};
|
|
395
|
+
let currentBodyStreamBinder;
|
|
396
|
+
/**
|
|
397
|
+
* Run `fn` with `binder` resolving outbound body-stream handles.
|
|
398
|
+
* @param binder
|
|
399
|
+
* @param fn
|
|
400
|
+
*/
|
|
401
|
+
function withBodyStreamBinder(binder, fn) {
|
|
402
|
+
currentBodyStreamBinder = binder;
|
|
403
|
+
try {
|
|
404
|
+
return fn();
|
|
405
|
+
} finally {
|
|
406
|
+
currentBodyStreamBinder = void 0;
|
|
245
407
|
}
|
|
246
|
-
reader.readU8();
|
|
247
|
-
if (reader.readU8() !== 1) throw new WireDecodeError("expected failure present byte = 1 when ok = false");
|
|
248
|
-
const code = reader.readString();
|
|
249
|
-
const name = reader.readString();
|
|
250
|
-
const message = reader.readString();
|
|
251
|
-
const stack = reader.readU8() === 1 ? reader.readString() : void 0;
|
|
252
|
-
const fields = reader.readU8() === 1 ? decodeWireValueFromReader(reader) : void 0;
|
|
253
|
-
const stdout = reader.readStringList();
|
|
254
|
-
const stderr = reader.readStringList();
|
|
255
|
-
const durationMs = reader.readF64();
|
|
256
|
-
const cpuTimeMs = reader.readF64();
|
|
257
|
-
const bridgeCalls = readBridgeCallRecords(reader);
|
|
258
|
-
reader.assertDone();
|
|
259
|
-
return {
|
|
260
|
-
runId,
|
|
261
|
-
result: {
|
|
262
|
-
status: "failed",
|
|
263
|
-
ok: false,
|
|
264
|
-
error: {
|
|
265
|
-
code,
|
|
266
|
-
name,
|
|
267
|
-
message,
|
|
268
|
-
stack,
|
|
269
|
-
fields
|
|
270
|
-
},
|
|
271
|
-
stdout,
|
|
272
|
-
stderr,
|
|
273
|
-
durationMs,
|
|
274
|
-
cpuTimeMs,
|
|
275
|
-
bridgeCalls
|
|
276
|
-
}
|
|
277
|
-
};
|
|
278
408
|
}
|
|
279
409
|
/**
|
|
280
|
-
*
|
|
281
|
-
*
|
|
282
|
-
*
|
|
283
|
-
* @param
|
|
410
|
+
* Read the extras blob and resolve an outbound body-stream handle when one
|
|
411
|
+
* rides in it (#128). Extras is a self-contained V8 blob holding a plain
|
|
412
|
+
* object — the forward-compatible field slot (§4.4.4).
|
|
413
|
+
* @param des
|
|
284
414
|
*/
|
|
285
|
-
function
|
|
286
|
-
const
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
const ok = reader.readBool();
|
|
295
|
-
const blocked = reader.readBool();
|
|
296
|
-
entries.push({
|
|
297
|
-
name,
|
|
298
|
-
startMs,
|
|
299
|
-
durationMs,
|
|
300
|
-
argBytes,
|
|
301
|
-
responseBytes,
|
|
302
|
-
ok,
|
|
303
|
-
blocked
|
|
304
|
-
});
|
|
415
|
+
function readExtras(des) {
|
|
416
|
+
const len = des.readUint32();
|
|
417
|
+
if (len === 0) return {};
|
|
418
|
+
const bytes = des.readRawBytes(len);
|
|
419
|
+
let extras;
|
|
420
|
+
try {
|
|
421
|
+
extras = v8.deserialize(bytes);
|
|
422
|
+
} catch {
|
|
423
|
+
throw new HostTypeError("[iso4] descriptor extras blob is malformed");
|
|
305
424
|
}
|
|
306
|
-
|
|
425
|
+
const streamId = extras !== null && typeof extras === "object" ? extras["bodyStream"] : void 0;
|
|
426
|
+
if (typeof streamId !== "number") return {};
|
|
427
|
+
if (currentBodyStreamBinder === void 0) throw new HostTypeError("[iso4] a stream body arrived on a leg that cannot carry one");
|
|
428
|
+
return { bodyStream: currentBodyStreamBinder(streamId) };
|
|
307
429
|
}
|
|
308
430
|
/**
|
|
309
|
-
*
|
|
431
|
+
* Methods that must not carry a body, per the fetch spec.
|
|
432
|
+
*/
|
|
433
|
+
const BODYLESS_METHODS = new Set(["GET", "HEAD"]);
|
|
434
|
+
/**
|
|
435
|
+
* Read one host-object payload, tag first, and construct the configured class.
|
|
310
436
|
*
|
|
311
|
-
*
|
|
312
|
-
*
|
|
313
|
-
*
|
|
314
|
-
* u8 prefixIdPresent (1 when ok = true)
|
|
315
|
-
* String prefixId
|
|
316
|
-
* u8 errorPresent (1 when ok = false)
|
|
317
|
-
* RunErrorPayload error
|
|
318
|
-
* ```
|
|
319
|
-
* @param buf
|
|
437
|
+
* Called from `_readHostObject`, which must return an object — Node throws
|
|
438
|
+
* `readHostObject must return an object` otherwise.
|
|
439
|
+
* @param des deserializer, positioned at the type tag
|
|
320
440
|
*/
|
|
321
|
-
function
|
|
322
|
-
const
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
reader.assertDone();
|
|
341
|
-
return {
|
|
342
|
-
ok: false,
|
|
343
|
-
error: {
|
|
344
|
-
code,
|
|
345
|
-
name,
|
|
346
|
-
message,
|
|
347
|
-
stack
|
|
348
|
-
}
|
|
349
|
-
};
|
|
350
|
-
}
|
|
351
|
-
const ENC_TAG_UNDEFINED = 0;
|
|
352
|
-
const ENC_TAG_NULL = 1;
|
|
353
|
-
const ENC_TAG_FALSE = 2;
|
|
354
|
-
const ENC_TAG_TRUE = 3;
|
|
355
|
-
const ENC_TAG_NUMBER = 4;
|
|
356
|
-
const ENC_TAG_STRING = 5;
|
|
357
|
-
const ENC_TAG_BIGINT = 6;
|
|
358
|
-
const ENC_TAG_BYTES = 7;
|
|
359
|
-
const ENC_TAG_ARRAY = 8;
|
|
360
|
-
const ENC_TAG_OBJECT = 9;
|
|
361
|
-
var WireWriter = class {
|
|
362
|
-
parts = [];
|
|
363
|
-
/**
|
|
364
|
-
* Objects currently on the recursion stack. Used for cycle detection.
|
|
365
|
-
* Mirrors the `visiting` Vec in Rust's `value_to_wire`.
|
|
366
|
-
*
|
|
367
|
-
* Path-based (add before recursing, delete after): allows diamond shapes
|
|
368
|
-
* (`{ a: x, b: x }` where x is the same object) but rejects true cycles.
|
|
369
|
-
*/
|
|
370
|
-
visiting = /* @__PURE__ */ new WeakSet();
|
|
371
|
-
writeU8(n) {
|
|
372
|
-
const b = Buffer.allocUnsafe(1);
|
|
373
|
-
b.writeUInt8(n, 0);
|
|
374
|
-
this.parts.push(b);
|
|
375
|
-
return this;
|
|
376
|
-
}
|
|
377
|
-
writeU32(n) {
|
|
378
|
-
const b = Buffer.allocUnsafe(4);
|
|
379
|
-
b.writeUInt32BE(n, 0);
|
|
380
|
-
this.parts.push(b);
|
|
381
|
-
return this;
|
|
382
|
-
}
|
|
383
|
-
writeF64(n) {
|
|
384
|
-
const b = Buffer.allocUnsafe(8);
|
|
385
|
-
b.writeDoubleBE(n, 0);
|
|
386
|
-
this.parts.push(b);
|
|
387
|
-
return this;
|
|
388
|
-
}
|
|
389
|
-
/**
|
|
390
|
-
* Write a JS `bigint` as a big-endian u64 (must fit in 64 bits).
|
|
391
|
-
* @param n
|
|
392
|
-
*/
|
|
393
|
-
writeU64BE(n) {
|
|
394
|
-
const b = Buffer.allocUnsafe(8);
|
|
395
|
-
b.writeUInt32BE(Number(n >> 32n & 4294967295n), 0);
|
|
396
|
-
b.writeUInt32BE(Number(n & 4294967295n), 4);
|
|
397
|
-
this.parts.push(b);
|
|
398
|
-
return this;
|
|
399
|
-
}
|
|
400
|
-
writeString(s) {
|
|
401
|
-
const encoded = Buffer.from(s, "utf8");
|
|
402
|
-
this.writeU32(encoded.byteLength);
|
|
403
|
-
this.parts.push(encoded);
|
|
404
|
-
return this;
|
|
405
|
-
}
|
|
406
|
-
writeValue(value) {
|
|
407
|
-
if (value === void 0) return this.writeU8(ENC_TAG_UNDEFINED);
|
|
408
|
-
if (value === null) return this.writeU8(ENC_TAG_NULL);
|
|
409
|
-
if (typeof value === "boolean") return this.writeU8(value ? ENC_TAG_TRUE : ENC_TAG_FALSE);
|
|
410
|
-
if (typeof value === "number") return this.writeU8(ENC_TAG_NUMBER).writeF64(value);
|
|
411
|
-
if (typeof value === "string") return this.writeU8(ENC_TAG_STRING).writeString(value);
|
|
412
|
-
if (typeof value === "bigint") {
|
|
413
|
-
const sign = value < 0n ? 1 : 0;
|
|
414
|
-
let magnitude = value < 0n ? -value : value;
|
|
415
|
-
const words = [];
|
|
416
|
-
while (magnitude > 0n) {
|
|
417
|
-
words.push(magnitude & 18446744073709551615n);
|
|
418
|
-
magnitude >>= 64n;
|
|
441
|
+
function readHostType(des) {
|
|
442
|
+
const tag = des.readUint32();
|
|
443
|
+
switch (tag) {
|
|
444
|
+
case 1: return new globalThis.Headers(readHeaders(des));
|
|
445
|
+
case 2: {
|
|
446
|
+
const url = readStr(des);
|
|
447
|
+
const method = readStr(des);
|
|
448
|
+
const headers = readHeaders(des);
|
|
449
|
+
const body = readBody(des);
|
|
450
|
+
const { bodyStream } = readExtras(des);
|
|
451
|
+
const init = {
|
|
452
|
+
method,
|
|
453
|
+
headers
|
|
454
|
+
};
|
|
455
|
+
if (!BODYLESS_METHODS.has(method.toUpperCase())) {
|
|
456
|
+
if (bodyStream !== void 0) {
|
|
457
|
+
init.body = bodyStream;
|
|
458
|
+
init.duplex = "half";
|
|
459
|
+
} else if (body !== null) init.body = body;
|
|
419
460
|
}
|
|
420
|
-
|
|
421
|
-
this.writeU8(sign);
|
|
422
|
-
this.writeU32(words.length);
|
|
423
|
-
for (const word of words) this.writeU64BE(word);
|
|
424
|
-
return this;
|
|
461
|
+
return new globalThis.Request(url, init);
|
|
425
462
|
}
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
this.visiting.delete(value);
|
|
439
|
-
return this;
|
|
440
|
-
}
|
|
441
|
-
if (typeof value === "object") {
|
|
442
|
-
const proto = Object.getPrototypeOf(value);
|
|
443
|
-
if (proto !== null && proto !== Object.prototype) {
|
|
444
|
-
const name = value.constructor?.name ?? "(unknown)";
|
|
445
|
-
throw new TypeError(`[iso4] encodeWireValue: cannot encode ${name} instance; only primitives, bigint, string, Uint8Array, and plain objects/arrays cross the boundary — copy the data into a plain object`);
|
|
446
|
-
}
|
|
447
|
-
if (this.visiting.has(value)) throw new TypeError("[iso4] encodeWireValue: cyclic or self-referential structure");
|
|
448
|
-
this.visiting.add(value);
|
|
449
|
-
const entries = Object.entries(value).filter(([k]) => k !== "__proto__");
|
|
450
|
-
this.writeU8(ENC_TAG_OBJECT);
|
|
451
|
-
this.writeU32(entries.length);
|
|
452
|
-
for (const [k, v] of entries) {
|
|
453
|
-
this.writeString(k);
|
|
454
|
-
this.writeValue(v);
|
|
455
|
-
}
|
|
456
|
-
this.visiting.delete(value);
|
|
457
|
-
return this;
|
|
463
|
+
case 3: {
|
|
464
|
+
const status = des.readUint32();
|
|
465
|
+
const statusText = readStr(des);
|
|
466
|
+
const headers = readHeaders(des);
|
|
467
|
+
const body = readBody(des);
|
|
468
|
+
const { bodyStream } = readExtras(des);
|
|
469
|
+
if (status === 0) return globalThis.Response.error();
|
|
470
|
+
return new globalThis.Response(bodyStream ?? body, {
|
|
471
|
+
status,
|
|
472
|
+
statusText,
|
|
473
|
+
headers
|
|
474
|
+
});
|
|
458
475
|
}
|
|
459
|
-
throw new
|
|
476
|
+
case 0: throw new HostTypeError("[iso4] payload carries the reserved invalid type tag");
|
|
477
|
+
default: throw new HostTypeError(`[iso4] received a ${tagName(tag)}; this build cannot materialise one`);
|
|
460
478
|
}
|
|
461
|
-
|
|
462
|
-
|
|
479
|
+
}
|
|
480
|
+
/**
|
|
481
|
+
* Deserializer that understands host objects.
|
|
482
|
+
*
|
|
483
|
+
* Extends `v8.Deserializer`, **not** `v8.DefaultDeserializer`: the latter's
|
|
484
|
+
* `_readHostObject` decodes Node's private typed-array host-object format and
|
|
485
|
+
* would misparse our tag. Safe because neither side ever writes that format —
|
|
486
|
+
* `_setTreatArrayBufferViewsAsHostObjects(false)` is set on every serializer.
|
|
487
|
+
*/
|
|
488
|
+
var HostTypeDeserializer = class extends v8.Deserializer {
|
|
489
|
+
_readHostObject() {
|
|
490
|
+
return readHostType(this);
|
|
463
491
|
}
|
|
464
492
|
};
|
|
493
|
+
//#endregion
|
|
494
|
+
//#region src/v8-codec.ts
|
|
465
495
|
/**
|
|
466
|
-
*
|
|
467
|
-
*
|
|
468
|
-
*
|
|
496
|
+
* Thrown when a value cannot be represented in the V8 serialization format.
|
|
497
|
+
*
|
|
498
|
+
* V8 raises a `DataCloneError`-style exception for functions, symbols,
|
|
499
|
+
* promises, `WeakMap`/`WeakSet`, and proxies. Everything else — including
|
|
500
|
+
* `Date`, `Map`, `Set`, `RegExp`, `Error`, `ArrayBuffer`, every `TypedArray`,
|
|
501
|
+
* `bigint`, and cyclic graphs — round-trips as a real instance.
|
|
502
|
+
*
|
|
503
|
+
* Internal: never surfaces through the public API. Callers translate it into
|
|
504
|
+
* the typed error the boundary expects (`ERR_HOST_BRIDGE` for bridge
|
|
505
|
+
* responses, a rejected data global at encode time).
|
|
506
|
+
*/
|
|
507
|
+
var ValueEncodeError = class extends TypeError {
|
|
508
|
+
name = "ValueEncodeError";
|
|
509
|
+
};
|
|
510
|
+
/**
|
|
511
|
+
* Thrown when a blob cannot be read back — a truncated payload, or a blob
|
|
512
|
+
* written by a V8 whose serialization format version this Node cannot read.
|
|
513
|
+
*
|
|
514
|
+
* The format version is checked once per connection at handshake time
|
|
515
|
+
* (see `client.ts`), so reaching this at run time means a corrupt payload.
|
|
469
516
|
*/
|
|
470
|
-
|
|
471
|
-
|
|
517
|
+
var ValueDecodeError = class extends TypeError {
|
|
518
|
+
name = "ValueDecodeError";
|
|
519
|
+
};
|
|
520
|
+
/**
|
|
521
|
+
* Serialize one JavaScript value into a V8 serialization blob.
|
|
522
|
+
* @param value the value to encode
|
|
523
|
+
* @throws {ValueEncodeError} when V8 refuses to clone the value
|
|
524
|
+
*/
|
|
525
|
+
function serializeValue(value) {
|
|
526
|
+
const serializer = new v8.DefaultSerializer();
|
|
527
|
+
serializer._setTreatArrayBufferViewsAsHostObjects(false);
|
|
528
|
+
serializer.writeHeader();
|
|
529
|
+
try {
|
|
530
|
+
serializer.writeValue(value);
|
|
531
|
+
} catch (error) {
|
|
532
|
+
throw new ValueEncodeError(`[iso4] cannot serialize value: ${error instanceof Error ? error.message : String(error)}`);
|
|
533
|
+
}
|
|
534
|
+
return serializer.releaseBuffer();
|
|
472
535
|
}
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
536
|
+
/**
|
|
537
|
+
* Serialize a value that may contain `Request`/`Response`/`Headers` **anywhere**
|
|
538
|
+
* inside it.
|
|
539
|
+
*
|
|
540
|
+
* Async because reading a body is. Use this on every leg where a host type can
|
|
541
|
+
* legitimately appear — bridge responses and data globals. Everything else keeps
|
|
542
|
+
* using {@link serializeValue}, which stays synchronous.
|
|
543
|
+
*
|
|
544
|
+
* Nesting is supported at any depth: the transform substitutes branded plain
|
|
545
|
+
* objects and the runtime rebuilds real instances on arrival
|
|
546
|
+
* (`docs/protocol.md` §4.4.6). Node's serializer exposes no host-object write
|
|
547
|
+
* hook, which is why the descriptor detour exists at all.
|
|
548
|
+
* @param value the value to encode
|
|
549
|
+
* @param brandKey the sandbox's session brand key — descriptors are stamped
|
|
550
|
+
* with it, and the runtime rehydrates only stamped descriptors
|
|
551
|
+
* @param streams the run's stream registry; a body outgrowing the probe is
|
|
552
|
+
* registered there and crosses as a stream handle instead of inline bytes.
|
|
553
|
+
* Omit on legs that must stay buffered (data globals, whose values replay).
|
|
554
|
+
*/
|
|
555
|
+
async function serializeHostValue(value, brandKey, streams) {
|
|
556
|
+
return serializeValue(await materializeHostTypes(value, brandKey, streams));
|
|
557
|
+
}
|
|
558
|
+
/**
|
|
559
|
+
* Drain and brand any `Request`/`Response`/`Headers` inside a data global so the
|
|
560
|
+
* synchronous payload encoder can write it.
|
|
561
|
+
*
|
|
562
|
+
* This is one of the two host → sandbox legs — how a real `Request` gets *into*
|
|
563
|
+
* the sandbox before the call API exists. Bodies are async and payload encoding
|
|
564
|
+
* is not, so the read happens here; both `prepare()` and `execute()` are already
|
|
565
|
+
* async, so it costs no API change.
|
|
566
|
+
*
|
|
567
|
+
* Nested host types are handled, at any depth.
|
|
568
|
+
* @param defs global definitions, mutated in place
|
|
569
|
+
* @param brandKey the sandbox's session brand key ({@link serializeHostValue})
|
|
570
|
+
*/
|
|
571
|
+
async function materializeHostTypesInGlobals(defs, brandKey) {
|
|
572
|
+
for (const def of defs) {
|
|
573
|
+
if (def.kind !== "data") continue;
|
|
574
|
+
def.value = await materializeHostTypes(def.value, brandKey);
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
/**
|
|
578
|
+
* Read one JavaScript value back from a V8 serialization blob.
|
|
579
|
+
* @param bytes the blob, exactly as produced by {@link serializeValue} or by
|
|
580
|
+
* the Rust `blob::serialize_value`
|
|
581
|
+
* @throws {ValueDecodeError} on a truncated, corrupt, or newer-format blob
|
|
582
|
+
*/
|
|
583
|
+
function deserializeValue(bytes) {
|
|
584
|
+
try {
|
|
585
|
+
const deserializer = new HostTypeDeserializer(bytes);
|
|
586
|
+
deserializer.readHeader();
|
|
587
|
+
return deserializer.readValue();
|
|
588
|
+
} catch (error) {
|
|
589
|
+
throw new ValueDecodeError(`[iso4] cannot deserialize value: ${error instanceof Error ? error.message : String(error)}`);
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
/**
|
|
593
|
+
* The handshake probe: a serialized `null`.
|
|
594
|
+
*
|
|
595
|
+
* Byte 0 is V8's header tag (`0xFF`) and byte 1 is the **format version** this
|
|
596
|
+
* Node writes. Each side sends its probe at connection setup so a format-
|
|
597
|
+
* version mismatch fails loudly at `createSandbox()` instead of corrupting a
|
|
598
|
+
* value mid-run. See `docs/protocol.md` §5.1.
|
|
599
|
+
*/
|
|
600
|
+
function serializationProbe() {
|
|
601
|
+
return serializeValue(null);
|
|
476
602
|
}
|
|
477
603
|
//#endregion
|
|
478
604
|
//#region src/ipc.ts
|
|
@@ -484,22 +610,116 @@ const TsToRustMessageTypes = {
|
|
|
484
610
|
PrefixRun: 4,
|
|
485
611
|
DisposePrefix: 5,
|
|
486
612
|
BridgeResponse: 6,
|
|
487
|
-
Terminate: 7
|
|
613
|
+
Terminate: 7,
|
|
614
|
+
/**
|
|
615
|
+
* Request a capacity/usage snapshot. Empty payload; answered with a
|
|
616
|
+
* `StatsResult` frame.
|
|
617
|
+
*/
|
|
618
|
+
Stats: 8,
|
|
619
|
+
/**
|
|
620
|
+
* One chunk of a streamed host-type body — only inside the granted credit
|
|
621
|
+
* window.
|
|
622
|
+
*/
|
|
623
|
+
StreamChunk: 9,
|
|
624
|
+
/**
|
|
625
|
+
* End of a streamed body: clean EOF or a source failure.
|
|
626
|
+
*/
|
|
627
|
+
StreamEnd: 10,
|
|
628
|
+
/**
|
|
629
|
+
* Credit grant for an OUTBOUND (sandbox → host) streamed body: the
|
|
630
|
+
* consumer read bytes, the runtime may send that many more (§5.5).
|
|
631
|
+
*/
|
|
632
|
+
StreamPull: 11,
|
|
633
|
+
/**
|
|
634
|
+
* The host dropped an outbound streamed body (consumer cancel, dispose);
|
|
635
|
+
* the runtime cancels the guest source.
|
|
636
|
+
*/
|
|
637
|
+
StreamCancel: 12
|
|
488
638
|
};
|
|
489
639
|
const RustToTsMessageTypes = {
|
|
490
640
|
BridgeCall: 1,
|
|
491
641
|
Result: 2,
|
|
492
642
|
PrecompileResult: 3,
|
|
493
|
-
Log: 4
|
|
643
|
+
Log: 4,
|
|
644
|
+
/**
|
|
645
|
+
* Handshake acknowledgement — the first frame the runtime sends on a new
|
|
646
|
+
* connection, answering `Authenticate`.
|
|
647
|
+
*/
|
|
648
|
+
Hello: 5,
|
|
649
|
+
/**
|
|
650
|
+
* Capacity/usage snapshot answering a `Stats` request.
|
|
651
|
+
*/
|
|
652
|
+
StatsResult: 6,
|
|
653
|
+
/**
|
|
654
|
+
* Final frame of a run whose Result reported pending background work:
|
|
655
|
+
* carries the `waitUntil` epilogue outcome and frees the run's
|
|
656
|
+
* connection slot.
|
|
657
|
+
*/
|
|
658
|
+
RunComplete: 7,
|
|
659
|
+
/**
|
|
660
|
+
* Streaming-body credit grant: the sandbox consumed bytes, the host may
|
|
661
|
+
* have that many more in flight.
|
|
662
|
+
*/
|
|
663
|
+
StreamPull: 8,
|
|
664
|
+
/**
|
|
665
|
+
* The sandbox cancelled a streamed body; stop pumping, release the source.
|
|
666
|
+
*/
|
|
667
|
+
StreamCancel: 9,
|
|
668
|
+
/**
|
|
669
|
+
* One chunk of an OUTBOUND (sandbox → host) streamed body, inside the
|
|
670
|
+
* host-granted credit window (§5.5).
|
|
671
|
+
*/
|
|
672
|
+
StreamChunk: 10,
|
|
673
|
+
/**
|
|
674
|
+
* End of an outbound streamed body: clean EOF, or a guest source failure
|
|
675
|
+
* whose message the pending consumer read rejects with.
|
|
676
|
+
*/
|
|
677
|
+
StreamEnd: 11
|
|
678
|
+
};
|
|
679
|
+
/**
|
|
680
|
+
* Handshake status the runtime reports on its `Hello` frame.
|
|
681
|
+
*/
|
|
682
|
+
const HelloStatus = {
|
|
683
|
+
Ok: 0,
|
|
684
|
+
ProtocolVersionMismatch: 1,
|
|
685
|
+
V8FormatMismatch: 2
|
|
494
686
|
};
|
|
495
687
|
var FrameReader = class {
|
|
496
|
-
|
|
688
|
+
/**
|
|
689
|
+
* Chunks exactly as the socket delivered them, oldest first, never merged
|
|
690
|
+
* on arrival.
|
|
691
|
+
*
|
|
692
|
+
* The obvious alternative — one accumulation buffer, each chunk appended
|
|
693
|
+
* with `Buffer.concat` — copies everything received so far on every chunk,
|
|
694
|
+
* so the total copying grows with the square of the frame size rather than
|
|
695
|
+
* linearly with it. A result at the default 16 MiB export cap arrives in
|
|
696
|
+
* roughly 250 socket reads and would cost some 2 GiB of copying to receive,
|
|
697
|
+
* all of it synchronous on the event loop, stalling the whole host and not
|
|
698
|
+
* merely the run that asked for it. The size is chosen by sandbox code, so
|
|
699
|
+
* that is untrusted input deciding how much work the host does.
|
|
700
|
+
*
|
|
701
|
+
* Held as a list instead, each byte is copied at most once, when a complete
|
|
702
|
+
* frame is handed out — and not even then when the frame sits inside a
|
|
703
|
+
* single chunk, which is every small frame.
|
|
704
|
+
*/
|
|
705
|
+
chunks = [];
|
|
706
|
+
/**
|
|
707
|
+
* Total bytes across {@link chunks}; kept in step rather than recomputed.
|
|
708
|
+
*/
|
|
709
|
+
buffered = 0;
|
|
497
710
|
pendingReads = [];
|
|
498
711
|
closedError = null;
|
|
499
712
|
push(chunk) {
|
|
500
713
|
if (this.closedError !== null) return;
|
|
501
|
-
|
|
502
|
-
|
|
714
|
+
if (chunk.byteLength > 0) {
|
|
715
|
+
this.chunks.push(Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength));
|
|
716
|
+
this.buffered += chunk.byteLength;
|
|
717
|
+
}
|
|
718
|
+
try {
|
|
719
|
+
this.flushPendingReads();
|
|
720
|
+
} catch (error) {
|
|
721
|
+
this.close(error instanceof Error ? error : new Error(String(error)));
|
|
722
|
+
}
|
|
503
723
|
}
|
|
504
724
|
readFrame() {
|
|
505
725
|
const frame = this.tryReadFrame();
|
|
@@ -525,7 +745,9 @@ var FrameReader = class {
|
|
|
525
745
|
close(error = /* @__PURE__ */ new Error("frame reader closed")) {
|
|
526
746
|
if (this.closedError !== null) return;
|
|
527
747
|
this.closedError = error;
|
|
528
|
-
|
|
748
|
+
try {
|
|
749
|
+
this.flushPendingReads();
|
|
750
|
+
} catch {}
|
|
529
751
|
while (this.pendingReads.length > 0) this.pendingReads.shift()?.reject(error);
|
|
530
752
|
}
|
|
531
753
|
flushPendingReads() {
|
|
@@ -536,8 +758,8 @@ var FrameReader = class {
|
|
|
536
758
|
}
|
|
537
759
|
}
|
|
538
760
|
tryReadFrame() {
|
|
539
|
-
if (this.
|
|
540
|
-
const length = this.
|
|
761
|
+
if (this.buffered < 4) return null;
|
|
762
|
+
const length = this.peekLength();
|
|
541
763
|
if (length === 0) {
|
|
542
764
|
const error = /* @__PURE__ */ new Error("frame length cannot be zero");
|
|
543
765
|
this.close(error);
|
|
@@ -548,10 +770,59 @@ var FrameReader = class {
|
|
|
548
770
|
this.close(error);
|
|
549
771
|
throw error;
|
|
550
772
|
}
|
|
551
|
-
if (this.
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
773
|
+
if (this.buffered < 4 + length) return null;
|
|
774
|
+
return decodeFrame(this.take(4 + length));
|
|
775
|
+
}
|
|
776
|
+
/**
|
|
777
|
+
* The frame's `u32` length prefix, which the socket may have split across
|
|
778
|
+
* chunks — a 4-byte field arriving in two reads is rare but perfectly legal,
|
|
779
|
+
* and reading it out of the head chunk alone would silently misread it.
|
|
780
|
+
*/
|
|
781
|
+
peekLength() {
|
|
782
|
+
const first = this.chunks[0];
|
|
783
|
+
if (first !== void 0 && first.byteLength >= 4) return first.readUInt32BE(0);
|
|
784
|
+
let value = 0;
|
|
785
|
+
let seen = 0;
|
|
786
|
+
for (const chunk of this.chunks) {
|
|
787
|
+
for (let i = 0; i < chunk.byteLength && seen < 4; i++, seen++) value = value * 256 + chunk[i];
|
|
788
|
+
if (seen === 4) break;
|
|
789
|
+
}
|
|
790
|
+
return value;
|
|
791
|
+
}
|
|
792
|
+
/**
|
|
793
|
+
* Remove and return the first `n` buffered bytes. The caller has already
|
|
794
|
+
* established that `n` bytes are there.
|
|
795
|
+
* @param n how many bytes to take, frame length prefix included
|
|
796
|
+
*/
|
|
797
|
+
take(n) {
|
|
798
|
+
const first = this.chunks[0];
|
|
799
|
+
if (first.byteLength === n) {
|
|
800
|
+
this.chunks.shift();
|
|
801
|
+
this.buffered -= n;
|
|
802
|
+
return first;
|
|
803
|
+
}
|
|
804
|
+
if (first.byteLength > n) {
|
|
805
|
+
this.chunks[0] = first.subarray(n);
|
|
806
|
+
this.buffered -= n;
|
|
807
|
+
return first.subarray(0, n);
|
|
808
|
+
}
|
|
809
|
+
const out = Buffer.allocUnsafe(n);
|
|
810
|
+
let offset = 0;
|
|
811
|
+
while (offset < n) {
|
|
812
|
+
const chunk = this.chunks[0];
|
|
813
|
+
const needed = n - offset;
|
|
814
|
+
if (chunk.byteLength <= needed) {
|
|
815
|
+
chunk.copy(out, offset);
|
|
816
|
+
offset += chunk.byteLength;
|
|
817
|
+
this.chunks.shift();
|
|
818
|
+
} else {
|
|
819
|
+
chunk.copy(out, offset, 0, needed);
|
|
820
|
+
this.chunks[0] = chunk.subarray(needed);
|
|
821
|
+
offset = n;
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
this.buffered -= n;
|
|
825
|
+
return out;
|
|
555
826
|
}
|
|
556
827
|
};
|
|
557
828
|
function encodeFrame(messageType, payload, maxFrameLength = DEFAULT_MAX_FRAME_LENGTH) {
|
|
@@ -582,15 +853,42 @@ function decodeFrame(bytes, maxFrameLength = DEFAULT_MAX_FRAME_LENGTH) {
|
|
|
582
853
|
function encodeTsToRustFrame(messageType, payload) {
|
|
583
854
|
return encodeFrame(messageType, payload);
|
|
584
855
|
}
|
|
856
|
+
/**
|
|
857
|
+
* Encode an `Authenticate` payload per `docs/protocol.md` §5.1:
|
|
858
|
+
* `u16 protocolVersion`, then `u32 probeLength + probe bytes`, then
|
|
859
|
+
* `u32 tokenLength + descriptor token bytes` (exactly 16).
|
|
860
|
+
* @param auth
|
|
861
|
+
*/
|
|
585
862
|
function encodeAuthenticatePayload(auth) {
|
|
586
863
|
if (!Number.isInteger(auth.protocolVersion)) throw new Error("protocolVersion must be an integer");
|
|
587
864
|
if (auth.protocolVersion < 0 || auth.protocolVersion > 65535) throw new Error(`protocolVersion out of u16 range: ${auth.protocolVersion}`);
|
|
588
|
-
|
|
589
|
-
const
|
|
865
|
+
if (auth.descriptorToken.byteLength !== 16) throw new Error(`descriptor token must be exactly 16 bytes, got ${auth.descriptorToken.byteLength}`);
|
|
866
|
+
const token = auth.descriptorToken;
|
|
867
|
+
const payload = Buffer.allocUnsafe(6 + auth.probe.byteLength + 4 + token.byteLength);
|
|
590
868
|
payload.writeUInt16BE(auth.protocolVersion, 0);
|
|
591
|
-
|
|
869
|
+
payload.writeUInt32BE(auth.probe.byteLength, 2);
|
|
870
|
+
Buffer.from(auth.probe.buffer, auth.probe.byteOffset, auth.probe.byteLength).copy(payload, 6);
|
|
871
|
+
const tokenStart = 6 + auth.probe.byteLength;
|
|
872
|
+
payload.writeUInt32BE(token.byteLength, tokenStart);
|
|
873
|
+
Buffer.from(token.buffer, token.byteOffset, token.byteLength).copy(payload, tokenStart + 4);
|
|
592
874
|
return payload;
|
|
593
875
|
}
|
|
876
|
+
function decodeHelloPayload(payload) {
|
|
877
|
+
const view = Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength);
|
|
878
|
+
if (view.byteLength < 5) throw new Error("payload too short for Hello");
|
|
879
|
+
const status = view.readUInt8(0);
|
|
880
|
+
const probeLength = view.readUInt32BE(1);
|
|
881
|
+
if (view.byteLength < 5 + probeLength + 4) throw new Error("Hello payload truncated (probe)");
|
|
882
|
+
const probe = view.subarray(5, 5 + probeLength);
|
|
883
|
+
const messageLength = view.readUInt32BE(5 + probeLength);
|
|
884
|
+
const messageStart = 5 + probeLength + 4;
|
|
885
|
+
if (view.byteLength < messageStart + messageLength) throw new Error("Hello payload truncated (message)");
|
|
886
|
+
return {
|
|
887
|
+
status,
|
|
888
|
+
probe,
|
|
889
|
+
message: view.subarray(messageStart, messageStart + messageLength).toString("utf8")
|
|
890
|
+
};
|
|
891
|
+
}
|
|
594
892
|
/**
|
|
595
893
|
* Wire tag for each `GlobalDefPayload` kind. Mirrors `HostGlobalDef` on the
|
|
596
894
|
* Rust side (`ipc.rs`).
|
|
@@ -625,6 +923,23 @@ var PayloadWriter = class {
|
|
|
625
923
|
this.parts.push(Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength));
|
|
626
924
|
return this;
|
|
627
925
|
}
|
|
926
|
+
/**
|
|
927
|
+
* Write a value slot: `u32 byteLength` + the V8 serialization blob.
|
|
928
|
+
* The single encoding for every value crossing the boundary — there is no
|
|
929
|
+
* tag byte because there is only one codec (`docs/protocol.md` §4).
|
|
930
|
+
* @param value
|
|
931
|
+
*/
|
|
932
|
+
writeValueBlob(value) {
|
|
933
|
+
return this.writeLengthPrefixedBytes(serializeValue(value));
|
|
934
|
+
}
|
|
935
|
+
/**
|
|
936
|
+
* Write an already-serialized value slot: `u32 byteLength` + blob bytes.
|
|
937
|
+
* @param blob
|
|
938
|
+
*/
|
|
939
|
+
writeLengthPrefixedBytes(blob) {
|
|
940
|
+
this.writeU32(blob.byteLength);
|
|
941
|
+
return this.writeBytes(blob);
|
|
942
|
+
}
|
|
628
943
|
writeOptionalString(s) {
|
|
629
944
|
if (s === void 0) this.writeU8(0);
|
|
630
945
|
else {
|
|
@@ -646,13 +961,14 @@ var PayloadWriter = class {
|
|
|
646
961
|
for (const def of defs) {
|
|
647
962
|
this.writeU8(GLOBAL_DEF_KIND[def.kind]);
|
|
648
963
|
this.writeString(def.name);
|
|
964
|
+
this.writeU8(def.enumerable ?? true ? 1 : 0);
|
|
649
965
|
switch (def.kind) {
|
|
650
966
|
case "bridge": break;
|
|
651
967
|
case "string":
|
|
652
968
|
this.writeString(def.expr);
|
|
653
969
|
break;
|
|
654
970
|
case "data":
|
|
655
|
-
this.
|
|
971
|
+
this.writeValueBlob(def.value);
|
|
656
972
|
break;
|
|
657
973
|
case "shim":
|
|
658
974
|
this.writeString(def.shim);
|
|
@@ -687,7 +1003,7 @@ var PayloadWriter = class {
|
|
|
687
1003
|
break;
|
|
688
1004
|
case "data":
|
|
689
1005
|
this.writeU8(1);
|
|
690
|
-
this.
|
|
1006
|
+
this.writeValueBlob(node.value);
|
|
691
1007
|
break;
|
|
692
1008
|
case "object":
|
|
693
1009
|
this.writeU8(2);
|
|
@@ -700,27 +1016,135 @@ var PayloadWriter = class {
|
|
|
700
1016
|
}
|
|
701
1017
|
return this;
|
|
702
1018
|
}
|
|
703
|
-
writeImportRebinds(rebinds) {
|
|
704
|
-
this.writeU32(rebinds.length);
|
|
705
|
-
for (const rebind of rebinds) {
|
|
706
|
-
this.writeString(rebind.specifier);
|
|
707
|
-
this.writeString(rebind.path);
|
|
708
|
-
}
|
|
709
|
-
return this;
|
|
1019
|
+
writeImportRebinds(rebinds) {
|
|
1020
|
+
this.writeU32(rebinds.length);
|
|
1021
|
+
for (const rebind of rebinds) {
|
|
1022
|
+
this.writeString(rebind.specifier);
|
|
1023
|
+
this.writeString(rebind.path);
|
|
1024
|
+
}
|
|
1025
|
+
return this;
|
|
1026
|
+
}
|
|
1027
|
+
writeOptionalCall(call) {
|
|
1028
|
+
if (call === void 0) this.writeU8(0);
|
|
1029
|
+
else {
|
|
1030
|
+
this.writeU8(1);
|
|
1031
|
+
this.writeString(call.exportPath);
|
|
1032
|
+
this.writeLengthPrefixedBytes(call.argsBlob);
|
|
1033
|
+
}
|
|
1034
|
+
return this;
|
|
1035
|
+
}
|
|
1036
|
+
writeResourceLimits(limits) {
|
|
1037
|
+
this.writeOptionalU32(limits.memoryMb);
|
|
1038
|
+
this.writeOptionalU32(limits.cpuTimeMs);
|
|
1039
|
+
this.writeOptionalU32(limits.wallTimeMs);
|
|
1040
|
+
this.writeOptionalU32(limits.maxExportBytes);
|
|
1041
|
+
this.writeOptionalU32(limits.maxStdoutBytes);
|
|
1042
|
+
this.writeOptionalU32(limits.maxStderrBytes);
|
|
1043
|
+
this.writeOptionalU32(limits.maxBridgeCallBytes);
|
|
1044
|
+
this.writeOptionalU32(limits.maxBridgeCalls);
|
|
1045
|
+
this.writeOptionalU32(limits.graceMs);
|
|
1046
|
+
this.writeOptionalU32(limits.hardMemoryMb);
|
|
1047
|
+
return this;
|
|
1048
|
+
}
|
|
1049
|
+
toBuffer() {
|
|
1050
|
+
return Buffer.concat(this.parts);
|
|
1051
|
+
}
|
|
1052
|
+
};
|
|
1053
|
+
/**
|
|
1054
|
+
* Raised when a frame payload cannot be decoded: truncated data, an invalid
|
|
1055
|
+
* presence byte, trailing bytes, or a value blob that does not hold the shape
|
|
1056
|
+
* the slot promises. Internal — never surfaces through the public API.
|
|
1057
|
+
*/
|
|
1058
|
+
var PayloadDecodeError = class extends Error {
|
|
1059
|
+
name = "PayloadDecodeError";
|
|
1060
|
+
};
|
|
1061
|
+
/**
|
|
1062
|
+
* Stateful cursor over a frame payload — the mirror of `PayloadReader` in
|
|
1063
|
+
* `ipc.rs`. Every read advances the offset; out-of-bounds reads throw
|
|
1064
|
+
* immediately so callers never see partial state.
|
|
1065
|
+
*/
|
|
1066
|
+
var PayloadReader = class {
|
|
1067
|
+
view;
|
|
1068
|
+
offset = 0;
|
|
1069
|
+
constructor(buf) {
|
|
1070
|
+
this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
1071
|
+
}
|
|
1072
|
+
get remaining() {
|
|
1073
|
+
return this.view.byteLength - this.offset;
|
|
1074
|
+
}
|
|
1075
|
+
readU8() {
|
|
1076
|
+
if (this.remaining < 1) throw new PayloadDecodeError("unexpected end of payload reading u8");
|
|
1077
|
+
return this.view.getUint8(this.offset++);
|
|
1078
|
+
}
|
|
1079
|
+
readU32() {
|
|
1080
|
+
if (this.remaining < 4) throw new PayloadDecodeError("unexpected end of payload reading u32");
|
|
1081
|
+
const n = this.view.getUint32(this.offset, false);
|
|
1082
|
+
this.offset += 4;
|
|
1083
|
+
return n;
|
|
1084
|
+
}
|
|
1085
|
+
readF64() {
|
|
1086
|
+
if (this.remaining < 8) throw new PayloadDecodeError("unexpected end of payload reading f64");
|
|
1087
|
+
const n = this.view.getFloat64(this.offset, false);
|
|
1088
|
+
this.offset += 8;
|
|
1089
|
+
return n;
|
|
1090
|
+
}
|
|
1091
|
+
/**
|
|
1092
|
+
* Read a `u64` (8 big-endian bytes) as a JS number — the u64s on the
|
|
1093
|
+
* wire are byte counts (heap, budget, RSS), far below 2^53. A value
|
|
1094
|
+
* above that is not a real byte count but frame corruption or
|
|
1095
|
+
* misalignment; failing loudly beats returning a silently rounded
|
|
1096
|
+
* number.
|
|
1097
|
+
*/
|
|
1098
|
+
readU64() {
|
|
1099
|
+
if (this.remaining < 8) throw new PayloadDecodeError("unexpected end of payload reading u64");
|
|
1100
|
+
const n = this.view.getBigUint64(this.offset, false);
|
|
1101
|
+
this.offset += 8;
|
|
1102
|
+
if (n > BigInt(Number.MAX_SAFE_INTEGER)) throw new PayloadDecodeError(`u64 exceeds the JS safe-integer range: ${n}`);
|
|
1103
|
+
return Number(n);
|
|
1104
|
+
}
|
|
1105
|
+
/**
|
|
1106
|
+
* Read an `Optional<u64>`: a presence byte, then 8 big-endian bytes.
|
|
1107
|
+
* Returned as a JS number — the only u64 on the wire is a heap byte count,
|
|
1108
|
+
* far below 2^53.
|
|
1109
|
+
*/
|
|
1110
|
+
readOptionalU64() {
|
|
1111
|
+
if (this.readU8() === 0) return void 0;
|
|
1112
|
+
return this.readU64();
|
|
710
1113
|
}
|
|
711
|
-
|
|
712
|
-
this.
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
this.writeOptionalU32(limits.maxExportBytes);
|
|
716
|
-
this.writeOptionalU32(limits.maxStdoutBytes);
|
|
717
|
-
this.writeOptionalU32(limits.maxStderrBytes);
|
|
718
|
-
this.writeOptionalU32(limits.maxBridgeCallBytes);
|
|
719
|
-
this.writeOptionalU32(limits.maxBridgeCalls);
|
|
720
|
-
return this;
|
|
1114
|
+
readBool() {
|
|
1115
|
+
const b = this.readU8();
|
|
1116
|
+
if (b !== 0 && b !== 1) throw new PayloadDecodeError(`invalid bool byte: 0x${b.toString(16).padStart(2, "0")}`);
|
|
1117
|
+
return b === 1;
|
|
721
1118
|
}
|
|
722
|
-
|
|
723
|
-
|
|
1119
|
+
readRawBytes(len) {
|
|
1120
|
+
if (this.remaining < len) throw new PayloadDecodeError(`unexpected end of payload: need ${len} bytes, have ${this.remaining}`);
|
|
1121
|
+
const slice = new Uint8Array(this.view.buffer, this.view.byteOffset + this.offset, len);
|
|
1122
|
+
this.offset += len;
|
|
1123
|
+
return slice;
|
|
1124
|
+
}
|
|
1125
|
+
readString() {
|
|
1126
|
+
return Buffer.from(this.readRawBytes(this.readU32())).toString("utf8");
|
|
1127
|
+
}
|
|
1128
|
+
readStringList() {
|
|
1129
|
+
const count = this.readU32();
|
|
1130
|
+
const items = [];
|
|
1131
|
+
for (let i = 0; i < count; i++) items.push(this.readString());
|
|
1132
|
+
return items;
|
|
1133
|
+
}
|
|
1134
|
+
/**
|
|
1135
|
+
* Read a value slot: `u32 byteLength` + V8 serialization blob.
|
|
1136
|
+
*/
|
|
1137
|
+
readValueBlob() {
|
|
1138
|
+
return deserializeValue(this.readRawBytes(this.readU32()));
|
|
1139
|
+
}
|
|
1140
|
+
/**
|
|
1141
|
+
* Read an `Optional<value slot>`: a presence byte, then the slot when set.
|
|
1142
|
+
*/
|
|
1143
|
+
readOptionalValueBlob() {
|
|
1144
|
+
return this.readU8() === 1 ? this.readValueBlob() : void 0;
|
|
1145
|
+
}
|
|
1146
|
+
assertDone() {
|
|
1147
|
+
if (this.remaining !== 0) throw new PayloadDecodeError(`${this.remaining} trailing bytes after expected end of payload`);
|
|
724
1148
|
}
|
|
725
1149
|
};
|
|
726
1150
|
/**
|
|
@@ -728,7 +1152,7 @@ var PayloadWriter = class {
|
|
|
728
1152
|
* @param options
|
|
729
1153
|
*/
|
|
730
1154
|
function encodeRunPayload(options) {
|
|
731
|
-
return new PayloadWriter().writeU32(options.runId).writeString(options.code).writeOptionalString(options.filename).writeResourceLimits(options.limits ?? {}).writeGlobalDefs(options.globals ?? []).writeImports(options.imports ?? []).toBuffer();
|
|
1155
|
+
return new PayloadWriter().writeU32(options.runId).writeString(options.code).writeOptionalString(options.filename).writeResourceLimits(options.limits ?? {}).writeGlobalDefs(options.globals ?? []).writeImports(options.imports ?? []).writeOptionalCall(options.call).toBuffer();
|
|
732
1156
|
}
|
|
733
1157
|
/**
|
|
734
1158
|
* Encode a `PrecompilePayload` per `docs/protocol.md` §5.2.
|
|
@@ -736,7 +1160,7 @@ function encodeRunPayload(options) {
|
|
|
736
1160
|
* @param options
|
|
737
1161
|
*/
|
|
738
1162
|
function encodePrecompilePayload(options) {
|
|
739
|
-
return new PayloadWriter().writeString(options.code).writeOptionalString(options.filename).writeResourceLimits(options.limits ?? {}).writeGlobalDefs(options.globals ?? []).writeImports(options.imports ?? []).toBuffer();
|
|
1163
|
+
return new PayloadWriter().writeU32(options.requestId).writeString(options.code).writeOptionalString(options.filename).writeResourceLimits(options.limits ?? {}).writeGlobalDefs(options.globals ?? []).writeImports(options.imports ?? []).toBuffer();
|
|
740
1164
|
}
|
|
741
1165
|
/**
|
|
742
1166
|
* Encode a `PrefixRunPayload` per `docs/protocol.md` §5.2.
|
|
@@ -745,7 +1169,8 @@ function encodePrecompilePayload(options) {
|
|
|
745
1169
|
* @param options
|
|
746
1170
|
*/
|
|
747
1171
|
function encodePrefixRunPayload(options) {
|
|
748
|
-
|
|
1172
|
+
if (options.code === void 0 === (options.call === void 0)) throw new Error("[iso4] PrefixRun must carry exactly one of code or call");
|
|
1173
|
+
return new PayloadWriter().writeU32(options.runId).writeString(options.prefixId).writeOptionalString(options.code).writeOptionalString(options.filename).writeResourceLimits(options.limits ?? {}).writeGlobalDefs(options.globals ?? []).writeImportRebinds(options.importRebinds ?? []).writeOptionalCall(options.call).toBuffer();
|
|
749
1174
|
}
|
|
750
1175
|
/**
|
|
751
1176
|
* Encode a `DisposePrefix` payload — just the PrefixId string.
|
|
@@ -755,62 +1180,69 @@ function encodeDisposePrefixPayload(prefixId) {
|
|
|
755
1180
|
return new PayloadWriter().writeString(prefixId).toBuffer();
|
|
756
1181
|
}
|
|
757
1182
|
/**
|
|
758
|
-
* Encode a `Terminate` payload
|
|
759
|
-
*
|
|
760
|
-
*
|
|
1183
|
+
* Encode a `Terminate` payload: the RunId (u32) of the run to stop plus a
|
|
1184
|
+
* mode byte. Soft (`0`, the default abort) abandons the run at its next
|
|
1185
|
+
* turn boundary — nothing is interrupted mid-execution, the instance
|
|
1186
|
+
* survives. Hard (`1`, opt-in via `hardAbortSignal`) interrupts executing
|
|
1187
|
+
* JS immediately; landing mid-turn costs the instance (see client.ts).
|
|
761
1188
|
* @param runId
|
|
1189
|
+
* @param hard
|
|
762
1190
|
*/
|
|
763
|
-
function encodeTerminatePayload(runId) {
|
|
764
|
-
return new PayloadWriter().writeU32(runId).toBuffer();
|
|
1191
|
+
function encodeTerminatePayload(runId, hard) {
|
|
1192
|
+
return new PayloadWriter().writeU32(runId).writeU8(hard ? 1 : 0).toBuffer();
|
|
765
1193
|
}
|
|
766
1194
|
/**
|
|
767
1195
|
* Decode a `BridgeCallPayload` from a `BridgeCall` frame sent by Rust.
|
|
768
1196
|
* Per `docs/protocol.md` §5.4.
|
|
1197
|
+
*
|
|
1198
|
+
* The whole argument list crosses as **one** value blob holding an array —
|
|
1199
|
+
* serializing N arguments together is measurably cheaper than N blobs, and it
|
|
1200
|
+
* preserves identity between arguments that reference the same object.
|
|
1201
|
+
* @param buf
|
|
1202
|
+
*/
|
|
1203
|
+
/**
|
|
1204
|
+
* Read just the `callId` off a `BridgeCall` frame payload.
|
|
1205
|
+
*
|
|
1206
|
+
* `callId` is the first field, ahead of the guest-controlled value blob, so it
|
|
1207
|
+
* is still recoverable when {@link decodeBridgeCallPayload} throws on the args.
|
|
1208
|
+
* That lets the client answer a call it could not decode instead of stranding
|
|
1209
|
+
* the peer on a response that never comes.
|
|
1210
|
+
*
|
|
1211
|
+
* Returns `undefined` only when the payload is too short to carry one.
|
|
1212
|
+
* @param buf
|
|
1213
|
+
*/
|
|
1214
|
+
function peekBridgeCallId(buf) {
|
|
1215
|
+
if (buf.byteLength < 8) return void 0;
|
|
1216
|
+
return (buf[4] << 24 | buf[5] << 16 | buf[6] << 8 | buf[7]) >>> 0;
|
|
1217
|
+
}
|
|
1218
|
+
/**
|
|
1219
|
+
* Read just the `runId` off a `BridgeCall` frame payload — the leading
|
|
1220
|
+
* field, recoverable even when the args blob fails to decode, so the error
|
|
1221
|
+
* response can echo the right run for demux routing.
|
|
769
1222
|
* @param buf
|
|
770
1223
|
*/
|
|
1224
|
+
function peekBridgeCallRunId(buf) {
|
|
1225
|
+
if (buf.byteLength < 4) return void 0;
|
|
1226
|
+
return (buf[0] << 24 | buf[1] << 16 | buf[2] << 8 | buf[3]) >>> 0;
|
|
1227
|
+
}
|
|
771
1228
|
function decodeBridgeCallPayload(buf) {
|
|
772
|
-
const
|
|
773
|
-
|
|
774
|
-
const
|
|
775
|
-
|
|
776
|
-
return view.readUInt8(offset++);
|
|
777
|
-
};
|
|
778
|
-
const readU32 = () => {
|
|
779
|
-
if (offset + 4 > view.byteLength) throw new Error("BridgeCall payload truncated (u32)");
|
|
780
|
-
const n = view.readUInt32BE(offset);
|
|
781
|
-
offset += 4;
|
|
782
|
-
return n;
|
|
783
|
-
};
|
|
784
|
-
const readString = () => {
|
|
785
|
-
const len = readU32();
|
|
786
|
-
if (offset + len > view.byteLength) throw new Error("BridgeCall payload truncated (string)");
|
|
787
|
-
const s = view.subarray(offset, offset + len).toString("utf8");
|
|
788
|
-
offset += len;
|
|
789
|
-
return s;
|
|
790
|
-
};
|
|
791
|
-
const readWireValue = () => {
|
|
792
|
-
const [value, consumed] = decodeWireValueFromSlice(new Uint8Array(view.buffer, view.byteOffset + offset, view.byteLength - offset));
|
|
793
|
-
offset += consumed;
|
|
794
|
-
return [value, consumed];
|
|
795
|
-
};
|
|
796
|
-
const callId = readU32();
|
|
797
|
-
const targetKindRaw = readU8();
|
|
1229
|
+
const reader = new PayloadReader(buf);
|
|
1230
|
+
const runId = reader.readU32();
|
|
1231
|
+
const callId = reader.readU32();
|
|
1232
|
+
const targetKindRaw = reader.readU8();
|
|
798
1233
|
if (targetKindRaw !== 0 && targetKindRaw !== 1) throw new Error(`invalid bridge targetKind: ${targetKindRaw}`);
|
|
799
1234
|
const targetKind = targetKindRaw;
|
|
800
|
-
const specifier = readU8() === 1 ? readString() : void 0;
|
|
801
|
-
const exportName = readString();
|
|
802
|
-
const
|
|
803
|
-
|
|
804
|
-
for (let i = 0; i < argCount; i++) {
|
|
805
|
-
const [value] = readWireValue();
|
|
806
|
-
args.push(value);
|
|
807
|
-
}
|
|
1235
|
+
const specifier = reader.readU8() === 1 ? reader.readString() : void 0;
|
|
1236
|
+
const exportName = reader.readString();
|
|
1237
|
+
const decoded = reader.readValueBlob();
|
|
1238
|
+
if (!Array.isArray(decoded)) throw new PayloadDecodeError(`BridgeCall args must decode to an array, got ${decoded === null ? "null" : typeof decoded}`);
|
|
808
1239
|
return {
|
|
1240
|
+
runId,
|
|
809
1241
|
callId,
|
|
810
1242
|
targetKind,
|
|
811
1243
|
specifier,
|
|
812
1244
|
exportName,
|
|
813
|
-
args
|
|
1245
|
+
args: decoded
|
|
814
1246
|
};
|
|
815
1247
|
}
|
|
816
1248
|
/**
|
|
@@ -818,8 +1250,8 @@ function decodeBridgeCallPayload(buf) {
|
|
|
818
1250
|
*
|
|
819
1251
|
* Own-enumerable properties beyond `name`/`message`/`stack` travel as
|
|
820
1252
|
* `fields` and reappear as direct own properties on the sandbox-side Error;
|
|
821
|
-
* properties
|
|
822
|
-
*
|
|
1253
|
+
* properties V8 refuses to clone (functions, symbols, …) are silently
|
|
1254
|
+
* dropped, mirroring the sandbox → host direction (`RunError.fields`).
|
|
823
1255
|
* @param err
|
|
824
1256
|
*/
|
|
825
1257
|
function bridgeErrorPayloadFromUnknown(err) {
|
|
@@ -837,7 +1269,7 @@ function bridgeErrorPayloadFromUnknown(err) {
|
|
|
837
1269
|
if (key === "name" || key === "message" || key === "stack") continue;
|
|
838
1270
|
try {
|
|
839
1271
|
const value = obj[key];
|
|
840
|
-
|
|
1272
|
+
serializeValue(value);
|
|
841
1273
|
fields[key] = value;
|
|
842
1274
|
hasFields = true;
|
|
843
1275
|
} catch {
|
|
@@ -851,54 +1283,536 @@ function bridgeErrorPayloadFromUnknown(err) {
|
|
|
851
1283
|
return {
|
|
852
1284
|
name,
|
|
853
1285
|
message,
|
|
854
|
-
encodedFields:
|
|
1286
|
+
encodedFields: serializeValue(fields)
|
|
855
1287
|
};
|
|
856
1288
|
} catch {
|
|
857
1289
|
return {
|
|
858
|
-
name: "Error",
|
|
859
|
-
message: "host handler failed"
|
|
1290
|
+
name: "Error",
|
|
1291
|
+
message: "host handler failed"
|
|
1292
|
+
};
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
/**
|
|
1296
|
+
* Encode a `BridgeResponsePayload` per `docs/protocol.md` §5.4.
|
|
1297
|
+
*
|
|
1298
|
+
* When `ok = true`, `encodedValue` holds the pre-serialized value blob.
|
|
1299
|
+
* When `ok = false`, `error` describes the handler rejection. The stack slot
|
|
1300
|
+
* is always written as absent — host stacks must not leak into the sandbox.
|
|
1301
|
+
* @param runId
|
|
1302
|
+
* @param callId
|
|
1303
|
+
* @param ok
|
|
1304
|
+
* @param encodedValue
|
|
1305
|
+
* @param error the handler rejection, when `ok = false`
|
|
1306
|
+
*/
|
|
1307
|
+
function encodeBridgeResponsePayload(runId, callId, ok, encodedValue, error) {
|
|
1308
|
+
const w = new PayloadWriter();
|
|
1309
|
+
w.writeU32(runId);
|
|
1310
|
+
w.writeU32(callId);
|
|
1311
|
+
if (ok) {
|
|
1312
|
+
w.writeU8(1);
|
|
1313
|
+
if (encodedValue !== void 0 && encodedValue.byteLength > 0) {
|
|
1314
|
+
w.writeU8(1);
|
|
1315
|
+
w.writeLengthPrefixedBytes(encodedValue);
|
|
1316
|
+
} else w.writeU8(0);
|
|
1317
|
+
} else {
|
|
1318
|
+
w.writeU8(0);
|
|
1319
|
+
w.writeString("ERR_HOST_BRIDGE");
|
|
1320
|
+
w.writeString(error?.name ?? "Error");
|
|
1321
|
+
w.writeString(error?.message ?? "host handler failed");
|
|
1322
|
+
w.writeU8(0);
|
|
1323
|
+
if (error?.encodedFields !== void 0 && error.encodedFields.byteLength > 0) {
|
|
1324
|
+
w.writeU8(1);
|
|
1325
|
+
w.writeLengthPrefixedBytes(error.encodedFields);
|
|
1326
|
+
} else w.writeU8(0);
|
|
1327
|
+
}
|
|
1328
|
+
return w.toBuffer();
|
|
1329
|
+
}
|
|
1330
|
+
/**
|
|
1331
|
+
* Decode a `RunComplete` frame payload.
|
|
1332
|
+
* @param buf the frame payload
|
|
1333
|
+
*/
|
|
1334
|
+
function decodeRunCompletePayload(buf) {
|
|
1335
|
+
const reader = new PayloadReader(buf);
|
|
1336
|
+
const runId = reader.readU32();
|
|
1337
|
+
const statusByte = reader.readU8();
|
|
1338
|
+
const status = [
|
|
1339
|
+
"settled",
|
|
1340
|
+
"truncated",
|
|
1341
|
+
"failed"
|
|
1342
|
+
][statusByte];
|
|
1343
|
+
if (status === void 0) throw new PayloadDecodeError(`unknown RunComplete status byte: ${statusByte}`);
|
|
1344
|
+
const durationMs = reader.readF64();
|
|
1345
|
+
const wallTimeMs = reader.readF64();
|
|
1346
|
+
const cpuTimeMs = reader.readF64();
|
|
1347
|
+
const stdout = reader.readStringList();
|
|
1348
|
+
const stderr = reader.readStringList();
|
|
1349
|
+
const bridgeCalls = readBridgeCallRecords(reader);
|
|
1350
|
+
const error = reader.readU8() === 1 ? {
|
|
1351
|
+
name: reader.readString(),
|
|
1352
|
+
message: reader.readString()
|
|
1353
|
+
} : void 0;
|
|
1354
|
+
reader.assertDone();
|
|
1355
|
+
const decoded = {
|
|
1356
|
+
runId,
|
|
1357
|
+
status,
|
|
1358
|
+
durationMs,
|
|
1359
|
+
wallTimeMs,
|
|
1360
|
+
cpuTimeMs,
|
|
1361
|
+
stdout,
|
|
1362
|
+
stderr,
|
|
1363
|
+
bridgeCalls
|
|
1364
|
+
};
|
|
1365
|
+
if (error !== void 0) decoded.error = error;
|
|
1366
|
+
return decoded;
|
|
1367
|
+
}
|
|
1368
|
+
/**
|
|
1369
|
+
* Streaming bodies — wire constants mirroring `ipc.rs`.
|
|
1370
|
+
*/
|
|
1371
|
+
const STREAM_CHUNK_MAX_BYTES = 64 * 1024;
|
|
1372
|
+
const STREAM_CREDIT_WINDOW_BYTES = 256 * 1024;
|
|
1373
|
+
/**
|
|
1374
|
+
* Bodies that end within this many bytes take the buffered path unchanged;
|
|
1375
|
+
* larger ones stream. Host-side policy, not wire contract.
|
|
1376
|
+
*/
|
|
1377
|
+
const STREAM_PROBE_BYTES = 64 * 1024;
|
|
1378
|
+
/**
|
|
1379
|
+
* Encode a `StreamChunk` payload: `u32 runId, u32 streamId, Bytes data`.
|
|
1380
|
+
* @param runId the run the stream belongs to
|
|
1381
|
+
* @param streamId the stream
|
|
1382
|
+
* @param data at most {@link STREAM_CHUNK_MAX_BYTES} bytes
|
|
1383
|
+
*/
|
|
1384
|
+
function encodeStreamChunkPayload(runId, streamId, data) {
|
|
1385
|
+
const out = Buffer.allocUnsafe(12 + data.byteLength);
|
|
1386
|
+
out.writeUInt32BE(runId, 0);
|
|
1387
|
+
out.writeUInt32BE(streamId, 4);
|
|
1388
|
+
out.writeUInt32BE(data.byteLength, 8);
|
|
1389
|
+
Buffer.from(data.buffer, data.byteOffset, data.byteLength).copy(out, 12);
|
|
1390
|
+
return out;
|
|
1391
|
+
}
|
|
1392
|
+
/**
|
|
1393
|
+
* Encode a `StreamEnd` payload: `u32 runId, u32 streamId, bool ok,
|
|
1394
|
+
* Optional<String> error` (only when `ok = false`).
|
|
1395
|
+
* @param runId the run
|
|
1396
|
+
* @param streamId the stream
|
|
1397
|
+
* @param error present = the source failed with this message
|
|
1398
|
+
*/
|
|
1399
|
+
function encodeStreamEndPayload(runId, streamId, error) {
|
|
1400
|
+
const writer = new PayloadWriter();
|
|
1401
|
+
writer.writeU32(runId);
|
|
1402
|
+
writer.writeU32(streamId);
|
|
1403
|
+
writer.writeU8(error === void 0 ? 1 : 0);
|
|
1404
|
+
if (error !== void 0) {
|
|
1405
|
+
writer.writeU8(1);
|
|
1406
|
+
writer.writeString(error);
|
|
1407
|
+
}
|
|
1408
|
+
return Buffer.concat(writer.parts);
|
|
1409
|
+
}
|
|
1410
|
+
/**
|
|
1411
|
+
* Decode a `StreamPull` payload: `u32 runId, u32 streamId, u32 credit`.
|
|
1412
|
+
* @param payload the frame payload
|
|
1413
|
+
*/
|
|
1414
|
+
function decodeStreamPullPayload(payload) {
|
|
1415
|
+
const reader = new PayloadReader(payload);
|
|
1416
|
+
const runId = reader.readU32();
|
|
1417
|
+
const streamId = reader.readU32();
|
|
1418
|
+
const credit = reader.readU32();
|
|
1419
|
+
reader.assertDone();
|
|
1420
|
+
return {
|
|
1421
|
+
runId,
|
|
1422
|
+
streamId,
|
|
1423
|
+
credit
|
|
1424
|
+
};
|
|
1425
|
+
}
|
|
1426
|
+
/**
|
|
1427
|
+
* Decode a `StreamCancel` payload: `u32 runId, u32 streamId, String reason`.
|
|
1428
|
+
* @param payload the frame payload
|
|
1429
|
+
*/
|
|
1430
|
+
function decodeStreamCancelPayload(payload) {
|
|
1431
|
+
const reader = new PayloadReader(payload);
|
|
1432
|
+
const runId = reader.readU32();
|
|
1433
|
+
const streamId = reader.readU32();
|
|
1434
|
+
const reason = reader.readString();
|
|
1435
|
+
reader.assertDone();
|
|
1436
|
+
return {
|
|
1437
|
+
runId,
|
|
1438
|
+
streamId,
|
|
1439
|
+
reason
|
|
1440
|
+
};
|
|
1441
|
+
}
|
|
1442
|
+
/**
|
|
1443
|
+
* Decode a `StreamChunk` payload (outbound direction — runtime → host):
|
|
1444
|
+
* `u32 runId, u32 streamId, Bytes data`.
|
|
1445
|
+
* @param payload the frame payload
|
|
1446
|
+
*/
|
|
1447
|
+
function decodeStreamChunkPayload(payload) {
|
|
1448
|
+
const reader = new PayloadReader(payload);
|
|
1449
|
+
const runId = reader.readU32();
|
|
1450
|
+
const streamId = reader.readU32();
|
|
1451
|
+
const data = reader.readRawBytes(reader.readU32());
|
|
1452
|
+
reader.assertDone();
|
|
1453
|
+
return {
|
|
1454
|
+
runId,
|
|
1455
|
+
streamId,
|
|
1456
|
+
data
|
|
1457
|
+
};
|
|
1458
|
+
}
|
|
1459
|
+
/**
|
|
1460
|
+
* Decode a `StreamEnd` payload (outbound direction): `u32 runId,
|
|
1461
|
+
* u32 streamId, bool ok, Optional<String> error`.
|
|
1462
|
+
* @param payload the frame payload
|
|
1463
|
+
*/
|
|
1464
|
+
function decodeStreamEndPayload(payload) {
|
|
1465
|
+
const reader = new PayloadReader(payload);
|
|
1466
|
+
const runId = reader.readU32();
|
|
1467
|
+
const streamId = reader.readU32();
|
|
1468
|
+
const ok = reader.readU8() === 1;
|
|
1469
|
+
let error;
|
|
1470
|
+
if (!ok) error = reader.readU8() === 1 ? reader.readString() : "the sandbox body source failed";
|
|
1471
|
+
reader.assertDone();
|
|
1472
|
+
const out = {
|
|
1473
|
+
runId,
|
|
1474
|
+
streamId
|
|
1475
|
+
};
|
|
1476
|
+
if (error !== void 0) out.error = error;
|
|
1477
|
+
return out;
|
|
1478
|
+
}
|
|
1479
|
+
/**
|
|
1480
|
+
* Encode a `StreamPull` payload for an outbound stream: `u32 runId,
|
|
1481
|
+
* u32 streamId, u32 credit` — the consumer read `credit` bytes, the runtime
|
|
1482
|
+
* may send that many more.
|
|
1483
|
+
* @param runId the run
|
|
1484
|
+
* @param streamId the stream
|
|
1485
|
+
* @param credit consumed byte count
|
|
1486
|
+
*/
|
|
1487
|
+
function encodeStreamPullPayload(runId, streamId, credit) {
|
|
1488
|
+
const writer = new PayloadWriter();
|
|
1489
|
+
writer.writeU32(runId);
|
|
1490
|
+
writer.writeU32(streamId);
|
|
1491
|
+
writer.writeU32(credit);
|
|
1492
|
+
return Buffer.concat(writer.parts);
|
|
1493
|
+
}
|
|
1494
|
+
/**
|
|
1495
|
+
* Encode a `StreamCancel` payload for an outbound stream: `u32 runId,
|
|
1496
|
+
* u32 streamId, String reason` — the consumer dropped the body.
|
|
1497
|
+
* @param runId the run
|
|
1498
|
+
* @param streamId the stream
|
|
1499
|
+
* @param reason forwarded to the guest source's cancel path
|
|
1500
|
+
*/
|
|
1501
|
+
function encodeStreamCancelPayload(runId, streamId, reason) {
|
|
1502
|
+
const writer = new PayloadWriter();
|
|
1503
|
+
writer.writeU32(runId);
|
|
1504
|
+
writer.writeU32(streamId);
|
|
1505
|
+
writer.writeString(reason);
|
|
1506
|
+
return Buffer.concat(writer.parts);
|
|
1507
|
+
}
|
|
1508
|
+
/**
|
|
1509
|
+
* Read just the post-Result flags byte off a `Result` frame payload,
|
|
1510
|
+
* without decoding the rest: bit 0 = `waitUntil` work pending, bit 1 =
|
|
1511
|
+
* outbound stream bodies open; nonzero = a `RunComplete` frame follows.
|
|
1512
|
+
* Both encoders write strict layouts with no trailing bytes, so on a
|
|
1513
|
+
* success payload the byte is second-to-last (followed only by the
|
|
1514
|
+
* `failurePresent = 0` byte); failures never carry post-Result work.
|
|
1515
|
+
* @param payload the raw Result frame payload
|
|
1516
|
+
*/
|
|
1517
|
+
function peekRunCompletionBackgroundFlags(payload) {
|
|
1518
|
+
if (payload.byteLength < 7) return 0;
|
|
1519
|
+
return payload[4] === 1 ? payload[payload.byteLength - 2] : 0;
|
|
1520
|
+
}
|
|
1521
|
+
/**
|
|
1522
|
+
* Read just the `runId` off a `Result` frame payload, without decoding the rest.
|
|
1523
|
+
*
|
|
1524
|
+
* The client correlates every `Result` against the `runId` it sent before it
|
|
1525
|
+
* accepts the frame as its own, so this runs on a payload that may belong to a
|
|
1526
|
+
* different run entirely — decoding the value blob first would be both wasted
|
|
1527
|
+
* work and a chance for another run's bytes to throw. `runId` is the first
|
|
1528
|
+
* field of the layout documented on {@link decodeRunCompletionPayload}.
|
|
1529
|
+
*
|
|
1530
|
+
* Returns `undefined` when the payload is too short to carry one, which is
|
|
1531
|
+
* itself a desync rather than a run this client can claim.
|
|
1532
|
+
* @param buf
|
|
1533
|
+
*/
|
|
1534
|
+
function peekRunCompletionRunId(buf) {
|
|
1535
|
+
if (buf.byteLength < 4) return void 0;
|
|
1536
|
+
return (buf[0] << 24 | buf[1] << 16 | buf[2] << 8 | buf[3]) >>> 0;
|
|
1537
|
+
}
|
|
1538
|
+
function decodeRunCompletionPayload(buf, resultKind) {
|
|
1539
|
+
const reader = new PayloadReader(buf);
|
|
1540
|
+
const runId = reader.readU32();
|
|
1541
|
+
if (reader.readBool()) {
|
|
1542
|
+
if (reader.readU8() !== 1) throw new PayloadDecodeError("expected success present byte = 1 when ok = true");
|
|
1543
|
+
const valueRaw = reader.readValueBlob();
|
|
1544
|
+
const skippedExports = reader.readStringList();
|
|
1545
|
+
const stdout = reader.readStringList();
|
|
1546
|
+
const stderr = reader.readStringList();
|
|
1547
|
+
const durationMs = reader.readF64();
|
|
1548
|
+
const wallTimeMs = reader.readF64();
|
|
1549
|
+
const cpuTimeMs = reader.readF64();
|
|
1550
|
+
const bridgeCalls = readBridgeCallRecords(reader);
|
|
1551
|
+
const heapUsedBytes = reader.readOptionalU64();
|
|
1552
|
+
const backgroundFlags = reader.readU8();
|
|
1553
|
+
reader.readU8();
|
|
1554
|
+
reader.assertDone();
|
|
1555
|
+
if (resultKind === "call") return {
|
|
1556
|
+
runId,
|
|
1557
|
+
backgroundFlags,
|
|
1558
|
+
result: {
|
|
1559
|
+
status: "completed",
|
|
1560
|
+
ok: true,
|
|
1561
|
+
value: valueRaw,
|
|
1562
|
+
stdout,
|
|
1563
|
+
stderr,
|
|
1564
|
+
durationMs,
|
|
1565
|
+
wallTimeMs,
|
|
1566
|
+
cpuTimeMs,
|
|
1567
|
+
bridgeCalls,
|
|
1568
|
+
heapUsedBytes
|
|
1569
|
+
}
|
|
1570
|
+
};
|
|
1571
|
+
return {
|
|
1572
|
+
runId,
|
|
1573
|
+
backgroundFlags,
|
|
1574
|
+
result: {
|
|
1575
|
+
status: "completed",
|
|
1576
|
+
ok: true,
|
|
1577
|
+
exports: exportsBlobToExports(valueRaw),
|
|
1578
|
+
skippedExports,
|
|
1579
|
+
stdout,
|
|
1580
|
+
stderr,
|
|
1581
|
+
durationMs,
|
|
1582
|
+
wallTimeMs,
|
|
1583
|
+
cpuTimeMs,
|
|
1584
|
+
bridgeCalls,
|
|
1585
|
+
heapUsedBytes
|
|
1586
|
+
}
|
|
1587
|
+
};
|
|
1588
|
+
}
|
|
1589
|
+
reader.readU8();
|
|
1590
|
+
if (reader.readU8() !== 1) throw new PayloadDecodeError("expected failure present byte = 1 when ok = false");
|
|
1591
|
+
const code = reader.readString();
|
|
1592
|
+
const name = reader.readString();
|
|
1593
|
+
const message = reader.readString();
|
|
1594
|
+
const stack = reader.readU8() === 1 ? reader.readString() : void 0;
|
|
1595
|
+
const fields = reader.readOptionalValueBlob();
|
|
1596
|
+
const reset = readResetInfo(reader);
|
|
1597
|
+
const stdout = reader.readStringList();
|
|
1598
|
+
const stderr = reader.readStringList();
|
|
1599
|
+
const durationMs = reader.readF64();
|
|
1600
|
+
const wallTimeMs = reader.readF64();
|
|
1601
|
+
const cpuTimeMs = reader.readF64();
|
|
1602
|
+
const bridgeCalls = readBridgeCallRecords(reader);
|
|
1603
|
+
const heapUsedBytes = reader.readOptionalU64();
|
|
1604
|
+
reader.assertDone();
|
|
1605
|
+
return {
|
|
1606
|
+
runId,
|
|
1607
|
+
backgroundFlags: 0,
|
|
1608
|
+
result: {
|
|
1609
|
+
status: "failed",
|
|
1610
|
+
ok: false,
|
|
1611
|
+
error: {
|
|
1612
|
+
code,
|
|
1613
|
+
name,
|
|
1614
|
+
message,
|
|
1615
|
+
stack,
|
|
1616
|
+
fields,
|
|
1617
|
+
...reset
|
|
1618
|
+
},
|
|
1619
|
+
stdout,
|
|
1620
|
+
stderr,
|
|
1621
|
+
durationMs,
|
|
1622
|
+
wallTimeMs,
|
|
1623
|
+
cpuTimeMs,
|
|
1624
|
+
bridgeCalls,
|
|
1625
|
+
heapUsedBytes
|
|
1626
|
+
}
|
|
1627
|
+
};
|
|
1628
|
+
}
|
|
1629
|
+
/**
|
|
1630
|
+
* The `ERR_INSTANCE_RESET` extras trailing every `RunErrorPayload`: an
|
|
1631
|
+
* optional cause class + culprit run id, present only on that code. Returned
|
|
1632
|
+
* as a spreadable fragment so plain errors add nothing to the error object.
|
|
1633
|
+
* @param reader
|
|
1634
|
+
*/
|
|
1635
|
+
function readResetInfo(reader) {
|
|
1636
|
+
const present = reader.readU8();
|
|
1637
|
+
if (present === 0) return void 0;
|
|
1638
|
+
if (present !== 1) throw new PayloadDecodeError(`invalid reset-info presence byte: ${present}`);
|
|
1639
|
+
const causeByte = reader.readU8();
|
|
1640
|
+
const resetCause = [
|
|
1641
|
+
"cpu",
|
|
1642
|
+
"memory",
|
|
1643
|
+
"abort",
|
|
1644
|
+
"internal",
|
|
1645
|
+
"wall"
|
|
1646
|
+
][causeByte];
|
|
1647
|
+
if (resetCause === void 0) throw new PayloadDecodeError(`invalid instance-reset cause byte: ${causeByte}`);
|
|
1648
|
+
return {
|
|
1649
|
+
resetCause,
|
|
1650
|
+
culpritRunId: reader.readU32()
|
|
1651
|
+
};
|
|
1652
|
+
}
|
|
1653
|
+
/**
|
|
1654
|
+
* Decode `List<BridgeCallRecord>` per `docs/protocol.md` §5.6. Names arrive
|
|
1655
|
+
* already resolved — the runtime owns the import handle table and the shim
|
|
1656
|
+
* naming convention, so no client-side mapping remains.
|
|
1657
|
+
* @param reader
|
|
1658
|
+
*/
|
|
1659
|
+
function readBridgeCallRecords(reader) {
|
|
1660
|
+
const count = reader.readU32();
|
|
1661
|
+
const entries = [];
|
|
1662
|
+
for (let i = 0; i < count; i++) {
|
|
1663
|
+
const name = reader.readString();
|
|
1664
|
+
const startMs = reader.readF64();
|
|
1665
|
+
const durationMs = reader.readF64();
|
|
1666
|
+
const argBytes = reader.readU32();
|
|
1667
|
+
const responseBytes = reader.readU32();
|
|
1668
|
+
const ok = reader.readBool();
|
|
1669
|
+
const blocked = reader.readBool();
|
|
1670
|
+
entries.push({
|
|
1671
|
+
name,
|
|
1672
|
+
startMs,
|
|
1673
|
+
durationMs,
|
|
1674
|
+
argBytes,
|
|
1675
|
+
responseBytes,
|
|
1676
|
+
ok,
|
|
1677
|
+
blocked
|
|
1678
|
+
});
|
|
1679
|
+
}
|
|
1680
|
+
return entries;
|
|
1681
|
+
}
|
|
1682
|
+
function exportsBlobToExports(raw) {
|
|
1683
|
+
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) throw new PayloadDecodeError(`exports must decode to an object, got: ${Array.isArray(raw) ? "array" : typeof raw}`);
|
|
1684
|
+
return raw;
|
|
1685
|
+
}
|
|
1686
|
+
/**
|
|
1687
|
+
* The leading `u32 requestId` of a `PrecompileResult` payload — how the
|
|
1688
|
+
* router matches a reply to its in-flight `precompile()` (replies can
|
|
1689
|
+
* return out of request order; see `PrecompilePayloadOptions.requestId`).
|
|
1690
|
+
* `undefined` when the payload is too short to carry one.
|
|
1691
|
+
* @param buf
|
|
1692
|
+
*/
|
|
1693
|
+
function peekPrecompileResultRequestId(buf) {
|
|
1694
|
+
if (buf.byteLength < 4) return void 0;
|
|
1695
|
+
return Buffer.from(buf.buffer, buf.byteOffset, 4).readUInt32BE(0);
|
|
1696
|
+
}
|
|
1697
|
+
/**
|
|
1698
|
+
* Decode a `PrecompileResultPayload` from a `PrecompileResult` frame.
|
|
1699
|
+
*
|
|
1700
|
+
* Wire layout per `docs/protocol.md` §5.7:
|
|
1701
|
+
* ```
|
|
1702
|
+
* u32 requestId (echo of the Precompile's)
|
|
1703
|
+
* u8 ok
|
|
1704
|
+
* u8 prefixIdPresent (1 when ok = true)
|
|
1705
|
+
* String prefixId
|
|
1706
|
+
* u8 errorPresent (1 when ok = false)
|
|
1707
|
+
* RunErrorPayload error
|
|
1708
|
+
* ```
|
|
1709
|
+
* @param buf
|
|
1710
|
+
*/
|
|
1711
|
+
function decodePrecompileResultPayload(buf) {
|
|
1712
|
+
const reader = new PayloadReader(buf);
|
|
1713
|
+
const requestId = reader.readU32();
|
|
1714
|
+
if (reader.readBool()) {
|
|
1715
|
+
if (reader.readU8() !== 1) throw new PayloadDecodeError("expected prefixId present byte = 1 when ok = true");
|
|
1716
|
+
const prefixId = reader.readString();
|
|
1717
|
+
reader.readU8();
|
|
1718
|
+
reader.assertDone();
|
|
1719
|
+
return {
|
|
1720
|
+
ok: true,
|
|
1721
|
+
requestId,
|
|
1722
|
+
prefixId
|
|
860
1723
|
};
|
|
861
1724
|
}
|
|
1725
|
+
reader.readU8();
|
|
1726
|
+
if (reader.readU8() !== 1) throw new PayloadDecodeError("expected error present byte = 1 when ok = false");
|
|
1727
|
+
const code = reader.readString();
|
|
1728
|
+
const name = reader.readString();
|
|
1729
|
+
const message = reader.readString();
|
|
1730
|
+
const stack = reader.readU8() === 1 ? reader.readString() : void 0;
|
|
1731
|
+
reader.readOptionalValueBlob();
|
|
1732
|
+
readResetInfo(reader);
|
|
1733
|
+
reader.assertDone();
|
|
1734
|
+
return {
|
|
1735
|
+
ok: false,
|
|
1736
|
+
requestId,
|
|
1737
|
+
error: {
|
|
1738
|
+
code,
|
|
1739
|
+
name,
|
|
1740
|
+
message,
|
|
1741
|
+
stack
|
|
1742
|
+
}
|
|
1743
|
+
};
|
|
862
1744
|
}
|
|
863
1745
|
/**
|
|
864
|
-
*
|
|
1746
|
+
* Decode a `StatsPayload` from a `StatsResult` frame.
|
|
865
1747
|
*
|
|
866
|
-
*
|
|
867
|
-
*
|
|
868
|
-
*
|
|
869
|
-
*
|
|
870
|
-
*
|
|
871
|
-
*
|
|
872
|
-
*
|
|
1748
|
+
* Wire layout per `docs/protocol.md` §5.7:
|
|
1749
|
+
* ```
|
|
1750
|
+
* u32 oneoffRunning
|
|
1751
|
+
* u32 warmBusy
|
|
1752
|
+
* u32 warmIdle
|
|
1753
|
+
* u64 idleHeapBytes
|
|
1754
|
+
* u64 warmBudgetBytes
|
|
1755
|
+
* u64 rssBytes
|
|
1756
|
+
* u8 underPressure
|
|
1757
|
+
* u32 prefixCount, then per prefix:
|
|
1758
|
+
* String prefixId
|
|
1759
|
+
* u32 idle
|
|
1760
|
+
* u32 busy
|
|
1761
|
+
* ```
|
|
1762
|
+
* @param buf the `StatsResult` frame payload
|
|
873
1763
|
*/
|
|
874
|
-
function
|
|
875
|
-
const
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
1764
|
+
function decodeStatsPayload(buf) {
|
|
1765
|
+
const reader = new PayloadReader(buf);
|
|
1766
|
+
const oneoffRunning = reader.readU32();
|
|
1767
|
+
const warmBusy = reader.readU32();
|
|
1768
|
+
const warmRuns = reader.readU32();
|
|
1769
|
+
const warmIdle = reader.readU32();
|
|
1770
|
+
const idleHeapBytes = reader.readU64();
|
|
1771
|
+
const warmBudgetBytes = reader.readU64();
|
|
1772
|
+
const rssBytes = reader.readU64();
|
|
1773
|
+
const usageBytes = reader.readU64();
|
|
1774
|
+
const hardLineBytes = reader.readU64();
|
|
1775
|
+
const underPressure = reader.readBool();
|
|
1776
|
+
const prefixCount = reader.readU32();
|
|
1777
|
+
const prefixes = [];
|
|
1778
|
+
for (let i = 0; i < prefixCount; i++) {
|
|
1779
|
+
const prefixId = reader.readString();
|
|
1780
|
+
const idle = reader.readU32();
|
|
1781
|
+
const busy = reader.readU32();
|
|
1782
|
+
prefixes.push({
|
|
1783
|
+
prefixId,
|
|
1784
|
+
idle,
|
|
1785
|
+
busy
|
|
1786
|
+
});
|
|
893
1787
|
}
|
|
894
|
-
|
|
1788
|
+
reader.assertDone();
|
|
1789
|
+
return {
|
|
1790
|
+
oneoffRunning,
|
|
1791
|
+
warmBusy,
|
|
1792
|
+
warmRuns,
|
|
1793
|
+
warmIdle,
|
|
1794
|
+
idleHeapBytes,
|
|
1795
|
+
warmBudgetBytes,
|
|
1796
|
+
rssBytes,
|
|
1797
|
+
usageBytes,
|
|
1798
|
+
hardLineBytes,
|
|
1799
|
+
underPressure,
|
|
1800
|
+
prefixes
|
|
1801
|
+
};
|
|
895
1802
|
}
|
|
896
1803
|
function parseRustToTsMessageType(byte) {
|
|
897
1804
|
switch (byte) {
|
|
898
1805
|
case RustToTsMessageTypes.BridgeCall:
|
|
899
1806
|
case RustToTsMessageTypes.Result:
|
|
900
1807
|
case RustToTsMessageTypes.PrecompileResult:
|
|
901
|
-
case RustToTsMessageTypes.Log:
|
|
1808
|
+
case RustToTsMessageTypes.Log:
|
|
1809
|
+
case RustToTsMessageTypes.Hello:
|
|
1810
|
+
case RustToTsMessageTypes.StatsResult:
|
|
1811
|
+
case RustToTsMessageTypes.RunComplete:
|
|
1812
|
+
case RustToTsMessageTypes.StreamPull:
|
|
1813
|
+
case RustToTsMessageTypes.StreamCancel:
|
|
1814
|
+
case RustToTsMessageTypes.StreamChunk:
|
|
1815
|
+
case RustToTsMessageTypes.StreamEnd: return byte;
|
|
902
1816
|
default: throw new Error(`unknown Rust->TS message type: ${formatByte(byte)}`);
|
|
903
1817
|
}
|
|
904
1818
|
}
|
|
@@ -919,16 +1833,17 @@ function importHandlerKey(specifier, path) {
|
|
|
919
1833
|
}
|
|
920
1834
|
/**
|
|
921
1835
|
* Thrown when the host's import configuration is structurally invalid in a
|
|
922
|
-
* way only the client can see
|
|
923
|
-
*
|
|
924
|
-
* `
|
|
925
|
-
* for
|
|
1836
|
+
* way only the client can see. `PrefixImpl.run` converts it into a failed
|
|
1837
|
+
* `RunResult` carrying `code`: `ERR_FROZEN_BINDING` for a rebind of a frozen
|
|
1838
|
+
* location (a source module), `ERR_INVALID_REBIND` for a non-function rebind
|
|
1839
|
+
* value. Matches the runtime-side enforcement for locations only Rust can see.
|
|
926
1840
|
*/
|
|
927
|
-
var
|
|
928
|
-
code
|
|
929
|
-
constructor(message) {
|
|
1841
|
+
var ImportRebindError = class extends Error {
|
|
1842
|
+
code;
|
|
1843
|
+
constructor(code, message) {
|
|
930
1844
|
super(message);
|
|
931
|
-
this.name = "
|
|
1845
|
+
this.name = "ImportRebindError";
|
|
1846
|
+
this.code = code;
|
|
932
1847
|
}
|
|
933
1848
|
};
|
|
934
1849
|
function processImports(imports) {
|
|
@@ -990,52 +1905,12 @@ function lowerNode(specifier, value, path, handlers, seen = /* @__PURE__ */ new
|
|
|
990
1905
|
entries
|
|
991
1906
|
};
|
|
992
1907
|
}
|
|
993
|
-
validateDataLeaf(specifier, value, path);
|
|
994
1908
|
return {
|
|
995
1909
|
kind: "data",
|
|
996
1910
|
value
|
|
997
1911
|
};
|
|
998
1912
|
}
|
|
999
1913
|
/**
|
|
1000
|
-
* Validate a `HostExportData` value. Supports primitives, plain
|
|
1001
|
-
* objects/arrays, `BigInt`, `Uint8Array` — the same set the wire codec can
|
|
1002
|
-
* carry back out of the sandbox. `Date`, `Map`, `Set`, circular refs, and
|
|
1003
|
-
* class instances throw with a clear pointer.
|
|
1004
|
-
*
|
|
1005
|
-
* @param specifier
|
|
1006
|
-
* @param value
|
|
1007
|
-
* @param path
|
|
1008
|
-
* @param seen
|
|
1009
|
-
*/
|
|
1010
|
-
function validateDataLeaf(specifier, value, path, seen = /* @__PURE__ */ new Set()) {
|
|
1011
|
-
if (value === null || value === void 0) return;
|
|
1012
|
-
switch (typeof value) {
|
|
1013
|
-
case "boolean":
|
|
1014
|
-
case "number":
|
|
1015
|
-
case "bigint":
|
|
1016
|
-
case "string": return;
|
|
1017
|
-
}
|
|
1018
|
-
if (value instanceof Uint8Array) return;
|
|
1019
|
-
if (value instanceof Date || value instanceof Map || value instanceof Set) throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: ${value.constructor.name} values are not supported as data leaves; supported: primitives, bigint, string, Uint8Array, plain objects/arrays`);
|
|
1020
|
-
if (typeof value === "object") {
|
|
1021
|
-
if (seen.has(value)) throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: circular references in data leaves are not supported`);
|
|
1022
|
-
seen.add(value);
|
|
1023
|
-
if (Array.isArray(value)) {
|
|
1024
|
-
value.forEach((item, i) => {
|
|
1025
|
-
validateDataLeaf(specifier, item, [...path, String(i)], seen);
|
|
1026
|
-
});
|
|
1027
|
-
seen.delete(value);
|
|
1028
|
-
return;
|
|
1029
|
-
}
|
|
1030
|
-
const proto = Object.getPrototypeOf(value);
|
|
1031
|
-
if (proto !== null && proto !== Object.prototype) throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: class instances are not supported as data leaves; copy the data into a plain object explicitly`);
|
|
1032
|
-
for (const [key, child] of Object.entries(value)) validateDataLeaf(specifier, child, [...path, key], seen);
|
|
1033
|
-
seen.delete(value);
|
|
1034
|
-
return;
|
|
1035
|
-
}
|
|
1036
|
-
throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: unsupported data value of type ${describeKind(value)}`);
|
|
1037
|
-
}
|
|
1038
|
-
/**
|
|
1039
1914
|
* Merge the handlers behind a `Prefix`'s host-module function leaves with the
|
|
1040
1915
|
* run's overrides and collect the rebind locations to send on the wire.
|
|
1041
1916
|
*
|
|
@@ -1043,7 +1918,8 @@ function validateDataLeaf(specifier, value, path, seen = /* @__PURE__ */ new Set
|
|
|
1043
1918
|
* modules are frozen; a non-function leaf value — there is nothing to
|
|
1044
1919
|
* dispatch to). Whether each location was actually declared as a function
|
|
1045
1920
|
* leaf at precompile time is enforced by the Rust runtime against the stored
|
|
1046
|
-
* prefix shape
|
|
1921
|
+
* prefix shape (`ERR_UNDECLARED_BINDING` for undeclared locations,
|
|
1922
|
+
* `ERR_FROZEN_BINDING` for frozen ones).
|
|
1047
1923
|
*
|
|
1048
1924
|
* @param runImports
|
|
1049
1925
|
* @param defaults handler map captured at precompile time
|
|
@@ -1056,7 +1932,7 @@ function mergeRebindImports(runImports, defaults) {
|
|
|
1056
1932
|
const handlers = new Map(defaults);
|
|
1057
1933
|
const rebinds = [];
|
|
1058
1934
|
for (const [specifier, value] of Object.entries(runImports)) {
|
|
1059
|
-
if (typeof value === "string") throw new
|
|
1935
|
+
if (typeof value === "string") throw new ImportRebindError("ERR_FROZEN_BINDING", `import '${specifier}' is a source module — source imports are frozen with the prefix and cannot be rebound at prefix.run() time`);
|
|
1060
1936
|
if (!isPlainObject(value)) throw new Error(`[@iso4/sandbox] imports['${specifier}'] override must be a plain object; got ${describeKind(value)}`);
|
|
1061
1937
|
walkRebind(specifier, value, [], handlers, rebinds);
|
|
1062
1938
|
}
|
|
@@ -1082,14 +1958,12 @@ function walkRebind(specifier, node, path, handlers, rebinds) {
|
|
|
1082
1958
|
walkRebind(specifier, value, newPath, handlers, rebinds);
|
|
1083
1959
|
continue;
|
|
1084
1960
|
}
|
|
1085
|
-
throw new
|
|
1961
|
+
throw new ImportRebindError("ERR_INVALID_REBIND", `import '${specifier}'.${newPath.join(".")} can only be rebound with a function; got ${describeKind(value)}`);
|
|
1086
1962
|
}
|
|
1087
1963
|
}
|
|
1088
1964
|
function isPlainObject(value) {
|
|
1089
1965
|
if (value === null || typeof value !== "object") return false;
|
|
1090
1966
|
if (Array.isArray(value)) return false;
|
|
1091
|
-
if (value instanceof Uint8Array || value instanceof Date) return false;
|
|
1092
|
-
if (value instanceof Map || value instanceof Set) return false;
|
|
1093
1967
|
const proto = Object.getPrototypeOf(value);
|
|
1094
1968
|
return proto === null || proto === Object.prototype;
|
|
1095
1969
|
}
|
|
@@ -1162,25 +2036,53 @@ function describeKind(value) {
|
|
|
1162
2036
|
//#endregion
|
|
1163
2037
|
//#region src/client.ts
|
|
1164
2038
|
/**
|
|
1165
|
-
* How long TS waits for Rust's
|
|
1166
|
-
* `Terminate
|
|
2039
|
+
* How long TS waits for Rust's `ERR_ABORTED` Result after sending a HARD
|
|
2040
|
+
* `Terminate`, before falling back to tearing the connection down.
|
|
1167
2041
|
*
|
|
1168
|
-
*
|
|
1169
|
-
*
|
|
1170
|
-
*
|
|
1171
|
-
*
|
|
1172
|
-
*
|
|
2042
|
+
* Hard aborts always answer promptly (a suspended run is abandoned on the
|
|
2043
|
+
* spot, executing JS is interrupted mid-turn), so no answer within this
|
|
2044
|
+
* window means the runtime cannot answer at all (wedged process). SOFT
|
|
2045
|
+
* aborts arm no fallback: a run spinning with no `cpuTimeMs` cap
|
|
2046
|
+
* legitimately cannot answer one until its own limits end the turn, and
|
|
2047
|
+
* tearing the connection down for that would fail every co-resident run of
|
|
2048
|
+
* a healthy runtime.
|
|
1173
2049
|
*/
|
|
1174
2050
|
const TERMINATE_GRACE_MS = 100;
|
|
1175
2051
|
/**
|
|
1176
|
-
*
|
|
1177
|
-
*
|
|
1178
|
-
*
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
*
|
|
1183
|
-
*
|
|
2052
|
+
* How long `connect()` waits for the runtime's `Hello` frame before giving up.
|
|
2053
|
+
* The runtime answers a handshake without touching V8 (the probe is computed
|
|
2054
|
+
* once at process start), so this only bites when the binary is wedged.
|
|
2055
|
+
*/
|
|
2056
|
+
const HELLO_TIMEOUT_MS = 5e3;
|
|
2057
|
+
/**
|
|
2058
|
+
* Shared placeholder for `RunEntry` callbacks between wiring phases —
|
|
2059
|
+
* allocating fresh `() => {}` closures per run is avoidable hot-path churn.
|
|
2060
|
+
*/
|
|
2061
|
+
function NOOP() {}
|
|
2062
|
+
/**
|
|
2063
|
+
* Thrown out of `createSandbox()` when the connection handshake fails.
|
|
2064
|
+
*
|
|
2065
|
+
* The common cause is a V8 serialization format-version mismatch between this
|
|
2066
|
+
* Node and the `@iso4/v8-*` binary: values cross the boundary as V8
|
|
2067
|
+
* serialization blobs, so the two V8s must agree on the format. Internal —
|
|
2068
|
+
* `@iso4/sandbox` does not export this type; it reaches callers as a plain
|
|
2069
|
+
* `Error` with `name = 'Iso4HandshakeError'`.
|
|
2070
|
+
*/
|
|
2071
|
+
var HandshakeError = class extends Error {
|
|
2072
|
+
constructor(message) {
|
|
2073
|
+
super(`[@iso4/sandbox] ${message}`);
|
|
2074
|
+
this.name = "Iso4HandshakeError";
|
|
2075
|
+
}
|
|
2076
|
+
};
|
|
2077
|
+
/**
|
|
2078
|
+
* Thrown out of a run when a hard abort did not produce a Result within
|
|
2079
|
+
* {@link TERMINATE_GRACE_MS} (or when the pre-run abort race tears down
|
|
2080
|
+
* before the run settles). The
|
|
2081
|
+
* connection is torn down (so the Rust isolate is reclaimed) before this
|
|
2082
|
+
* propagates, and the client is marked unusable so the pool replaces it rather
|
|
2083
|
+
* than reusing a half-dead slot. `index.ts` catches this and synthesizes the
|
|
2084
|
+
* `ERR_ABORTED` `RunResult`. When the graceful path succeeds instead, no error
|
|
2085
|
+
* is thrown — the real `ERR_ABORTED` Result flows back through the router.
|
|
1184
2086
|
*/
|
|
1185
2087
|
var RunAbortedError = class extends Error {
|
|
1186
2088
|
/**
|
|
@@ -1193,94 +2095,366 @@ var RunAbortedError = class extends Error {
|
|
|
1193
2095
|
this.reason = reason;
|
|
1194
2096
|
}
|
|
1195
2097
|
};
|
|
2098
|
+
/**
|
|
2099
|
+
* Thrown when a frame arrives that cannot belong to any run in flight on this
|
|
2100
|
+
* connection: a `Result` or `RunComplete` carrying a run id nothing here is
|
|
2101
|
+
* waiting on, or a frame type with no place in the protocol. Either way the
|
|
2102
|
+
* two sides have lost agreement about what this connection is doing, so
|
|
2103
|
+
* nothing it delivers from now on can be attributed with confidence.
|
|
2104
|
+
*
|
|
2105
|
+
* The connection is torn down before this propagates — every run in flight on
|
|
2106
|
+
* it fails with this error — because a peer that is mid-run on someone else's
|
|
2107
|
+
* frames must never be handed to the next caller. `index.ts` catches this and
|
|
2108
|
+
* synthesizes the `ERR_PROTOCOL_DESYNC` `RunResult` — a displaced run never
|
|
2109
|
+
* executed, so there is no partial telemetry to report.
|
|
2110
|
+
*/
|
|
2111
|
+
var ProtocolDesyncError = class extends Error {
|
|
2112
|
+
constructor(message) {
|
|
2113
|
+
super(`[@iso4/sandbox] ${message}`);
|
|
2114
|
+
this.name = "Iso4ProtocolDesyncError";
|
|
2115
|
+
}
|
|
2116
|
+
};
|
|
1196
2117
|
var RuntimeIpcClient = class RuntimeIpcClient {
|
|
1197
2118
|
socket;
|
|
1198
2119
|
reader;
|
|
1199
2120
|
disposed = false;
|
|
1200
2121
|
/**
|
|
1201
|
-
* Set when
|
|
1202
|
-
* must not be returned to the pool's
|
|
1203
|
-
* checks `usable` and
|
|
2122
|
+
* Set when this connection was torn down (abort fallback, desync, peer
|
|
2123
|
+
* close). A broken client must not be returned to the pool's idle list —
|
|
2124
|
+
* the connection registry checks `usable` and drops it instead.
|
|
1204
2125
|
*/
|
|
1205
2126
|
broken = false;
|
|
1206
|
-
|
|
2127
|
+
/**
|
|
2128
|
+
* Runs in flight on this connection, keyed by run id — the router's only
|
|
2129
|
+
* routing table. Several runs share one connection; every frame finds its
|
|
2130
|
+
* owner by run id alone.
|
|
2131
|
+
*/
|
|
2132
|
+
runs = /* @__PURE__ */ new Map();
|
|
2133
|
+
/**
|
|
2134
|
+
* Everything routed on this connection that a connection-level failure
|
|
2135
|
+
* would take down: runs (executing AND grace-phase — an entry lives until
|
|
2136
|
+
* its final frame) plus in-flight control requests. The pool's
|
|
2137
|
+
* per-connection cap reads this, so the blast-radius bound covers all of
|
|
2138
|
+
* it. Both counts move synchronously from the call that adds them
|
|
2139
|
+
* (`runRawCode`/`prefixRun`/`precompile`), which keeps the pool's
|
|
2140
|
+
* same-tick load observation exact.
|
|
2141
|
+
*/
|
|
2142
|
+
get load() {
|
|
2143
|
+
return this.runs.size + this.precompileWaiters.size + this.controlWaiters.length;
|
|
2144
|
+
}
|
|
2145
|
+
/**
|
|
2146
|
+
* Pending `stats()` requests, FIFO — sound because the runtime answers
|
|
2147
|
+
* `Stats` inline in its demux loop, so replies come back in request
|
|
2148
|
+
* order. See {@link ControlWaiter}.
|
|
2149
|
+
*/
|
|
2150
|
+
controlWaiters = [];
|
|
2151
|
+
/**
|
|
2152
|
+
* Pending `precompile()` requests keyed by their wire `requestId`.
|
|
2153
|
+
* Precompiles are answered on runtime worker threads, so with several in
|
|
2154
|
+
* flight on one connection the replies can return out of request order —
|
|
2155
|
+
* FIFO matching would cross-assign prefix ids between callers.
|
|
2156
|
+
*/
|
|
2157
|
+
precompileWaiters = /* @__PURE__ */ new Map();
|
|
2158
|
+
/**
|
|
2159
|
+
* Session brand key for host-type descriptors written on this connection.
|
|
2160
|
+
*/
|
|
2161
|
+
brandKey;
|
|
2162
|
+
constructor(socket, brandKey) {
|
|
1207
2163
|
this.socket = socket;
|
|
2164
|
+
this.brandKey = brandKey;
|
|
1208
2165
|
this.reader = new FrameReader();
|
|
1209
2166
|
socket.on("data", (chunk) => {
|
|
1210
2167
|
this.reader.push(chunk);
|
|
1211
2168
|
});
|
|
1212
2169
|
socket.once("error", (error) => {
|
|
2170
|
+
this.broken = true;
|
|
1213
2171
|
this.reader.close(error);
|
|
1214
2172
|
});
|
|
1215
2173
|
socket.once("end", () => {
|
|
2174
|
+
this.broken = true;
|
|
1216
2175
|
this.reader.close(/* @__PURE__ */ new Error("socket ended"));
|
|
1217
2176
|
});
|
|
1218
2177
|
socket.once("close", () => {
|
|
2178
|
+
this.broken = true;
|
|
1219
2179
|
this.reader.close(/* @__PURE__ */ new Error("socket closed"));
|
|
1220
2180
|
});
|
|
1221
2181
|
}
|
|
1222
2182
|
/**
|
|
1223
2183
|
* A client is usable while its connection is intact. Once an in-flight abort
|
|
1224
|
-
* (or a dispose) tears the socket down it becomes unusable and
|
|
1225
|
-
* replace it.
|
|
2184
|
+
* (or a dispose, or a desync) tears the socket down it becomes unusable and
|
|
2185
|
+
* the pool must replace it.
|
|
2186
|
+
*
|
|
2187
|
+
* The socket is consulted directly as well as the `broken` flag: a socket can
|
|
2188
|
+
* be destroyed without either handler above having run yet (a synchronous
|
|
2189
|
+
* `destroy()` earlier in the same tick), and a recycled dead connection fails
|
|
2190
|
+
* every future run drawn from that slot.
|
|
1226
2191
|
*/
|
|
1227
2192
|
get usable() {
|
|
1228
|
-
return !this.disposed && !this.broken;
|
|
2193
|
+
return !this.disposed && !this.broken && !this.socket.destroyed && !this.socket.closed;
|
|
1229
2194
|
}
|
|
2195
|
+
/**
|
|
2196
|
+
* Open a connection and complete the handshake.
|
|
2197
|
+
*
|
|
2198
|
+
* Values cross this socket as V8 serialization blobs, so both V8s must agree
|
|
2199
|
+
* on the serialization format version. Each side sends a probe (a serialized
|
|
2200
|
+
* `null`, whose second byte is the writer's format version) in the handshake
|
|
2201
|
+
* and the mismatch is fatal here — once per connection — rather than
|
|
2202
|
+
* corrupting a value mid-run. The runtime answers with exactly one `Hello`
|
|
2203
|
+
* frame; anything else tears the connection down. Once the handshake is
|
|
2204
|
+
* done the connection's frame router starts and owns the reader for the
|
|
2205
|
+
* connection's lifetime.
|
|
2206
|
+
* @param options
|
|
2207
|
+
*/
|
|
1230
2208
|
static async connect(options) {
|
|
1231
|
-
const client = new RuntimeIpcClient(await connectSocket(options.socketPath));
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
2209
|
+
const client = new RuntimeIpcClient(await connectSocket(options.socketPath), brandKeyForToken(options.descriptorToken));
|
|
2210
|
+
try {
|
|
2211
|
+
await client.write(encodeTsToRustFrame(TsToRustMessageTypes.Authenticate, encodeAuthenticatePayload({
|
|
2212
|
+
protocolVersion: 2,
|
|
2213
|
+
probe: serializationProbe(),
|
|
2214
|
+
descriptorToken: options.descriptorToken
|
|
2215
|
+
})));
|
|
2216
|
+
await client.awaitHello();
|
|
2217
|
+
} catch (error) {
|
|
2218
|
+
await client.dispose();
|
|
2219
|
+
throw error;
|
|
2220
|
+
}
|
|
2221
|
+
client.routeFrames();
|
|
1236
2222
|
return client;
|
|
1237
2223
|
}
|
|
2224
|
+
/**
|
|
2225
|
+
* Read and validate the runtime's `Hello` frame.
|
|
2226
|
+
*
|
|
2227
|
+
* Three ways this fails, all fatal and all reported with the same actionable
|
|
2228
|
+
* remedy — the host package and the native binary are released in lockstep
|
|
2229
|
+
* (`docs/protocol.md` §8), so a mismatch means they are out of sync:
|
|
2230
|
+
* the runtime reports a bad status, the frame never arrives, or the
|
|
2231
|
+
* runtime's own probe cannot be read by this Node.
|
|
2232
|
+
*/
|
|
2233
|
+
async awaitHello() {
|
|
2234
|
+
let timer;
|
|
2235
|
+
const frame = await Promise.race([this.reader.readRustToTsFrame(), new Promise((_resolve, reject) => {
|
|
2236
|
+
timer = setTimeout(() => {
|
|
2237
|
+
reject(new HandshakeError(`V8 runtime did not answer the handshake within ${HELLO_TIMEOUT_MS}ms`));
|
|
2238
|
+
}, HELLO_TIMEOUT_MS);
|
|
2239
|
+
timer.unref?.();
|
|
2240
|
+
})]).finally(() => {
|
|
2241
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
2242
|
+
});
|
|
2243
|
+
if (frame.messageType !== RustToTsMessageTypes.Hello) throw new HandshakeError(`expected a Hello frame from the V8 runtime, got message type 0x${frame.messageType.toString(16).padStart(2, "0")}`);
|
|
2244
|
+
const hello = decodeHelloPayload(frame.payload);
|
|
2245
|
+
if (hello.status !== HelloStatus.Ok) throw new HandshakeError(hello.message.length > 0 ? hello.message : `V8 runtime rejected the handshake (status ${hello.status})`);
|
|
2246
|
+
try {
|
|
2247
|
+
if (deserializeValue(hello.probe) !== null) throw new Error("probe did not decode to null");
|
|
2248
|
+
} catch (error) {
|
|
2249
|
+
throw new HandshakeError(`V8 serialization format mismatch: this Node cannot read values written by the iso4-v8 binary (${error instanceof Error ? error.message : String(error)}). Update @iso4/sandbox and @iso4/v8-* together — they are released in lockstep.`);
|
|
2250
|
+
}
|
|
2251
|
+
}
|
|
1238
2252
|
nextRunId = 0;
|
|
1239
2253
|
nextRunIdValue() {
|
|
1240
|
-
|
|
2254
|
+
do
|
|
2255
|
+
this.nextRunId = this.nextRunId + 1 >>> 0;
|
|
2256
|
+
while (this.nextRunId === 0 || this.runs.has(this.nextRunId));
|
|
1241
2257
|
return this.nextRunId;
|
|
1242
2258
|
}
|
|
1243
2259
|
async runRawCode(code, options) {
|
|
1244
2260
|
if (this.disposed) throw new Error("runtime IPC client is disposed");
|
|
1245
2261
|
const runId = this.nextRunIdValue();
|
|
1246
|
-
|
|
2262
|
+
return this.executeRun(runId, encodeTsToRustFrame(TsToRustMessageTypes.Run, encodeRunPayload({
|
|
1247
2263
|
runId,
|
|
1248
2264
|
code,
|
|
1249
2265
|
filename: options?.filename,
|
|
1250
2266
|
limits: options?.limits,
|
|
1251
2267
|
globals: options?.globals,
|
|
1252
|
-
imports: options?.imports
|
|
1253
|
-
|
|
1254
|
-
|
|
2268
|
+
imports: options?.imports,
|
|
2269
|
+
call: options?.call
|
|
2270
|
+
})), makeDispatcher(options?.dispatch ?? {}, options?.importDispatch), options?.signal, options?.hardAbortSignal, options?.streams);
|
|
1255
2271
|
}
|
|
1256
|
-
async
|
|
2272
|
+
async prefixRun(options) {
|
|
1257
2273
|
if (this.disposed) throw new Error("runtime IPC client is disposed");
|
|
1258
|
-
|
|
2274
|
+
const runId = this.nextRunIdValue();
|
|
2275
|
+
return this.executeRun(runId, encodeTsToRustFrame(TsToRustMessageTypes.PrefixRun, encodePrefixRunPayload({
|
|
2276
|
+
prefixId: options.prefixId,
|
|
1259
2277
|
code: options.code,
|
|
1260
2278
|
filename: options.filename,
|
|
1261
2279
|
limits: options.limits,
|
|
1262
2280
|
globals: options.globals,
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
2281
|
+
importRebinds: options.importRebinds,
|
|
2282
|
+
call: options.call,
|
|
2283
|
+
runId
|
|
2284
|
+
})), makeDispatcher(options.dispatch ?? {}, options.importDispatch), options.signal, options.hardAbortSignal, options.streams);
|
|
2285
|
+
}
|
|
2286
|
+
/**
|
|
2287
|
+
* Shared body of `runRawCode` and `prefixRun`: register the run with the
|
|
2288
|
+
* router, write its request frame, start its stream pumps, and await its
|
|
2289
|
+
* settlement. Registration happens *before* the write so the router can
|
|
2290
|
+
* never see a frame for a run it does not know yet.
|
|
2291
|
+
*
|
|
2292
|
+
* ── In-flight abort (soft and hard) ────────────────────────────────────────
|
|
2293
|
+
* When `signal` fires mid-run — including while a bridge call is in flight —
|
|
2294
|
+
* we send a SOFT `Terminate` frame (runId + mode 0) and keep the connection
|
|
2295
|
+
* routing. The runtime abandons the run at its next turn boundary: nothing
|
|
2296
|
+
* is interrupted mid-execution, the instance survives, and a real
|
|
2297
|
+
* `ERR_ABORTED` `Result` (carrying duration, CPU time, and the bridge
|
|
2298
|
+
* records collected so far) flows back through the router. No fallback
|
|
2299
|
+
* timer: a run spinning synchronously with no `cpuTimeMs` cap legitimately
|
|
2300
|
+
* cannot answer a soft abort until its own limits end the turn — that is
|
|
2301
|
+
* the documented soft-abort contract, and tearing the connection down for
|
|
2302
|
+
* it would fail every co-resident run for a healthy runtime.
|
|
2303
|
+
*
|
|
2304
|
+
* When `hardAbortSignal` fires, we send a HARD `Terminate` (mode 1): the
|
|
2305
|
+
* runtime interrupts executing JS immediately (tainting the instance when
|
|
2306
|
+
* the kill lands mid-turn) or abandons a suspended run exactly like soft.
|
|
2307
|
+
* Hard always answers promptly, so it keeps the {@link TERMINATE_GRACE_MS}
|
|
2308
|
+
* fallback: no Result within the window means the runtime cannot answer at
|
|
2309
|
+
* all (wedged process) and `abortConnection` tears the connection down —
|
|
2310
|
+
* the reader closes, every run in flight fails, and Rust observes EOF (see
|
|
2311
|
+
* DESIGN.md §14.7). This run then rejects `RunAbortedError`, which
|
|
2312
|
+
* `index.ts` maps to a synthesized `ERR_ABORTED` `RunResult`. Any late
|
|
2313
|
+
* `BridgeResponse` from an orphaned handler is harmless on every path:
|
|
2314
|
+
* routed connections discard it runtime-side (stale callId), a torn-down
|
|
2315
|
+
* socket is gone.
|
|
2316
|
+
* @param runId
|
|
2317
|
+
* @param frame the encoded `Run`/`PrefixRun` frame
|
|
2318
|
+
* @param dispatcher
|
|
2319
|
+
* @param signal
|
|
2320
|
+
* @param hardAbortSignal
|
|
2321
|
+
* @param streams
|
|
2322
|
+
*/
|
|
2323
|
+
async executeRun(runId, frame, dispatcher, signal, hardAbortSignal, streams) {
|
|
2324
|
+
const entry = {
|
|
2325
|
+
dispatcher,
|
|
2326
|
+
streams,
|
|
2327
|
+
outStreams: new OutboundStreamRegistry({
|
|
2328
|
+
pull: (streamId, credit) => {
|
|
2329
|
+
this.write(encodeTsToRustFrame(TsToRustMessageTypes.StreamPull, encodeStreamPullPayload(runId, streamId, credit))).catch(() => {});
|
|
2330
|
+
},
|
|
2331
|
+
cancel: (streamId, reason) => {
|
|
2332
|
+
this.write(encodeTsToRustFrame(TsToRustMessageTypes.StreamCancel, encodeStreamCancelPayload(runId, streamId, reason))).catch(() => {});
|
|
2333
|
+
}
|
|
2334
|
+
}),
|
|
2335
|
+
signal,
|
|
2336
|
+
hardAbortSignal,
|
|
2337
|
+
resolve: NOOP,
|
|
2338
|
+
reject: NOOP,
|
|
2339
|
+
detachAbort: NOOP
|
|
2340
|
+
};
|
|
2341
|
+
const settled = new Promise((resolve, reject) => {
|
|
2342
|
+
entry.resolve = resolve;
|
|
2343
|
+
entry.reject = reject;
|
|
2344
|
+
});
|
|
2345
|
+
settled.catch(() => {});
|
|
2346
|
+
let graceTimer;
|
|
2347
|
+
const beginSoftAbort = () => {
|
|
2348
|
+
this.write(encodeTsToRustFrame(TsToRustMessageTypes.Terminate, encodeTerminatePayload(runId, false))).catch(() => {});
|
|
2349
|
+
};
|
|
2350
|
+
const beginHardAbort = () => {
|
|
2351
|
+
this.write(encodeTsToRustFrame(TsToRustMessageTypes.Terminate, encodeTerminatePayload(runId, true))).catch(() => {});
|
|
2352
|
+
if (graceTimer === void 0) {
|
|
2353
|
+
graceTimer = setTimeout(() => {
|
|
2354
|
+
this.abortConnection();
|
|
2355
|
+
}, TERMINATE_GRACE_MS);
|
|
2356
|
+
graceTimer.unref?.();
|
|
2357
|
+
}
|
|
2358
|
+
};
|
|
2359
|
+
if (signal !== void 0 || hardAbortSignal !== void 0) {
|
|
2360
|
+
if (signal !== void 0 && !signal.aborted) signal.addEventListener("abort", beginSoftAbort, { once: true });
|
|
2361
|
+
if (hardAbortSignal !== void 0 && !hardAbortSignal.aborted) hardAbortSignal.addEventListener("abort", beginHardAbort, { once: true });
|
|
2362
|
+
entry.detachAbort = () => {
|
|
2363
|
+
signal?.removeEventListener("abort", beginSoftAbort);
|
|
2364
|
+
hardAbortSignal?.removeEventListener("abort", beginHardAbort);
|
|
2365
|
+
if (graceTimer !== void 0) clearTimeout(graceTimer);
|
|
2366
|
+
};
|
|
2367
|
+
}
|
|
2368
|
+
this.runs.set(runId, entry);
|
|
2369
|
+
try {
|
|
2370
|
+
await this.write(frame);
|
|
2371
|
+
this.activateStreams(streams, runId);
|
|
2372
|
+
if (hardAbortSignal?.aborted) beginHardAbort();
|
|
2373
|
+
else if (signal?.aborted) beginSoftAbort();
|
|
2374
|
+
} catch (error) {
|
|
2375
|
+
if (this.runs.delete(runId)) {
|
|
2376
|
+
entry.detachAbort();
|
|
2377
|
+
entry.reject(error instanceof Error ? error : new Error(String(error)));
|
|
2378
|
+
}
|
|
2379
|
+
}
|
|
2380
|
+
try {
|
|
2381
|
+
return await settled;
|
|
2382
|
+
} catch (error) {
|
|
2383
|
+
if (signal?.aborted) throw new RunAbortedError(signal.reason);
|
|
2384
|
+
if (hardAbortSignal?.aborted) throw new RunAbortedError(hardAbortSignal.reason);
|
|
2385
|
+
throw error;
|
|
1268
2386
|
}
|
|
1269
|
-
throw new Error("connection closed before receiving a PrecompileResult frame");
|
|
1270
2387
|
}
|
|
1271
|
-
|
|
2388
|
+
nextPrecompileId = 0;
|
|
2389
|
+
nextPrecompileIdValue() {
|
|
2390
|
+
do
|
|
2391
|
+
this.nextPrecompileId = this.nextPrecompileId + 1 >>> 0;
|
|
2392
|
+
while (this.precompileWaiters.has(this.nextPrecompileId));
|
|
2393
|
+
return this.nextPrecompileId;
|
|
2394
|
+
}
|
|
2395
|
+
async precompile(options) {
|
|
1272
2396
|
if (this.disposed) throw new Error("runtime IPC client is disposed");
|
|
1273
|
-
const
|
|
1274
|
-
|
|
1275
|
-
|
|
2397
|
+
const requestId = this.nextPrecompileIdValue();
|
|
2398
|
+
const frame = encodeTsToRustFrame(TsToRustMessageTypes.Precompile, encodePrecompilePayload({
|
|
2399
|
+
requestId,
|
|
1276
2400
|
code: options.code,
|
|
1277
2401
|
filename: options.filename,
|
|
1278
2402
|
limits: options.limits,
|
|
1279
2403
|
globals: options.globals,
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
2404
|
+
imports: options.imports
|
|
2405
|
+
}));
|
|
2406
|
+
const reply = new Promise((resolve, reject) => {
|
|
2407
|
+
this.precompileWaiters.set(requestId, {
|
|
2408
|
+
resolve,
|
|
2409
|
+
reject
|
|
2410
|
+
});
|
|
2411
|
+
});
|
|
2412
|
+
reply.catch(NOOP);
|
|
2413
|
+
try {
|
|
2414
|
+
await this.write(frame);
|
|
2415
|
+
} catch (error) {
|
|
2416
|
+
this.precompileWaiters.delete(requestId);
|
|
2417
|
+
throw error;
|
|
2418
|
+
}
|
|
2419
|
+
return reply;
|
|
2420
|
+
}
|
|
2421
|
+
/**
|
|
2422
|
+
* Request the runtime's capacity/usage snapshot. Empty request
|
|
2423
|
+
* payload; the reply is one `StatsResult` frame. Sent on the sandbox's
|
|
2424
|
+
* dedicated control connection so it never queues behind runs.
|
|
2425
|
+
*/
|
|
2426
|
+
async stats() {
|
|
2427
|
+
if (this.disposed) throw new Error("runtime IPC client is disposed");
|
|
2428
|
+
return decodeStatsPayload(await this.controlRequest(encodeTsToRustFrame(TsToRustMessageTypes.Stats, new Uint8Array(0)), RustToTsMessageTypes.StatsResult));
|
|
2429
|
+
}
|
|
2430
|
+
/**
|
|
2431
|
+
* Write a request answered by exactly one payload-only reply frame
|
|
2432
|
+
* (`Precompile` → `PrecompileResult`, `Stats` → `StatsResult`) and await
|
|
2433
|
+
* that reply through the router. Replies carry no correlation id, so the
|
|
2434
|
+
* router matches them FIFO per expected frame type — a reply nobody is
|
|
2435
|
+
* waiting on is a desync, the same contract the run path enforces.
|
|
2436
|
+
* @param frame the encoded request frame
|
|
2437
|
+
* @param expects the reply frame type
|
|
2438
|
+
*/
|
|
2439
|
+
async controlRequest(frame, expects) {
|
|
2440
|
+
let waiter;
|
|
2441
|
+
const reply = new Promise((resolve, reject) => {
|
|
2442
|
+
waiter = {
|
|
2443
|
+
expects,
|
|
2444
|
+
resolve,
|
|
2445
|
+
reject
|
|
2446
|
+
};
|
|
2447
|
+
});
|
|
2448
|
+
reply.catch(() => {});
|
|
2449
|
+
this.controlWaiters.push(waiter);
|
|
2450
|
+
try {
|
|
2451
|
+
await this.write(frame);
|
|
2452
|
+
} catch (error) {
|
|
2453
|
+
const at = this.controlWaiters.indexOf(waiter);
|
|
2454
|
+
if (at !== -1) this.controlWaiters.splice(at, 1);
|
|
2455
|
+
throw error;
|
|
2456
|
+
}
|
|
2457
|
+
return reply;
|
|
1284
2458
|
}
|
|
1285
2459
|
async disposePrefix(prefixId) {
|
|
1286
2460
|
if (this.disposed) return;
|
|
@@ -1300,111 +2474,346 @@ var RuntimeIpcClient = class RuntimeIpcClient {
|
|
|
1300
2474
|
});
|
|
1301
2475
|
}
|
|
1302
2476
|
/**
|
|
1303
|
-
*
|
|
1304
|
-
*
|
|
1305
|
-
*
|
|
1306
|
-
*
|
|
1307
|
-
*
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
*
|
|
1317
|
-
*
|
|
1318
|
-
*
|
|
1319
|
-
* `
|
|
1320
|
-
*
|
|
1321
|
-
*
|
|
1322
|
-
*
|
|
1323
|
-
*
|
|
1324
|
-
*
|
|
1325
|
-
*
|
|
1326
|
-
*
|
|
1327
|
-
*
|
|
1328
|
-
*
|
|
1329
|
-
*
|
|
1330
|
-
*
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
2477
|
+
* Tear down the connection in response to an in-flight abort the runtime
|
|
2478
|
+
* did not answer. Idempotent. Marks the client `broken` (so the pool
|
|
2479
|
+
* replaces it), closes the frame reader (which stops the router — it fails
|
|
2480
|
+
* every run and control request still in flight), and destroys the socket
|
|
2481
|
+
* (so the Rust session sees EOF and drops its isolates).
|
|
2482
|
+
*/
|
|
2483
|
+
abortConnection() {
|
|
2484
|
+
if (this.broken) return;
|
|
2485
|
+
this.broken = true;
|
|
2486
|
+
this.reader.close(/* @__PURE__ */ new Error("[@iso4/sandbox] connection torn down: an aborted run got no answer from the runtime"));
|
|
2487
|
+
this.socket.destroy();
|
|
2488
|
+
}
|
|
2489
|
+
/**
|
|
2490
|
+
* The connection's frame router — the single consumer of the frame reader
|
|
2491
|
+
* for the connection's lifetime, started right after the handshake. Every
|
|
2492
|
+
* run-tagged frame is routed to its run's entry by the run id it leads
|
|
2493
|
+
* with; `Result`/`RunComplete` frames for a run id nothing here is waiting
|
|
2494
|
+
* on are the desync signal ({@link ProtocolDesyncError}), while late
|
|
2495
|
+
* `BridgeCall`/stream frames for an already-completed run are discarded the
|
|
2496
|
+
* way the runtime discards late `BridgeResponse`s.
|
|
2497
|
+
*
|
|
2498
|
+
* The loop ends only when the reader closes (peer EOF, socket error,
|
|
2499
|
+
* dispose, abort fallback) or a routing error is thrown (desync, a decode
|
|
2500
|
+
* throw on guest-controlled bytes that cannot be answered inline). Either
|
|
2501
|
+
* way the connection is done: framing or attribution is no longer
|
|
2502
|
+
* trustworthy, so everything in flight fails now rather than waiting on
|
|
2503
|
+
* frames that will never be delivered — and the connection never goes back
|
|
2504
|
+
* to the pool.
|
|
2505
|
+
*/
|
|
2506
|
+
routeFrames() {
|
|
2507
|
+
(async () => {
|
|
2508
|
+
try {
|
|
2509
|
+
for await (const frame of this.reader) {
|
|
2510
|
+
const pending = this.routeFrame(frame);
|
|
2511
|
+
if (pending !== void 0) await pending;
|
|
2512
|
+
}
|
|
2513
|
+
} catch (error) {
|
|
2514
|
+
this.broken = true;
|
|
2515
|
+
const failure = error instanceof Error ? error : new Error(String(error));
|
|
2516
|
+
this.reader.close(failure);
|
|
2517
|
+
this.socket.destroy();
|
|
2518
|
+
for (const [, entry] of this.runs) {
|
|
2519
|
+
entry.detachAbort();
|
|
2520
|
+
entry.streams?.releaseAll();
|
|
2521
|
+
entry.outStreams.failAll(failure);
|
|
2522
|
+
if (entry.epilogue !== void 0) entry.epilogue(void 0);
|
|
2523
|
+
else entry.reject(failure);
|
|
2524
|
+
}
|
|
2525
|
+
this.runs.clear();
|
|
2526
|
+
for (const waiter of this.controlWaiters.splice(0)) waiter.reject(failure);
|
|
2527
|
+
for (const [, waiter] of this.precompileWaiters) waiter.reject(failure);
|
|
2528
|
+
this.precompileWaiters.clear();
|
|
2529
|
+
}
|
|
2530
|
+
})();
|
|
2531
|
+
}
|
|
2532
|
+
/**
|
|
2533
|
+
* Dispatch one frame to its owner. Throws to end the connection (the
|
|
2534
|
+
* router's catch fails everything in flight). Synchronous except for a
|
|
2535
|
+
* BridgeCall that writes an inline response — that arm returns a promise
|
|
2536
|
+
* for the loop to await; everything else returns `undefined` so routing a
|
|
2537
|
+
* frame costs no promise.
|
|
2538
|
+
* @param frame
|
|
2539
|
+
*/
|
|
2540
|
+
routeFrame(frame) {
|
|
2541
|
+
switch (frame.messageType) {
|
|
2542
|
+
case RustToTsMessageTypes.Result:
|
|
2543
|
+
this.routeResult(frame.payload);
|
|
2544
|
+
return;
|
|
2545
|
+
case RustToTsMessageTypes.RunComplete:
|
|
2546
|
+
this.routeRunComplete(frame.payload);
|
|
2547
|
+
return;
|
|
2548
|
+
case RustToTsMessageTypes.Log: return;
|
|
2549
|
+
case RustToTsMessageTypes.PrecompileResult: {
|
|
2550
|
+
const requestId = peekPrecompileResultRequestId(frame.payload);
|
|
2551
|
+
const waiter = requestId === void 0 ? void 0 : this.precompileWaiters.get(requestId);
|
|
2552
|
+
if (requestId === void 0 || waiter === void 0) throw new ProtocolDesyncError(`PrecompileResult carries requestId ${requestId ?? "(truncated payload)"} but no precompile with that id is pending on this connection`);
|
|
2553
|
+
this.precompileWaiters.delete(requestId);
|
|
2554
|
+
waiter.resolve(frame.payload);
|
|
2555
|
+
return;
|
|
2556
|
+
}
|
|
2557
|
+
case RustToTsMessageTypes.StatsResult: {
|
|
2558
|
+
const waiter = this.controlWaiters[0];
|
|
2559
|
+
if (waiter === void 0 || waiter.expects !== frame.messageType) throw new ProtocolDesyncError(`unexpected frame type 0x${frame.messageType.toString(16).padStart(2, "0")} with no matching request pending on this connection`);
|
|
2560
|
+
this.controlWaiters.shift();
|
|
2561
|
+
waiter.resolve(frame.payload);
|
|
2562
|
+
return;
|
|
2563
|
+
}
|
|
2564
|
+
case RustToTsMessageTypes.BridgeCall: {
|
|
2565
|
+
const runId = peekBridgeCallRunId(frame.payload);
|
|
2566
|
+
if (runId === void 0) throw new ProtocolDesyncError("BridgeCall payload too short to carry a run id");
|
|
2567
|
+
const entry = this.runs.get(runId);
|
|
2568
|
+
if (entry === void 0) return void 0;
|
|
2569
|
+
return this.dispatchBridgeCallFrame(frame.payload, entry, runId);
|
|
2570
|
+
}
|
|
2571
|
+
case RustToTsMessageTypes.StreamChunk: {
|
|
2572
|
+
const chunk = decodeStreamChunkPayload(frame.payload);
|
|
2573
|
+
this.runs.get(chunk.runId)?.outStreams.deliverChunk(chunk.streamId, chunk.data);
|
|
2574
|
+
return;
|
|
2575
|
+
}
|
|
2576
|
+
case RustToTsMessageTypes.StreamEnd: {
|
|
2577
|
+
const end = decodeStreamEndPayload(frame.payload);
|
|
2578
|
+
this.runs.get(end.runId)?.outStreams.deliverEnd(end.streamId, end.error);
|
|
2579
|
+
return;
|
|
2580
|
+
}
|
|
2581
|
+
case RustToTsMessageTypes.StreamPull: {
|
|
2582
|
+
const pull = decodeStreamPullPayload(frame.payload);
|
|
2583
|
+
const owner = this.streamOwner(pull.runId);
|
|
2584
|
+
if (owner === void 0) return void 0;
|
|
2585
|
+
const source = owner.streams.sources.get(pull.streamId);
|
|
2586
|
+
if (source === void 0) return void 0;
|
|
2587
|
+
source.credit += pull.credit;
|
|
2588
|
+
this.pumpStream(owner.streams, owner.runId, pull.streamId);
|
|
2589
|
+
return;
|
|
2590
|
+
}
|
|
2591
|
+
case RustToTsMessageTypes.StreamCancel: {
|
|
2592
|
+
const cancel = decodeStreamCancelPayload(frame.payload);
|
|
2593
|
+
const owner = this.streamOwner(cancel.runId);
|
|
2594
|
+
if (owner === void 0) return void 0;
|
|
2595
|
+
const source = owner.streams.sources.get(cancel.streamId);
|
|
2596
|
+
if (source === void 0) return void 0;
|
|
2597
|
+
source.done = true;
|
|
2598
|
+
source.reader.cancel(cancel.reason).catch(() => {});
|
|
2599
|
+
owner.streams.sources.delete(cancel.streamId);
|
|
2600
|
+
return;
|
|
2601
|
+
}
|
|
2602
|
+
default: throw new ProtocolDesyncError(`unexpected frame type 0x${frame.messageType.toString(16).padStart(2, "0")}`);
|
|
2603
|
+
}
|
|
2604
|
+
}
|
|
2605
|
+
/**
|
|
2606
|
+
* Route a `Result` frame: Rust echoes the `runId` of the payload it is
|
|
2607
|
+
* answering onto every completion path (`session.rs` →
|
|
2608
|
+
* `wire::encode_run_completion_payload`), so a `Result` for a run id nothing
|
|
2609
|
+
* here is waiting on is proof the two sides disagree about what this
|
|
2610
|
+
* connection is doing.
|
|
2611
|
+
* @param payload
|
|
2612
|
+
*/
|
|
2613
|
+
routeResult(payload) {
|
|
2614
|
+
const runId = peekRunCompletionRunId(payload);
|
|
2615
|
+
const entry = runId === void 0 ? void 0 : this.runs.get(runId);
|
|
2616
|
+
if (runId === void 0 || entry === void 0 || entry.epilogue !== void 0) throw new ProtocolDesyncError(`Result frame carries runId ${runId ?? "(truncated payload)"} but no run with that id is awaiting a Result on this connection — the runtime is answering a run this client does not know`);
|
|
2617
|
+
entry.detachAbort();
|
|
2618
|
+
entry.detachAbort = NOOP;
|
|
2619
|
+
const flags = peekRunCompletionBackgroundFlags(payload);
|
|
2620
|
+
if (flags === 0) {
|
|
2621
|
+
this.runs.delete(runId);
|
|
2622
|
+
entry.streams?.releaseAll();
|
|
2623
|
+
entry.resolve({
|
|
2624
|
+
result: payload,
|
|
2625
|
+
graceWork: false,
|
|
2626
|
+
outStreams: entry.outStreams
|
|
2627
|
+
});
|
|
2628
|
+
return;
|
|
2629
|
+
}
|
|
2630
|
+
let settleEpilogue;
|
|
2631
|
+
const epilogue = new Promise((resolve) => {
|
|
2632
|
+
settleEpilogue = resolve;
|
|
2633
|
+
});
|
|
2634
|
+
entry.epilogue = settleEpilogue;
|
|
2635
|
+
const signal = entry.signal;
|
|
2636
|
+
const hardAbortSignal = entry.hardAbortSignal;
|
|
2637
|
+
const cancelGrace = (hard) => () => {
|
|
2638
|
+
this.write(encodeTsToRustFrame(TsToRustMessageTypes.Terminate, encodeTerminatePayload(runId, hard))).catch(() => {});
|
|
2639
|
+
};
|
|
2640
|
+
const cancelSoft = cancelGrace(false);
|
|
2641
|
+
const cancelHard = cancelGrace(true);
|
|
2642
|
+
if (hardAbortSignal?.aborted || signal?.aborted) {
|
|
2643
|
+
(hardAbortSignal?.aborted ? cancelHard : cancelSoft)();
|
|
2644
|
+
entry.detachAbort = NOOP;
|
|
2645
|
+
} else {
|
|
2646
|
+
signal?.addEventListener("abort", cancelSoft, { once: true });
|
|
2647
|
+
hardAbortSignal?.addEventListener("abort", cancelHard, { once: true });
|
|
2648
|
+
entry.detachAbort = () => {
|
|
2649
|
+
signal?.removeEventListener("abort", cancelSoft);
|
|
2650
|
+
hardAbortSignal?.removeEventListener("abort", cancelHard);
|
|
2651
|
+
};
|
|
2652
|
+
}
|
|
2653
|
+
entry.resolve({
|
|
2654
|
+
result: payload,
|
|
2655
|
+
epilogue,
|
|
2656
|
+
graceWork: (flags & 1) !== 0,
|
|
2657
|
+
outStreams: entry.outStreams
|
|
2658
|
+
});
|
|
2659
|
+
}
|
|
2660
|
+
/**
|
|
2661
|
+
* Route a `RunComplete` frame — the end of a run whose Result reported
|
|
2662
|
+
* pending `waitUntil` work. One for a run id without a pending epilogue is
|
|
2663
|
+
* the same desync signal as a stray `Result`.
|
|
2664
|
+
* @param payload
|
|
1337
2665
|
*/
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
2666
|
+
routeRunComplete(payload) {
|
|
2667
|
+
const report = decodeRunCompletePayload(payload);
|
|
2668
|
+
const entry = this.runs.get(report.runId);
|
|
2669
|
+
if (entry === void 0 || entry.epilogue === void 0) throw new ProtocolDesyncError(`RunComplete frame carries runId ${report.runId} but no run with that id is in its waitUntil grace phase on this connection`);
|
|
2670
|
+
this.runs.delete(report.runId);
|
|
2671
|
+
entry.detachAbort();
|
|
2672
|
+
entry.streams?.releaseAll();
|
|
2673
|
+
entry.outStreams.failAll(/* @__PURE__ */ new Error("[@iso4/sandbox] the run completed before its body stream terminated"));
|
|
2674
|
+
entry.epilogue(report);
|
|
2675
|
+
}
|
|
2676
|
+
/**
|
|
2677
|
+
* Resolve which run's stream registry a stream frame addresses. Stream ids
|
|
2678
|
+
* are per-run, so the run id is the only safe routing key: with several
|
|
2679
|
+
* runs in flight a match-by-stream-id fallback could credit or cancel the
|
|
2680
|
+
* wrong run's source. The production runtime tags every stream frame with
|
|
2681
|
+
* a real run id — run id 0 (the wire's "validation disabled" marker, used
|
|
2682
|
+
* only by the direct-fd mode) arriving here means the two sides disagree
|
|
2683
|
+
* about what this connection is doing, the same desync contract as a
|
|
2684
|
+
* stray Result.
|
|
2685
|
+
* @param runId the frame's run id
|
|
2686
|
+
*/
|
|
2687
|
+
streamOwner(runId) {
|
|
2688
|
+
if (runId === 0) throw new ProtocolDesyncError("stream frame carries runId 0 — the runtime never leaves stream frames unattributed on a session connection");
|
|
2689
|
+
const streams = this.runs.get(runId)?.streams;
|
|
2690
|
+
return streams === void 0 ? void 0 : {
|
|
2691
|
+
streams,
|
|
2692
|
+
runId
|
|
1350
2693
|
};
|
|
1351
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1352
|
-
try {
|
|
1353
|
-
return await this.drainFrames(dispatcher);
|
|
1354
|
-
} catch (error) {
|
|
1355
|
-
if (signal?.aborted) throw new RunAbortedError(signal.reason);
|
|
1356
|
-
throw error;
|
|
1357
|
-
} finally {
|
|
1358
|
-
if (graceTimer !== void 0) clearTimeout(graceTimer);
|
|
1359
|
-
signal?.removeEventListener("abort", onAbort);
|
|
1360
|
-
}
|
|
1361
2694
|
}
|
|
1362
2695
|
/**
|
|
1363
|
-
*
|
|
1364
|
-
*
|
|
1365
|
-
*
|
|
1366
|
-
*
|
|
2696
|
+
* Start pumps for every stream registered since the last activation,
|
|
2697
|
+
* seeding each with the initial credit window. Called right after the
|
|
2698
|
+
* frame carrying the stream handles has been written.
|
|
2699
|
+
* @param streams the run's registry
|
|
2700
|
+
* @param runId the run the streams belong to
|
|
1367
2701
|
*/
|
|
1368
|
-
|
|
1369
|
-
if (
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
2702
|
+
activateStreams(streams, runId) {
|
|
2703
|
+
if (streams === void 0) return;
|
|
2704
|
+
for (const id of streams.takeNewIds()) {
|
|
2705
|
+
const source = streams.sources.get(id);
|
|
2706
|
+
if (source === void 0) continue;
|
|
2707
|
+
source.credit = STREAM_CREDIT_WINDOW_BYTES;
|
|
2708
|
+
this.pumpStream(streams, runId, id);
|
|
2709
|
+
}
|
|
1373
2710
|
}
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
message: e instanceof Error ? e.message : String(e)
|
|
1399
|
-
})));
|
|
2711
|
+
/**
|
|
2712
|
+
* Pump one stream: send buffered probe chunks first, then pull the source,
|
|
2713
|
+
* staying inside the credit window and the per-chunk cap. Fire-and-forget;
|
|
2714
|
+
* re-entered by credit grants. Errors end the stream with a `StreamEnd`
|
|
2715
|
+
* carrying the message — the sandbox's pending read rejects catchably.
|
|
2716
|
+
* @param streams the run's registry
|
|
2717
|
+
* @param runId the run
|
|
2718
|
+
* @param streamId the stream to pump
|
|
2719
|
+
*/
|
|
2720
|
+
pumpStream(streams, runId, streamId) {
|
|
2721
|
+
const source = streams.sources.get(streamId);
|
|
2722
|
+
if (source === void 0 || source.pumping || source.done) return;
|
|
2723
|
+
source.pumping = true;
|
|
2724
|
+
(async () => {
|
|
2725
|
+
try {
|
|
2726
|
+
while (source.credit > 0 && !source.done) {
|
|
2727
|
+
let chunk = source.prefix.shift();
|
|
2728
|
+
if (chunk === void 0) {
|
|
2729
|
+
const { done, value } = await source.reader.read();
|
|
2730
|
+
if (done) {
|
|
2731
|
+
source.done = true;
|
|
2732
|
+
streams.sources.delete(streamId);
|
|
2733
|
+
await this.write(encodeTsToRustFrame(TsToRustMessageTypes.StreamEnd, encodeStreamEndPayload(runId, streamId)));
|
|
2734
|
+
return;
|
|
1400
2735
|
}
|
|
1401
|
-
|
|
1402
|
-
}
|
|
2736
|
+
chunk = value;
|
|
2737
|
+
}
|
|
2738
|
+
const limit = Math.min(STREAM_CHUNK_MAX_BYTES, source.credit);
|
|
2739
|
+
if (chunk.byteLength > limit) {
|
|
2740
|
+
source.prefix.unshift(chunk.subarray(limit));
|
|
2741
|
+
chunk = chunk.subarray(0, limit);
|
|
2742
|
+
}
|
|
2743
|
+
source.credit -= chunk.byteLength;
|
|
2744
|
+
await this.write(encodeTsToRustFrame(TsToRustMessageTypes.StreamChunk, encodeStreamChunkPayload(runId, streamId, chunk)));
|
|
1403
2745
|
}
|
|
1404
|
-
|
|
2746
|
+
} catch (error) {
|
|
2747
|
+
source.done = true;
|
|
2748
|
+
source.reader.cancel().catch(() => {});
|
|
2749
|
+
streams.sources.delete(streamId);
|
|
2750
|
+
await this.write(encodeTsToRustFrame(TsToRustMessageTypes.StreamEnd, encodeStreamEndPayload(runId, streamId, error instanceof Error ? error.message : String(error)))).catch(() => {});
|
|
2751
|
+
} finally {
|
|
2752
|
+
source.pumping = false;
|
|
1405
2753
|
}
|
|
2754
|
+
})();
|
|
2755
|
+
}
|
|
2756
|
+
/**
|
|
2757
|
+
* Handle one `BridgeCall` frame: decode, dispatch to the owning run's
|
|
2758
|
+
* handler (fire-and-forget), and answer decode/dispatch failures inline.
|
|
2759
|
+
*
|
|
2760
|
+
* Dispatches are fire-and-forget — the router does NOT await the handler,
|
|
2761
|
+
* so it continues routing frames immediately. When the Rust side fires a
|
|
2762
|
+
* wall timeout it sends a `Result` frame; the router delivers it without
|
|
2763
|
+
* waiting for the handler. The handler promise is then **orphaned**: any
|
|
2764
|
+
* in-flight I/O or timers continue to completion, and Rust silently ignores
|
|
2765
|
+
* any late `BridgeResponse` that arrives after the run has completed (see
|
|
2766
|
+
* session.rs).
|
|
2767
|
+
* @param payload the frame payload
|
|
2768
|
+
* @param entry the owning run's routing entry
|
|
2769
|
+
* @param runId the run the frame belongs to (already peeked by the router)
|
|
2770
|
+
*/
|
|
2771
|
+
async dispatchBridgeCallFrame(payload, entry, runId) {
|
|
2772
|
+
const { dispatcher, streams } = entry;
|
|
2773
|
+
let call;
|
|
2774
|
+
try {
|
|
2775
|
+
call = decodeBridgeCallPayload(payload);
|
|
2776
|
+
} catch (error) {
|
|
2777
|
+
const callId = peekBridgeCallId(payload);
|
|
2778
|
+
if (callId === void 0) throw error;
|
|
2779
|
+
await this.write(encodeTsToRustFrame(TsToRustMessageTypes.BridgeResponse, encodeBridgeResponsePayload(runId, callId, false, void 0, {
|
|
2780
|
+
name: "TypeError",
|
|
2781
|
+
message: `host could not decode bridge call arguments: ${error instanceof Error ? error.message : String(error)}`
|
|
2782
|
+
})));
|
|
2783
|
+
return;
|
|
2784
|
+
}
|
|
2785
|
+
if (dispatcher === void 0) await this.write(encodeTsToRustFrame(TsToRustMessageTypes.BridgeResponse, encodeBridgeResponsePayload(call.runId, call.callId, false, void 0, {
|
|
2786
|
+
name: "Error",
|
|
2787
|
+
message: "no bridge dispatcher configured"
|
|
2788
|
+
})));
|
|
2789
|
+
else {
|
|
2790
|
+
const { runId: frameRunId, callId } = call;
|
|
2791
|
+
dispatcher({
|
|
2792
|
+
targetKind: call.targetKind,
|
|
2793
|
+
specifier: call.specifier,
|
|
2794
|
+
exportName: call.exportName,
|
|
2795
|
+
args: call.args
|
|
2796
|
+
}).then(async (value) => {
|
|
2797
|
+
let encoded;
|
|
2798
|
+
try {
|
|
2799
|
+
encoded = await serializeHostValue(value, this.brandKey, streams);
|
|
2800
|
+
} catch (e) {
|
|
2801
|
+
return this.write(encodeTsToRustFrame(TsToRustMessageTypes.BridgeResponse, encodeBridgeResponsePayload(frameRunId, callId, false, void 0, {
|
|
2802
|
+
name: "Error",
|
|
2803
|
+
message: e instanceof Error ? e.message : String(e)
|
|
2804
|
+
})));
|
|
2805
|
+
}
|
|
2806
|
+
await this.write(encodeTsToRustFrame(TsToRustMessageTypes.BridgeResponse, encodeBridgeResponsePayload(frameRunId, callId, true, encoded)));
|
|
2807
|
+
if (this.runs.has(frameRunId)) this.activateStreams(streams, runId);
|
|
2808
|
+
else streams?.releaseAll();
|
|
2809
|
+
}, (err) => this.write(encodeTsToRustFrame(TsToRustMessageTypes.BridgeResponse, encodeBridgeResponsePayload(frameRunId, callId, false, void 0, bridgeErrorPayloadFromUnknown(err))))).catch(async (err) => {
|
|
2810
|
+
try {
|
|
2811
|
+
await this.write(encodeTsToRustFrame(TsToRustMessageTypes.BridgeResponse, encodeBridgeResponsePayload(frameRunId, callId, false, void 0, bridgeErrorPayloadFromUnknown(err))));
|
|
2812
|
+
} catch {
|
|
2813
|
+
if (this.runs.has(frameRunId)) this.abortConnection();
|
|
2814
|
+
}
|
|
2815
|
+
});
|
|
1406
2816
|
}
|
|
1407
|
-
throw new Error("connection closed before receiving a Result frame");
|
|
1408
2817
|
}
|
|
1409
2818
|
async write(frame) {
|
|
1410
2819
|
await new Promise((resolve, reject) => {
|
|
@@ -1424,7 +2833,7 @@ var RuntimeIpcClient = class RuntimeIpcClient {
|
|
|
1424
2833
|
* the runtime resolves import handle IDs before the frame is sent, so both
|
|
1425
2834
|
* lookups are plain name-addressed.
|
|
1426
2835
|
*
|
|
1427
|
-
* Returns `undefined` when both maps are empty so the
|
|
2836
|
+
* Returns `undefined` when both maps are empty so the router short-circuits to
|
|
1428
2837
|
* an "unconfigured bridge" error response.
|
|
1429
2838
|
* @param globals
|
|
1430
2839
|
* @param imports
|
|
@@ -1452,82 +2861,237 @@ function connectSocket(socketPath) {
|
|
|
1452
2861
|
socket.once("error", reject);
|
|
1453
2862
|
});
|
|
1454
2863
|
}
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
2864
|
+
/**
|
|
2865
|
+
* The waiter queue is at `maxQueuedRuns`: the run is shed as a failed
|
|
2866
|
+
* result with `error.code: 'ERR_QUEUE_FULL'` instead of growing an
|
|
2867
|
+
* unbounded, memory-holding queue.
|
|
2868
|
+
*/
|
|
2869
|
+
var QueueFullError = class extends Error {
|
|
2870
|
+
constructor(message) {
|
|
2871
|
+
super(message);
|
|
2872
|
+
this.name = "QueueFullError";
|
|
2873
|
+
}
|
|
2874
|
+
};
|
|
2875
|
+
/**
|
|
2876
|
+
* FIFO admission over a fixed number of run slots. Purely a counter — it
|
|
2877
|
+
* never touches connections.
|
|
2878
|
+
*/
|
|
2879
|
+
var SlotPool = class {
|
|
2880
|
+
capacity;
|
|
2881
|
+
maxQueued;
|
|
2882
|
+
active = 0;
|
|
1459
2883
|
waiters = [];
|
|
2884
|
+
disposed = false;
|
|
2885
|
+
constructor(capacity, maxQueued) {
|
|
2886
|
+
this.capacity = capacity;
|
|
2887
|
+
this.maxQueued = maxQueued;
|
|
2888
|
+
}
|
|
2889
|
+
/**
|
|
2890
|
+
* Callers currently queued for a slot — `stats()` reports this as
|
|
2891
|
+
* `queueDepth`.
|
|
2892
|
+
*/
|
|
2893
|
+
get queueDepth() {
|
|
2894
|
+
return this.waiters.length;
|
|
2895
|
+
}
|
|
2896
|
+
/**
|
|
2897
|
+
* Take a slot, or queue FIFO until one frees.
|
|
2898
|
+
* @param signal
|
|
2899
|
+
* The caller's abort signal, honoured *while queued*. Per-run
|
|
2900
|
+
* `wallTimeMs` / `cpuTimeMs` cannot bound that wait: the caller is
|
|
2901
|
+
* upstream of the runtime and its `Run` frame has not been sent yet.
|
|
2902
|
+
* `AbortSignal.timeout()` composes as a queue-wait bound — there is no
|
|
2903
|
+
* separate timeout knob.
|
|
2904
|
+
* @param hardAbortSignal
|
|
2905
|
+
* The caller's hard-abort signal. Soft and hard only differ once a run
|
|
2906
|
+
* is executing; while queued, either firing dequeues the caller the
|
|
2907
|
+
* same way.
|
|
2908
|
+
*/
|
|
2909
|
+
acquire(signal, hardAbortSignal) {
|
|
2910
|
+
if (this.disposed) return Promise.reject(/* @__PURE__ */ new Error("runtime is disposed"));
|
|
2911
|
+
if (signal?.aborted) return Promise.reject(new RunAbortedError(signal.reason));
|
|
2912
|
+
if (hardAbortSignal?.aborted) return Promise.reject(new RunAbortedError(hardAbortSignal.reason));
|
|
2913
|
+
if (this.active < this.capacity) {
|
|
2914
|
+
this.active++;
|
|
2915
|
+
return Promise.resolve();
|
|
2916
|
+
}
|
|
2917
|
+
if (this.waiters.length >= this.maxQueued) return Promise.reject(new QueueFullError(`run queue is full (${this.waiters.length} queued behind ${this.capacity} executing runs, maxQueuedRuns: ${this.maxQueued}); the sandbox is overloaded — retry later, or raise maxQueuedRuns`));
|
|
2918
|
+
return new Promise((resolve, reject) => {
|
|
2919
|
+
const waiter = {
|
|
2920
|
+
resolve,
|
|
2921
|
+
reject
|
|
2922
|
+
};
|
|
2923
|
+
if (signal === void 0 && hardAbortSignal === void 0) {
|
|
2924
|
+
this.waiters.push(waiter);
|
|
2925
|
+
return;
|
|
2926
|
+
}
|
|
2927
|
+
const dequeue = (reason) => {
|
|
2928
|
+
const at = this.waiters.indexOf(waiter);
|
|
2929
|
+
if (at !== -1) this.waiters.splice(at, 1);
|
|
2930
|
+
reject(new RunAbortedError(reason));
|
|
2931
|
+
};
|
|
2932
|
+
const onAbort = () => dequeue(signal?.reason);
|
|
2933
|
+
const onHardAbort = () => dequeue(hardAbortSignal?.reason);
|
|
2934
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
2935
|
+
hardAbortSignal?.addEventListener("abort", onHardAbort, { once: true });
|
|
2936
|
+
const settle = () => {
|
|
2937
|
+
signal?.removeEventListener("abort", onAbort);
|
|
2938
|
+
hardAbortSignal?.removeEventListener("abort", onHardAbort);
|
|
2939
|
+
};
|
|
2940
|
+
waiter.resolve = () => {
|
|
2941
|
+
settle();
|
|
2942
|
+
resolve();
|
|
2943
|
+
};
|
|
2944
|
+
waiter.reject = (error) => {
|
|
2945
|
+
settle();
|
|
2946
|
+
reject(error);
|
|
2947
|
+
};
|
|
2948
|
+
this.waiters.push(waiter);
|
|
2949
|
+
});
|
|
2950
|
+
}
|
|
2951
|
+
/**
|
|
2952
|
+
* Free a slot. The longest-queued caller takes it directly; only when
|
|
2953
|
+
* nobody waits does the active count drop.
|
|
2954
|
+
*/
|
|
2955
|
+
release() {
|
|
2956
|
+
const next = this.waiters.shift();
|
|
2957
|
+
if (next !== void 0) {
|
|
2958
|
+
next.resolve();
|
|
2959
|
+
return;
|
|
2960
|
+
}
|
|
2961
|
+
this.active--;
|
|
2962
|
+
}
|
|
2963
|
+
dispose() {
|
|
2964
|
+
if (this.disposed) return;
|
|
2965
|
+
this.disposed = true;
|
|
2966
|
+
for (const { reject } of this.waiters.splice(0)) reject(/* @__PURE__ */ new Error("runtime disposed"));
|
|
2967
|
+
}
|
|
2968
|
+
};
|
|
2969
|
+
/**
|
|
2970
|
+
* The sandbox's open connections, shared by run id multiplexing: each
|
|
2971
|
+
* carries up to {@link RUNS_PER_CONNECTION} concurrent runs, one is opened
|
|
2972
|
+
* lazily when every open connection is at the cap, and a broken one is
|
|
2973
|
+
* dropped when observed so the next caller opens a replacement.
|
|
2974
|
+
*/
|
|
2975
|
+
var ConnectionRegistry = class {
|
|
2976
|
+
/**
|
|
2977
|
+
* Every open connection — `stats()` reports this (plus in-flight opens)
|
|
2978
|
+
* as `openConnections`. A connection that died stays counted until the
|
|
2979
|
+
* next `tryAcquire()` observes and drops it — the number is the
|
|
2980
|
+
* registry's ledger, not a per-read socket probe.
|
|
2981
|
+
*/
|
|
2982
|
+
connections = [];
|
|
2983
|
+
/**
|
|
2984
|
+
* Connects in flight — counted in the ledger so a burst of opens is
|
|
2985
|
+
* visible, not a blind spot.
|
|
2986
|
+
*/
|
|
2987
|
+
opening = 0;
|
|
1460
2988
|
connect;
|
|
1461
2989
|
disposed = false;
|
|
1462
|
-
constructor(
|
|
1463
|
-
this.free = [...clients];
|
|
2990
|
+
constructor(connect) {
|
|
1464
2991
|
this.connect = connect;
|
|
1465
2992
|
}
|
|
2993
|
+
get openConnections() {
|
|
2994
|
+
return this.connections.length + this.opening;
|
|
2995
|
+
}
|
|
1466
2996
|
/**
|
|
1467
|
-
*
|
|
1468
|
-
*
|
|
1469
|
-
*
|
|
1470
|
-
*
|
|
2997
|
+
* A usable connection below the per-connection run cap, or `undefined`
|
|
2998
|
+
* when every one is full (the caller opens a fresh one via {@link open}).
|
|
2999
|
+
*
|
|
3000
|
+
* Synchronous on purpose: the caller starts its run in the same tick, and
|
|
3001
|
+
* run registration in the client is synchronous from that call — so the
|
|
3002
|
+
* load this observed cannot go stale under it, and the cap is exact
|
|
3003
|
+
* rather than best-effort. First-fit keeps packing deterministic:
|
|
3004
|
+
* connection count settles at ceil(active runs / cap). A connection that
|
|
3005
|
+
* died is dropped here, not handed out.
|
|
3006
|
+
*/
|
|
3007
|
+
tryAcquire() {
|
|
3008
|
+
if (this.disposed) throw new Error("runtime is disposed");
|
|
3009
|
+
for (let i = 0; i < this.connections.length; i++) {
|
|
3010
|
+
const client = this.connections[i];
|
|
3011
|
+
if (!client.usable) {
|
|
3012
|
+
client.dispose().catch(() => {});
|
|
3013
|
+
this.connections.splice(i, 1);
|
|
3014
|
+
i--;
|
|
3015
|
+
continue;
|
|
3016
|
+
}
|
|
3017
|
+
if (client.load < 4) return client;
|
|
3018
|
+
}
|
|
3019
|
+
}
|
|
3020
|
+
/**
|
|
3021
|
+
* Open a fresh connection and add it to the shared set. Concurrent
|
|
3022
|
+
* callers that all found the set full each open one — a cold burst can
|
|
3023
|
+
* briefly open more connections than the steady-state packing needs;
|
|
3024
|
+
* they are kept and reused, so the count follows demand from then on. A
|
|
3025
|
+
* failed connect fails this caller's run; the registry never shrinks
|
|
3026
|
+
* silently.
|
|
1471
3027
|
*/
|
|
1472
|
-
async
|
|
1473
|
-
|
|
3028
|
+
async open() {
|
|
3029
|
+
if (this.disposed) throw new Error("runtime is disposed");
|
|
3030
|
+
this.opening++;
|
|
1474
3031
|
try {
|
|
1475
|
-
|
|
3032
|
+
const client = await this.connect();
|
|
3033
|
+
if (this.disposed) {
|
|
3034
|
+
client.dispose().catch(() => {});
|
|
3035
|
+
throw new Error("runtime is disposed");
|
|
3036
|
+
}
|
|
3037
|
+
this.connections.push(client);
|
|
3038
|
+
return client;
|
|
1476
3039
|
} finally {
|
|
1477
|
-
this.
|
|
3040
|
+
this.opening--;
|
|
1478
3041
|
}
|
|
1479
3042
|
}
|
|
1480
3043
|
async dispose() {
|
|
1481
3044
|
if (this.disposed) return;
|
|
1482
3045
|
this.disposed = true;
|
|
1483
|
-
|
|
1484
|
-
await Promise.all(this.free.splice(0).map((c) => c.dispose()));
|
|
3046
|
+
await Promise.all(this.connections.splice(0).map((client) => client.dispose()));
|
|
1485
3047
|
}
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
3048
|
+
};
|
|
3049
|
+
/**
|
|
3050
|
+
* What `createSandbox` hands to `SandboxImpl`: slot admission composed with
|
|
3051
|
+
* connection sharing, exposed through the same borrow-run shape as before.
|
|
3052
|
+
*/
|
|
3053
|
+
var RunPool = class {
|
|
3054
|
+
slots;
|
|
3055
|
+
connections;
|
|
3056
|
+
constructor(maxConcurrentRuns, maxQueuedRuns, connect) {
|
|
3057
|
+
this.slots = new SlotPool(maxConcurrentRuns, maxQueuedRuns);
|
|
3058
|
+
this.connections = new ConnectionRegistry(connect);
|
|
1496
3059
|
}
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
if (!client.usable) {
|
|
1503
|
-
this.replace(client).catch(() => {});
|
|
1504
|
-
return;
|
|
1505
|
-
}
|
|
1506
|
-
const next = this.waiters.shift();
|
|
1507
|
-
if (next !== void 0) next.resolve(client);
|
|
1508
|
-
else this.free.push(client);
|
|
3060
|
+
get queueDepth() {
|
|
3061
|
+
return this.slots.queueDepth;
|
|
3062
|
+
}
|
|
3063
|
+
get openConnections() {
|
|
3064
|
+
return this.connections.openConnections;
|
|
1509
3065
|
}
|
|
1510
3066
|
/**
|
|
1511
|
-
*
|
|
1512
|
-
*
|
|
1513
|
-
*
|
|
1514
|
-
*
|
|
1515
|
-
*
|
|
3067
|
+
* Take a run slot (queueing FIFO when `maxConcurrentRuns` are executing),
|
|
3068
|
+
* pick a shared connection, run `fn`, then release the slot when `fn`
|
|
3069
|
+
* settles — which is at the run's Result. A run that ended with pending
|
|
3070
|
+
* `waitUntil` work holds no slot during its grace phase: the grace frames
|
|
3071
|
+
* ride the shared connection, routed by run id, until its RunComplete.
|
|
3072
|
+
* @param fn ran with the shared connection
|
|
3073
|
+
* @param signal the caller's abort signal, honoured while queued
|
|
3074
|
+
* @param hardAbortSignal the caller's hard-abort signal — while queued it
|
|
3075
|
+
* dequeues exactly like `signal`
|
|
1516
3076
|
*/
|
|
1517
|
-
async
|
|
1518
|
-
await
|
|
1519
|
-
|
|
1520
|
-
let fresh;
|
|
3077
|
+
async withClient(fn, signal, hardAbortSignal) {
|
|
3078
|
+
await this.slots.acquire(signal, hardAbortSignal);
|
|
3079
|
+
let client;
|
|
1521
3080
|
try {
|
|
1522
|
-
|
|
1523
|
-
} catch {
|
|
1524
|
-
|
|
3081
|
+
client = this.connections.tryAcquire() ?? await this.connections.open();
|
|
3082
|
+
} catch (error) {
|
|
3083
|
+
this.slots.release();
|
|
3084
|
+
throw error;
|
|
1525
3085
|
}
|
|
1526
|
-
|
|
1527
|
-
await
|
|
1528
|
-
|
|
3086
|
+
try {
|
|
3087
|
+
return await fn(client);
|
|
3088
|
+
} finally {
|
|
3089
|
+
this.slots.release();
|
|
1529
3090
|
}
|
|
1530
|
-
|
|
3091
|
+
}
|
|
3092
|
+
async dispose() {
|
|
3093
|
+
this.slots.dispose();
|
|
3094
|
+
await this.connections.dispose();
|
|
1531
3095
|
}
|
|
1532
3096
|
};
|
|
1533
3097
|
//#endregion
|
|
@@ -1538,6 +3102,12 @@ function isBridgeWithShim(v) {
|
|
|
1538
3102
|
function isDataGlobal(v) {
|
|
1539
3103
|
return typeof v === "object" && v !== null && v.kind === "data";
|
|
1540
3104
|
}
|
|
3105
|
+
function isBridgeGlobal(v) {
|
|
3106
|
+
return typeof v === "object" && v !== null && v.kind === "bridge";
|
|
3107
|
+
}
|
|
3108
|
+
function isStringGlobal(v) {
|
|
3109
|
+
return typeof v === "object" && v !== null && v.kind === "string";
|
|
3110
|
+
}
|
|
1541
3111
|
/**
|
|
1542
3112
|
* Private bridge-dispatch name for a `BridgeWithShim` handler. This is a wire
|
|
1543
3113
|
* dispatch key and an object-property key — never interpolated into generated
|
|
@@ -1565,18 +3135,34 @@ function processGlobals(globals) {
|
|
|
1565
3135
|
for (const [name, value] of Object.entries(globals)) if (typeof value === "function") {
|
|
1566
3136
|
defs.push({
|
|
1567
3137
|
kind: "bridge",
|
|
1568
|
-
name
|
|
3138
|
+
name,
|
|
3139
|
+
enumerable: true
|
|
1569
3140
|
});
|
|
1570
3141
|
dispatch[name] = value;
|
|
1571
3142
|
} else if (typeof value === "string") defs.push({
|
|
1572
3143
|
kind: "string",
|
|
1573
3144
|
name,
|
|
1574
|
-
expr: value
|
|
3145
|
+
expr: value,
|
|
3146
|
+
enumerable: true
|
|
3147
|
+
});
|
|
3148
|
+
else if (isBridgeGlobal(value)) {
|
|
3149
|
+
defs.push({
|
|
3150
|
+
kind: "bridge",
|
|
3151
|
+
name,
|
|
3152
|
+
enumerable: value.enumerable ?? true
|
|
3153
|
+
});
|
|
3154
|
+
dispatch[name] = value.handler;
|
|
3155
|
+
} else if (isStringGlobal(value)) defs.push({
|
|
3156
|
+
kind: "string",
|
|
3157
|
+
name,
|
|
3158
|
+
expr: value.expr,
|
|
3159
|
+
enumerable: value.enumerable ?? true
|
|
1575
3160
|
});
|
|
1576
3161
|
else if (isDataGlobal(value)) defs.push({
|
|
1577
3162
|
kind: "data",
|
|
1578
3163
|
name,
|
|
1579
|
-
value: value.value
|
|
3164
|
+
value: value.value,
|
|
3165
|
+
enumerable: value.enumerable ?? true
|
|
1580
3166
|
});
|
|
1581
3167
|
else if (isBridgeWithShim(value)) {
|
|
1582
3168
|
const handlerName = shimHandlerName(name);
|
|
@@ -1584,7 +3170,8 @@ function processGlobals(globals) {
|
|
|
1584
3170
|
kind: "shim",
|
|
1585
3171
|
name,
|
|
1586
3172
|
shim: value.shim,
|
|
1587
|
-
handlerName
|
|
3173
|
+
handlerName,
|
|
3174
|
+
enumerable: value.enumerable ?? true
|
|
1588
3175
|
});
|
|
1589
3176
|
dispatch[handlerName] = value.handler;
|
|
1590
3177
|
}
|
|
@@ -1597,34 +3184,61 @@ function processGlobals(globals) {
|
|
|
1597
3184
|
* Resolve bridge globals for a `prefix.run()` call.
|
|
1598
3185
|
*
|
|
1599
3186
|
* String/data globals and shim *wrappers* are already compiled into the
|
|
1600
|
-
*
|
|
1601
|
-
*
|
|
3187
|
+
* declared prefix state, replayed by the runtime when the prefix evaluates —
|
|
3188
|
+
* only the bridge *stubs* they call need re-installing per run (bridge stubs
|
|
3189
|
+
* are bound to the run's socket). So
|
|
1602
3190
|
* every returned def is `kind: 'bridge'`, and shimmed globals are routed to
|
|
1603
3191
|
* their private `__iso4_<name>_h` key so rebinding updates the handler the
|
|
1604
3192
|
* shim calls, without touching the shim itself.
|
|
1605
3193
|
* @param runGlobals
|
|
1606
3194
|
* @param precompileGlobals
|
|
1607
3195
|
*/
|
|
3196
|
+
/**
|
|
3197
|
+
* Resolve a per-run override for a declared bridge global.
|
|
3198
|
+
*
|
|
3199
|
+
* An omitted key falls back to the precompile-time handler (the intended
|
|
3200
|
+
* default). But a key that IS supplied yet is not a function — the runtime
|
|
3201
|
+
* shape TypeScript cannot catch, e.g. a tenant handler that resolves to
|
|
3202
|
+
* `undefined` — throws instead of silently reusing the (often broader) default,
|
|
3203
|
+
* which would be a fail-open exactly where the API is used to narrow privilege.
|
|
3204
|
+
* This matches the imports side, which already rejects a non-function rebind.
|
|
3205
|
+
* @param runGlobals the per-run rebind map
|
|
3206
|
+
* @param name the declared global's name
|
|
3207
|
+
* @param fallback the precompile-time handler used when no override is supplied
|
|
3208
|
+
*/
|
|
3209
|
+
function resolveOverride(runGlobals, name, fallback) {
|
|
3210
|
+
if (!Object.hasOwn(runGlobals, name)) return fallback;
|
|
3211
|
+
const override = runGlobals[name];
|
|
3212
|
+
if (typeof override !== "function") throw new TypeError(`[iso4] global override "${name}" must be a function, got ${override === null ? "null" : typeof override}`);
|
|
3213
|
+
return override;
|
|
3214
|
+
}
|
|
1608
3215
|
function extractBridgeGlobals(runGlobals, precompileGlobals) {
|
|
1609
3216
|
const defs = [];
|
|
1610
3217
|
const dispatch = {};
|
|
1611
3218
|
for (const [name, value] of Object.entries(precompileGlobals)) {
|
|
1612
|
-
if (typeof value === "string" || isDataGlobal(value)) continue;
|
|
3219
|
+
if (typeof value === "string" || isStringGlobal(value) || isDataGlobal(value)) continue;
|
|
1613
3220
|
if (isBridgeWithShim(value)) {
|
|
1614
3221
|
const handlerName = shimHandlerName(name);
|
|
1615
|
-
const override = runGlobals[name];
|
|
1616
3222
|
defs.push({
|
|
1617
3223
|
kind: "bridge",
|
|
1618
|
-
name: handlerName
|
|
3224
|
+
name: handlerName,
|
|
3225
|
+
enumerable: true
|
|
1619
3226
|
});
|
|
1620
|
-
dispatch[handlerName] =
|
|
3227
|
+
dispatch[handlerName] = resolveOverride(runGlobals, name, value.handler);
|
|
3228
|
+
} else if (isBridgeGlobal(value)) {
|
|
3229
|
+
defs.push({
|
|
3230
|
+
kind: "bridge",
|
|
3231
|
+
name,
|
|
3232
|
+
enumerable: value.enumerable ?? true
|
|
3233
|
+
});
|
|
3234
|
+
dispatch[name] = resolveOverride(runGlobals, name, value.handler);
|
|
1621
3235
|
} else if (typeof value === "function") {
|
|
1622
|
-
const override = runGlobals[name];
|
|
1623
3236
|
defs.push({
|
|
1624
3237
|
kind: "bridge",
|
|
1625
|
-
name
|
|
3238
|
+
name,
|
|
3239
|
+
enumerable: true
|
|
1626
3240
|
});
|
|
1627
|
-
dispatch[name] =
|
|
3241
|
+
dispatch[name] = resolveOverride(runGlobals, name, value);
|
|
1628
3242
|
}
|
|
1629
3243
|
}
|
|
1630
3244
|
for (const [name, override] of Object.entries(runGlobals)) {
|
|
@@ -1632,7 +3246,8 @@ function extractBridgeGlobals(runGlobals, precompileGlobals) {
|
|
|
1632
3246
|
if (typeof override === "function") {
|
|
1633
3247
|
defs.push({
|
|
1634
3248
|
kind: "bridge",
|
|
1635
|
-
name
|
|
3249
|
+
name,
|
|
3250
|
+
enumerable: true
|
|
1636
3251
|
});
|
|
1637
3252
|
dispatch[name] = override;
|
|
1638
3253
|
}
|
|
@@ -1647,19 +3262,27 @@ function extractBridgeGlobals(runGlobals, precompileGlobals) {
|
|
|
1647
3262
|
/**
|
|
1648
3263
|
* \@iso4/sandbox - public entry point.
|
|
1649
3264
|
*
|
|
1650
|
-
* Spawns the Rust V8 subprocess,
|
|
1651
|
-
*
|
|
3265
|
+
* Spawns the Rust V8 subprocess, admits runs through a slot pool over
|
|
3266
|
+
* lazily opened UDS connections, and exposes the `Sandbox` + `Prefix` API.
|
|
1652
3267
|
*/
|
|
1653
3268
|
async function createSandbox(options) {
|
|
3269
|
+
if (options !== void 0 && "maxIsolates" in options) throw new TypeError("[@iso4/sandbox] maxIsolates was removed: capacity admits runs, not connections — set maxConcurrentRuns instead (same default: os.availableParallelism())");
|
|
1654
3270
|
const binaryPath = resolveRuntimeBinary(options);
|
|
1655
|
-
|
|
1656
|
-
const
|
|
1657
|
-
const
|
|
3271
|
+
validateMemoryMb(options?.memoryMb, "memoryMb");
|
|
3272
|
+
const warmBudgetBytes = resolveWarmBudgetBytes(options?.memoryBudgetMb);
|
|
3273
|
+
const maxConcurrentRuns = options?.maxConcurrentRuns ?? defaultMaxConcurrentRuns(warmBudgetBytes, options?.memoryMb);
|
|
3274
|
+
if (!Number.isInteger(maxConcurrentRuns) || maxConcurrentRuns < 1) throw new TypeError("[@iso4/sandbox] maxConcurrentRuns must be an integer >= 1");
|
|
3275
|
+
const maxQueuedRuns = options?.maxQueuedRuns ?? 100 * maxConcurrentRuns;
|
|
3276
|
+
if (!Number.isInteger(maxQueuedRuns) || maxQueuedRuns < 0) throw new TypeError("[@iso4/sandbox] maxQueuedRuns must be an integer >= 0");
|
|
3277
|
+
const socketDir = await mkdtemp(join(tmpdir(), "iso4-v8-"));
|
|
3278
|
+
const socketPath = join(socketDir, "runtime.sock");
|
|
3279
|
+
const descriptorToken = randomBytes(16);
|
|
3280
|
+
const brandKey = brandKeyForToken(descriptorToken);
|
|
1658
3281
|
const proc = spawn(binaryPath, [
|
|
1659
3282
|
"--socket",
|
|
1660
3283
|
socketPath,
|
|
1661
|
-
"--
|
|
1662
|
-
|
|
3284
|
+
"--warm-budget-bytes",
|
|
3285
|
+
String(warmBudgetBytes)
|
|
1663
3286
|
], { stdio: [
|
|
1664
3287
|
"ignore",
|
|
1665
3288
|
"ignore",
|
|
@@ -1668,19 +3291,94 @@ async function createSandbox(options) {
|
|
|
1668
3291
|
proc.once("error", (err) => {
|
|
1669
3292
|
process.stderr.write(`[@iso4/sandbox] failed to start V8 process: ${err.message}\n`);
|
|
1670
3293
|
});
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
3294
|
+
try {
|
|
3295
|
+
await waitForSocket(socketPath, proc);
|
|
3296
|
+
const connect = () => RuntimeIpcClient.connect({
|
|
3297
|
+
socketPath,
|
|
3298
|
+
descriptorToken
|
|
3299
|
+
});
|
|
3300
|
+
return new SandboxImpl(proc, new RunPool(maxConcurrentRuns, maxQueuedRuns, connect), await connect(), socketPath, brandKey, options?.memoryMb);
|
|
3301
|
+
} catch (error) {
|
|
3302
|
+
proc.kill();
|
|
3303
|
+
await rm(socketDir, {
|
|
3304
|
+
recursive: true,
|
|
3305
|
+
force: true
|
|
3306
|
+
}).catch(() => {});
|
|
3307
|
+
throw error;
|
|
3308
|
+
}
|
|
3309
|
+
}
|
|
3310
|
+
/**
|
|
3311
|
+
* The warm budget in bytes — the ONE capacity fact the runtime needs
|
|
3312
|
+
* (celld's model): the RSS mark it sheds against, `0` = disabled.
|
|
3313
|
+
* Independent of `memoryMb`: RSS is measured, not derived from per-isolate
|
|
3314
|
+
* caps, so an uncapped-heap sandbox is budgeted all the same.
|
|
3315
|
+
* @param memoryBudgetMb the explicit budget knob (`0` opts out of
|
|
3316
|
+
* watermarks entirely, like celld's `CELLD_MAX_RSS_MB=0`), or undefined
|
|
3317
|
+
* for the container-aware default
|
|
3318
|
+
*/
|
|
3319
|
+
function resolveWarmBudgetBytes(memoryBudgetMb) {
|
|
3320
|
+
if (memoryBudgetMb !== void 0 && !Number.isFinite(memoryBudgetMb)) throw new TypeError("[@iso4/sandbox] memoryBudgetMb must be a finite number of megabytes");
|
|
3321
|
+
const budgetMb = memoryBudgetMb ?? defaultMemoryBudgetMb();
|
|
3322
|
+
return Math.min(Math.max(0, Math.floor(budgetMb * 1024 * 1024)), Number.MAX_SAFE_INTEGER);
|
|
3323
|
+
}
|
|
3324
|
+
/**
|
|
3325
|
+
* The Node-host reserve subtracted from the container limit before any
|
|
3326
|
+
* capacity line is drawn. Mirrors the runtime's `container.rs`
|
|
3327
|
+
* `NODE_RESERVE_BYTES` — change both together. A measured reserve replaces
|
|
3328
|
+
* this constant later (#165).
|
|
3329
|
+
*/
|
|
3330
|
+
const NODE_RESERVE_MB = 256;
|
|
3331
|
+
/**
|
|
3332
|
+
* Default memory budget (the 80% shedding mark): 80% of what remains of the
|
|
3333
|
+
* container limit after the Node-host reserve — container/cgroup-aware via
|
|
3334
|
+
* `process.constrainedMemory()` (`os.totalmem()` lies inside containers;
|
|
3335
|
+
* the fallback covers bare metal, where constrainedMemory reports 0). The
|
|
3336
|
+
* runtime compares it against measured GLOBAL container memory (the same
|
|
3337
|
+
* limit's usage), and derives its own hard admission line at 90% of the
|
|
3338
|
+
* identical base.
|
|
3339
|
+
*
|
|
3340
|
+
* Floored at 64 MB: on a host at or below the reserve the subtraction goes
|
|
3341
|
+
* to zero or negative, and a zero DEFAULT would silently disable the
|
|
3342
|
+
* watermarks on exactly the memory-starved machines that need them most
|
|
3343
|
+
* (`memoryBudgetMb: 0` stays the only deliberate opt-out). The floor makes
|
|
3344
|
+
* such a host shed warmth aggressively instead — degraded, never
|
|
3345
|
+
* unprotected — and says so on stderr.
|
|
3346
|
+
*/
|
|
3347
|
+
function defaultMemoryBudgetMb() {
|
|
3348
|
+
const constrained = process.constrainedMemory?.() || Number.POSITIVE_INFINITY;
|
|
3349
|
+
const totalMb = Math.min(constrained, totalmem()) / (1024 * 1024);
|
|
3350
|
+
const budgetMb = Math.floor((totalMb - NODE_RESERVE_MB) * .8);
|
|
3351
|
+
if (budgetMb < 64) {
|
|
3352
|
+
process.stderr.write(`[@iso4/sandbox] host memory (${Math.floor(totalMb)} MB) leaves no room for a warm budget after the ${NODE_RESERVE_MB} MB host reserve — flooring the budget at 64 MB (expect aggressive eviction); set memoryBudgetMb explicitly to tune or 0 to disable\n`);
|
|
3353
|
+
return 64;
|
|
3354
|
+
}
|
|
3355
|
+
return budgetMb;
|
|
1677
3356
|
}
|
|
1678
|
-
|
|
3357
|
+
/**
|
|
3358
|
+
* Default `maxConcurrentRuns`: the core count, unless that many worst-case
|
|
3359
|
+
* heaps could not fit inside the memory budget — then the budget bounds it
|
|
3360
|
+
* (`min(cores, budget / ceiling)`, at least 1). The worst case is each
|
|
3361
|
+
* isolate's terminating ceiling (`memoryMb` plus its headroom band), not the
|
|
3362
|
+
* advertised number. With an uncapped heap (`memoryMb: 0`) or a disabled
|
|
3363
|
+
* budget there is nothing to bound with, so the default stays the core
|
|
3364
|
+
* count.
|
|
3365
|
+
* @param warmBudgetBytes
|
|
3366
|
+
* @param memoryMb
|
|
3367
|
+
*/
|
|
3368
|
+
function defaultMaxConcurrentRuns(warmBudgetBytes, memoryMb) {
|
|
3369
|
+
const cores = availableParallelism();
|
|
3370
|
+
const capMb = hardCeilingMb(memoryMb) ?? 128 + heapBandMb(128);
|
|
3371
|
+
if (capMb <= 0 || warmBudgetBytes <= 0) return cores;
|
|
3372
|
+
const fitting = Math.floor(warmBudgetBytes / (capMb * 1024 * 1024));
|
|
3373
|
+
return Math.max(1, Math.min(cores, fitting));
|
|
3374
|
+
}
|
|
3375
|
+
async function waitForSocket(socketPath, proc, timeoutMs = 5e3) {
|
|
1679
3376
|
const deadline = Date.now() + timeoutMs;
|
|
1680
3377
|
while (Date.now() < deadline) try {
|
|
1681
3378
|
await access(socketPath);
|
|
1682
3379
|
return;
|
|
1683
3380
|
} catch {
|
|
3381
|
+
if (proc.exitCode !== null || proc.signalCode !== null) throw new Error(`[@iso4/sandbox] the V8 process exited before its socket appeared (exit code ${proc.exitCode}, signal ${proc.signalCode}). Its own diagnostics are on this process's stderr.`);
|
|
1684
3382
|
await new Promise((resolve) => {
|
|
1685
3383
|
setTimeout(resolve, 50);
|
|
1686
3384
|
});
|
|
@@ -1693,7 +3391,7 @@ async function waitForSocket(socketPath, timeoutMs = 5e3) {
|
|
|
1693
3391
|
* is retained for backward compatibility; `reason` carries whatever was passed
|
|
1694
3392
|
* to `abort(reason)`.
|
|
1695
3393
|
*
|
|
1696
|
-
* When graceful termination
|
|
3394
|
+
* When graceful termination succeeds, Rust sends a real `ERR_ABORTED`
|
|
1697
3395
|
* Result and `from` carries its telemetry — duration, CPU time, bridge records,
|
|
1698
3396
|
* and any logs produced before the abort landed — which is grafted onto the
|
|
1699
3397
|
* aborted shape. When it falls back to socket teardown (or the signal was
|
|
@@ -1702,6 +3400,139 @@ async function waitForSocket(socketPath, timeoutMs = 5e3) {
|
|
|
1702
3400
|
* @param reason
|
|
1703
3401
|
* @param from
|
|
1704
3402
|
*/
|
|
3403
|
+
/**
|
|
3404
|
+
* Synthesized result for a run displaced by a connection desync. The run never
|
|
3405
|
+
* reached the isolate, so unlike {@link abortedResult} there is no partial
|
|
3406
|
+
* telemetry to carry over — every field is empty by construction.
|
|
3407
|
+
* @param error
|
|
3408
|
+
*/
|
|
3409
|
+
/**
|
|
3410
|
+
* Map a decoded `RunComplete` frame to the public {@link WaitUntilResult},
|
|
3411
|
+
* synthesizing a truncated report when the connection died mid-grace.
|
|
3412
|
+
* @param report the decoded frame, or `undefined` on connection loss
|
|
3413
|
+
*/
|
|
3414
|
+
function waitUntilResultFrom(report) {
|
|
3415
|
+
if (report === void 0) return {
|
|
3416
|
+
status: "truncated",
|
|
3417
|
+
durationMs: 0,
|
|
3418
|
+
wallTimeMs: 0,
|
|
3419
|
+
cpuTimeMs: 0,
|
|
3420
|
+
stdout: [],
|
|
3421
|
+
stderr: [],
|
|
3422
|
+
bridgeCalls: [],
|
|
3423
|
+
error: {
|
|
3424
|
+
name: "Error",
|
|
3425
|
+
message: "connection lost during the waitUntil grace phase"
|
|
3426
|
+
}
|
|
3427
|
+
};
|
|
3428
|
+
const out = {
|
|
3429
|
+
status: report.status,
|
|
3430
|
+
durationMs: report.durationMs,
|
|
3431
|
+
wallTimeMs: report.wallTimeMs,
|
|
3432
|
+
cpuTimeMs: report.cpuTimeMs,
|
|
3433
|
+
stdout: report.stdout,
|
|
3434
|
+
stderr: report.stderr,
|
|
3435
|
+
bridgeCalls: report.bridgeCalls
|
|
3436
|
+
};
|
|
3437
|
+
if (report.error !== void 0) out.error = report.error;
|
|
3438
|
+
return out;
|
|
3439
|
+
}
|
|
3440
|
+
/**
|
|
3441
|
+
* A heap cap must be an integer number of megabytes ≥ 0 (0 = uncapped):
|
|
3442
|
+
* the wire carries it as a u32, and a fractional or negative value would
|
|
3443
|
+
* silently misencode instead of capping.
|
|
3444
|
+
* @param value the candidate cap — a plain number, or the two-line object
|
|
3445
|
+
* @param where the option name for the error message
|
|
3446
|
+
*/
|
|
3447
|
+
function validateMemoryMb(value, where) {
|
|
3448
|
+
if (value === void 0) return;
|
|
3449
|
+
if (typeof value === "number") {
|
|
3450
|
+
if (!Number.isInteger(value) || value < 0) throw new TypeError(`[@iso4/sandbox] ${where} must be an integer >= 0 (megabytes; 0 = uncapped)`);
|
|
3451
|
+
return;
|
|
3452
|
+
}
|
|
3453
|
+
if (value === null || typeof value !== "object") throw new TypeError(`[@iso4/sandbox] ${where} must be a number of megabytes or { soft?, hard }`);
|
|
3454
|
+
if (!Number.isInteger(value.hard) || value.hard < 1) throw new TypeError(`[@iso4/sandbox] ${where}.hard must be an integer >= 1 (megabytes) — write memoryMb: 0 for uncapped`);
|
|
3455
|
+
if (value.soft === void 0) return;
|
|
3456
|
+
if (!Number.isInteger(value.soft) || value.soft < 1) throw new TypeError(`[@iso4/sandbox] ${where}.soft must be an integer >= 1 (megabytes) — omit it for a hard line only`);
|
|
3457
|
+
if (value.soft >= value.hard) throw new TypeError(`[@iso4/sandbox] ${where}.soft (${value.soft}) must be below ${where}.hard (${value.hard})`);
|
|
3458
|
+
}
|
|
3459
|
+
/**
|
|
3460
|
+
* Headroom above a managed cap before the terminating line — mirrors
|
|
3461
|
+
* `policy::heap_band_mb` in the runtime, which is the source of truth (the
|
|
3462
|
+
* wire sends the cap, not the band; this copy only sizes host-side
|
|
3463
|
+
* defaults). Geometric mean of the cap and 8 MB: 8 → +8, 128 → +32.
|
|
3464
|
+
* @param capMb
|
|
3465
|
+
*/
|
|
3466
|
+
function heapBandMb(capMb) {
|
|
3467
|
+
return capMb <= 0 ? 0 : Math.round(Math.sqrt(8 * capMb));
|
|
3468
|
+
}
|
|
3469
|
+
/**
|
|
3470
|
+
* The terminating ceiling a cap implies for a REUSED instance — the widest
|
|
3471
|
+
* of the two paths, so the number capacity planning reserves. A one-off's
|
|
3472
|
+
* ceiling is the bare cap (no band).
|
|
3473
|
+
* @param value a resolved `memoryMb` setting
|
|
3474
|
+
*/
|
|
3475
|
+
function hardCeilingMb(value) {
|
|
3476
|
+
if (value === void 0) return void 0;
|
|
3477
|
+
if (typeof value === "number") return value + heapBandMb(value);
|
|
3478
|
+
return value.hard;
|
|
3479
|
+
}
|
|
3480
|
+
/**
|
|
3481
|
+
* Split a `memoryMb` setting into the two wire fields. A plain number is
|
|
3482
|
+
* managed — the runtime derives the terminating line from it, so no override
|
|
3483
|
+
* is sent; the object form sends both explicitly, with an absent `soft`
|
|
3484
|
+
* carried as `0` (no retirement line).
|
|
3485
|
+
* @param value a resolved `memoryMb` setting
|
|
3486
|
+
*/
|
|
3487
|
+
function heapCapsForWire(value) {
|
|
3488
|
+
if (value === void 0) return {};
|
|
3489
|
+
if (typeof value === "number") return { memoryMb: value };
|
|
3490
|
+
return {
|
|
3491
|
+
memoryMb: value.soft ?? 0,
|
|
3492
|
+
hardMemoryMb: value.hard
|
|
3493
|
+
};
|
|
3494
|
+
}
|
|
3495
|
+
/**
|
|
3496
|
+
* The failed result for a run shed at the host-side queue bound
|
|
3497
|
+
* (`maxQueuedRuns`). Nothing reached the runtime, so telemetry is genuinely
|
|
3498
|
+
* zero. Distinct from `ERR_CAPACITY` (the runtime's memory admission):
|
|
3499
|
+
* this wall is queue depth, that one is memory.
|
|
3500
|
+
* @param error the pool's refusal, carrying the bound in its message
|
|
3501
|
+
*/
|
|
3502
|
+
function queueFullResult(error) {
|
|
3503
|
+
return {
|
|
3504
|
+
status: "failed",
|
|
3505
|
+
ok: false,
|
|
3506
|
+
error: {
|
|
3507
|
+
code: "ERR_QUEUE_FULL",
|
|
3508
|
+
name: "Error",
|
|
3509
|
+
message: error.message
|
|
3510
|
+
},
|
|
3511
|
+
stdout: [],
|
|
3512
|
+
stderr: [],
|
|
3513
|
+
durationMs: 0,
|
|
3514
|
+
wallTimeMs: 0,
|
|
3515
|
+
cpuTimeMs: 0,
|
|
3516
|
+
bridgeCalls: []
|
|
3517
|
+
};
|
|
3518
|
+
}
|
|
3519
|
+
function desyncResult(error) {
|
|
3520
|
+
return {
|
|
3521
|
+
status: "failed",
|
|
3522
|
+
ok: false,
|
|
3523
|
+
error: {
|
|
3524
|
+
code: "ERR_PROTOCOL_DESYNC",
|
|
3525
|
+
name: error.name,
|
|
3526
|
+
message: error.message
|
|
3527
|
+
},
|
|
3528
|
+
stdout: [],
|
|
3529
|
+
stderr: [],
|
|
3530
|
+
durationMs: 0,
|
|
3531
|
+
wallTimeMs: 0,
|
|
3532
|
+
cpuTimeMs: 0,
|
|
3533
|
+
bridgeCalls: []
|
|
3534
|
+
};
|
|
3535
|
+
}
|
|
1705
3536
|
function abortedResult(reason, from) {
|
|
1706
3537
|
return {
|
|
1707
3538
|
status: "aborted",
|
|
@@ -1715,6 +3546,7 @@ function abortedResult(reason, from) {
|
|
|
1715
3546
|
stdout: from?.stdout ?? [],
|
|
1716
3547
|
stderr: from?.stderr ?? [],
|
|
1717
3548
|
durationMs: from?.durationMs ?? 0,
|
|
3549
|
+
wallTimeMs: from?.wallTimeMs ?? 0,
|
|
1718
3550
|
cpuTimeMs: from?.cpuTimeMs ?? 0,
|
|
1719
3551
|
bridgeCalls: from?.bridgeCalls ?? []
|
|
1720
3552
|
};
|
|
@@ -1722,43 +3554,152 @@ function abortedResult(reason, from) {
|
|
|
1722
3554
|
var SandboxImpl = class {
|
|
1723
3555
|
proc;
|
|
1724
3556
|
pool;
|
|
3557
|
+
/**
|
|
3558
|
+
* Control connection for `stats()` — outside the pool so a snapshot
|
|
3559
|
+
* answers even when every run slot is busy.
|
|
3560
|
+
*/
|
|
3561
|
+
statsClient;
|
|
1725
3562
|
socketPath;
|
|
3563
|
+
/**
|
|
3564
|
+
* Uniform per-isolate heap cap, set once at `createSandbox` and
|
|
3565
|
+
* injected into every frame's limits — the wire still carries `memoryMb`
|
|
3566
|
+
* per run, this is simply the only writer. `undefined` defers to the
|
|
3567
|
+
* runtime default (128 MB).
|
|
3568
|
+
*/
|
|
3569
|
+
memoryMb;
|
|
3570
|
+
/**
|
|
3571
|
+
* Last-resort cleanup registered on the host's `exit`, removed by
|
|
3572
|
+
* `dispose()` so a program that creates and disposes many sandboxes does not
|
|
3573
|
+
* accumulate listeners.
|
|
3574
|
+
*/
|
|
3575
|
+
exitHook;
|
|
3576
|
+
/**
|
|
3577
|
+
* Session brand key for host-type descriptors (see `web-codec.ts`) —
|
|
3578
|
+
* derived from the sandbox's random descriptor token, stamped onto every
|
|
3579
|
+
* descriptor this host emits.
|
|
3580
|
+
*/
|
|
3581
|
+
brandKey;
|
|
1726
3582
|
_alive = true;
|
|
1727
|
-
constructor(proc, pool, socketPath) {
|
|
3583
|
+
constructor(proc, pool, statsClient, socketPath, brandKey, memoryMb) {
|
|
1728
3584
|
this.proc = proc;
|
|
1729
3585
|
this.pool = pool;
|
|
3586
|
+
this.statsClient = statsClient;
|
|
1730
3587
|
this.socketPath = socketPath;
|
|
3588
|
+
this.brandKey = brandKey;
|
|
3589
|
+
this.memoryMb = memoryMb;
|
|
1731
3590
|
proc.once("exit", () => {
|
|
1732
3591
|
this._alive = false;
|
|
1733
3592
|
});
|
|
3593
|
+
this.exitHook = () => {
|
|
3594
|
+
this.proc.kill();
|
|
3595
|
+
try {
|
|
3596
|
+
rmSync(dirname(this.socketPath), {
|
|
3597
|
+
recursive: true,
|
|
3598
|
+
force: true
|
|
3599
|
+
});
|
|
3600
|
+
} catch {}
|
|
3601
|
+
};
|
|
3602
|
+
process.once("exit", this.exitHook);
|
|
1734
3603
|
}
|
|
1735
3604
|
get alive() {
|
|
1736
3605
|
return this._alive;
|
|
1737
3606
|
}
|
|
1738
3607
|
async run(options) {
|
|
1739
3608
|
if (options.signal?.aborted) return abortedResult(options.signal.reason);
|
|
3609
|
+
if (options.hardAbortSignal?.aborted) return abortedResult(options.hardAbortSignal.reason);
|
|
3610
|
+
if (typeof options.limits?.memoryMb === "object") throw new TypeError("[@iso4/sandbox] limits.memoryMb takes a number of megabytes — the { soft, hard } form belongs on createSandbox or prepare, whose instances are reused");
|
|
3611
|
+
validateMemoryMb(options.limits?.memoryMb, "limits.memoryMb");
|
|
3612
|
+
const runMemoryMb = options.limits?.memoryMb ?? this.memoryMb;
|
|
1740
3613
|
const { defs, dispatch } = processGlobals(options.globals ?? {});
|
|
3614
|
+
await materializeHostTypesInGlobals(defs, this.brandKey);
|
|
1741
3615
|
const { bindings, handlers } = processImports(options.imports);
|
|
3616
|
+
const streams = new StreamSourceRegistry();
|
|
3617
|
+
const call = options.call === void 0 ? void 0 : {
|
|
3618
|
+
exportPath: options.call.export,
|
|
3619
|
+
argsBlob: await serializeHostValue(options.call.args ?? [], this.brandKey, streams)
|
|
3620
|
+
};
|
|
1742
3621
|
try {
|
|
1743
3622
|
return await this.pool.withClient(async (client) => {
|
|
1744
|
-
const
|
|
3623
|
+
const raw = await client.runRawCode(options.code, {
|
|
1745
3624
|
filename: options.filename,
|
|
1746
|
-
limits:
|
|
3625
|
+
limits: {
|
|
3626
|
+
...options.limits,
|
|
3627
|
+
...heapCapsForWire(runMemoryMb)
|
|
3628
|
+
},
|
|
1747
3629
|
globals: defs,
|
|
1748
3630
|
dispatch,
|
|
1749
3631
|
imports: bindings,
|
|
1750
3632
|
importDispatch: handlers,
|
|
1751
|
-
signal: options.signal
|
|
1752
|
-
|
|
1753
|
-
|
|
3633
|
+
signal: options.signal,
|
|
3634
|
+
hardAbortSignal: options.hardAbortSignal,
|
|
3635
|
+
call,
|
|
3636
|
+
streams
|
|
3637
|
+
});
|
|
3638
|
+
const decoded = withBodyStreamBinder((id) => raw.outStreams.attach(id), () => call === void 0 ? decodeRunCompletionPayload(raw.result).result : decodeRunCompletionPayload(raw.result, "call").result);
|
|
3639
|
+
if (raw.epilogue !== void 0 && raw.graceWork && decoded.ok) decoded.waitUntil = raw.epilogue.then(waitUntilResultFrom);
|
|
3640
|
+
if (decoded.status === "failed" && decoded.error.code === "ERR_ABORTED") {
|
|
3641
|
+
if (options.signal?.aborted) return abortedResult(options.signal.reason, decoded);
|
|
3642
|
+
if (options.hardAbortSignal?.aborted) return abortedResult(options.hardAbortSignal.reason, decoded);
|
|
3643
|
+
}
|
|
1754
3644
|
return decoded;
|
|
1755
|
-
});
|
|
3645
|
+
}, options.signal, options.hardAbortSignal);
|
|
1756
3646
|
} catch (error) {
|
|
3647
|
+
streams.releaseAll();
|
|
1757
3648
|
if (error instanceof RunAbortedError) return abortedResult(error.reason);
|
|
3649
|
+
if (error instanceof QueueFullError) return queueFullResult(error);
|
|
3650
|
+
if (error instanceof ProtocolDesyncError) return desyncResult(error);
|
|
1758
3651
|
throw error;
|
|
1759
3652
|
}
|
|
1760
3653
|
}
|
|
1761
3654
|
/**
|
|
3655
|
+
* A capacity/usage snapshot from the runtime's registry merged with the
|
|
3656
|
+
* host pool's queue counter. See {@link Sandbox.stats}.
|
|
3657
|
+
*/
|
|
3658
|
+
async stats() {
|
|
3659
|
+
const raw = await this.statsClient.stats();
|
|
3660
|
+
return {
|
|
3661
|
+
activeRuns: raw.oneoffRunning + raw.warmRuns,
|
|
3662
|
+
queueDepth: this.pool.queueDepth,
|
|
3663
|
+
openConnections: this.pool.openConnections,
|
|
3664
|
+
warmInstances: raw.warmBusy + raw.warmIdle,
|
|
3665
|
+
idleInstances: raw.warmIdle,
|
|
3666
|
+
idleHeapBytes: raw.idleHeapBytes,
|
|
3667
|
+
budgetBytes: raw.warmBudgetBytes,
|
|
3668
|
+
rssBytes: raw.rssBytes,
|
|
3669
|
+
usageBytes: raw.usageBytes,
|
|
3670
|
+
hardLineBytes: raw.hardLineBytes,
|
|
3671
|
+
underPressure: raw.underPressure,
|
|
3672
|
+
prefixes: Object.fromEntries(raw.prefixes.map((p) => [p.prefixId, {
|
|
3673
|
+
idle: p.idle,
|
|
3674
|
+
busy: p.busy
|
|
3675
|
+
}]))
|
|
3676
|
+
};
|
|
3677
|
+
}
|
|
3678
|
+
/**
|
|
3679
|
+
* Load a module once and read its serializable exports — the deploy path.
|
|
3680
|
+
* Function exports are skipped and reported; failures reject, like
|
|
3681
|
+
* `prepare()`. See {@link Sandbox.readExports}.
|
|
3682
|
+
* @param options
|
|
3683
|
+
*/
|
|
3684
|
+
async readExports(options) {
|
|
3685
|
+
const result = await this.run({
|
|
3686
|
+
code: options.code,
|
|
3687
|
+
filename: options.filename,
|
|
3688
|
+
limits: options.limits
|
|
3689
|
+
});
|
|
3690
|
+
if (result.status !== "completed") {
|
|
3691
|
+
const err = new Error(result.error.message);
|
|
3692
|
+
err.name = result.error.name;
|
|
3693
|
+
err.code = result.error.code;
|
|
3694
|
+
if (result.error.stack) err.stack = result.error.stack;
|
|
3695
|
+
throw err;
|
|
3696
|
+
}
|
|
3697
|
+
return {
|
|
3698
|
+
exports: result.exports,
|
|
3699
|
+
skippedExports: result.skippedExports
|
|
3700
|
+
};
|
|
3701
|
+
}
|
|
3702
|
+
/**
|
|
1762
3703
|
* @deprecated Renamed to {@link SandboxImpl.prepare}; kept as an alias.
|
|
1763
3704
|
* @param options
|
|
1764
3705
|
*/
|
|
@@ -1766,19 +3707,25 @@ var SandboxImpl = class {
|
|
|
1766
3707
|
return this.prepare(options);
|
|
1767
3708
|
}
|
|
1768
3709
|
/**
|
|
1769
|
-
*
|
|
3710
|
+
* Validate and prepare a prefix for repeated runs. See
|
|
1770
3711
|
* {@link Sandbox.prepare}.
|
|
1771
3712
|
* @param options
|
|
1772
3713
|
*/
|
|
1773
3714
|
async prepare(options) {
|
|
3715
|
+
validateMemoryMb(options.memoryMb, "memoryMb");
|
|
3716
|
+
const prefixMemoryMb = options.memoryMb ?? this.memoryMb;
|
|
1774
3717
|
return this.pool.withClient(async (client) => {
|
|
1775
3718
|
const rawGlobals = options.globals ?? {};
|
|
1776
3719
|
const { defs } = processGlobals(rawGlobals);
|
|
3720
|
+
await materializeHostTypesInGlobals(defs, this.brandKey);
|
|
1777
3721
|
const { bindings, handlers } = processImports(options.imports);
|
|
1778
3722
|
const result = decodePrecompileResultPayload(await client.precompile({
|
|
1779
3723
|
code: options.code,
|
|
1780
3724
|
filename: options.filename,
|
|
1781
|
-
limits:
|
|
3725
|
+
limits: {
|
|
3726
|
+
...options.limits,
|
|
3727
|
+
...heapCapsForWire(prefixMemoryMb)
|
|
3728
|
+
},
|
|
1782
3729
|
globals: defs,
|
|
1783
3730
|
imports: bindings
|
|
1784
3731
|
}));
|
|
@@ -1789,16 +3736,21 @@ var SandboxImpl = class {
|
|
|
1789
3736
|
if (result.error.stack) err.stack = result.error.stack;
|
|
1790
3737
|
throw err;
|
|
1791
3738
|
}
|
|
1792
|
-
return new PrefixImpl(result.prefixId, this.pool, rawGlobals, handlers);
|
|
3739
|
+
return new PrefixImpl(result.prefixId, this.pool, rawGlobals, handlers, this.brandKey, prefixMemoryMb);
|
|
1793
3740
|
});
|
|
1794
3741
|
}
|
|
1795
3742
|
async dispose() {
|
|
1796
3743
|
if (!this._alive) return;
|
|
1797
3744
|
this._alive = false;
|
|
3745
|
+
process.removeListener("exit", this.exitHook);
|
|
1798
3746
|
await this.pool.dispose();
|
|
3747
|
+
await this.statsClient.dispose();
|
|
1799
3748
|
this.proc.kill();
|
|
1800
3749
|
try {
|
|
1801
|
-
await
|
|
3750
|
+
await rm(dirname(this.socketPath), {
|
|
3751
|
+
recursive: true,
|
|
3752
|
+
force: true
|
|
3753
|
+
});
|
|
1802
3754
|
} catch {}
|
|
1803
3755
|
}
|
|
1804
3756
|
async [Symbol.asyncDispose]() {
|
|
@@ -1820,32 +3772,80 @@ var PrefixImpl = class {
|
|
|
1820
3772
|
* `(specifier, path)`. Same rebinding rules as `defaultGlobals` — a
|
|
1821
3773
|
* `prefix.run()` may override a subset of function leaves; everything else
|
|
1822
3774
|
* falls back to these. Source modules and data leaves are frozen in the
|
|
1823
|
-
*
|
|
1824
|
-
* the prefix in the Rust runtime, which
|
|
1825
|
-
*
|
|
3775
|
+
* declared prefix state and not represented here. The declared shape itself lives with
|
|
3776
|
+
* the prefix in the Rust runtime, which rejects rebind attempts outside it
|
|
3777
|
+
* (`ERR_UNDECLARED_BINDING`) or at frozen locations (`ERR_FROZEN_BINDING`).
|
|
1826
3778
|
*/
|
|
1827
3779
|
defaultImportHandlers;
|
|
3780
|
+
/**
|
|
3781
|
+
* THIS prefix's heap cap (`prepare({ memoryMb })`, falling back to the
|
|
3782
|
+
* sandbox default). Warm instances serving the prefix are created with
|
|
3783
|
+
* it; a per-run value stays impossible — the cap is baked into the
|
|
3784
|
+
* isolate at creation and instances are shared.
|
|
3785
|
+
*/
|
|
3786
|
+
memoryMb;
|
|
3787
|
+
/**
|
|
3788
|
+
* Session brand key for host-type descriptors — see `SandboxImpl`.
|
|
3789
|
+
*/
|
|
3790
|
+
brandKey;
|
|
1828
3791
|
_alive = true;
|
|
1829
|
-
constructor(id, pool, defaultGlobals, defaultImportHandlers) {
|
|
3792
|
+
constructor(id, pool, defaultGlobals, defaultImportHandlers, brandKey, memoryMb) {
|
|
1830
3793
|
this.id = id;
|
|
1831
3794
|
this.pool = pool;
|
|
1832
3795
|
this.defaultGlobals = defaultGlobals;
|
|
1833
3796
|
this.defaultImportHandlers = defaultImportHandlers;
|
|
3797
|
+
this.brandKey = brandKey;
|
|
3798
|
+
this.memoryMb = memoryMb;
|
|
1834
3799
|
}
|
|
1835
3800
|
get alive() {
|
|
1836
3801
|
return this._alive;
|
|
1837
3802
|
}
|
|
1838
3803
|
/**
|
|
1839
|
-
* Execute dynamic code against this prefix
|
|
3804
|
+
* Execute dynamic code against this prefix. See
|
|
1840
3805
|
* {@link Prefix.execute}.
|
|
3806
|
+
* @param options
|
|
1841
3807
|
*/
|
|
1842
3808
|
async execute(options) {
|
|
1843
3809
|
return this.run(options);
|
|
1844
3810
|
}
|
|
1845
3811
|
/**
|
|
3812
|
+
* @param options
|
|
1846
3813
|
* @deprecated Renamed to {@link PrefixImpl.execute}; kept as an alias.
|
|
1847
3814
|
*/
|
|
1848
3815
|
async run(options) {
|
|
3816
|
+
return await this.dispatch(options, { code: options.code });
|
|
3817
|
+
}
|
|
3818
|
+
/**
|
|
3819
|
+
* Call a function exported by this prefix's module — no postfix compiled.
|
|
3820
|
+
* See {@link Prefix.call}.
|
|
3821
|
+
* @param options
|
|
3822
|
+
*/
|
|
3823
|
+
async call(options) {
|
|
3824
|
+
const streams = new StreamSourceRegistry();
|
|
3825
|
+
const call = {
|
|
3826
|
+
exportPath: options.export,
|
|
3827
|
+
argsBlob: await serializeHostValue(options.args ?? [], this.brandKey, streams)
|
|
3828
|
+
};
|
|
3829
|
+
return await this.dispatch(options, {
|
|
3830
|
+
call,
|
|
3831
|
+
streams
|
|
3832
|
+
});
|
|
3833
|
+
}
|
|
3834
|
+
/**
|
|
3835
|
+
* Shared body of {@link run} and {@link call}: disposal/abort guards,
|
|
3836
|
+
* bridge-global extraction, import-rebind merging, and the PrefixRun round
|
|
3837
|
+
* trip. `payload` carries the postfix source or the call — exactly one, as
|
|
3838
|
+
* the wire demands; it also selects how the result blob decodes.
|
|
3839
|
+
* @param options
|
|
3840
|
+
* @param options.globals
|
|
3841
|
+
* @param options.imports
|
|
3842
|
+
* @param options.limits
|
|
3843
|
+
* @param options.signal
|
|
3844
|
+
* @param options.hardAbortSignal
|
|
3845
|
+
* @param options.filename
|
|
3846
|
+
* @param payload
|
|
3847
|
+
*/
|
|
3848
|
+
async dispatch(options, payload) {
|
|
1849
3849
|
if (!this._alive) return {
|
|
1850
3850
|
status: "failed",
|
|
1851
3851
|
ok: false,
|
|
@@ -1857,49 +3857,68 @@ var PrefixImpl = class {
|
|
|
1857
3857
|
stdout: [],
|
|
1858
3858
|
stderr: [],
|
|
1859
3859
|
durationMs: 0,
|
|
3860
|
+
wallTimeMs: 0,
|
|
1860
3861
|
cpuTimeMs: 0,
|
|
1861
3862
|
bridgeCalls: []
|
|
1862
3863
|
};
|
|
1863
3864
|
if (options.signal?.aborted) return abortedResult(options.signal.reason);
|
|
3865
|
+
if (options.hardAbortSignal?.aborted) return abortedResult(options.hardAbortSignal.reason);
|
|
3866
|
+
if (options.limits !== void 0 && "memoryMb" in options.limits) throw new TypeError("[@iso4/sandbox] limits.memoryMb is not a per-run option for prefix runs: the cap is baked into the shared warm isolates at creation — set it per prefix via prepare({ memoryMb }), or the sandbox default via createSandbox({ memoryMb })");
|
|
1864
3867
|
const { defs, dispatch } = extractBridgeGlobals(options.globals ?? {}, this.defaultGlobals);
|
|
1865
3868
|
let merged;
|
|
1866
3869
|
try {
|
|
1867
3870
|
merged = mergeRebindImports(options.imports, this.defaultImportHandlers);
|
|
1868
3871
|
} catch (e) {
|
|
1869
|
-
if (e instanceof
|
|
3872
|
+
if (e instanceof ImportRebindError) return {
|
|
1870
3873
|
status: "failed",
|
|
1871
3874
|
ok: false,
|
|
1872
3875
|
error: {
|
|
1873
|
-
code:
|
|
3876
|
+
code: e.code,
|
|
1874
3877
|
name: "Error",
|
|
1875
3878
|
message: e.message
|
|
1876
3879
|
},
|
|
1877
3880
|
stdout: [],
|
|
1878
3881
|
stderr: [],
|
|
1879
3882
|
durationMs: 0,
|
|
3883
|
+
wallTimeMs: 0,
|
|
1880
3884
|
cpuTimeMs: 0,
|
|
1881
3885
|
bridgeCalls: []
|
|
1882
3886
|
};
|
|
1883
3887
|
throw e;
|
|
1884
3888
|
}
|
|
3889
|
+
const streams = payload.streams ?? new StreamSourceRegistry();
|
|
1885
3890
|
try {
|
|
1886
3891
|
return await this.pool.withClient(async (client) => {
|
|
1887
|
-
const
|
|
3892
|
+
const raw = await client.prefixRun({
|
|
1888
3893
|
prefixId: this.id,
|
|
1889
|
-
code:
|
|
3894
|
+
code: payload.code,
|
|
1890
3895
|
filename: options.filename,
|
|
1891
|
-
limits:
|
|
3896
|
+
limits: {
|
|
3897
|
+
...options.limits,
|
|
3898
|
+
...heapCapsForWire(this.memoryMb)
|
|
3899
|
+
},
|
|
1892
3900
|
globals: defs,
|
|
1893
3901
|
dispatch,
|
|
1894
3902
|
importRebinds: merged.rebinds,
|
|
1895
3903
|
importDispatch: merged.handlers,
|
|
1896
|
-
signal: options.signal
|
|
1897
|
-
|
|
1898
|
-
|
|
3904
|
+
signal: options.signal,
|
|
3905
|
+
hardAbortSignal: options.hardAbortSignal,
|
|
3906
|
+
call: payload.call,
|
|
3907
|
+
streams
|
|
3908
|
+
});
|
|
3909
|
+
const decoded = withBodyStreamBinder((id) => raw.outStreams.attach(id), () => payload.call === void 0 ? decodeRunCompletionPayload(raw.result).result : decodeRunCompletionPayload(raw.result, "call").result);
|
|
3910
|
+
if (raw.epilogue !== void 0 && raw.graceWork && decoded.ok) decoded.waitUntil = raw.epilogue.then(waitUntilResultFrom);
|
|
3911
|
+
if (decoded.status === "failed" && decoded.error.code === "ERR_ABORTED") {
|
|
3912
|
+
if (options.signal?.aborted) return abortedResult(options.signal.reason, decoded);
|
|
3913
|
+
if (options.hardAbortSignal?.aborted) return abortedResult(options.hardAbortSignal.reason, decoded);
|
|
3914
|
+
}
|
|
1899
3915
|
return decoded;
|
|
1900
|
-
});
|
|
3916
|
+
}, options.signal, options.hardAbortSignal);
|
|
1901
3917
|
} catch (error) {
|
|
3918
|
+
streams.releaseAll();
|
|
1902
3919
|
if (error instanceof RunAbortedError) return abortedResult(error.reason);
|
|
3920
|
+
if (error instanceof QueueFullError) return queueFullResult(error);
|
|
3921
|
+
if (error instanceof ProtocolDesyncError) return desyncResult(error);
|
|
1903
3922
|
throw error;
|
|
1904
3923
|
}
|
|
1905
3924
|
}
|