@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,694 @@
1
+ /**
2
+ * workerd-facet-host.ts — how a resident process is actually made, on workerd.
3
+ *
4
+ * `process-fabric.ts` says what a resident process IS, in terms no
5
+ * runtime owns: a boot spec, a start contract, a handle that can be routed to
6
+ * and released. This module is the one implementation of that on Cloudflare,
7
+ * and everything here is a workerd mechanism rather than a Nimbus concept —
8
+ * `ctx.facets`, the Worker Loader, `ctx.exports`, and the facet-index
9
+ * arithmetic the slot book exists to satisfy.
10
+ *
11
+ * The split is what lets the contract be read without the platform: a host
12
+ * that is not a Durable Object implements `ProcessHost` against the same
13
+ * `HostedProcess` and never imports this file.
14
+ */
15
+
16
+ import { disposeRpcResource } from '@nimbus-sh/core/_shared/rpc-dispose.js';
17
+ import {
18
+ getCtxExports,
19
+ supervisorEntrypoint,
20
+ supervisorEntrypointName,
21
+ } from './ctx-exports.js';
22
+ import {
23
+ beginLoaderFetch,
24
+ recordLoaderId,
25
+ withDynamicWorkerCapNamed,
26
+ } from './loader-ledger.js';
27
+ import {
28
+ RESIDENT_PROCESS_CLASS,
29
+ requireStagedBootAssembler,
30
+ residentLoaderConfig,
31
+ type HostedProcess,
32
+ type OneShotCodeSpec,
33
+ type OneShotParams,
34
+ type ProcessHostParams,
35
+ type ResidentBootSpec,
36
+ type ResidentDiskReader,
37
+ type ResidentSupervisorProps,
38
+ } from './process-fabric.js';
39
+
40
+ // ── Loaded-worker entrypoint plumbing ───────────────────────────────────────
41
+
42
+ /** Structural surface of a NimbusLoadedEntrypoint RPC stub. */
43
+ export interface LoadedWorkerEntrypointStub {
44
+ handleHttpRequest?: (request: Request) => Promise<Response>;
45
+ fetch?(request: Request): Promise<Response>;
46
+ }
47
+
48
+ export interface NimbusCtxExports {
49
+ NimbusLoadedEntrypoint?: (options: {
50
+ props: {
51
+ key: string;
52
+ name: string | null;
53
+ depth: number;
54
+ supervisor: { doId: string; pid: number; writerId: string };
55
+ stage?: unknown;
56
+ };
57
+ }) => LoadedWorkerEntrypointStub;
58
+ }
59
+
60
+ export function getNimbusCtxExports(): NimbusCtxExports {
61
+ const ctxExports = getCtxExports();
62
+ if (!ctxExports || typeof ctxExports !== 'object') {
63
+ throw new Error('Nimbus: ctx.exports unavailable');
64
+ }
65
+ return ctxExports as NimbusCtxExports;
66
+ }
67
+
68
+ /**
69
+ * Mint a NimbusLoadedEntrypoint stub for a keyed dynamic worker. Used by the
70
+ * one-shot runtime paths, which run a program to completion inside a single
71
+ * request rather than leaving it resident: their module map is assembled in
72
+ * that stateless entrypoint's own isolate, never in a session DO.
73
+ */
74
+ export async function createLoadedWorkerEntrypoint(
75
+ ctxExports: NimbusCtxExports,
76
+ supervisor: { doId: string; pid: number; writerId: string },
77
+ stage: unknown,
78
+ name: string | null = null,
79
+ ): Promise<LoadedWorkerEntrypointStub> {
80
+ if (!ctxExports.NimbusLoadedEntrypoint) {
81
+ throw new Error('Nimbus: ctx.exports.NimbusLoadedEntrypoint unavailable');
82
+ }
83
+ return await ctxExports.NimbusLoadedEntrypoint({
84
+ props: {
85
+ key: `nimbus-process:${supervisor.doId}:${supervisor.pid}`,
86
+ name,
87
+ depth: 0,
88
+ supervisor,
89
+ stage,
90
+ },
91
+ });
92
+ }
93
+
94
+ /**
95
+ * Total bytes a dynamic Worker's module map may carry, across every member of
96
+ * it. A hard platform limit, not a policy knob: 62 MiB lands and 64 MiB is
97
+ * refused with "Dynamic Worker code size (N bytes) exceeds the maximum allowed
98
+ * size of 67108864 bytes", confirmed at five sizes with two trials each. The
99
+ * budget is shared, so a ruby process is already 34.3 MiB down before its disk
100
+ * is counted.
101
+ */
102
+ export const DYNAMIC_WORKER_CODE_LIMIT_BYTES = 67_108_864;
103
+
104
+ /**
105
+ * Refuse a module map over {@link DYNAMIC_WORKER_CODE_LIMIT_BYTES}, naming
106
+ * the largest members. The platform's own refusal reports one number for a
107
+ * budget shared across every member of the map, which tells the operator
108
+ * nothing about WHAT to shrink — so every fabric seam that assembles a map
109
+ * runs this before the loader sees it.
110
+ *
111
+ * Costed to its two paths. Under the ceiling: one length read per member —
112
+ * UTF-16 code units for text, which equal UTF-8 bytes for the ASCII module
113
+ * text the generators emit and undercount otherwise; the platform's own
114
+ * refusal still backstops the exotic case, because this check exists to name
115
+ * members, not to be the ceiling. Over it: exact UTF-8 sizes, computed only
116
+ * then, sorted so the biggest lever is first.
117
+ */
118
+ export function assertModuleMapWithinCodeLimit(modules: Record<string, unknown>): void {
119
+ let estimate = 0;
120
+ for (const content of Object.values(modules)) {
121
+ estimate += memberBytes(content, null);
122
+ }
123
+ if (estimate <= DYNAMIC_WORKER_CODE_LIMIT_BYTES) return;
124
+
125
+ const encoder = new TextEncoder();
126
+ const sized = Object.entries(modules)
127
+ .map(([name, content]) => ({ name, bytes: memberBytes(content, encoder) }))
128
+ .sort((a, b) => b.bytes - a.bytes);
129
+ const total = sized.reduce((sum, member) => sum + member.bytes, 0);
130
+ const top = sized.slice(0, 5)
131
+ .map(({ name, bytes }) => `'${name}' (${bytes.toLocaleString('en-US')} bytes)`)
132
+ .join(', ');
133
+ throw new Error(
134
+ `Nimbus: dynamic-worker module map is ${total.toLocaleString('en-US')} bytes, over the `
135
+ + `${DYNAMIC_WORKER_CODE_LIMIT_BYTES.toLocaleString('en-US')}-byte platform ceiling shared by `
136
+ + `every member. Largest members: ${top}`,
137
+ );
138
+ }
139
+
140
+ /**
141
+ * Bytes one module-map member carries, across the loader's content kinds
142
+ * (plain string, `{ js | cjs | py | text }`, `{ wasm | data }`). With an
143
+ * encoder, text is measured exactly; without one, by code-unit length.
144
+ */
145
+ function memberBytes(content: unknown, encoder: TextEncoder | null): number {
146
+ const textBytes = (text: string): number =>
147
+ encoder ? encoder.encode(text).byteLength : text.length;
148
+ if (typeof content === 'string') return textBytes(content);
149
+ if (content !== null && typeof content === 'object') {
150
+ for (const value of Object.values(content)) {
151
+ if (typeof value === 'string') return textBytes(value);
152
+ if (value instanceof ArrayBuffer) return value.byteLength;
153
+ if (ArrayBuffer.isView(value)) return value.byteLength;
154
+ }
155
+ }
156
+ return 0;
157
+ }
158
+
159
+ // ── Facet plumbing ──────────────────────────────────────────────────────────
160
+
161
+ /** The subset of a facet stub a resident process exposes to whoever opened it. */
162
+ interface ResidentFacetStub {
163
+ startProcess(args?: unknown): Promise<unknown>;
164
+ handleHttpRequest(request: Request): Promise<Response>;
165
+ /**
166
+ * A facet stub is a Durable Object stub, so it fetches. That is the one path
167
+ * an upgrade can take: a 101 owns a live socket, which the RPC
168
+ * Request/Response transport reconstructs rather than hands over.
169
+ */
170
+ fetch(request: Request): Promise<Response>;
171
+ }
172
+
173
+ /** `ctx.facets` — a Durable Object's named child actors. */
174
+ interface FacetContainer {
175
+ get(name: string, start: () => Promise<{ class: unknown }>): ResidentFacetStub;
176
+ abort(name: string, reason?: unknown): void;
177
+ delete(name: string): void;
178
+ /**
179
+ * Present on deployed Cloudflare workerd, absent from the pinned
180
+ * `@cloudflare/workers-types` and from local workerd ≤ 1.20260603.1 — see
181
+ * {@link cloneFacetStorage}, the one way the fabric calls it.
182
+ */
183
+ clone?(src: string, dst: string): void;
184
+ }
185
+
186
+ /** What an unkeyed `LOADER.load` hands back. */
187
+ interface LoadedWorkerStub {
188
+ getEntrypoint(): LoadedWorkerEntrypointStub;
189
+ }
190
+
191
+ /**
192
+ * `env.LOADER` — the Worker Loader binding, as used from inside a DO.
193
+ *
194
+ * Both arms are here because both are the same platform affordance seen from
195
+ * the two lifetimes Nimbus runs programs under: `get` is keyed and yields a
196
+ * Durable Object class, so a resident process can be re-entered; `load` is
197
+ * unkeyed and yields a stateless entrypoint, which is all a program that ends
198
+ * with its call can ever need.
199
+ */
200
+ interface WorkerLoaderBinding {
201
+ get(id: string, code: () => Promise<unknown>): { getDurableObjectClass(name: string): unknown };
202
+ load(code: unknown): LoadedWorkerStub;
203
+ }
204
+
205
+ /**
206
+ * The bindings `openResidentFacet` needs off whichever DO is hosting. A
207
+ * staged boot's assembler may read more off the same env (Nimbus's reads
208
+ * ASSETS); the env travels to it whole, so nothing further is named here.
209
+ */
210
+ export interface ResidentFacetEnv {
211
+ LOADER?: WorkerLoaderBinding;
212
+ }
213
+
214
+ function facetContainer(ctx: DurableObjectState): FacetContainer {
215
+ const facets = (ctx as { facets?: unknown }).facets as FacetContainer | undefined;
216
+ if (!facets || typeof facets.get !== 'function') {
217
+ throw new Error(
218
+ 'Nimbus: ctx.facets is unavailable in this Durable Object; '
219
+ + 'resident processes cannot be hosted',
220
+ );
221
+ }
222
+ return facets;
223
+ }
224
+
225
+ /**
226
+ * Fork one facet's entire SQLite into another by copy-on-write — the one way
227
+ * the fabric calls `ctx.facets.clone`, because the raw call carries a hazard
228
+ * measured on production workerd: ANY `src` that does not resolve to a
229
+ * populated facet — a typo, a name not created yet, not merely the obvious
230
+ * `''`/`'.'`/`'/'` — silently EMPTIES the destination and reports success. A
231
+ * blocklist of bad names would pass a typo straight through and wipe a
232
+ * process's filesystem while returning ok, so validation is positive on both
233
+ * ends: the source must answer as populated before the clone runs, the
234
+ * destination must answer as populated after it, and anything else fails
235
+ * loud.
236
+ *
237
+ * `populated` is the caller's probe because populated-ness is the caller's
238
+ * schema. The hosting actor cannot read a facet's SQLite from outside it, and
239
+ * an EMPTIED facet still reports a 4,096-byte database — one page, the empty
240
+ * file — so only a check that positively finds the caller's own data means
241
+ * anything. The post-clone probe is not redundant with the pre-clone one: the
242
+ * probe answers off the caller's accounting, and the capture races un-awaited
243
+ * writes to the source, so the destination is verified rather than inferred.
244
+ *
245
+ * The primitive itself, measured: a reflink, 18–31 ms for a 45.73 MB corpus
246
+ * and 34–54 ms for 1 GB — flat, because nothing is copied — with the data
247
+ * visible from the destination's constructor. Same-Durable-Object only.
248
+ * Quiesce and await writes to the source first; the destination name consumes
249
+ * a facet ID on first use like any other facet name; and the shared ~10 GiB
250
+ * storage budget grants no copy-on-write credit — crossing it resets the
251
+ * object rather than raising an error.
252
+ */
253
+ export async function cloneFacetStorage(
254
+ ctx: DurableObjectState,
255
+ clone: {
256
+ src: string;
257
+ dst: string;
258
+ populated(name: string): boolean | Promise<boolean>;
259
+ },
260
+ ): Promise<void> {
261
+ const facets = facetContainer(ctx);
262
+ if (typeof facets.clone !== 'function') {
263
+ throw new Error(
264
+ 'Nimbus: ctx.facets.clone is unavailable in this runtime; the reflink image '
265
+ + 'path needs deployed Cloudflare workerd (local workerd <= 1.20260603.1 lacks it)',
266
+ );
267
+ }
268
+ const { src, dst } = clone;
269
+ if (!(await clone.populated(src))) {
270
+ throw new Error(
271
+ `Nimbus: refusing to clone facet '${src}' into '${dst}': the source does not `
272
+ + 'answer as populated, and cloning an unresolvable source silently EMPTIES '
273
+ + 'the destination while reporting success',
274
+ );
275
+ }
276
+ facets.clone(src, dst);
277
+ if (!(await clone.populated(dst))) {
278
+ throw new Error(
279
+ `Nimbus: clone of facet '${src}' left the destination '${dst}' without the `
280
+ + "source's data; the destination must not be booted from",
281
+ );
282
+ }
283
+ }
284
+
285
+ /**
286
+ * The facet name for a slot. Reused, and that is the entire point.
287
+ *
288
+ * A Durable Object admits 65,536 facets over its LIFETIME: the IDs are
289
+ * append-only and are never reclaimed, so the bound is on facets ever CREATED,
290
+ * not facets alive at once. Naming a facet after its pid, when pids never
291
+ * repeat, therefore burned one of those IDs on every spawn — a long-lived
292
+ * session would eventually exhaust its facet index with no way back, and the
293
+ * failure is unrecoverable rather than merely slow.
294
+ *
295
+ * Reusing a NAME costs no new ID. So the name comes from a free list and the
296
+ * pid stays what it always was: the process identity in the ProcessTable. The
297
+ * two were only ever conflated because one of them happened to be handy.
298
+ */
299
+ export function residentFacetName(slot: number): string {
300
+ return `proc-slot-${slot}`;
301
+ }
302
+
303
+ /**
304
+ * Facet IDs a Durable Object is granted over its LIFETIME. Append-only and
305
+ * never reclaimed, so crossing it is unrecoverable for the object — which is
306
+ * why the ledger below counts consumption durably instead of leaving the
307
+ * bound as prose the slot book merely respects.
308
+ */
309
+ export const FACET_ID_LIFETIME_BUDGET = 65_536;
310
+
311
+ /** Where the ledger persists the count of facet names ever minted. */
312
+ export const FACET_NAME_HIGH_WATER_KEY = 'fabric_facet_name_high_water';
313
+
314
+ /** One hosting actor's slot book. */
315
+ interface SlotBook {
316
+ /** Returned slots, lowest reused first so the high-water mark stays low. */
317
+ free: number[];
318
+ /** The next never-yet-issued slot. */
319
+ next: number;
320
+ /** Slot held by each live pid, so release can find it. */
321
+ held: Map<number, number>;
322
+ /**
323
+ * The durable high-water of names ever minted, as an adopt-then-advance
324
+ * chain. It starts as the read of {@link FACET_NAME_HIGH_WATER_KEY} and
325
+ * every later link writes only a LARGER count — a fresh incarnation restarts
326
+ * `next` at zero, and a write that had not adopted first would clobber the
327
+ * lifetime count down to this incarnation's. The chain never rejects.
328
+ */
329
+ ledger: Promise<number>;
330
+ /** The largest count the chain has adopted or written, for sync reads. */
331
+ ledgerKnown: number;
332
+ }
333
+
334
+ /**
335
+ * Slot books, per hosting actor, because the facet index is per Durable
336
+ * Object.
337
+ *
338
+ * Keyed weakly off `ctx`, and that is sound rather than lossy: a facet cannot
339
+ * outlive the Durable Object hosting it, so a book that goes away with its
340
+ * host describes nothing that still exists. A fresh incarnation restarts at
341
+ * slot 0 and re-attaches to the SQLite a previous incarnation left there —
342
+ * which is safe for the reason the store is sealed until it has reconciled.
343
+ * Its persisted cursor is either datable against the current authority, in
344
+ * which case the ACQUIRE delta brings it current, or it carries a different
345
+ * VFS epoch, in which case `invalidatedSince` can only answer poison and the
346
+ * whole store is dropped. A process therefore cannot boot onto a previous
347
+ * tenant's filesystem even when release never ran.
348
+ */
349
+ const slotBooks = new WeakMap<DurableObjectState, SlotBook>();
350
+
351
+ function slotBook(ctx: DurableObjectState): SlotBook {
352
+ let book = slotBooks.get(ctx);
353
+ if (!book) {
354
+ const created: SlotBook = {
355
+ free: [],
356
+ next: 0,
357
+ held: new Map(),
358
+ ledger: Promise.resolve(0),
359
+ ledgerKnown: 0,
360
+ };
361
+ created.ledger = Promise.resolve(ctx.storage.get(FACET_NAME_HIGH_WATER_KEY))
362
+ .then((value) => (typeof value === 'number' ? value : 0))
363
+ .catch(() => 0)
364
+ .then((adopted) => {
365
+ created.ledgerKnown = Math.max(created.ledgerKnown, adopted);
366
+ return adopted;
367
+ });
368
+ book = created;
369
+ slotBooks.set(ctx, book);
370
+ }
371
+ return book;
372
+ }
373
+
374
+ /**
375
+ * The lifetime facet-ID ledger: how many facet names this fabric has ever
376
+ * minted on the Durable Object, against the 65,536 the platform will ever
377
+ * grant it. `consumed` only ever counts FIRST uses — a reused name, in this
378
+ * incarnation or any earlier one, cost no new ID, which is the slot book's
379
+ * whole reason to exist. Surfaced so an operator can see proximity to a wall
380
+ * whose crossing is unrecoverable, instead of discovering it from the
381
+ * platform's opaque failure.
382
+ */
383
+ export async function facetIdBudget(
384
+ ctx: DurableObjectState,
385
+ ): Promise<{ consumed: number; budget: number }> {
386
+ const book = slotBook(ctx);
387
+ const durable = await book.ledger;
388
+ return {
389
+ consumed: Math.max(durable, book.next),
390
+ budget: FACET_ID_LIFETIME_BUDGET,
391
+ };
392
+ }
393
+
394
+ /** Take a slot for `pid`, reusing a returned one before minting a new name. */
395
+ function acquireSlot(ctx: DurableObjectState, pid: number): number {
396
+ const book = slotBook(ctx);
397
+ const existing = book.held.get(pid);
398
+ if (existing !== undefined) return existing;
399
+ const reused = book.free.length > 0;
400
+ const slot = reused ? book.free.shift()! : book.next++;
401
+ book.held.set(pid, slot);
402
+ if (!reused) recordNameMinted(ctx, book);
403
+ return slot;
404
+ }
405
+
406
+ /**
407
+ * Advance the durable ledger to this incarnation's name count, if it is a new
408
+ * lifetime high. Chained behind adoption so the comparison is always against
409
+ * the real persisted value; a failed write leaves the old link's count and the
410
+ * next mint tries again — the ledger may transiently undercount, never over.
411
+ */
412
+ function recordNameMinted(ctx: DurableObjectState, book: SlotBook): void {
413
+ const count = book.next;
414
+ book.ledger = book.ledger.then(async (durable) => {
415
+ if (count <= durable) return durable;
416
+ try {
417
+ await ctx.storage.put(FACET_NAME_HIGH_WATER_KEY, count);
418
+ } catch {
419
+ return durable;
420
+ }
421
+ book.ledgerKnown = Math.max(book.ledgerKnown, count);
422
+ return count;
423
+ });
424
+ }
425
+
426
+ /**
427
+ * Name the facet-ID budget on a creation failure at the wall; below it, hand
428
+ * the error back untouched. Exhaustion is the one failure here the platform
429
+ * reports opaquely AND that no teardown, retry or reset can undo, so the
430
+ * ledger — the only witness to the real cause — does the naming. Not a
431
+ * threshold: the comparison is against the budget itself.
432
+ */
433
+ function withFacetBudgetNamed(consumed: number, error: unknown): unknown {
434
+ if (consumed < FACET_ID_LIFETIME_BUDGET) return error;
435
+ const platform = error instanceof Error ? error.message : String(error);
436
+ return new Error(
437
+ `Nimbus: facet creation failed with this Durable Object's `
438
+ + `${FACET_ID_LIFETIME_BUDGET.toLocaleString('en-US')} facet-ID lifetime budget consumed `
439
+ + `(${consumed} facet names ever created). Facet IDs are append-only and never reclaimed, `
440
+ + `so this failure is permanent for the object: ${platform}`,
441
+ { cause: error },
442
+ );
443
+ }
444
+
445
+ /** Return `pid`'s slot to the free list. */
446
+ function releaseSlot(ctx: DurableObjectState, pid: number): void {
447
+ const book = slotBook(ctx);
448
+ const slot = book.held.get(pid);
449
+ if (slot === undefined) return;
450
+ book.held.delete(pid);
451
+ book.free.push(slot);
452
+ book.free.sort((a, b) => a - b);
453
+ }
454
+
455
+
456
+ /**
457
+ * What `openResidentFacet` hands back: a running process, minus its placement.
458
+ *
459
+ * `slot` rides along because the caller's `describe` needs the facet's real
460
+ * name and the slot is not derivable from the pid — that indirection is the
461
+ * whole point of the free list. Reading it back out of the book later would
462
+ * also race the release that empties it.
463
+ */
464
+ export type ResidentFacet = Omit<HostedProcess, 'describe'> & { slot: number };
465
+
466
+ /**
467
+ * Open a resident process as a facet of the actor whose `ctx` and `env` are
468
+ * given, and start its runner.
469
+ *
470
+ * This is the ONE way a resident process comes into existence, and every
471
+ * substrate goes through it: the facet host calls it with the coordinator's
472
+ * own `ctx`, the peer host calls it — over one RPC — with a sibling session
473
+ * DO's. Everything a substrate could plausibly want to special-case is a
474
+ * PARAMETER here rather than a branch: which actor hosts the child, and how
475
+ * the boot spec's by-path members are read.
476
+ */
477
+ export function openResidentFacet(
478
+ ctx: DurableObjectState,
479
+ env: ResidentFacetEnv,
480
+ disk: () => ResidentDiskReader,
481
+ supervisor: ResidentSupervisorProps,
482
+ params: ProcessHostParams,
483
+ ): ResidentFacet {
484
+ const facets = facetContainer(ctx);
485
+ const book = slotBook(ctx);
486
+ const slot = acquireSlot(ctx, params.pid);
487
+ const name = residentFacetName(slot);
488
+ // The start callback is the ONLY way this facet is ever created, and it
489
+ // fires AT MOST ONCE. Every later use goes through the stub below, so the
490
+ // callback running a second time means the facet was released or died —
491
+ // and re-running it would evaluate the user's program again, answering a
492
+ // request from a process they never started while the one they did start
493
+ // is gone. Both cases are reported instead.
494
+ let evaluated = false;
495
+ let released = false;
496
+ const start = async (): Promise<{ class: unknown }> => {
497
+ if (released) {
498
+ throw new Error(`Nimbus: resident process ${params.pid} is no longer running`);
499
+ }
500
+ if (evaluated) {
501
+ throw new Error(
502
+ `Nimbus: resident process ${params.pid} is no longer loaded (its facet was lost); `
503
+ + 'it is not restarted',
504
+ );
505
+ }
506
+ evaluated = true;
507
+ return { class: residentProcessClass(ctx, env, disk, supervisor, params) };
508
+ };
509
+ let facet: ResidentFacetStub;
510
+ try {
511
+ facet = facets.get(name, start);
512
+ } catch (error) {
513
+ releaseSlot(ctx, params.pid);
514
+ throw withFacetBudgetNamed(Math.max(book.ledgerKnown, book.next), error);
515
+ }
516
+
517
+ let disposed = false;
518
+ const release = async () => {
519
+ if (disposed) return;
520
+ disposed = true;
521
+ released = true;
522
+ try { facets.abort(name, new Error('Nimbus: resident process released')); } catch { /* already gone */ }
523
+ try { facets.delete(name); } catch { /* already gone */ }
524
+ // Only after the facet is gone. A slot handed out while its previous
525
+ // tenant were still being torn down would have two processes on one name.
526
+ releaseSlot(ctx, params.pid);
527
+ };
528
+
529
+ let started: Promise<unknown>;
530
+ try {
531
+ started = facet.startProcess(params.startArgs);
532
+ } catch (error) {
533
+ void release();
534
+ throw withFacetBudgetNamed(Math.max(book.ledgerKnown, book.next), error);
535
+ }
536
+ // The rejection that carries the platform's failure at ID exhaustion is
537
+ // this one, and it is annotated AFTER awaiting the ledger — the first
538
+ // failure of a fresh incarnation must compare against the persisted count,
539
+ // not the zero its adoption read has not yet replaced.
540
+ started = started.catch(async (error) => {
541
+ const durable = await book.ledger;
542
+ throw withFacetBudgetNamed(Math.max(durable, book.next), error);
543
+ });
544
+ // A caller reads whichever of `started` and the lifecycle it needs, so keep
545
+ // the runtime from reporting the other as an unhandled rejection.
546
+ started.catch(() => {});
547
+ return {
548
+ started,
549
+ // A facet cannot die without taking its Durable Object — and this object —
550
+ // with it, so there is no independent death to report.
551
+ lost: new Promise<never>(() => {}),
552
+ handleHttpRequest: (request: Request) => facet.handleHttpRequest(request),
553
+ handleWebSocketRequest: (request: Request) => facet.fetch(request),
554
+ release,
555
+ slot,
556
+ };
557
+ }
558
+
559
+ /**
560
+ * The dynamic worker's Durable Object class, minted in the caller's request
561
+ * context. `LOADER.get` runs its callback only on a cache miss, so a process
562
+ * assembles its module map at most once and the bytes never stay resident in
563
+ * the hosting DO's heap.
564
+ */
565
+ function residentProcessClass(
566
+ ctx: DurableObjectState,
567
+ env: ResidentFacetEnv,
568
+ disk: () => ResidentDiskReader,
569
+ supervisor: ResidentSupervisorProps,
570
+ params: ProcessHostParams,
571
+ ): unknown {
572
+ const loader = env.LOADER;
573
+ if (!loader || typeof loader.get !== 'function') {
574
+ throw new Error(
575
+ 'Nimbus: env.LOADER binding missing or invalid. Resident processes require '
576
+ + 'the Worker Loader binding; add it via worker_loaders in wrangler.jsonc.',
577
+ );
578
+ }
579
+ try {
580
+ const worker = loader
581
+ .get(params.workerKey, () => residentWorkerConfig(env, disk, supervisor, params.boot))
582
+ .getDurableObjectClass(RESIDENT_PROCESS_CLASS);
583
+ recordLoaderId(ctx, params.workerKey);
584
+ return worker;
585
+ } catch (error) {
586
+ throw withDynamicWorkerCapNamed(ctx, error);
587
+ }
588
+ }
589
+
590
+ /**
591
+ * Run one program to completion as an UNKEYED dynamic worker.
592
+ *
593
+ * Unkeyed is the whole difference from `openResidentFacet`: nothing can
594
+ * re-resolve this worker into a later request's context, so it can never be a
595
+ * routeable target and never has to be released by name. It exists for the
596
+ * duration of one call and its stubs are dropped as that call unwinds.
597
+ *
598
+ * Shared by both substrates on purpose. `peer` places processes that have a
599
+ * residency to place; a one-shot has none, and shipping its fully-inline map
600
+ * across a sibling hop would meet the 32 MiB RPC ceiling that by-path boot
601
+ * specs exist to avoid — for a run that gains nothing by moving.
602
+ */
603
+ export async function runOneShotWorker<T>(
604
+ ctx: DurableObjectState,
605
+ env: ResidentFacetEnv,
606
+ supervisor: ResidentSupervisorProps,
607
+ params: OneShotParams,
608
+ consume: (response: Response) => Promise<T>,
609
+ ): Promise<T> {
610
+ const loader = env.LOADER;
611
+ if (!loader || typeof loader.load !== 'function') {
612
+ throw new Error(
613
+ 'Nimbus: env.LOADER binding missing or invalid. Running a program requires '
614
+ + 'the Worker Loader binding; add it via worker_loaders in wrangler.jsonc.',
615
+ );
616
+ }
617
+ const supervisorRpc = supervisorEntrypoint();
618
+ let supervisorBinding: unknown;
619
+ let worker: LoadedWorkerStub | undefined;
620
+ let entrypoint: LoadedWorkerEntrypointStub | undefined;
621
+ try {
622
+ // Built before the capability is minted: nothing can write as this writer
623
+ // until there is a program to do the writing, and a map that fails to
624
+ // assemble should not have granted append authority on its way out.
625
+ let spec: OneShotCodeSpec | undefined = await params.code();
626
+ assertModuleMapWithinCodeLimit(spec.modules);
627
+ if (supervisorRpc) {
628
+ params.onWriterActivated(params.writerId);
629
+ supervisorBinding = supervisorRpc({ props: supervisor });
630
+ }
631
+ worker = loader.load({
632
+ compatibilityDate: spec.compatibilityDate,
633
+ compatibilityFlags: spec.compatibilityFlags,
634
+ mainModule: spec.mainModule,
635
+ modules: spec.modules,
636
+ ...(supervisorBinding ? { env: { SUPERVISOR: supervisorBinding } } : {}),
637
+ });
638
+ // The loader has taken the map; holding it here would keep a second full
639
+ // copy of the program alive for as long as the program runs.
640
+ spec = undefined;
641
+ entrypoint = worker.getEntrypoint();
642
+ // Narrowed by the runtime check; kept as a property call on the stub —
643
+ // extracting the method builds a pipelined `fetch.call` path workerd
644
+ // refuses for dynamically-loaded workers.
645
+ const ep = entrypoint as LoadedWorkerEntrypointStub & { fetch(request: Request): Promise<Response> };
646
+ if (typeof ep.fetch !== 'function') {
647
+ throw new Error('Nimbus: one-shot runtime entrypoint has no fetch method');
648
+ }
649
+ params.onLoaded?.();
650
+ // The unkeyed worker is a live dynamic worker for exactly this call, so
651
+ // the run is a Loader fetch on the hosting actor's ledger — bracketed,
652
+ // never wrapped: see beginLoaderFetch for the measured DO-poisoning
653
+ // hazard, and the pipelined-`fetch.call` note above for its sibling.
654
+ const endFetch = beginLoaderFetch(ctx);
655
+ let response: Response;
656
+ try {
657
+ response = await ep.fetch(params.request);
658
+ } finally {
659
+ endFetch();
660
+ }
661
+ try {
662
+ return await consume(response);
663
+ } finally {
664
+ disposeRpcResource(response);
665
+ }
666
+ } catch (error) {
667
+ throw withDynamicWorkerCapNamed(ctx, error);
668
+ } finally {
669
+ disposeRpcResource(entrypoint);
670
+ disposeRpcResource(worker);
671
+ disposeRpcResource(supervisorBinding);
672
+ }
673
+ }
674
+
675
+ async function residentWorkerConfig(
676
+ env: ResidentFacetEnv,
677
+ disk: () => ResidentDiskReader,
678
+ supervisor: ResidentSupervisorProps,
679
+ boot: ResidentBootSpec,
680
+ ): Promise<Record<string, unknown>> {
681
+ const config = boot.kind === 'staged'
682
+ ? await requireStagedBootAssembler()(env, boot.stage)
683
+ : await residentLoaderConfig(boot.code, disk());
684
+ assertModuleMapWithinCodeLimit(
685
+ (config as { modules?: Record<string, unknown> }).modules ?? {},
686
+ );
687
+ const supervisorRpc = supervisorEntrypoint();
688
+ if (!supervisorRpc) {
689
+ throw new Error(
690
+ `Nimbus: ctx.exports.${supervisorEntrypointName() ?? '<supervisor entrypoint>'} unavailable`,
691
+ );
692
+ }
693
+ return { ...config, env: { SUPERVISOR: supervisorRpc({ props: supervisor }) } };
694
+ }