@nimbus-sh/fabric 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +487 -0
  3. package/dist/alarms.d.ts +134 -0
  4. package/dist/alarms.d.ts.map +1 -0
  5. package/dist/alarms.js +214 -0
  6. package/dist/bindings.d.ts +316 -0
  7. package/dist/bindings.d.ts.map +1 -0
  8. package/dist/bindings.js +678 -0
  9. package/dist/ctx-exports.d.ts +47 -0
  10. package/dist/ctx-exports.d.ts.map +1 -0
  11. package/dist/ctx-exports.js +54 -0
  12. package/dist/facet-image-store.d.ts +112 -0
  13. package/dist/facet-image-store.d.ts.map +1 -0
  14. package/dist/facet-image-store.js +181 -0
  15. package/dist/fanout-pool.d.ts +223 -0
  16. package/dist/fanout-pool.d.ts.map +1 -0
  17. package/dist/fanout-pool.js +368 -0
  18. package/dist/index.d.ts +26 -0
  19. package/dist/index.d.ts.map +1 -0
  20. package/dist/index.js +25 -0
  21. package/dist/inner-do-registry.d.ts +41 -0
  22. package/dist/inner-do-registry.d.ts.map +1 -0
  23. package/dist/inner-do-registry.js +51 -0
  24. package/dist/launch-journal.d.ts +170 -0
  25. package/dist/launch-journal.d.ts.map +1 -0
  26. package/dist/launch-journal.js +154 -0
  27. package/dist/launch-pacer.d.ts +173 -0
  28. package/dist/launch-pacer.d.ts.map +1 -0
  29. package/dist/launch-pacer.js +193 -0
  30. package/dist/loader-ledger.d.ts +57 -0
  31. package/dist/loader-ledger.d.ts.map +1 -0
  32. package/dist/loader-ledger.js +91 -0
  33. package/dist/loader-pool.d.ts +315 -0
  34. package/dist/loader-pool.d.ts.map +1 -0
  35. package/dist/loader-pool.js +666 -0
  36. package/dist/process-fabric.d.ts +524 -0
  37. package/dist/process-fabric.d.ts.map +1 -0
  38. package/dist/process-fabric.js +388 -0
  39. package/dist/process-host.d.ts +132 -0
  40. package/dist/process-host.d.ts.map +1 -0
  41. package/dist/process-host.js +444 -0
  42. package/dist/vendor/errors.d.ts +24 -0
  43. package/dist/vendor/errors.d.ts.map +1 -0
  44. package/dist/vendor/errors.js +46 -0
  45. package/dist/vendor/serialize.d.ts +3 -0
  46. package/dist/vendor/serialize.d.ts.map +1 -0
  47. package/dist/vendor/serialize.js +25 -0
  48. package/dist/vendor/types.d.ts +69 -0
  49. package/dist/vendor/types.d.ts.map +1 -0
  50. package/dist/vendor/types.js +4 -0
  51. package/dist/workerd-facet-host.d.ts +207 -0
  52. package/dist/workerd-facet-host.d.ts.map +1 -0
  53. package/dist/workerd-facet-host.js +508 -0
  54. package/dist/ws-hibernation-config.d.ts +73 -0
  55. package/dist/ws-hibernation-config.d.ts.map +1 -0
  56. package/dist/ws-hibernation-config.js +93 -0
  57. package/package.json +62 -0
  58. package/src/alarms.ts +275 -0
  59. package/src/bindings.ts +871 -0
  60. package/src/ctx-exports.ts +77 -0
  61. package/src/facet-image-store.ts +196 -0
  62. package/src/fanout-pool.ts +503 -0
  63. package/src/index.ts +26 -0
  64. package/src/inner-do-registry.ts +58 -0
  65. package/src/launch-journal.ts +229 -0
  66. package/src/launch-pacer.ts +231 -0
  67. package/src/loader-ledger.ts +112 -0
  68. package/src/loader-pool.ts +984 -0
  69. package/src/process-fabric.ts +729 -0
  70. package/src/process-host.ts +566 -0
  71. package/src/vendor/errors.ts +56 -0
  72. package/src/vendor/serialize.ts +37 -0
  73. package/src/vendor/types.ts +75 -0
  74. package/src/workerd-facet-host.ts +694 -0
  75. package/src/ws-hibernation-config.ts +123 -0
@@ -0,0 +1,666 @@
1
+ /**
2
+ * loader-pool.ts — Nimbus loader-isolate pool based on cloudflare-parallel.
3
+ *
4
+ * Adds Nimbus-specific behavior to the upstream pool design:
5
+ * 1. **Stable-slot isolate reuse**. Upstream's #counter++ gives every
6
+ * dispatch a fresh isolate — fine for one-off AI calls, terrible for
7
+ * running 67 npm tarball extractions (cold-start dominates). We pin
8
+ * each job to `slot = cursor % concurrency` and use stable loader
9
+ * IDs `nfp:${fnHash}:slot-${i}:g${generation}`, so a pool of
10
+ * concurrency=4 keeps at most 4 warm isolates rather than N fresh ones.
11
+ * 2. **Nimbus defaults**: compatibilityDate = CF_COMPAT_DATE (matches
12
+ * the supervisor worker), compatibilityFlags = ['nodejs_compat'],
13
+ * globalOutbound = undefined (inherit parent network so the facet can
14
+ * reach https://registry.npmjs.org without a proxy binding).
15
+ * 3. **Supervisor autoinjection**. The pool grabs the embedder's
16
+ * registered supervisor entrypoint stub (see `supervisorEntrypoint` in
17
+ * ctx-exports.ts) and forwards it as `env.SUPERVISOR` to every facet,
18
+ * same pattern as git-network-facet.ts. Callers can add more bindings
19
+ * via `extraBindings`.
20
+ * 4. **Fail-loud defaults**: timeout 60s, retries 0, onError 'throw'.
21
+ * Caller opts in to leniency.
22
+ *
23
+ * The vendored directory contains only the upstream serialization, error,
24
+ * and binding types used by this implementation.
25
+ */
26
+ import { CF_COMPAT_DATE } from '@nimbus-sh/core/constants.js';
27
+ import { supervisorEntrypoint } from './ctx-exports.js';
28
+ import { disposeRpcResource } from '@nimbus-sh/core/_shared/rpc-dispose.js';
29
+ import { serializeFunction, hashSource } from './vendor/serialize.js';
30
+ import { beginLoaderFetch, recordLoaderId, withDynamicWorkerCapNamed } from './loader-ledger.js';
31
+ import { assertModuleMapWithinCodeLimit } from './workerd-facet-host.js';
32
+ import { recordFailure, setLastFacetId, getLastRpcFrame } from '@nimbus-sh/core/observability/oom-discriminator.js';
33
+ import { classifyError } from '@nimbus-sh/core/observability/oom-classify.js';
34
+ import { BindingError, ExecutionError, RetryExhaustedError, TimeoutError, } from './vendor/errors.js';
35
+ /**
36
+ * esbuild runtime helpers re-declared at the top of every generated facet
37
+ * module. esbuild emits `__name(fn, "fn")` wrappers around every named
38
+ * function or arrow-with-binding-name; `fn.toString()` yields a body that
39
+ * references `__name` by bare identifier. The supervisor bundle declares
40
+ * `__name` at its own top level, but the binding does NOT cross isolate
41
+ * boundaries — the facet's worker.js must re-declare it.
42
+ *
43
+ * The shim is bytes-stable so it doesn't perturb the loader-cache key;
44
+ * if esbuild ever emits a new helper we'll see a "<name> is not defined"
45
+ * error in the facet, add it here, and every slot rebuilds.
46
+ */
47
+ const ESBUILD_RUNTIME_SHIM = [
48
+ 'const __defProp = Object.defineProperty;',
49
+ 'const __name = (target, value) => __defProp(target, "name", { value, configurable: true });',
50
+ 'const __nimbusDisposeRpcResult = (value) => {',
51
+ ' if ((typeof value !== "object" && typeof value !== "function") || value === null) return;',
52
+ ' const dispose = value[Symbol.dispose];',
53
+ ' if (typeof dispose === "function") { try { dispose.call(value); } catch {} }',
54
+ '};',
55
+ 'const __nimbusUseRpcResult = async (promise, use) => {',
56
+ ' const value = await promise;',
57
+ ' try { return await use(value); }',
58
+ ' finally { __nimbusDisposeRpcResult(value); }',
59
+ '};',
60
+ ].join('\n');
61
+ /** Assemble the exact JavaScript module parsed by a dynamic loader worker. */
62
+ export function assembleLoaderWorkerModuleSource(options) {
63
+ const lines = [
64
+ 'import { WorkerEntrypoint } from "cloudflare:workers";',
65
+ ];
66
+ const wasmEntries = options.wasmEntries ?? [];
67
+ if (wasmEntries.length > 0) {
68
+ lines.push('');
69
+ lines.push('// ── Pool-injected WebAssembly modules ─────────────────────');
70
+ for (const entry of wasmEntries) {
71
+ lines.push(`import __NIMBUS_WASM_${entry.id} from './${entry.name}';`);
72
+ }
73
+ lines.push('globalThis.__NIMBUS_WASM = globalThis.__NIMBUS_WASM || {};');
74
+ for (const entry of wasmEntries) {
75
+ lines.push(`globalThis.__NIMBUS_WASM[${JSON.stringify(entry.name)}] = __NIMBUS_WASM_${entry.id};`);
76
+ }
77
+ lines.push('// ── End pool-injected WebAssembly modules ─────────────────');
78
+ }
79
+ lines.push('', '// ── esbuild runtime shim ──────────────────────────────────', '// When Nimbus is bundled by wrangler/esbuild, our facet function', '// is transformed into `__name(async function …, "…")` at emit', '// time. `fn.toString()` then yields the wrapped function body,', '// but `__name` and its helpers are module-local in the SUPERVISOR', '// bundle and do NOT cross into the facet isolate. Redeclare them', '// here so facet bodies survive the toString() round-trip.', ESBUILD_RUNTIME_SHIM, '// ── End esbuild runtime shim ──────────────────────────────', '');
80
+ if (options.preamble) {
81
+ lines.push('// ── Preamble (pool-level helpers) ─────────────────────────', options.preamble, '// ── End preamble ──────────────────────────────────────────', '');
82
+ }
83
+ lines.push(`const __fn__ = ${options.fnSource};`);
84
+ lines.push('');
85
+ const callExpr = options.hasBindings
86
+ ? '__fn__(...args, this.env)'
87
+ : '__fn__(...args)';
88
+ lines.push('export default class extends WorkerEntrypoint {', ' execute(...args) {', ` const result = ${callExpr};`, ' if (result instanceof Promise) return result;', ' return result;', ' }', '}');
89
+ return lines.join('\n');
90
+ }
91
+ /**
92
+ * Nimbus-scoped parallel dispatch over `env.LOADER`. Tasks are pure
93
+ * functions whose last argument is an `env` object containing the
94
+ * forwarded bindings (default: `{ SUPERVISOR }`).
95
+ *
96
+ * Typical use:
97
+ *
98
+ * const pool = new LoaderPool(env, ctx, {
99
+ * concurrency: 4,
100
+ * tag: 'npm-install',
101
+ * });
102
+ * const results = await pool.map(
103
+ * async (pkg, env) => env.SUPERVISOR.writeBatch(buildPayload(pkg)),
104
+ * toFetch,
105
+ * );
106
+ */
107
+ export class LoaderPool {
108
+ loader;
109
+ /** The hosting actor, as the loader-ledger's per-DO key. */
110
+ ctx;
111
+ concurrency;
112
+ defaultTimeoutMs;
113
+ defaultRetries;
114
+ tag;
115
+ slotGenerations = new Map();
116
+ bindings;
117
+ preamble;
118
+ preambleHash;
119
+ /**
120
+ * WASM modules to ship in the LOADER `modules` map. See
121
+ * LoaderPoolOptions.wasmModules for the rationale. Stored in
122
+ * insertion order so the per-import preamble we generate matches
123
+ * across pool dispatches (cache-key stability).
124
+ */
125
+ wasmModules;
126
+ /** Hash of (name + byte length + first/last bytes) of every wasm
127
+ * module, folded into the loader cache key so changes invalidate
128
+ * warm slots. Hashing the FULL bytes would be O(20+ MiB) per dispatch
129
+ * and is unnecessary — wasm bytes are pinned at deploy time, the
130
+ * length+endpoints are a strong-enough fingerprint. */
131
+ wasmHash;
132
+ /**
133
+ * Short prefix of the owning DO's id, baked into the loader.get()
134
+ * cache key so warm isolates are scoped to ONE session. Without this,
135
+ * session A's pool and session B's pool (same `tag` + `fnHash`) share
136
+ * an isolate — which means B's writeBatch RPCs routed through A's
137
+ * env.SUPERVISOR binding (minted with A's doId at construction
138
+ * time). B's install reports success but the writes land in A's VFS,
139
+ * leaving B with only the git-clone seed files (~119 instead of ~1491).
140
+ * 12 chars is enough entropy for DO ids to collide-free per process.
141
+ */
142
+ doIdShort;
143
+ constructor(env, ctx, opts) {
144
+ // A host hands its whole env over; the binding is claimed here and the
145
+ // claim is checked on the next line.
146
+ const loader = env?.LOADER;
147
+ if (!loader || typeof loader.get !== 'function') {
148
+ throw new BindingError('LoaderPool: env.LOADER binding missing or invalid. ' +
149
+ 'Add a [[worker_loaders]] entry to wrangler.jsonc.');
150
+ }
151
+ this.loader = loader;
152
+ this.ctx = ctx;
153
+ this.concurrency = Math.max(1, opts?.concurrency ?? 4);
154
+ this.defaultTimeoutMs = opts?.timeoutMs ?? 60_000;
155
+ this.defaultRetries = Math.max(0, opts?.retries ?? 0);
156
+ this.tag = opts?.tag ?? 'facet';
157
+ this.preamble = opts?.preamble;
158
+ // Include preamble in the cache-bucket key so changes to bundled helpers
159
+ // invalidate warm slots. Empty preamble → '0' suffix (stable).
160
+ this.preambleHash = this.preamble ? hashSource(this.preamble) : '0';
161
+ this.doIdShort = opts?.cacheScope === 'global'
162
+ ? 'global'
163
+ : ctx.id.toString().slice(0, 12);
164
+ // Materialise the wasm-modules table. Sanitise each name into a
165
+ // valid JS identifier for the static import binding; key collisions
166
+ // (e.g. 'esbuild.wasm' and 'esbuild_wasm' both sanitise to
167
+ // 'esbuild_wasm') are rejected loudly because the generated worker
168
+ // would otherwise have duplicate imports. Order is preserved.
169
+ const wasmEntries = [];
170
+ const seenIds = new Set();
171
+ if (opts?.wasmModules) {
172
+ for (const [name, bytes] of Object.entries(opts.wasmModules)) {
173
+ if (!(bytes instanceof ArrayBuffer)) {
174
+ // Reached only when a caller broke the declared option type, so the
175
+ // value is whatever it really was rather than the ArrayBuffer here.
176
+ const got = bytes?.constructor?.name;
177
+ throw new BindingError(`LoaderPool: wasmModules['${name}'] must be ArrayBuffer ` +
178
+ `(got ${got || typeof bytes}).`);
179
+ }
180
+ const id = name.replace(/[^A-Za-z0-9_]/g, '_').replace(/^[^A-Za-z_]/, '_');
181
+ if (seenIds.has(id)) {
182
+ throw new BindingError(`LoaderPool: wasmModules key '${name}' collides with another after ` +
183
+ `identifier-sanitisation (id='${id}'). Pick distinct module names.`);
184
+ }
185
+ seenIds.add(id);
186
+ wasmEntries.push({ name, id, bytes });
187
+ }
188
+ }
189
+ this.wasmModules = wasmEntries;
190
+ // Fingerprint: name + length + first/last byte of each module.
191
+ // Hashing 20+ MiB of wasm per dispatch would be wasteful; this
192
+ // fingerprint is bytes-stable for a given deployed bundle and only
193
+ // changes when the wasm itself changes (deploy-time event).
194
+ if (wasmEntries.length === 0) {
195
+ this.wasmHash = '0';
196
+ }
197
+ else {
198
+ const fp = wasmEntries
199
+ .map((w) => {
200
+ const u = new Uint8Array(w.bytes);
201
+ const len = u.byteLength;
202
+ const first = len > 0 ? u[0] : 0;
203
+ const last = len > 0 ? u[len - 1] : 0;
204
+ return `${w.name}:${len}:${first}:${last}`;
205
+ })
206
+ .join('|');
207
+ this.wasmHash = hashSource(fp);
208
+ }
209
+ const bindings = { ...(opts?.extraBindings ?? {}) };
210
+ if (!opts?.omitSupervisor) {
211
+ const supervisorRpc = supervisorEntrypoint();
212
+ if (supervisorRpc) {
213
+ // INSTALL-HONESTY: peer-DO branch supplies coordinator's doId
214
+ // via supervisorDoIdOverride so SUPERVISOR.* RPCs route back
215
+ // to the user's session DO, not the peer DO. Default to the
216
+ // local ctx.id (single-DO callers and the in-DO in-DO fanout path).
217
+ const supDoId = opts?.supervisorDoIdOverride ?? ctx.id.toString();
218
+ bindings.SUPERVISOR = supervisorRpc({
219
+ props: { doId: supDoId, pid: opts?.supervisorPid ?? 0 },
220
+ });
221
+ }
222
+ else {
223
+ // Supervisor entrypoint unavailable — running without ctx.exports
224
+ // (e.g. unit-test harness, or LOADER.load contexts where the
225
+ // bindings.SUPERVISOR auto-wire isn't set up). We still construct
226
+ // the pool but the facet will get env.SUPERVISOR === undefined.
227
+ // Callers that need SUPERVISOR should check availability before
228
+ // dispatch. (A facet that tries to call env.SUPERVISOR.writeBatch
229
+ // will throw a plain TypeError; that's the clearest failure mode.)
230
+ }
231
+ }
232
+ this.bindings = Object.keys(bindings).length > 0 ? bindings : undefined;
233
+ }
234
+ /** Effective concurrency used when no per-call override is supplied. */
235
+ get defaultConcurrency() {
236
+ return this.concurrency;
237
+ }
238
+ #resolve(opts) {
239
+ return {
240
+ timeoutMs: Math.max(0, opts?.timeoutMs ?? this.defaultTimeoutMs),
241
+ retries: Math.max(0, opts?.retries ?? this.defaultRetries),
242
+ };
243
+ }
244
+ /**
245
+ * Materialise per-call wasm bytes into the {name,id,bytes} shape
246
+ * the import-build path expects. Mirrors the constructor's logic
247
+ * (identifier sanitisation + collision check) but ALSO rejects
248
+ * collisions with constructor-time entries.
249
+ *
250
+ * Returns [] when there are no per-call entries — that's the hot
251
+ * path (every existing pool dispatch).
252
+ */
253
+ #materialisePerCallWasm(perCall) {
254
+ if (!perCall)
255
+ return [];
256
+ const out = [];
257
+ const ctorIds = new Set(this.wasmModules.map((w) => w.id));
258
+ const seen = new Set();
259
+ for (const [name, bytes] of Object.entries(perCall)) {
260
+ if (!(bytes instanceof ArrayBuffer)) {
261
+ const got = bytes?.constructor?.name;
262
+ throw new BindingError(`LoaderPool: per-call wasmModules['${name}'] must be ` +
263
+ `ArrayBuffer (got ${got || typeof bytes}).`);
264
+ }
265
+ const id = name.replace(/[^A-Za-z0-9_]/g, '_').replace(/^[^A-Za-z_]/, '_');
266
+ if (ctorIds.has(id)) {
267
+ throw new BindingError(`LoaderPool: per-call wasmModules key '${name}' (sanitised ` +
268
+ `id='${id}') collides with a constructor-time wasm module. ` +
269
+ `Per-call modules cannot shadow pool-defaults. Pick a distinct name.`);
270
+ }
271
+ if (seen.has(id)) {
272
+ throw new BindingError(`LoaderPool: per-call wasmModules key '${name}' (sanitised ` +
273
+ `id='${id}') collides with another per-call key. Pick distinct names.`);
274
+ }
275
+ seen.add(id);
276
+ out.push({ name, id, bytes });
277
+ }
278
+ return out;
279
+ }
280
+ /**
281
+ * Compute a stable fingerprint of a list of {name,bytes} entries.
282
+ * Returns '0' for the empty list (cache-key bytes-stable for the
283
+ * common no-per-call-wasm case). Same fingerprinting strategy as
284
+ * the constructor's `wasmHash`: name + length + first/last byte
285
+ * per module. Hashing all bytes would be O(20+ MiB) per dispatch
286
+ * for nothing — the length+endpoints fingerprint is a strong-
287
+ * enough discriminator and identical bytes produce identical
288
+ * fingerprints (warm reuse).
289
+ *
290
+ * Per-call wasm fingerprinting MUST be content-sensitive: when a user
291
+ * compiles two .c files (e.g. `clang a.c -o a` then `clang b.c -o b`)
292
+ * the resulting .wasm binaries may differ by only a few bytes deep
293
+ * inside the code section. The old fingerprint
294
+ * `name + len + first + last` collided for such cases, returning the
295
+ * same cache key and forcing a warm-isolate reuse that served the
296
+ * FIRST binary's WebAssembly.Module on the second dispatch (verified
297
+ * in prod: ./a and ./b were both 7572 bytes with identical first/last
298
+ * bytes, differing only at offset 651 — clang-state-fix wave repro).
299
+ *
300
+ * Fix: hash the ACTUAL bytes via djb2 over the full content. Per-call
301
+ * wasm is typically the user's compiled binary (KBs to a few MiB);
302
+ * djb2 of a few MiB takes microseconds on the supervisor side and
303
+ * runs once per dispatch (not per request — warm-reuse-on-match still
304
+ * works for the legitimate "same bytes" case). The savings of NOT
305
+ * hashing the wasm were marginal; the correctness cost was severe.
306
+ */
307
+ #fingerprintWasm(entries) {
308
+ if (entries.length === 0)
309
+ return '0';
310
+ const parts = [];
311
+ for (const w of entries) {
312
+ const u = new Uint8Array(w.bytes);
313
+ const len = u.byteLength;
314
+ // djb2 over the bytes. Faster than crypto.subtle.digest at small
315
+ // sizes, deterministic, and good enough for cache-key
316
+ // disambiguation (NOT cryptographic — the loader cache doesn't
317
+ // protect against malicious inputs).
318
+ let h = 5381;
319
+ for (let i = 0; i < len; i++) {
320
+ h = ((h << 5) + h + u[i]) | 0;
321
+ }
322
+ parts.push(`${w.name}:${len}:${(h >>> 0).toString(36)}`);
323
+ }
324
+ return hashSource(parts.join('|'));
325
+ }
326
+ /**
327
+ * Build the WorkerCode blob that the loader callback will return.
328
+ * Same bytes every time for a given function and slot, allowing workerd
329
+ * to reuse the isolate.
330
+ *
331
+ * Always prepends the ESBUILD_RUNTIME_SHIM so stringified functions that
332
+ * reference esbuild-emitted helpers (__name, __defProp, etc.) don't
333
+ * crash the facet with "__name is not defined". User preambles are
334
+ * appended below the shim.
335
+ */
336
+ #buildCode(fnSource, perCallWasmEntries) {
337
+ const workerOpts = {
338
+ compatibilityDate: CF_COMPAT_DATE,
339
+ compatibilityFlags: ['nodejs_compat'],
340
+ // Inherit parent network so the facet can reach registry.npmjs.org.
341
+ globalOutbound: undefined,
342
+ env: this.bindings,
343
+ };
344
+ // ── WASM module imports ───────────────────────────────────────────
345
+ // Each entry in `wasmModules` (constructor-time + per-call) is
346
+ // registered in the LOADER's modules map (below) as
347
+ // `{ wasm: ArrayBuffer }`. workerd compiles each during the
348
+ // worker's module-load phase (eval permitted there) and the
349
+ // standard ESM import binding receives the resulting
350
+ // WebAssembly.Module. We expose them on `globalThis.__NIMBUS_WASM`
351
+ // so the user fn can read them at request time without having to
352
+ // re-import (the user fn is serialized via fn.toString and doesn't
353
+ // carry import statements).
354
+ //
355
+ // Per-call entries (passed via LoaderCallOptions.wasmModules
356
+ // — used by the wasm-runner shell command) are appended to the same
357
+ // table. Naming collision with constructor entries is rejected
358
+ // upstream in #materialisePerCallWasm so the import block here
359
+ // doesn't have to deduplicate.
360
+ const allWasmEntries = [
361
+ ...this.wasmModules,
362
+ ...(perCallWasmEntries ?? []),
363
+ ];
364
+ const moduleSource = assembleLoaderWorkerModuleSource({
365
+ fnSource,
366
+ preamble: this.preamble,
367
+ wasmEntries: allWasmEntries,
368
+ hasBindings: this.bindings !== undefined,
369
+ });
370
+ // Modules map: the entry worker.js source plus any wasm modules the
371
+ // pool was constructed with. Workerd parses the modules map at
372
+ // worker-load time and resolves the static `import` statements
373
+ // we generated above against this map. The wasm-shape entry
374
+ // (`{ wasm: ArrayBuffer }`) tells workerd to compile during the
375
+ // module-load phase — the only phase where wasm code generation
376
+ // is permitted in this deploy.
377
+ //
378
+ // Per-call entries are appended after constructor entries so the
379
+ // map order matches the import order in the generated worker.js
380
+ // (matters only for human-readable diffs; workerd doesn't care).
381
+ const modules = { 'worker.js': moduleSource };
382
+ for (const w of allWasmEntries) {
383
+ modules[w.name] = { wasm: w.bytes };
384
+ }
385
+ assertModuleMapWithinCodeLimit(modules);
386
+ return {
387
+ compatibilityDate: workerOpts.compatibilityDate,
388
+ compatibilityFlags: workerOpts.compatibilityFlags,
389
+ mainModule: 'worker.js',
390
+ modules,
391
+ env: workerOpts.env,
392
+ // globalOutbound: undefined = inherit parent network; omitting the key
393
+ // from the returned object has the same effect (codegen treats
394
+ // absence as inherit when the key is explicitly stated; here we keep
395
+ // it absent to match the cloudflare-parallel semantics).
396
+ };
397
+ }
398
+ /**
399
+ * Dispatch a single task to the slot isolate. `slotIndex` picks which
400
+ * warm isolate services the call; callers round-robin slots themselves.
401
+ */
402
+ async #dispatchSlot(fnSource, fnHash, slotIndex, args, resilience, perCallWasm) {
403
+ // Per-call wasm fingerprint. Mixed into the cache key so two calls
404
+ // with different bytes hit different slots (no cache poisoning).
405
+ // For the common case (no per-call wasm) the fingerprint is '0',
406
+ // which is bytes-stable so warm reuse is unaffected.
407
+ const perCallWasmEntries = this.#materialisePerCallWasm(perCallWasm);
408
+ const perCallWasmHash = this.#fingerprintWasm(perCallWasmEntries);
409
+ // Cache key includes the short DO id so warm isolates are scoped to
410
+ // ONE session. See the doIdShort field comment for why — without it,
411
+ // a later session's pool reuses the warm worker from a previous
412
+ // session (which still carries the old session's env.SUPERVISOR
413
+ // binding), and writeBatch RPCs land in the wrong DO's VFS.
414
+ const buildId = (generation) => `nfp:${this.tag}:${this.doIdShort}:${fnHash}:${this.preambleHash}:${this.wasmHash}:${perCallWasmHash}:slot-${slotIndex}:g${generation}`;
415
+ let id = buildId(this.slotGenerations.get(slotIndex) ?? 0);
416
+ const code = this.#buildCode(fnSource, perCallWasmEntries);
417
+ // W5 Lever 5: record the dispatch so /api/_diag/memory shows the
418
+ // last-facet-id even on a hang or silent kill. Bounded — single
419
+ // slot updated on every dispatch.
420
+ try {
421
+ setLastFacetId(id, slotIndex);
422
+ }
423
+ catch { /* best-effort */ }
424
+ const runOnce = async () => {
425
+ // loader.get() is synchronous from the caller's POV; the callback
426
+ // is only invoked on cache miss. We wrap the callback tightly so a
427
+ // retry doesn't rebuild workerCode — that's already stable here.
428
+ //
429
+ // The returned `stub` is the cached worker reference. We deliberately
430
+ // do NOT dispose it: loader.get() is designed for warm-slot reuse
431
+ // across dispatches (same `id` returns the same cached worker),
432
+ // and disposing would invalidate that cache.
433
+ //
434
+ // We USED to also dispose the per-dispatch `entrypoint` stub in a
435
+ // finally block here (added in 3c47b44 to prevent QueueState::ACTIVE
436
+ // during cold-start install). Empirically that broke dispatch on
437
+ // every slot after the first: once the finally ran
438
+ // `entrypoint[Symbol.dispose]()`, subsequent dispatches on the
439
+ // same cached slot hung — SupervisorRPC.writeBatch logged
440
+ // 'canceled', the DO-side _rpcWriteBatch completed OK, but the
441
+ // pool never saw the result and every task stalled to the 60s
442
+ // per-task timeout at 0/13 packages. Removing the per-dispatch
443
+ // dispose restored 13/13 in ~2.3s in dev.
444
+ //
445
+ // The pool-level dispose() method below (also from 3c47b44) is
446
+ // fine and stays — it only tears down the long-lived SUPERVISOR
447
+ // binding stub once the whole pool is done, which does NOT
448
+ // invalidate any in-flight slot's entrypoint reference.
449
+ const stub = this.loader.get(id, async () => code);
450
+ recordLoaderId(this.ctx, id);
451
+ const entrypoint = stub.getEntrypoint();
452
+ // Direct property call, awaited by this frame — bracketed, never
453
+ // wrapped. See beginLoaderFetch for the measured DO-poisoning hazard.
454
+ const endFetch = beginLoaderFetch(this.ctx);
455
+ try {
456
+ const out = await entrypoint.execute(...args);
457
+ return out;
458
+ }
459
+ catch (err) {
460
+ if (err instanceof Error) {
461
+ throw new ExecutionError(err.message, err.stack);
462
+ }
463
+ throw new ExecutionError(String(err));
464
+ }
465
+ finally {
466
+ endFetch();
467
+ }
468
+ };
469
+ const maxAttempts = 1 + resilience.retries;
470
+ let lastError;
471
+ let retriedCloneRefusal = false;
472
+ let attempt = 0;
473
+ while (attempt < maxAttempts) {
474
+ try {
475
+ if (resilience.timeoutMs > 0) {
476
+ // Race runOnce() against a settable timer. CRITICAL: clear
477
+ // the timer in a finally so the timer's reject closure (which
478
+ // transitively roots `args` — i.e. the per-task payload sent
479
+ // to the slot, including 28 MiB pre-bundle slices) doesn't
480
+ // hold its references for the full timeoutMs after the race
481
+ // settles.
482
+ //
483
+ // Before this fix: a facet OOM at t=0 left the slice rooted
484
+ // for the remaining timeoutMs (default 60s for pre-bundle).
485
+ // With concurrency=2, two consecutive OOMs could pin
486
+ // ~56 MiB of slice memory in the supervisor heap for a full
487
+ // minute — alongside an in-flight cirrus-real boot, that's
488
+ // enough to push a shared isolate over the 128 MiB cap.
489
+ // See plan in close-plan-2026-04-28.
490
+ let timerId;
491
+ try {
492
+ return await Promise.race([
493
+ runOnce(),
494
+ new Promise((_, reject) => {
495
+ timerId = setTimeout(() => reject(new TimeoutError(resilience.timeoutMs)), resilience.timeoutMs);
496
+ }),
497
+ ]);
498
+ }
499
+ finally {
500
+ if (timerId !== undefined)
501
+ clearTimeout(timerId);
502
+ }
503
+ }
504
+ return await runOnce();
505
+ }
506
+ catch (err) {
507
+ lastError = err instanceof Error ? err : new Error(String(err));
508
+ const cause = classifyError(lastError);
509
+ // W5 Lever 5: classify + record. We push on EVERY failed
510
+ // attempt (not just the final retry-exhausted throw) so the
511
+ // ring captures transient SQLITE_NOMEM / clone-refused
512
+ // patterns that still ultimately succeed. Ring is bounded
513
+ // (50 entries) so noise is self-limiting.
514
+ try {
515
+ recordFailure({
516
+ at: Date.now(),
517
+ phase: 'rpc',
518
+ cause,
519
+ rssEstimateBytes: 0, heapUsedBytes: 0,
520
+ lruBytes: 0, inFlightBytes: 0,
521
+ lastRpcFrame: getLastRpcFrame(),
522
+ lastFacetId: { codeId: id, slotIndex, atMs: Date.now() },
523
+ message: lastError.message,
524
+ });
525
+ }
526
+ catch { /* fail-soft */ }
527
+ if (cause === 'clone_refused' && !retriedCloneRefusal) {
528
+ retriedCloneRefusal = true;
529
+ const generation = (this.slotGenerations.get(slotIndex) ?? 0) + 1;
530
+ this.slotGenerations.set(slotIndex, generation);
531
+ id = buildId(generation);
532
+ try {
533
+ setLastFacetId(id, slotIndex);
534
+ }
535
+ catch { /* best-effort */ }
536
+ // If the supervisor DO is stale, a newer loader still cannot
537
+ // deserialize back into it; only recycling that DO heals the
538
+ // reverse direction. This refresh targets the stale-loader case.
539
+ continue;
540
+ }
541
+ if (attempt < maxAttempts - 1) {
542
+ // 100 * 2^attempt, capped at 2s so retries don't compound waiting.
543
+ const delay = Math.min(2000, 100 * Math.pow(2, attempt));
544
+ await new Promise((r) => setTimeout(r, delay));
545
+ }
546
+ attempt++;
547
+ }
548
+ }
549
+ // On the way out only, so retries do not stack the annotation: a cap hit
550
+ // carries the ledger — which ids hold slots, and that a keyed id never
551
+ // gives one back — instead of the platform's bare message.
552
+ const named = withDynamicWorkerCapNamed(this.ctx, lastError);
553
+ if (maxAttempts > 1) {
554
+ throw new RetryExhaustedError(maxAttempts, named);
555
+ }
556
+ throw named;
557
+ }
558
+ #prepare(fn) {
559
+ const fnSource = serializeFunction(fn);
560
+ const fnHash = hashSource(fnSource);
561
+ return { fnSource, fnHash };
562
+ }
563
+ /**
564
+ * Run `fn` once with `arg` on a slot isolate. Returns the result or
565
+ * throws TimeoutError / RetryExhaustedError / ExecutionError.
566
+ */
567
+ async submit(fn, arg, opts) {
568
+ const { fnSource, fnHash } = this.#prepare(fn);
569
+ const resilience = this.#resolve(opts);
570
+ return (await this.#dispatchSlot(fnSource, fnHash, 0, [arg], resilience, opts?.wasmModules));
571
+ }
572
+ /**
573
+ * Run `fn` on every item in `items`, at most `concurrency` at a time,
574
+ * pinned to stable slots so warm isolates are reused.
575
+ *
576
+ * Results are returned in input order. Failure handling per `onError`.
577
+ */
578
+ async map(fn, items, opts) {
579
+ if (items.length === 0)
580
+ return [];
581
+ const { fnSource, fnHash } = this.#prepare(fn);
582
+ return this.#mapInternal(fnSource, fnHash, items, opts);
583
+ }
584
+ /**
585
+ * Same shape as `map`, but accepts a pre-serialized function source
586
+ * string instead of a live function reference. Used by
587
+ * `FanoutPool`'s peer-DO leg, where the function was already
588
+ * serialized on the coordinator side and forwarded over RPC.
589
+ *
590
+ * The fnSource MUST be the output of `serializeFunction(fn)`
591
+ * (typically forwarded directly from a coordinator RPC). Bytes-
592
+ * stable invariants:
593
+ * - `fnHash = hashSource(fnSource)` must be deterministic so
594
+ * warm slots are correctly keyed.
595
+ * - `fnSource` must NOT reference `this` — same rule as
596
+ * `serializeFunction`.
597
+ *
598
+ * No fn-validation runs here (it already ran on the coordinator);
599
+ * the peer trusts the caller to forward a valid serialization.
600
+ */
601
+ async mapSource(fnSource, items, opts) {
602
+ if (items.length === 0)
603
+ return [];
604
+ const fnHash = hashSource(fnSource);
605
+ return this.#mapInternal(fnSource, fnHash, items, opts);
606
+ }
607
+ async #mapInternal(fnSource, fnHash, items, opts) {
608
+ const resilience = this.#resolve(opts);
609
+ const concurrency = Math.max(1, Math.min(opts?.concurrency ?? this.concurrency, items.length));
610
+ const onError = opts?.onError ?? 'throw';
611
+ const settled = new Array(items.length);
612
+ let cursor = 0;
613
+ const runSlot = async (slotIndex) => {
614
+ while (true) {
615
+ const idx = cursor++;
616
+ if (idx >= items.length)
617
+ return;
618
+ try {
619
+ const value = (await this.#dispatchSlot(fnSource, fnHash, slotIndex, [items[idx]], resilience, opts?.wasmModules));
620
+ settled[idx] = { ok: true, value };
621
+ }
622
+ catch (err) {
623
+ const error = err instanceof Error ? err : new Error(String(err));
624
+ if (onError === 'throw')
625
+ throw error;
626
+ settled[idx] = { ok: false, error };
627
+ }
628
+ }
629
+ };
630
+ await Promise.all(Array.from({ length: concurrency }, (_, slotIndex) => runSlot(slotIndex)));
631
+ if (onError === 'null') {
632
+ return settled.map((s) => (s.ok ? s.value : null));
633
+ }
634
+ if (onError === 'skip') {
635
+ return settled
636
+ .filter((s) => s.ok)
637
+ .map((s) => s.value);
638
+ }
639
+ // onError === 'throw' — all slots succeeded.
640
+ return settled.map((s) => s.value);
641
+ }
642
+ /**
643
+ * Release any RPC stubs held by the pool. Call this once the caller
644
+ * is done with the pool (post-`map`/`submit`) so the underlying
645
+ * stubs don't linger in workerd's deferred-destruction queue.
646
+ *
647
+ * Primary target: the SUPERVISOR binding stub we minted at
648
+ * construction time (via the registered supervisor entrypoint). It's
649
+ * a cross-isolate RPC stub — without explicit disposal it stays
650
+ * referenced until the parent isolate's event-handler context
651
+ * finishes, which during npm install means "until the whole install
652
+ * completes" — long enough to accumulate alongside other leaked
653
+ * stubs and trip the QueueState::ACTIVE fatal.
654
+ *
655
+ * Safe to call more than once; idempotent.
656
+ */
657
+ dispose() {
658
+ if (!this.bindings)
659
+ return;
660
+ for (const key of Object.keys(this.bindings)) {
661
+ disposeRpcResource(this.bindings[key]);
662
+ }
663
+ // Prevent double-dispose from re-running the loop.
664
+ this.bindings = undefined;
665
+ }
666
+ }