@iso4/sandbox 0.8.1 → 0.10.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 +55 -15
- package/dist/index.d.mts +174 -63
- package/dist/index.mjs +165 -29
- package/package.json +11 -11
package/README.md
CHANGED
|
@@ -33,9 +33,9 @@ tracks musl support).
|
|
|
33
33
|
import { createSandbox } from '@iso4/sandbox'
|
|
34
34
|
import { createSafeFetch } from '@iso4/fetch'
|
|
35
35
|
|
|
36
|
-
const sandbox = await createSandbox({ memoryMb: 128 }) // per-isolate heap
|
|
36
|
+
const sandbox = await createSandbox({ memoryMb: 128 }) // per-isolate memory cap (JS heap + buffers)
|
|
37
37
|
|
|
38
|
-
//
|
|
38
|
+
// Store host setup once; it is evaluated on each cold start
|
|
39
39
|
const prefix = await sandbox.prepare({
|
|
40
40
|
code: `
|
|
41
41
|
const config = { apiBase: 'https://api.example.com' }
|
|
@@ -52,7 +52,7 @@ const result = await prefix.execute({
|
|
|
52
52
|
const res = await fetch(config.apiBase + '/users')
|
|
53
53
|
export default { count: res.length }
|
|
54
54
|
`,
|
|
55
|
-
limits: { cpuTimeMs: 200, wallTimeMs: 5_000 }, //
|
|
55
|
+
limits: { cpuTimeMs: 200, wallTimeMs: 5_000 }, // memory cap: prepare({ memoryMb }) or the sandbox default
|
|
56
56
|
})
|
|
57
57
|
|
|
58
58
|
if (result.ok) {
|
|
@@ -99,6 +99,30 @@ it before installing them. `RESERVED_WORDS` is a `Set` of names that cannot be
|
|
|
99
99
|
a binding in module source, such as `class` or `eval`; iso4 refuses
|
|
100
100
|
host-module export names in it, except `default`.
|
|
101
101
|
|
|
102
|
+
`prepare()` stores the prefix without running it, and checks only what needs
|
|
103
|
+
no isolate: global names, the import shape, and option ranges. A prefix that
|
|
104
|
+
does not compile, throws, or imports something unknown fails its first run
|
|
105
|
+
with the prefix's own code (`ERR_USER_CODE`, `ERR_MODULE_NOT_FOUND`,
|
|
106
|
+
`ERR_IMPORT`, `ERR_PREFIX_BRIDGE_CALL`, `ERR_PREFIX_DID_NOT_SETTLE`,
|
|
107
|
+
`ERR_WARMUP_LIMIT`). Validate it yourself where it matters — parse the
|
|
108
|
+
source with a tool such as `oxc`, or do one trial run (its instance stays
|
|
109
|
+
warm, so nothing is wasted):
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
const prefix = await sandbox.prepare({ code })
|
|
113
|
+
const check = await prefix.execute({ code: 'export default 0' })
|
|
114
|
+
if (!check.ok)
|
|
115
|
+
throw new Error(`broken prefix: ${check.error.message}`)
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
A failure of the prefix itself carries `error.stage === 'prefix'`, so a
|
|
119
|
+
host can tell it from a failure of the run code. The runtime remembers it:
|
|
120
|
+
`prefix.status` becomes `'broken'`, `prefix.error` holds the failure, and
|
|
121
|
+
every later `execute()`/`call()` rejects with `ERR_PREFIX_BROKEN` (its
|
|
122
|
+
`cause` is that failure) without booting an isolate. `dispose()` still
|
|
123
|
+
works; the only retry is a new `prepare()`. Failures that depend on load
|
|
124
|
+
(`ERR_WARMUP_LIMIT`, `ERR_MEMORY_LIMIT`) never break a prefix.
|
|
125
|
+
|
|
102
126
|
To check generated names before `prepare()` instead of getting a failed
|
|
103
127
|
setup back, import the predicates from `@iso4/sandbox/utils`. That entry
|
|
104
128
|
never loads the client or the native binary:
|
|
@@ -142,7 +166,16 @@ prefix.execute({ globals: { unknown: handler } }) // ❌ TS error
|
|
|
142
166
|
|
|
143
167
|
## Resource limits
|
|
144
168
|
|
|
169
|
+
`prepare({ limits })` sets the defaults for every run on that prefix. A run's
|
|
170
|
+
own `limits` overrides them field by field; anything set in neither place
|
|
171
|
+
takes the runtime default.
|
|
172
|
+
|
|
145
173
|
```ts
|
|
174
|
+
const prefix = await sandbox.prepare({ code: prefixCode, limits: { cpuTimeMs: 200, maxBridgeCalls: 10 } })
|
|
175
|
+
|
|
176
|
+
prefix.execute({ code: agentCode }) // cpuTimeMs 200, maxBridgeCalls 10
|
|
177
|
+
prefix.execute({ code: agentCode, limits: { cpuTimeMs: 50 } }) // cpuTimeMs 50, maxBridgeCalls 10
|
|
178
|
+
|
|
146
179
|
prefix.execute({
|
|
147
180
|
code: agentCode,
|
|
148
181
|
limits: {
|
|
@@ -190,7 +223,7 @@ one call at a time, so concurrency means more instances (the engine can
|
|
|
190
223
|
already interleave several runs on one instance — that switches on with
|
|
191
224
|
wire multiplexing). Top-level names never collide across runs
|
|
192
225
|
(each run is its own module). A prefix that can't finish evaluating under
|
|
193
|
-
the fixed warm-up budget
|
|
226
|
+
the fixed warm-up budget fails the cold-starting call with
|
|
194
227
|
`ERR_WARMUP_LIMIT`. `console.*` from prefix evaluation arrives on the
|
|
195
228
|
cold-starting call's result.
|
|
196
229
|
|
|
@@ -198,7 +231,7 @@ Residency is bounded by memory, not by a count:
|
|
|
198
231
|
|
|
199
232
|
```ts
|
|
200
233
|
const sandbox = await createSandbox({
|
|
201
|
-
memoryMb: 128, // default
|
|
234
|
+
memoryMb: 128, // default memory cap per isolate, JS heap + buffers (override per prefix at prepare())
|
|
202
235
|
memoryBudgetMb: 2048, // RSS mark for the whole runtime process (0 = off)
|
|
203
236
|
hostReserveMb: 128, // container memory held back for this host process
|
|
204
237
|
})
|
|
@@ -207,21 +240,24 @@ const sandbox = await createSandbox({
|
|
|
207
240
|
`memoryMb` means two different things depending on whether the isolate is
|
|
208
241
|
reused.
|
|
209
242
|
|
|
210
|
-
**On a prefix**, the number is the retirement line: an instance whose
|
|
243
|
+
**On a prefix**, the number is the retirement line: an instance whose memory sits
|
|
211
244
|
above it when two runs in a row finish takes no new runs and drops once the
|
|
212
245
|
runs it is already serving complete. Nothing fails. The terminating line sits a
|
|
213
246
|
headroom band above it (`round(sqrt(8 × memoryMb))` MB, so 128 → 160); crossing
|
|
214
247
|
_that_ kills the run and fails its co-residents, and only a runaway allocation
|
|
215
248
|
gets there. The band is what lets a grown instance be replaced instead of
|
|
216
|
-
killing a run at the number — an optimization for reuse.
|
|
249
|
+
killing a run at the number — an optimization for reuse. Both lines count the
|
|
250
|
+
JS heap and buffer memory (ArrayBuffers, typed arrays, `resize()` growth, stream
|
|
251
|
+
chunks) together.
|
|
217
252
|
|
|
218
253
|
```ts
|
|
219
254
|
await sandbox.prepare({ code, memoryMb: { soft: 96, hard: 256 } }) // exact lines
|
|
220
255
|
await sandbox.prepare({ code, memoryMb: { hard: 128 } }) // terminate at 128, never retire
|
|
221
256
|
```
|
|
222
257
|
|
|
223
|
-
**On a one-off `run()`**, the number is
|
|
224
|
-
|
|
258
|
+
**On a one-off `run()`**, the number is the terminating line — `memoryMb: 128`
|
|
259
|
+
ends the run at 128 (checked every ~10 ms and at every turn end, so it can
|
|
260
|
+
overshoot briefly). A fresh isolate is never reused, so there is nothing to retire
|
|
225
261
|
and no band. It takes a plain number for the same reason: a soft line would
|
|
226
262
|
be inert.
|
|
227
263
|
|
|
@@ -250,7 +286,7 @@ the container is genuinely too small for `maxConcurrentRuns × memoryMb` —
|
|
|
250
286
|
`createSandbox` warns at startup when those two contradict each other.
|
|
251
287
|
|
|
252
288
|
`sandbox.stats()` reports the live picture — active runs, queue depth, warm and
|
|
253
|
-
idle instance counts, summed idle
|
|
289
|
+
idle instance counts, summed idle memory, `budgetBytes` / `rssBytes`, whether the
|
|
254
290
|
runtime is currently `underPressure`, and per-prefix counts. It answers on a
|
|
255
291
|
dedicated connection, so it works even when every run slot is busy.
|
|
256
292
|
|
|
@@ -413,8 +449,9 @@ interface RunError {
|
|
|
413
449
|
message: string
|
|
414
450
|
stack?: string
|
|
415
451
|
fields?: Record<string, unknown> // all other own-enumerable props of the thrown error
|
|
416
|
-
resetCause?: 'cpu' | 'memory' | 'wall' | 'abort' | 'internal' // ERR_INSTANCE_RESET only
|
|
452
|
+
resetCause?: 'cpu' | 'memory' | 'wall' | 'abort' | 'internal' | 'unsupported' // ERR_INSTANCE_RESET only
|
|
417
453
|
culpritRunId?: number // ERR_INSTANCE_RESET only: the run whose interruption reset the instance
|
|
454
|
+
stage?: 'prefix' // the prefix itself failed to evaluate on this run's cold start
|
|
418
455
|
}
|
|
419
456
|
```
|
|
420
457
|
|
|
@@ -424,13 +461,15 @@ crashed, binary not found) and for invalid options, the same way `prepare()`
|
|
|
424
461
|
does. `sandbox.run()`, `prefix.run()` and `prefix.call()` reject with an
|
|
425
462
|
`Error` whose `code` is a `SetupErrorCode`: `ERR_RESERVED_NAME` (a global
|
|
426
463
|
name the runtime owns), `ERR_UNDECLARED_BINDING`, `ERR_FROZEN_BINDING` or
|
|
427
|
-
`ERR_INVALID_REBIND` (a rebind the prefix does not allow),
|
|
428
|
-
`ERR_PREFIX_DISPOSED
|
|
464
|
+
`ERR_INVALID_REBIND` (a rebind the prefix does not allow),
|
|
465
|
+
`ERR_PREFIX_DISPOSED`, or `ERR_PREFIX_BROKEN` (the prefix failed to
|
|
466
|
+
evaluate on an earlier run; `cause` is that failure). The client checks
|
|
467
|
+
these before anything is sent, and
|
|
429
468
|
the runtime repeats the checks. A malformed option, such as a limit out of range or a
|
|
430
469
|
global name that is not a well-formed string, rejects with a plain
|
|
431
470
|
`TypeError`. Nothing ran, so retrying with the same options can never
|
|
432
|
-
succeed. Every other code, including
|
|
433
|
-
result.
|
|
471
|
+
succeed. Every other code, including a syntax error (`ERR_USER_CODE`
|
|
472
|
+
named `SyntaxError`), is a result.
|
|
434
473
|
|
|
435
474
|
```ts
|
|
436
475
|
import type { SetupErrorCode } from '@iso4/sandbox'
|
|
@@ -441,6 +480,7 @@ const setupCodes: readonly string[] = [
|
|
|
441
480
|
'ERR_FROZEN_BINDING',
|
|
442
481
|
'ERR_INVALID_REBIND',
|
|
443
482
|
'ERR_PREFIX_DISPOSED',
|
|
483
|
+
'ERR_PREFIX_BROKEN',
|
|
444
484
|
] satisfies SetupErrorCode[]
|
|
445
485
|
|
|
446
486
|
try {
|
package/dist/index.d.mts
CHANGED
|
@@ -12,17 +12,19 @@
|
|
|
12
12
|
* parallel. See DESIGN.md §1 and §13.
|
|
13
13
|
*/
|
|
14
14
|
/**
|
|
15
|
-
* The two
|
|
15
|
+
* The two memory lines a REUSED isolate is held to, when the managed default
|
|
16
16
|
* is not what you want. One-off `run()` isolates are never reused and take a
|
|
17
|
-
* plain `memoryMb` number
|
|
17
|
+
* plain `memoryMb` number with no soft line.
|
|
18
18
|
*
|
|
19
|
-
* - `hard` **terminates**:
|
|
19
|
+
* - `hard` **terminates**: one cap for the JS heap and buffer memory
|
|
20
|
+
* (ArrayBuffers and typed arrays, including `resize()` growth, and stream
|
|
21
|
+
* chunks) together. Crossing it kills whatever JS is
|
|
20
22
|
* executing, taints the instance, and fails its co-resident runs with
|
|
21
23
|
* `ERR_INSTANCE_RESET`. This is the ceiling the container reserves against
|
|
22
24
|
* its admission line.
|
|
23
|
-
* - `soft` **retires**: a warm instance whose
|
|
24
|
-
* consecutive finishes takes no further runs and is
|
|
25
|
-
* it is already serving complete. No run fails and nothing is terminated —
|
|
25
|
+
* - `soft` **retires**: a warm instance whose memory (JS heap plus buffers)
|
|
26
|
+
* sits above it at two consecutive finishes takes no further runs and is
|
|
27
|
+
* dropped once the runs it is already serving complete. No run fails and nothing is terminated —
|
|
26
28
|
* it is how a prefix that accumulates memory across reuse gets replaced
|
|
27
29
|
* instead of eventually killing a run. Omit it for a hard line only.
|
|
28
30
|
*
|
|
@@ -52,8 +54,9 @@ interface MemoryLimit {
|
|
|
52
54
|
*/
|
|
53
55
|
interface OneOffResourceLimits extends ResourceLimits {
|
|
54
56
|
/**
|
|
55
|
-
* Hard cap on this run's isolate memory, in megabytes —
|
|
56
|
-
*
|
|
57
|
+
* Hard cap on this run's isolate memory, in megabytes — one limit for the
|
|
58
|
+
* JS heap and buffer memory together. The run is ended once it holds more,
|
|
59
|
+
* checked every ~10 ms and at every turn end, so it can overshoot briefly.
|
|
57
60
|
*
|
|
58
61
|
* A one-off always gets a fresh isolate, so — unlike a prefix's reused
|
|
59
62
|
* instances — there is nothing to retire and no headroom band. The number
|
|
@@ -437,7 +440,9 @@ type HostExportData = null | undefined | boolean | number | bigint | string | Da
|
|
|
437
440
|
* Args and return are `unknown` — the bridge serialises/deserialises values
|
|
438
441
|
* with V8 ValueSerializer; we don't try to model that at the type level.
|
|
439
442
|
* The one invariant that matters (functions cannot cross the boundary as
|
|
440
|
-
* argument values) is enforced at runtime by the V8 layer, not here.
|
|
443
|
+
* argument values) is enforced at runtime by the V8 layer, not here. Arrays
|
|
444
|
+
* with holes are refused as arguments too, host-side, and the sandbox call
|
|
445
|
+
* rejects with a catchable `TypeError` before the handler runs.
|
|
441
446
|
*
|
|
442
447
|
* Use specific function types for your handlers and let TypeScript infer
|
|
443
448
|
* them through `HostGlobals`, `RebindGlobals<G>`, and `RebindImports<M>`.
|
|
@@ -510,8 +515,8 @@ interface SandboxOptions {
|
|
|
510
515
|
*/
|
|
511
516
|
maxQueuedRuns?: number;
|
|
512
517
|
/**
|
|
513
|
-
* Default hard cap on memory each isolate can use, in megabytes.
|
|
514
|
-
* the
|
|
518
|
+
* Default hard cap on memory each isolate can use, in megabytes. One
|
|
519
|
+
* limit for the JS heap and all buffer memory together; also determines
|
|
515
520
|
* the BridgeResponse frame read cap (the sandbox cannot receive a
|
|
516
521
|
* response larger than its own memory budget).
|
|
517
522
|
*
|
|
@@ -547,7 +552,7 @@ interface SandboxOptions {
|
|
|
547
552
|
* cgroup's working set, Node host included, the number the container's
|
|
548
553
|
* OOM killer acts on (where no cgroup exists, e.g. macOS, it falls back
|
|
549
554
|
* to the runtime child's own RSS). At/above the mark it evicts idle warm
|
|
550
|
-
* instances by `
|
|
555
|
+
* instances by `memoryBytes × idleTime^1.2` score (highest first) AND stops
|
|
551
556
|
* pooling new instances — prefix runs without an idle instance execute
|
|
552
557
|
* on cold one-off isolates — until usage falls back to 80 % of the mark
|
|
553
558
|
* (hysteresis, so eviction doesn't flap). Reusing an already-warm
|
|
@@ -652,12 +657,13 @@ interface SandboxStats {
|
|
|
652
657
|
*/
|
|
653
658
|
idleInstances: number;
|
|
654
659
|
/**
|
|
655
|
-
* Summed
|
|
660
|
+
* Summed memory of the idle instances in bytes (JS heap plus buffer
|
|
661
|
+
* memory, as {@link RunSuccess.memoryBytes}), each measured after its
|
|
656
662
|
* last call — or, where the runtime's idle settle is switched on, after
|
|
657
663
|
* the collection a parked instance runs, which is the smaller and truer
|
|
658
|
-
* number (a busy instance's current
|
|
664
|
+
* number (a busy instance's current memory is unknown mid-call).
|
|
659
665
|
*/
|
|
660
|
-
|
|
666
|
+
idleMemoryBytes: number;
|
|
661
667
|
/**
|
|
662
668
|
* The memory mark the runtime sheds against, in bytes —
|
|
663
669
|
* `memoryBudgetMb` as the runtime received it. 0 = watermarks disabled.
|
|
@@ -732,12 +738,32 @@ interface Sandbox {
|
|
|
732
738
|
* deploy/registration path (IaC-style declaration exports read when a
|
|
733
739
|
* function is created, never per request). Builds no prefix and retains
|
|
734
740
|
* nothing. Function exports are skipped and reported, so a module that
|
|
735
|
-
* also exports handlers reads cleanly. Rejects on
|
|
736
|
-
*
|
|
741
|
+
* also exports handlers reads cleanly. Rejects on a syntax or runtime
|
|
742
|
+
* error (`ERR_USER_CODE`), a missing import, or any other run failure.
|
|
737
743
|
*/
|
|
738
744
|
readExports: (options: ReadExportsOptions) => Promise<ReadExportsResult>;
|
|
739
745
|
/**
|
|
740
|
-
*
|
|
746
|
+
* Prepare a prefix of code for repeated runs.
|
|
747
|
+
*
|
|
748
|
+
* `prepare()` stores the source and declared shape; it does not evaluate
|
|
749
|
+
* the prefix. It rejects only for options it can check without running
|
|
750
|
+
* anything: a reserved or malformed global name, an invalid import shape,
|
|
751
|
+
* a bad limit or `memoryMb`. A prefix that does not compile, throws at top
|
|
752
|
+
* level, imports something unknown, calls the bridge, never settles, or
|
|
753
|
+
* exceeds the warm-up budget fails on its first `execute()`/`call()` as an
|
|
754
|
+
* `{ ok: false }` result with the matching {@link RunErrorCode}
|
|
755
|
+
* (`ERR_USER_CODE`, `ERR_MODULE_NOT_FOUND`, `ERR_IMPORT`,
|
|
756
|
+
* `ERR_PREFIX_BRIDGE_CALL`, `ERR_PREFIX_DID_NOT_SETTLE`,
|
|
757
|
+
* `ERR_WARMUP_LIMIT`). Validating a prefix is the caller's job: parse the
|
|
758
|
+
* source yourself (an `oxc`/`acorn` pass catches syntax errors), or do one
|
|
759
|
+
* trial run after `prepare()` — its instance stays warm, so nothing is
|
|
760
|
+
* wasted:
|
|
761
|
+
*
|
|
762
|
+
* ```ts
|
|
763
|
+
* const prefix = await sandbox.prepare({ code })
|
|
764
|
+
* const check = await prefix.execute({ code: 'export default 0' })
|
|
765
|
+
* if (!check.ok) throw new Error(`broken prefix: ${check.error.message}`)
|
|
766
|
+
* ```
|
|
741
767
|
*
|
|
742
768
|
* The type parameter `G` is inferred from the `globals` you pass and flows
|
|
743
769
|
* into the returned `Prefix<G>`. This lets TypeScript enforce at the call
|
|
@@ -838,14 +864,14 @@ interface PrecompileOptions<G extends HostGlobals, M extends Imports> {
|
|
|
838
864
|
*/
|
|
839
865
|
imports?: M;
|
|
840
866
|
/**
|
|
841
|
-
*
|
|
867
|
+
* Default limits for every `execute()`/`call()` on this prefix. A run's
|
|
868
|
+
* own `limits` overrides them field by field, so a run can change one
|
|
869
|
+
* knob without restating the rest; a field set in neither place takes the
|
|
870
|
+
* runtime default. Checked here like per-run limits (a `TypeError` for a
|
|
871
|
+
* bad value). The heap cap is not part of this: set it with `memoryMb`.
|
|
842
872
|
*
|
|
843
|
-
*
|
|
844
|
-
*
|
|
845
|
-
* configurable: prefix evaluation runs under the fixed warm-up budget
|
|
846
|
-
* (1 s wall / 1 s CPU) — a prefix that cannot evaluate inside it is
|
|
847
|
-
* rejected with `ERR_WARMUP_LIMIT` at `prepare()` time, because it could
|
|
848
|
-
* never cold-start a warm instance either.
|
|
873
|
+
* Prefix evaluation itself runs under the fixed warm-up budget
|
|
874
|
+
* (1 s wall / 1 s CPU), not these limits.
|
|
849
875
|
*/
|
|
850
876
|
limits?: ResourceLimits;
|
|
851
877
|
/**
|
|
@@ -912,16 +938,45 @@ interface Prefix<G extends HostGlobals = {}, M extends Imports = {}> {
|
|
|
912
938
|
*/
|
|
913
939
|
call: (options: PrefixCallOptions<G, M>) => Promise<CallResult>;
|
|
914
940
|
/**
|
|
915
|
-
* Release the prepared prefix. Subsequent run() calls reject
|
|
941
|
+
* Release the prepared prefix. Subsequent run() calls reject with
|
|
942
|
+
* `ERR_PREFIX_DISPOSED`. Idempotent, and works on a broken prefix too.
|
|
916
943
|
*/
|
|
917
944
|
dispose: () => Promise<void>;
|
|
918
945
|
/**
|
|
919
946
|
* Enables `await using prefix = await sandbox.precompile(...)` syntax.
|
|
920
947
|
*/
|
|
921
948
|
[Symbol.asyncDispose]: () => Promise<void>;
|
|
949
|
+
/**
|
|
950
|
+
* `true` until `dispose()`. A broken prefix is still alive: it is held
|
|
951
|
+
* by the runtime and the host still owns its disposal.
|
|
952
|
+
*/
|
|
922
953
|
readonly alive: boolean;
|
|
954
|
+
/**
|
|
955
|
+
* `'ready'` until the runtime reports a prefix-stage failure, `'broken'`
|
|
956
|
+
* from then on (see {@link PrefixStatus}), `'disposed'` after
|
|
957
|
+
* `dispose()`. The client learns `'broken'` from the first run's
|
|
958
|
+
* `{ ok: false, error: { stage: 'prefix' } }` result, or from an
|
|
959
|
+
* `ERR_PREFIX_BROKEN` refusal if that result went to another client.
|
|
960
|
+
*/
|
|
961
|
+
readonly status: PrefixStatus;
|
|
962
|
+
/**
|
|
963
|
+
* The stored cold-start failure once the prefix is broken, `undefined`
|
|
964
|
+
* before. Kept through `dispose()`. Always has `code`, `name`, `message`
|
|
965
|
+
* and `stack`; `stage` and `fields` are present only when this client saw
|
|
966
|
+
* the failing run's own result rather than a later `ERR_PREFIX_BROKEN`
|
|
967
|
+
* refusal.
|
|
968
|
+
*/
|
|
969
|
+
readonly error: RunError | undefined;
|
|
923
970
|
}
|
|
924
971
|
/**
|
|
972
|
+
* Lifecycle of a {@link Prefix}. `'broken'` means the prefix failed to
|
|
973
|
+
* evaluate with one of its own, repeatable errors; every later run is
|
|
974
|
+
* refused with `ERR_PREFIX_BROKEN` and the only retry is a new `prepare()`.
|
|
975
|
+
* Load-dependent cold-start failures (`ERR_WARMUP_LIMIT`,
|
|
976
|
+
* `ERR_MEMORY_LIMIT`) never break a prefix — the next run cold-starts again.
|
|
977
|
+
*/
|
|
978
|
+
type PrefixStatus = "ready" | "broken" | "disposed";
|
|
979
|
+
/**
|
|
925
980
|
* Options for `prefix.run()`.
|
|
926
981
|
*
|
|
927
982
|
* `G` is the declared-globals shape from the matching `precompile()` call.
|
|
@@ -954,6 +1009,10 @@ interface PrefixRunOptions<G extends HostGlobals, M extends Imports> {
|
|
|
954
1009
|
* `ERR_INVALID_REBIND` for a non-function override value.
|
|
955
1010
|
*/
|
|
956
1011
|
imports?: RebindImports<M>;
|
|
1012
|
+
/**
|
|
1013
|
+
* Limits for this run, applied field by field on top of the prefix's
|
|
1014
|
+
* `prepare({ limits })` defaults. `memoryMb` is not a per-run option here.
|
|
1015
|
+
*/
|
|
957
1016
|
limits?: ResourceLimits;
|
|
958
1017
|
/**
|
|
959
1018
|
* Abort the run. Firing this is always SOFT: while queued the caller is
|
|
@@ -995,6 +1054,10 @@ interface PrefixCallOptions<G extends HostGlobals, M extends Imports> extends Ca
|
|
|
995
1054
|
* rules as {@link PrefixRunOptions.imports}.
|
|
996
1055
|
*/
|
|
997
1056
|
imports?: RebindImports<M>;
|
|
1057
|
+
/**
|
|
1058
|
+
* Limits for this call, applied field by field on top of the prefix's
|
|
1059
|
+
* `prepare({ limits })` defaults. `memoryMb` is not a per-run option here.
|
|
1060
|
+
*/
|
|
998
1061
|
limits?: ResourceLimits;
|
|
999
1062
|
/**
|
|
1000
1063
|
* Abort the run. Firing this is always SOFT: while queued the caller is
|
|
@@ -1097,8 +1160,8 @@ interface ReadExportsOptions {
|
|
|
1097
1160
|
}
|
|
1098
1161
|
/**
|
|
1099
1162
|
* What `sandbox.readExports()` resolves to. Unlike `run()`, failures reject
|
|
1100
|
-
* the returned promise
|
|
1101
|
-
*
|
|
1163
|
+
* the returned promise, since the deploy path treats a broken module as
|
|
1164
|
+
* exceptional rather than as a result variant.
|
|
1102
1165
|
*/
|
|
1103
1166
|
interface ReadExportsResult {
|
|
1104
1167
|
exports: SandboxExports;
|
|
@@ -1148,9 +1211,11 @@ interface CallSuccess {
|
|
|
1148
1211
|
stdout: string[];
|
|
1149
1212
|
stderr: string[];
|
|
1150
1213
|
/**
|
|
1151
|
-
* Complete wall-clock from
|
|
1152
|
-
* waits, engine time for co-resident runs, machinery:
|
|
1153
|
-
* exceed the `wallTimeMs` limit, which counts
|
|
1214
|
+
* Complete wall-clock from when the run starts executing to the processed
|
|
1215
|
+
* conclusion — async waits, engine time for co-resident runs, machinery:
|
|
1216
|
+
* everything. May exceed the `wallTimeMs` limit, which counts
|
|
1217
|
+
* {@link wallTimeMs} instead. Waiting for a free CPU before the run starts
|
|
1218
|
+
* is in none of the three clocks.
|
|
1154
1219
|
*/
|
|
1155
1220
|
durationMs: number;
|
|
1156
1221
|
/**
|
|
@@ -1173,11 +1238,20 @@ interface CallSuccess {
|
|
|
1173
1238
|
queueWaitMs?: number;
|
|
1174
1239
|
bridgeCalls: BridgeCallEntry[];
|
|
1175
1240
|
/**
|
|
1176
|
-
*
|
|
1177
|
-
*
|
|
1178
|
-
* `
|
|
1179
|
-
|
|
1180
|
-
|
|
1241
|
+
* Memory of the isolate that served this call, in bytes: the JS heap plus
|
|
1242
|
+
* buffer memory (ArrayBuffers and typed arrays, including memory grown with
|
|
1243
|
+
* `resize()`, and stream chunks). Read once when the call ends, on prefix
|
|
1244
|
+
* and one-off calls alike; it includes garbage not yet collected (a warm
|
|
1245
|
+
* instance pushed over its soft line by buffers, with objects alone under
|
|
1246
|
+
* it, is collected once first). A call that sends its result early
|
|
1247
|
+
* (`waitUntil` work, open stream bodies) reports a reading taken at that
|
|
1248
|
+
* moment, before any run-end collection, so it can differ from the figure
|
|
1249
|
+
* the soft line uses. `0` on a prefix call whose instance could not be
|
|
1250
|
+
* measured (failed warm-up, dead instance). `undefined` when the call was
|
|
1251
|
+
* answered without a reading: refused before it started, or a result too
|
|
1252
|
+
* large to send.
|
|
1253
|
+
*/
|
|
1254
|
+
memoryBytes?: number;
|
|
1181
1255
|
/**
|
|
1182
1256
|
* Present when the call registered background work with `waitUntil` —
|
|
1183
1257
|
* see {@link RunSuccess.waitUntil}. Never rejects.
|
|
@@ -1336,11 +1410,12 @@ interface RunSuccess {
|
|
|
1336
1410
|
*/
|
|
1337
1411
|
stderr: string[];
|
|
1338
1412
|
/**
|
|
1339
|
-
* Complete wall-clock time of the run (
|
|
1340
|
-
* conclusion), measured in the runtime — async waits, engine
|
|
1341
|
-
* co-resident runs, machinery: everything. May exceed the
|
|
1342
|
-
* limit, which counts {@link wallTimeMs} instead.
|
|
1343
|
-
*
|
|
1413
|
+
* Complete wall-clock time of the run (from when it starts executing to
|
|
1414
|
+
* the processed conclusion), measured in the runtime — async waits, engine
|
|
1415
|
+
* time for co-resident runs, machinery: everything. May exceed the
|
|
1416
|
+
* `wallTimeMs` limit, which counts {@link wallTimeMs} instead. Waiting for
|
|
1417
|
+
* a free CPU before the run starts is in none of the three clocks.
|
|
1418
|
+
* Milliseconds with microsecond resolution.
|
|
1344
1419
|
*/
|
|
1345
1420
|
durationMs: number;
|
|
1346
1421
|
/**
|
|
@@ -1363,9 +1438,12 @@ interface RunSuccess {
|
|
|
1363
1438
|
* resolution.
|
|
1364
1439
|
*
|
|
1365
1440
|
* The wait sits outside the other three clocks, which the runtime measures
|
|
1366
|
-
* from
|
|
1367
|
-
* {@link durationMs} plus frame transit
|
|
1368
|
-
*
|
|
1441
|
+
* from when the run starts executing — end to end, a caller sees this plus
|
|
1442
|
+
* {@link durationMs} plus frame transit plus the runtime's own wait for a
|
|
1443
|
+
* free CPU before the run starts. That CPU wait is not counted in
|
|
1444
|
+
* `queueWaitMs`, `durationMs`, `wallTimeMs` or `cpuTimeMs`; later CPU waits
|
|
1445
|
+
* are inside {@link durationMs}. Rising `queueWaitMs` is the sign that
|
|
1446
|
+
* admission, not the code, is the bottleneck.
|
|
1369
1447
|
*/
|
|
1370
1448
|
queueWaitMs?: number;
|
|
1371
1449
|
/**
|
|
@@ -1375,12 +1453,21 @@ interface RunSuccess {
|
|
|
1375
1453
|
*/
|
|
1376
1454
|
bridgeCalls: BridgeCallEntry[];
|
|
1377
1455
|
/**
|
|
1378
|
-
*
|
|
1379
|
-
*
|
|
1380
|
-
*
|
|
1381
|
-
* one-off
|
|
1382
|
-
|
|
1383
|
-
|
|
1456
|
+
* Memory of the isolate that served this run, in bytes: the JS heap plus
|
|
1457
|
+
* buffer memory (ArrayBuffers and typed arrays, including memory grown with
|
|
1458
|
+
* `resize()`, and stream chunks). Read once when the run ends, on prefix
|
|
1459
|
+
* and one-off runs alike; on a prefix it feeds eviction, since warm
|
|
1460
|
+
* instances keep their memory between calls. It includes garbage not yet
|
|
1461
|
+
* collected (a warm instance pushed over its soft line by buffers, with
|
|
1462
|
+
* objects alone under it, is collected once first). A run that sends its
|
|
1463
|
+
* result early (`waitUntil` work, open stream bodies) reports a reading
|
|
1464
|
+
* taken at that moment, before any run-end collection, so it can differ
|
|
1465
|
+
* from the figure the soft line uses. `0` on a prefix run whose instance
|
|
1466
|
+
* could not be measured (failed warm-up, dead instance). `undefined` when
|
|
1467
|
+
* the run was answered without a reading: refused before it started, or a
|
|
1468
|
+
* result too large to send.
|
|
1469
|
+
*/
|
|
1470
|
+
memoryBytes?: number;
|
|
1384
1471
|
/**
|
|
1385
1472
|
* Present when the run registered background work with `waitUntil`:
|
|
1386
1473
|
* the value in this result was delivered early, the work keeps running
|
|
@@ -1409,12 +1496,21 @@ interface RunFailure {
|
|
|
1409
1496
|
queueWaitMs?: number;
|
|
1410
1497
|
bridgeCalls: BridgeCallEntry[];
|
|
1411
1498
|
/**
|
|
1412
|
-
*
|
|
1413
|
-
*
|
|
1414
|
-
*
|
|
1415
|
-
* one-off
|
|
1416
|
-
|
|
1417
|
-
|
|
1499
|
+
* Memory of the isolate that served this run, in bytes: the JS heap plus
|
|
1500
|
+
* buffer memory (ArrayBuffers and typed arrays, including memory grown with
|
|
1501
|
+
* `resize()`, and stream chunks). Read once when the run ends, on prefix
|
|
1502
|
+
* and one-off runs alike; on a prefix it feeds eviction, since warm
|
|
1503
|
+
* instances keep their memory between calls. It includes garbage not yet
|
|
1504
|
+
* collected (a warm instance pushed over its soft line by buffers, with
|
|
1505
|
+
* objects alone under it, is collected once first). A run that sends its
|
|
1506
|
+
* result early (`waitUntil` work, open stream bodies) reports a reading
|
|
1507
|
+
* taken at that moment, before any run-end collection, so it can differ
|
|
1508
|
+
* from the figure the soft line uses. `0` on a prefix run whose instance
|
|
1509
|
+
* could not be measured (failed warm-up, dead instance). `undefined` when
|
|
1510
|
+
* the run was answered without a reading: refused before it started, or a
|
|
1511
|
+
* result too large to send.
|
|
1512
|
+
*/
|
|
1513
|
+
memoryBytes?: number;
|
|
1418
1514
|
}
|
|
1419
1515
|
/**
|
|
1420
1516
|
* The run was stopped by an abort — a pre-aborted or mid-run `signal` passed to
|
|
@@ -1486,12 +1582,26 @@ interface RunError {
|
|
|
1486
1582
|
* the victims of one reset, so they can be correlated.
|
|
1487
1583
|
*/
|
|
1488
1584
|
culpritRunId?: number;
|
|
1585
|
+
/**
|
|
1586
|
+
* `'prefix'` when the cold start this run paid for failed with one of the
|
|
1587
|
+
* prefix's own, repeatable errors (`ERR_USER_CODE`, `ERR_MODULE_NOT_FOUND`,
|
|
1588
|
+
* `ERR_IMPORT`, `ERR_PREFIX_BRIDGE_CALL`, `ERR_PREFIX_DID_NOT_SETTLE`), so
|
|
1589
|
+
* the failure is the prefix's, not the run code's. Absent for run-code
|
|
1590
|
+
* failures and for load-dependent cold-start failures (`ERR_WARMUP_LIMIT`,
|
|
1591
|
+
* `ERR_MEMORY_LIMIT`), which do not break the prefix. The same run moves
|
|
1592
|
+
* {@link Prefix.status} to `'broken'` (DESIGN.md §16.4).
|
|
1593
|
+
*/
|
|
1594
|
+
stage?: "prefix";
|
|
1489
1595
|
}
|
|
1490
1596
|
/**
|
|
1491
1597
|
* Why a shared instance was reset under an innocent victim — see
|
|
1492
|
-
* `RunError.resetCause`.
|
|
1598
|
+
* `RunError.resetCause`. Every cause describes what the culprit run
|
|
1599
|
+
* (`culpritRunId`) did, never this run.
|
|
1600
|
+
*
|
|
1601
|
+
* `'unsupported'`: the culprit used something the runtime does not support
|
|
1602
|
+
* (today: dynamic `import()`), so the runtime ended it.
|
|
1493
1603
|
*/
|
|
1494
|
-
type ResetCause = "cpu" | "memory" | "wall" | "abort" | "internal";
|
|
1604
|
+
type ResetCause = "cpu" | "memory" | "wall" | "abort" | "internal" | "unsupported";
|
|
1495
1605
|
/**
|
|
1496
1606
|
* Why a run's options were refused before anything ran. `sandbox.run()`,
|
|
1497
1607
|
* `prefix.run()`, `prefix.call()` and `prepare()` reject with an `Error`
|
|
@@ -1501,15 +1611,16 @@ type ResetCause = "cpu" | "memory" | "wall" | "abort" | "internal";
|
|
|
1501
1611
|
* answer the same way. `ERR_PREFIX_DISPOSED`: the prefix was disposed, or the
|
|
1502
1612
|
* runtime no longer holds it.
|
|
1503
1613
|
*/
|
|
1504
|
-
type SetupErrorCode = "ERR_PREFIX_DISPOSED" | "ERR_UNDECLARED_BINDING" | "ERR_RESERVED_NAME" | "ERR_FROZEN_BINDING" | "ERR_INVALID_REBIND";
|
|
1614
|
+
type SetupErrorCode = "ERR_PREFIX_DISPOSED" | "ERR_PREFIX_BROKEN" | "ERR_UNDECLARED_BINDING" | "ERR_RESERVED_NAME" | "ERR_FROZEN_BINDING" | "ERR_INVALID_REBIND";
|
|
1505
1615
|
/**
|
|
1506
1616
|
* Why a run failed, in a `{ ok: false }` result. Setup refusals are thrown
|
|
1507
|
-
* instead and carry a {@link SetupErrorCode}. `
|
|
1508
|
-
* `
|
|
1617
|
+
* instead and carry a {@link SetupErrorCode}. `readExports()` rejects on
|
|
1618
|
+
* any failure; `prepare()` never runs anything, so a broken prefix reports
|
|
1619
|
+
* these on its first run.
|
|
1509
1620
|
*/
|
|
1510
|
-
type RunErrorCode = "ERR_USER_CODE" | "ERR_MEMORY_LIMIT" | "ERR_CPU_TIMEOUT" | "ERR_WALL_TIMEOUT" | "ERR_ABORTED" | "ERR_MODULE_NOT_FOUND" | "
|
|
1621
|
+
type RunErrorCode = "ERR_USER_CODE" | "ERR_MEMORY_LIMIT" | "ERR_CPU_TIMEOUT" | "ERR_WALL_TIMEOUT" | "ERR_ABORTED" | "ERR_MODULE_NOT_FOUND" | "ERR_IMPORT" | "ERR_FUNCTION_ARGUMENT_NOT_SUPPORTED" | "ERR_EXPORT_NOT_SERIALIZABLE" | "ERR_TYPE_NOT_SERIALIZABLE" | "ERR_EXPORT_TOO_LARGE" | "ERR_CALL_TARGET_NOT_FOUND" | "ERR_HOST_BRIDGE" | "ERR_BRIDGE_PAYLOAD_TOO_LARGE" | "ERR_BRIDGE_CALL_LIMIT_EXCEEDED" | "ERR_INSTANCE_RESET" | "ERR_CAPACITY_MEMORY" | "ERR_QUEUE_FULL" | "ERR_PREFIX_DID_NOT_SETTLE" | "ERR_PREFIX_BRIDGE_CALL" | "ERR_WARMUP_LIMIT" | "ERR_PROTOCOL_DESYNC" | "ERR_INTERNAL";
|
|
1511
1622
|
//#endregion
|
|
1512
1623
|
//#region src/index.d.ts
|
|
1513
1624
|
declare function createSandbox(options?: SandboxOptions): Promise<Sandbox>;
|
|
1514
1625
|
//#endregion
|
|
1515
|
-
export { type BridgeCallEntry, type BridgeCallEntryBase, type BridgeCallFailureReason, type BridgeGlobal, type BridgeWithShim, type CallResult, type CallSuccess, type CallTarget, type CreateSandbox, type DataGlobal, type GlobalOptions, type HostExportData, type HostExportFunction, type HostGlobalValue, type HostGlobals, type HostModuleObject, type HostModuleValue, type ImportValue, type Imports, type MemoryLimit, type OneOffResourceLimits, type PrecompileOptions, type Prefix, type PrefixCallOptions, type PrefixRunOptions, type ReadExportsOptions, type ReadExportsResult, type RebindGlobals, type RebindHostModule, type RebindImports, type RebindValue, type ResetCause, type ResourceLimits, type RunCallOptions, type RunError, type RunErrorCode, type RunFailure, type RunOptions, type RunResult, type RunSuccess, type Sandbox, type SandboxExports, type SandboxOptions, type SandboxStats, type SetupErrorCode, type StringGlobal, type WaitUntilResult, createSandbox };
|
|
1626
|
+
export { type BridgeCallEntry, type BridgeCallEntryBase, type BridgeCallFailureReason, type BridgeGlobal, type BridgeWithShim, type CallResult, type CallSuccess, type CallTarget, type CreateSandbox, type DataGlobal, type GlobalOptions, type HostExportData, type HostExportFunction, type HostGlobalValue, type HostGlobals, type HostModuleObject, type HostModuleValue, type ImportValue, type Imports, type MemoryLimit, type OneOffResourceLimits, type PrecompileOptions, type Prefix, type PrefixCallOptions, type PrefixRunOptions, type PrefixStatus, type ReadExportsOptions, type ReadExportsResult, type RebindGlobals, type RebindHostModule, type RebindImports, type RebindValue, type ResetCause, type ResourceLimits, type RunCallOptions, type RunError, type RunErrorCode, type RunFailure, type RunOptions, type RunResult, type RunSuccess, type Sandbox, type SandboxExports, type SandboxOptions, type SandboxStats, type SetupErrorCode, type StringGlobal, type WaitUntilResult, createSandbox };
|
package/dist/index.mjs
CHANGED
|
@@ -1093,6 +1093,10 @@ var PayloadDecodeError = class extends Error {
|
|
|
1093
1093
|
var PayloadReader = class {
|
|
1094
1094
|
view;
|
|
1095
1095
|
offset = 0;
|
|
1096
|
+
/**
|
|
1097
|
+
* Byte length of the blob the last `readValueBlob()` consumed.
|
|
1098
|
+
*/
|
|
1099
|
+
lastValueBlobBytes = 0;
|
|
1096
1100
|
constructor(buf) {
|
|
1097
1101
|
this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
1098
1102
|
}
|
|
@@ -1181,7 +1185,8 @@ var PayloadReader = class {
|
|
|
1181
1185
|
* Read a value slot: `u32 byteLength` + V8 serialization blob.
|
|
1182
1186
|
*/
|
|
1183
1187
|
readValueBlob() {
|
|
1184
|
-
|
|
1188
|
+
this.lastValueBlobBytes = this.readU32();
|
|
1189
|
+
return deserializeValue(this.readRawBytes(this.lastValueBlobBytes));
|
|
1185
1190
|
}
|
|
1186
1191
|
/**
|
|
1187
1192
|
* Read an `Optional<value slot>`: a presence byte, then the slot when set.
|
|
@@ -1310,6 +1315,7 @@ function decodeBridgeCallPayload(buf) {
|
|
|
1310
1315
|
};
|
|
1311
1316
|
const decoded = reader.readValueBlob();
|
|
1312
1317
|
if (!Array.isArray(decoded)) throw new PayloadDecodeError(`BridgeCall args must decode to an array, got ${decoded === null ? "null" : typeof decoded}`);
|
|
1318
|
+
assertNoArrayHoles(decoded, reader.lastValueBlobBytes);
|
|
1313
1319
|
return {
|
|
1314
1320
|
runId,
|
|
1315
1321
|
callId,
|
|
@@ -1318,6 +1324,50 @@ function decodeBridgeCallPayload(buf) {
|
|
|
1318
1324
|
};
|
|
1319
1325
|
}
|
|
1320
1326
|
/**
|
|
1327
|
+
* Refuse bridge arguments holding an array with holes, at any depth
|
|
1328
|
+
* (DESIGN.md §12.1). A dense slot costs at least one wire byte, so array
|
|
1329
|
+
* lengths summing past the blob size prove a hole before any index is read.
|
|
1330
|
+
* @param args the decoded argument list
|
|
1331
|
+
* @param blobBytes byte length of the value blob the arguments arrived in
|
|
1332
|
+
*/
|
|
1333
|
+
function assertNoArrayHoles(args, blobBytes) {
|
|
1334
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1335
|
+
const stack = [args];
|
|
1336
|
+
let slots = 0;
|
|
1337
|
+
for (let v = stack.pop(); v !== void 0; v = stack.pop()) {
|
|
1338
|
+
if (seen.has(v)) continue;
|
|
1339
|
+
seen.add(v);
|
|
1340
|
+
if (Array.isArray(v)) {
|
|
1341
|
+
slots += v.length;
|
|
1342
|
+
if (slots > blobBytes) throw new PayloadDecodeError("bridge call argument contains an array with holes");
|
|
1343
|
+
for (let i = 0; i < v.length; i++) {
|
|
1344
|
+
if (!(i in v)) throw new PayloadDecodeError("bridge call argument contains an array with holes");
|
|
1345
|
+
const item = v[i];
|
|
1346
|
+
if (item !== null && typeof item === "object") stack.push(item);
|
|
1347
|
+
}
|
|
1348
|
+
const keys = Object.keys(v);
|
|
1349
|
+
for (let j = v.length; j < keys.length; j++) {
|
|
1350
|
+
const item = v[keys[j]];
|
|
1351
|
+
if (item !== null && typeof item === "object") stack.push(item);
|
|
1352
|
+
}
|
|
1353
|
+
continue;
|
|
1354
|
+
}
|
|
1355
|
+
const proto = Object.getPrototypeOf(v);
|
|
1356
|
+
if (proto === Object.prototype || proto === null) for (const key in v) {
|
|
1357
|
+
const item = v[key];
|
|
1358
|
+
if (item !== null && typeof item === "object") stack.push(item);
|
|
1359
|
+
}
|
|
1360
|
+
else if (v instanceof Map) {
|
|
1361
|
+
for (const k of v.keys()) if (k !== null && typeof k === "object") stack.push(k);
|
|
1362
|
+
for (const item of v.values()) if (item !== null && typeof item === "object") stack.push(item);
|
|
1363
|
+
} else if (v instanceof Set) {
|
|
1364
|
+
for (const item of v) if (item !== null && typeof item === "object") stack.push(item);
|
|
1365
|
+
} else if (v instanceof Error) {
|
|
1366
|
+
if (v.cause !== null && typeof v.cause === "object") stack.push(v.cause);
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
/**
|
|
1321
1371
|
* Build a `BridgeErrorPayload` from whatever a host handler threw.
|
|
1322
1372
|
*
|
|
1323
1373
|
* Own-enumerable properties beyond `name`/`message`/`stack` travel as
|
|
@@ -1632,7 +1682,7 @@ function decodeRunCompletionPayload(buf, resultKind, droppedCallIds) {
|
|
|
1632
1682
|
const wallTimeMs = reader.readF64();
|
|
1633
1683
|
const cpuTimeMs = reader.readF64();
|
|
1634
1684
|
const bridgeCalls = readBridgeCallRecords(reader, droppedCallIds);
|
|
1635
|
-
const
|
|
1685
|
+
const memoryBytes = reader.readOptionalU64();
|
|
1636
1686
|
const backgroundFlags = reader.readU8();
|
|
1637
1687
|
reader.readU8();
|
|
1638
1688
|
reader.assertDone();
|
|
@@ -1650,7 +1700,7 @@ function decodeRunCompletionPayload(buf, resultKind, droppedCallIds) {
|
|
|
1650
1700
|
wallTimeMs,
|
|
1651
1701
|
cpuTimeMs,
|
|
1652
1702
|
bridgeCalls,
|
|
1653
|
-
|
|
1703
|
+
memoryBytes
|
|
1654
1704
|
}
|
|
1655
1705
|
};
|
|
1656
1706
|
return {
|
|
@@ -1668,7 +1718,7 @@ function decodeRunCompletionPayload(buf, resultKind, droppedCallIds) {
|
|
|
1668
1718
|
wallTimeMs,
|
|
1669
1719
|
cpuTimeMs,
|
|
1670
1720
|
bridgeCalls,
|
|
1671
|
-
|
|
1721
|
+
memoryBytes
|
|
1672
1722
|
}
|
|
1673
1723
|
};
|
|
1674
1724
|
}
|
|
@@ -1680,13 +1730,15 @@ function decodeRunCompletionPayload(buf, resultKind, droppedCallIds) {
|
|
|
1680
1730
|
const stack = reader.readU8() === 1 ? reader.readString() : void 0;
|
|
1681
1731
|
const fields = reader.readOptionalValueBlob();
|
|
1682
1732
|
const reset = readResetInfo(reader);
|
|
1733
|
+
const stage = readPrefixStage(reader);
|
|
1734
|
+
const prefixCause = readErrorCause(reader);
|
|
1683
1735
|
const stdout = reader.readStringList();
|
|
1684
1736
|
const stderr = reader.readStringList();
|
|
1685
1737
|
const durationMs = reader.readF64();
|
|
1686
1738
|
const wallTimeMs = reader.readF64();
|
|
1687
1739
|
const cpuTimeMs = reader.readF64();
|
|
1688
1740
|
const bridgeCalls = readBridgeCallRecords(reader, droppedCallIds);
|
|
1689
|
-
const
|
|
1741
|
+
const memoryBytes = reader.readOptionalU64();
|
|
1690
1742
|
reader.assertDone();
|
|
1691
1743
|
return {
|
|
1692
1744
|
runId,
|
|
@@ -1701,7 +1753,8 @@ function decodeRunCompletionPayload(buf, resultKind, droppedCallIds) {
|
|
|
1701
1753
|
message,
|
|
1702
1754
|
stack,
|
|
1703
1755
|
fields,
|
|
1704
|
-
...reset
|
|
1756
|
+
...reset,
|
|
1757
|
+
...stage
|
|
1705
1758
|
},
|
|
1706
1759
|
stdout,
|
|
1707
1760
|
stderr,
|
|
@@ -1709,8 +1762,46 @@ function decodeRunCompletionPayload(buf, resultKind, droppedCallIds) {
|
|
|
1709
1762
|
wallTimeMs,
|
|
1710
1763
|
cpuTimeMs,
|
|
1711
1764
|
bridgeCalls,
|
|
1712
|
-
|
|
1713
|
-
}
|
|
1765
|
+
memoryBytes
|
|
1766
|
+
},
|
|
1767
|
+
...prefixCause === void 0 ? {} : { prefixCause }
|
|
1768
|
+
};
|
|
1769
|
+
}
|
|
1770
|
+
/**
|
|
1771
|
+
* The stage byte trailing every `RunErrorPayload`: `1` when the prefix failed
|
|
1772
|
+
* to evaluate on this run's cold start. A spreadable fragment, so run-stage
|
|
1773
|
+
* errors add nothing.
|
|
1774
|
+
* @param reader
|
|
1775
|
+
*/
|
|
1776
|
+
function readPrefixStage(reader) {
|
|
1777
|
+
const byte = reader.readU8();
|
|
1778
|
+
if (byte === 0) return {};
|
|
1779
|
+
if (byte !== 1) throw new PayloadDecodeError(`invalid prefix-stage byte: ${byte}`);
|
|
1780
|
+
return { stage: "prefix" };
|
|
1781
|
+
}
|
|
1782
|
+
/**
|
|
1783
|
+
* The optional cause trailing every `RunErrorPayload`, present only on an
|
|
1784
|
+
* `ERR_PREFIX_BROKEN` refusal: the stored cold-start failure's code, name,
|
|
1785
|
+
* message and stack.
|
|
1786
|
+
* @param reader
|
|
1787
|
+
*/
|
|
1788
|
+
function readErrorCause(reader) {
|
|
1789
|
+
const present = reader.readU8();
|
|
1790
|
+
if (present === 0) return void 0;
|
|
1791
|
+
if (present !== 1) throw new PayloadDecodeError(`invalid error-cause presence byte: ${present}`);
|
|
1792
|
+
const code = reader.readString();
|
|
1793
|
+
const name = reader.readString();
|
|
1794
|
+
const message = reader.readString();
|
|
1795
|
+
const stack = reader.readU8() === 1 ? reader.readString() : void 0;
|
|
1796
|
+
return stack === void 0 ? {
|
|
1797
|
+
code,
|
|
1798
|
+
name,
|
|
1799
|
+
message
|
|
1800
|
+
} : {
|
|
1801
|
+
code,
|
|
1802
|
+
name,
|
|
1803
|
+
message,
|
|
1804
|
+
stack
|
|
1714
1805
|
};
|
|
1715
1806
|
}
|
|
1716
1807
|
/**
|
|
@@ -1729,7 +1820,8 @@ function readResetInfo(reader) {
|
|
|
1729
1820
|
"memory",
|
|
1730
1821
|
"abort",
|
|
1731
1822
|
"internal",
|
|
1732
|
-
"wall"
|
|
1823
|
+
"wall",
|
|
1824
|
+
"unsupported"
|
|
1733
1825
|
][causeByte];
|
|
1734
1826
|
if (resetCause === void 0) throw new PayloadDecodeError(`invalid instance-reset cause byte: ${causeByte}`);
|
|
1735
1827
|
return {
|
|
@@ -1840,6 +1932,8 @@ function decodePrecompileResultPayload(buf) {
|
|
|
1840
1932
|
const stack = reader.readU8() === 1 ? reader.readString() : void 0;
|
|
1841
1933
|
reader.readOptionalValueBlob();
|
|
1842
1934
|
readResetInfo(reader);
|
|
1935
|
+
readPrefixStage(reader);
|
|
1936
|
+
readErrorCause(reader);
|
|
1843
1937
|
reader.assertDone();
|
|
1844
1938
|
return {
|
|
1845
1939
|
ok: false,
|
|
@@ -1860,7 +1954,7 @@ function decodePrecompileResultPayload(buf) {
|
|
|
1860
1954
|
* u32 oneoffRunning
|
|
1861
1955
|
* u32 warmBusy
|
|
1862
1956
|
* u32 warmIdle
|
|
1863
|
-
* u64
|
|
1957
|
+
* u64 idleMemoryBytes
|
|
1864
1958
|
* u64 warmBudgetBytes
|
|
1865
1959
|
* u64 rssBytes
|
|
1866
1960
|
* u8 underPressure
|
|
@@ -1877,7 +1971,7 @@ function decodeStatsPayload(buf) {
|
|
|
1877
1971
|
const warmBusy = reader.readU32();
|
|
1878
1972
|
const warmRuns = reader.readU32();
|
|
1879
1973
|
const warmIdle = reader.readU32();
|
|
1880
|
-
const
|
|
1974
|
+
const idleMemoryBytes = reader.readU64();
|
|
1881
1975
|
const warmBudgetBytes = reader.readU64();
|
|
1882
1976
|
const rssBytes = reader.readU64();
|
|
1883
1977
|
const usageBytes = reader.readU64();
|
|
@@ -1901,7 +1995,7 @@ function decodeStatsPayload(buf) {
|
|
|
1901
1995
|
warmBusy,
|
|
1902
1996
|
warmRuns,
|
|
1903
1997
|
warmIdle,
|
|
1904
|
-
|
|
1998
|
+
idleMemoryBytes,
|
|
1905
1999
|
warmBudgetBytes,
|
|
1906
2000
|
rssBytes,
|
|
1907
2001
|
usageBytes,
|
|
@@ -2058,10 +2152,8 @@ var RuntimeIpcClient = class RuntimeIpcClient {
|
|
|
2058
2152
|
*/
|
|
2059
2153
|
controlWaiters = [];
|
|
2060
2154
|
/**
|
|
2061
|
-
* Pending `precompile()` requests keyed by their wire `requestId
|
|
2062
|
-
*
|
|
2063
|
-
* flight on one connection the replies can return out of request order —
|
|
2064
|
-
* FIFO matching would cross-assign prefix ids between callers.
|
|
2155
|
+
* Pending `precompile()` requests keyed by their wire `requestId`, so a
|
|
2156
|
+
* reply is matched by id and never by arrival order.
|
|
2065
2157
|
*/
|
|
2066
2158
|
precompileWaiters = /* @__PURE__ */ new Map();
|
|
2067
2159
|
/**
|
|
@@ -3862,7 +3954,8 @@ const SETUP_ERROR_CODES = new Set([
|
|
|
3862
3954
|
"ERR_UNDECLARED_BINDING",
|
|
3863
3955
|
"ERR_FROZEN_BINDING",
|
|
3864
3956
|
"ERR_INVALID_REBIND",
|
|
3865
|
-
"ERR_PREFIX_DISPOSED"
|
|
3957
|
+
"ERR_PREFIX_DISPOSED",
|
|
3958
|
+
"ERR_PREFIX_BROKEN"
|
|
3866
3959
|
]);
|
|
3867
3960
|
/**
|
|
3868
3961
|
* The error `prepare()`, `readExports()` and `run()` throw for a failure the
|
|
@@ -4012,7 +4105,7 @@ var SandboxImpl = class {
|
|
|
4012
4105
|
openConnections: this.pool.openConnections,
|
|
4013
4106
|
warmInstances: raw.warmBusy + raw.warmIdle,
|
|
4014
4107
|
idleInstances: raw.warmIdle,
|
|
4015
|
-
|
|
4108
|
+
idleMemoryBytes: raw.idleMemoryBytes,
|
|
4016
4109
|
budgetBytes: raw.warmBudgetBytes,
|
|
4017
4110
|
rssBytes: raw.rssBytes,
|
|
4018
4111
|
usageBytes: raw.usageBytes,
|
|
@@ -4026,8 +4119,8 @@ var SandboxImpl = class {
|
|
|
4026
4119
|
}
|
|
4027
4120
|
/**
|
|
4028
4121
|
* Load a module once and read its serializable exports — the deploy path.
|
|
4029
|
-
* Function exports are skipped and reported; failures reject
|
|
4030
|
-
*
|
|
4122
|
+
* Function exports are skipped and reported; failures reject. See
|
|
4123
|
+
* {@link Sandbox.readExports}.
|
|
4031
4124
|
* @param options
|
|
4032
4125
|
*/
|
|
4033
4126
|
async readExports(options) {
|
|
@@ -4050,11 +4143,12 @@ var SandboxImpl = class {
|
|
|
4050
4143
|
return this.prepare(options);
|
|
4051
4144
|
}
|
|
4052
4145
|
/**
|
|
4053
|
-
*
|
|
4146
|
+
* Store a prefix for repeated runs; nothing is evaluated. See
|
|
4054
4147
|
* {@link Sandbox.prepare}.
|
|
4055
4148
|
* @param options
|
|
4056
4149
|
*/
|
|
4057
4150
|
async prepare(options) {
|
|
4151
|
+
if (typeof options.code !== "string") throw new TypeError(`prepare({ code }) must be a string, got ${options.code === null ? "null" : typeof options.code}`);
|
|
4058
4152
|
validateMemoryMb(options.memoryMb, "memoryMb");
|
|
4059
4153
|
validateLimits(options.limits);
|
|
4060
4154
|
const prefixMemoryMb = options.memoryMb ?? this.memoryMb;
|
|
@@ -4075,7 +4169,7 @@ var SandboxImpl = class {
|
|
|
4075
4169
|
imports: bindings
|
|
4076
4170
|
}));
|
|
4077
4171
|
if (!result.ok) throw thrownRunError(result.error);
|
|
4078
|
-
return new PrefixImpl(result.prefixId, this.pool, declaredGlobals, handlers, declaredImportShape(bindings), this.brandKey, prefixMemoryMb);
|
|
4172
|
+
return new PrefixImpl(result.prefixId, this.pool, declaredGlobals, handlers, declaredImportShape(bindings), this.brandKey, prefixMemoryMb, wireLimits(options.limits));
|
|
4079
4173
|
});
|
|
4080
4174
|
}
|
|
4081
4175
|
async dispose() {
|
|
@@ -4121,11 +4215,20 @@ var PrefixImpl = class {
|
|
|
4121
4215
|
*/
|
|
4122
4216
|
memoryMb;
|
|
4123
4217
|
/**
|
|
4218
|
+
* `prepare({ limits })` snapshot: the per-run defaults, overridden field by field.
|
|
4219
|
+
*/
|
|
4220
|
+
defaultLimits;
|
|
4221
|
+
/**
|
|
4124
4222
|
* Session brand key for host-type descriptors — see `SandboxImpl`.
|
|
4125
4223
|
*/
|
|
4126
4224
|
brandKey;
|
|
4127
|
-
|
|
4128
|
-
|
|
4225
|
+
_status = "ready";
|
|
4226
|
+
/**
|
|
4227
|
+
* The cold-start failure that broke this prefix, cached from the first
|
|
4228
|
+
* result or refusal that reported it; later runs throw it without a round trip.
|
|
4229
|
+
*/
|
|
4230
|
+
_error;
|
|
4231
|
+
constructor(id, pool, declaredGlobals, defaultImportHandlers, declaredImports, brandKey, memoryMb, defaultLimits = {}) {
|
|
4129
4232
|
this.id = id;
|
|
4130
4233
|
this.pool = pool;
|
|
4131
4234
|
this.declaredGlobals = declaredGlobals;
|
|
@@ -4133,9 +4236,34 @@ var PrefixImpl = class {
|
|
|
4133
4236
|
this.declaredImports = declaredImports;
|
|
4134
4237
|
this.brandKey = brandKey;
|
|
4135
4238
|
this.memoryMb = memoryMb;
|
|
4239
|
+
this.defaultLimits = defaultLimits;
|
|
4136
4240
|
}
|
|
4137
4241
|
get alive() {
|
|
4138
|
-
return this.
|
|
4242
|
+
return this._status !== "disposed";
|
|
4243
|
+
}
|
|
4244
|
+
get status() {
|
|
4245
|
+
return this._status;
|
|
4246
|
+
}
|
|
4247
|
+
get error() {
|
|
4248
|
+
return this._error;
|
|
4249
|
+
}
|
|
4250
|
+
/**
|
|
4251
|
+
* Remember the prefix-stage failure that broke this prefix. Disposal wins.
|
|
4252
|
+
* @param error the stored cold-start failure
|
|
4253
|
+
*/
|
|
4254
|
+
markBroken(error) {
|
|
4255
|
+
if (this._status !== "ready") return;
|
|
4256
|
+
this._status = "broken";
|
|
4257
|
+
this._error = error;
|
|
4258
|
+
}
|
|
4259
|
+
/**
|
|
4260
|
+
* The `ERR_PREFIX_BROKEN` refusal, with the cold-start failure as `cause`.
|
|
4261
|
+
* @param cause the stored failure, or the one a runtime refusal carried
|
|
4262
|
+
*/
|
|
4263
|
+
brokenError(cause = this._error) {
|
|
4264
|
+
const err = setupError("ERR_PREFIX_BROKEN", `prefix '${this.id}' is broken: its cold start failed with ${cause?.code}: ${cause?.message}`);
|
|
4265
|
+
err.cause = cause;
|
|
4266
|
+
return err;
|
|
4139
4267
|
}
|
|
4140
4268
|
/**
|
|
4141
4269
|
* Execute dynamic code against this prefix. See
|
|
@@ -4179,7 +4307,8 @@ var PrefixImpl = class {
|
|
|
4179
4307
|
* @param buildPayload
|
|
4180
4308
|
*/
|
|
4181
4309
|
async dispatch(options, buildPayload) {
|
|
4182
|
-
if (
|
|
4310
|
+
if (this._status === "disposed") throw setupError("ERR_PREFIX_DISPOSED", `prefix '${this.id}' has been disposed or never existed`);
|
|
4311
|
+
if (this._status === "broken") throw this.brokenError();
|
|
4183
4312
|
if (options.signal?.aborted) return abortedResult(options.signal.reason);
|
|
4184
4313
|
if (options.hardAbortSignal?.aborted) return abortedResult(options.hardAbortSignal.reason);
|
|
4185
4314
|
validateLimits(options.limits);
|
|
@@ -4201,6 +4330,7 @@ var PrefixImpl = class {
|
|
|
4201
4330
|
code: payload.code,
|
|
4202
4331
|
filename: options.filename,
|
|
4203
4332
|
limits: {
|
|
4333
|
+
...this.defaultLimits,
|
|
4204
4334
|
...wireLimits(options.limits),
|
|
4205
4335
|
...heapCapsForWire(this.memoryMb)
|
|
4206
4336
|
},
|
|
@@ -4213,7 +4343,13 @@ var PrefixImpl = class {
|
|
|
4213
4343
|
call: payload.call,
|
|
4214
4344
|
streams
|
|
4215
4345
|
});
|
|
4216
|
-
const
|
|
4346
|
+
const completion = withBodyStreamBinder((id) => raw.outStreams.attach(id), () => payload.call === void 0 ? decodeRunCompletionPayload(raw.result, void 0, raw.droppedCallIds) : decodeRunCompletionPayload(raw.result, "call", raw.droppedCallIds));
|
|
4347
|
+
const decoded = completion.result;
|
|
4348
|
+
if (decoded.status === "failed" && decoded.error.code === "ERR_PREFIX_BROKEN") {
|
|
4349
|
+
if (completion.prefixCause !== void 0) this.markBroken(completion.prefixCause);
|
|
4350
|
+
throw this.brokenError(completion.prefixCause ?? this._error);
|
|
4351
|
+
}
|
|
4352
|
+
if (decoded.status === "failed" && decoded.error.stage === "prefix") this.markBroken(decoded.error);
|
|
4217
4353
|
if (decoded.status === "failed" && SETUP_ERROR_CODES.has(decoded.error.code)) throw thrownRunError({
|
|
4218
4354
|
...decoded.error,
|
|
4219
4355
|
code: decoded.error.code
|
|
@@ -4234,8 +4370,8 @@ var PrefixImpl = class {
|
|
|
4234
4370
|
}
|
|
4235
4371
|
}
|
|
4236
4372
|
async dispose() {
|
|
4237
|
-
if (
|
|
4238
|
-
this.
|
|
4373
|
+
if (this._status === "disposed") return;
|
|
4374
|
+
this._status = "disposed";
|
|
4239
4375
|
this.declaredGlobals = /* @__PURE__ */ new Map();
|
|
4240
4376
|
this.defaultImportHandlers = /* @__PURE__ */ new Map();
|
|
4241
4377
|
this.declaredImports = [];
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@iso4/sandbox",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Fast, sandboxed V8 isolate runtime for agent-generated JavaScript. Two-process architecture for crash isolation.",
|
|
6
6
|
"keywords": [
|
|
@@ -42,21 +42,21 @@
|
|
|
42
42
|
"dist"
|
|
43
43
|
],
|
|
44
44
|
"devDependencies": {
|
|
45
|
-
"@changesets/cli": "^2.
|
|
45
|
+
"@changesets/cli": "^2.31.1",
|
|
46
46
|
"@codspeed/vitest-plugin": "^5.7.1",
|
|
47
|
-
"@schplitt/eslint-config": "^1.5.
|
|
48
|
-
"@types/node": "^24.
|
|
49
|
-
"eslint": "^10.
|
|
47
|
+
"@schplitt/eslint-config": "^1.5.4",
|
|
48
|
+
"@types/node": "^24.19.4",
|
|
49
|
+
"eslint": "^10.15.0",
|
|
50
50
|
"tsdown": "^0.21.10",
|
|
51
|
-
"tsnapi": "^1.
|
|
51
|
+
"tsnapi": "^1.6.1",
|
|
52
52
|
"typescript": "^6.0.3",
|
|
53
|
-
"vitest": "^4.1.
|
|
53
|
+
"vitest": "^4.1.12"
|
|
54
54
|
},
|
|
55
55
|
"optionalDependencies": {
|
|
56
|
-
"@iso4/v8-darwin-arm64": "^0.
|
|
57
|
-
"@iso4/v8-darwin-x64": "^0.
|
|
58
|
-
"@iso4/v8-linux-arm64-gnu": "^0.
|
|
59
|
-
"@iso4/v8-linux-x64-gnu": "^0.
|
|
56
|
+
"@iso4/v8-darwin-arm64": "^0.10.0",
|
|
57
|
+
"@iso4/v8-darwin-x64": "^0.10.0",
|
|
58
|
+
"@iso4/v8-linux-arm64-gnu": "^0.10.0",
|
|
59
|
+
"@iso4/v8-linux-x64-gnu": "^0.10.0"
|
|
60
60
|
},
|
|
61
61
|
"engines": {
|
|
62
62
|
"node": ">=24.0.0"
|