@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,566 @@
1
+ /**
2
+ * process-host.ts — the two substrates a resident process can run on, and the
3
+ * one value that picks between them.
4
+ *
5
+ * `process-fabric.ts` owns what a resident process IS. This module
6
+ * owns only where it lives, behind `ProcessHost`:
7
+ *
8
+ * facet — the process is a named child actor of the user's own session DO.
9
+ * peer — the process is a named child actor of a SIBLING session DO, and
10
+ * the coordinator reaches it over one held-open RPC.
11
+ *
12
+ * Both call the same `openResidentFacet`. The peer leg is not a second process
13
+ * implementation; it is the same call made on a different actor, which is why
14
+ * the runner, the boot spec, the class name, the writer handshake, the start
15
+ * contract and the lifecycle are shared code rather than parallel paths.
16
+ *
17
+ * Choosing between them
18
+ * ─────────────────────
19
+ * One value for the whole deployment, resolved by the embedder's config seam
20
+ * (Nimbus reads `NIMBUS_PROCESS_HOST` in the worker's own selector) and
21
+ * handed to `createProcessHost`. No spawn site chooses; no program name, mode
22
+ * or payload size reaches the choice. If a decision about a particular
23
+ * process ever appears here, the heavy/light classifier has grown back and
24
+ * should be deleted again.
25
+ *
26
+ * | | spawn | memory | CPU | SQLite |
27
+ * |----------|------------|-------------|------------|--------|
28
+ * | facet | 8-16 ms | independent | SHARED | own |
29
+ * | peer | 242-359 ms | independent | independent| own |
30
+ *
31
+ * Facet CPU is shared because facets are separate isolates inside ONE actor
32
+ * thread: awaiting I/O yields it completely (measured 0 ms of sibling impact),
33
+ * but a non-yielding loop stalls every sibling for its full duration
34
+ * (measured 6,852 ms). A peer pays ~20x the spawn cost to buy that back.
35
+ *
36
+ * What the peer leg has to do differently, and why none of it reaches the
37
+ * process
38
+ * ────────────────────────────────────────────────────────────────────────
39
+ * payloads — a whole structured-clone RPC value is capped at 32 MiB, and
40
+ * pi's node snapshot alone serializes to 44,252,709 bytes. Boot
41
+ * specs name their large members BY PATH, so what crosses is a
42
+ * path and the host reads the bytes off the coordinator's disk in
43
+ * 4 MiB ranges through the supervisor. Nothing large is ever an
44
+ * RPC argument, so nothing has to be streamed or replayed.
45
+ * requests — workerd refuses to transfer an object owned by a
46
+ * dynamically-loaded worker across a sibling-DO hop, so a request
47
+ * travels to the peer as PARTS and the response comes back as
48
+ * parts, both with plain `ReadableStream` bodies that RPC carries
49
+ * with flow control. A live SSE body still streams; nothing is
50
+ * buffered.
51
+ * liveness — the host leg is held open for the process's whole life, which
52
+ * is also what keeps the hosting DO resident. A peer therefore
53
+ * never outlives its coordinator: the coordinator dying cancels
54
+ * the inbound call and the facet dies with it. Nothing in this
55
+ * fabric arms an alarm, on either substrate.
56
+ *
57
+ * WebSockets are the one thing on that list the RPC path cannot carry at all.
58
+ * A 101 Response owns a live socket, and RPC's Request/Response transport
59
+ * reconstructs a value rather than handing the socket over, so an upgrade
60
+ * stays on FETCH semantics for every hop: a facet is fetched directly, and a
61
+ * peer is fetched as a service binding which then fetches its hosted facet.
62
+ * Two headers carry what the RPC arguments would have — see
63
+ * {@link HOSTED_WEBSOCKET_KEY_HEADER} — and a per-process capability makes
64
+ * that pair unforgeable by anything that did not open the process.
65
+ */
66
+
67
+ import { disposeRpcResource } from '@nimbus-sh/core/_shared/rpc-dispose.js';
68
+ import { isTransientDoReset } from '@nimbus-sh/core/observability/oom-classify.js';
69
+ import { PEER_RETRY_BACKOFF_MS, PEER_TRANSIENT_RESET_RETRIES } from './fanout-pool.js';
70
+ import {
71
+ type HostedProcess,
72
+ type OneShotParams,
73
+ type ProcessHost,
74
+ type ProcessHostParams,
75
+ type ProcessImageDelivery,
76
+ type ResidentBootSpec,
77
+ type ResidentDiskReader,
78
+ type ResidentSupervisorProps,
79
+ } from './process-fabric.js';
80
+ import {
81
+ DYNAMIC_WORKER_CODE_LIMIT_BYTES,
82
+ openResidentFacet,
83
+ residentFacetName,
84
+ runOneShotWorker,
85
+ type ResidentFacetEnv,
86
+ } from './workerd-facet-host.js';
87
+ import { BindingError } from './vendor/errors.js';
88
+
89
+ /** The substrates this deployment can be configured for. */
90
+ export type ProcessHostMode = 'facet' | 'peer';
91
+
92
+ /**
93
+ * The substrate for this deployment, resolved once. The mode arrives already
94
+ * decided — the embedder owns the config var that picks it, and refuses an
95
+ * unrecognized value there rather than defaulting, because a typo that
96
+ * silently kept the old substrate would make an operator's comparison a lie.
97
+ * `disk` is the coordinator's own filesystem reader; the peer host does not
98
+ * take it, because a peer reads the same disk through the supervisor instead.
99
+ */
100
+ export function createProcessHost(
101
+ mode: ProcessHostMode,
102
+ ctx: DurableObjectState,
103
+ env: unknown,
104
+ disk: () => ResidentDiskReader,
105
+ ): ProcessHost {
106
+ return mode === 'peer'
107
+ ? new PeerProcessHost(ctx, env)
108
+ : new FacetProcessHost(ctx, env, disk);
109
+ }
110
+
111
+ // ── facet: the process is a child of the user's own session DO ──────────────
112
+
113
+ class FacetProcessHost implements ProcessHost {
114
+ /**
115
+ * The process shares its session's Durable Object, so the session's own
116
+ * store is reachable by copy-on-write — and its storage budget is the same
117
+ * budget. Both halves of that follow from the one fact, and neither is
118
+ * optional.
119
+ */
120
+ readonly imageDelivery: ProcessImageDelivery = {
121
+ reflink: 'same-object',
122
+ moduleCeilingBytes: DYNAMIC_WORKER_CODE_LIMIT_BYTES,
123
+ storageSharedWithSession: true,
124
+ };
125
+
126
+ private readonly env: ResidentFacetEnv;
127
+ private readonly coordDoId: string;
128
+
129
+ constructor(
130
+ private readonly ctx: DurableObjectState,
131
+ env: unknown,
132
+ private readonly disk: () => ResidentDiskReader,
133
+ ) {
134
+ this.env = (env ?? {}) as ResidentFacetEnv;
135
+ this.coordDoId = ctx.id.toString();
136
+ }
137
+
138
+ runOnce<T>(params: OneShotParams, consume: (response: Response) => Promise<T>): Promise<T> {
139
+ return runOneShotWorker(
140
+ this.ctx,
141
+ this.env,
142
+ { doId: this.coordDoId, pid: params.pid, writerId: params.writerId },
143
+ params,
144
+ consume,
145
+ );
146
+ }
147
+
148
+ async open(params: ProcessHostParams): Promise<HostedProcess> {
149
+ const supervisor: ResidentSupervisorProps = {
150
+ doId: this.coordDoId,
151
+ pid: params.pid,
152
+ writerId: params.writerId,
153
+ };
154
+ const { slot, ...facet } = openResidentFacet(this.ctx, this.env, this.disk, supervisor, params);
155
+ return {
156
+ ...facet,
157
+ describe: () =>
158
+ `facet '${residentFacetName(slot)}' (pid ${params.pid})`
159
+ + ` of session ${this.coordDoId.slice(-12)}`
160
+ + `; ${describeImageDelivery(this.imageDelivery)}`,
161
+ };
162
+ }
163
+ }
164
+
165
+ /**
166
+ * The operator-facing half of the substrate difference, on the one line an
167
+ * operator actually reads. A comment in this file would not have told anyone
168
+ * who flipped the config that the image path changed under them.
169
+ */
170
+ function describeImageDelivery(delivery: ProcessImageDelivery): string {
171
+ return `fs image: reflink ${delivery.reflink}, module map ≤ ${delivery.moduleCeilingBytes}B, `
172
+ + `storage ${delivery.storageSharedWithSession ? 'shared with the session' : 'its own'}`;
173
+ }
174
+
175
+ // ── peer: the process is a child of a sibling session DO ────────────────────
176
+
177
+ /**
178
+ * How many sibling names to try before accepting one that co-located with a
179
+ * process already running. Measured: 1 shared pair in 24 fresh peers.
180
+ */
181
+ const PEER_PLACEMENT_MAX_ATTEMPTS = 4;
182
+
183
+ /**
184
+ * This workerd process's identity. Module scope, so two Durable Objects
185
+ * reporting the same token are in the same process — which is exactly the CPU
186
+ * sharing a peer exists to avoid, and the only way to detect it.
187
+ */
188
+ let _isolateToken: string | null = null;
189
+ export function isolateToken(): string {
190
+ if (!_isolateToken) _isolateToken = crypto.randomUUID();
191
+ return _isolateToken;
192
+ }
193
+
194
+ /** Options the coordinator hands a hosting peer. */
195
+ export interface HostProcessOpts {
196
+ coordinatorDoId: string;
197
+ pid: number;
198
+ writerId: string;
199
+ workerKey: string;
200
+ /** Unforgeable capability for the fetch-semantic WebSocket hop. */
201
+ webSocketCapability: string;
202
+ startArgs?: unknown;
203
+ }
204
+
205
+ /**
206
+ * Inbound HTTP for a peer-hosted process travels as PARTS, not as a
207
+ * Request/Response pair: workerd refuses to transfer an object owned by a
208
+ * dynamically-loaded worker across a sibling-DO hop. Bodies are plain
209
+ * ReadableStreams, which RPC carries with flow control, so nothing is buffered
210
+ * and a live SSE body still streams.
211
+ */
212
+ export interface HostedHttpRequest {
213
+ method: string;
214
+ url: string;
215
+ headers: [string, string][];
216
+ body: ReadableStream | null;
217
+ }
218
+
219
+ export interface HostedHttpResponse {
220
+ status: number;
221
+ statusText: string;
222
+ headers: [string, string][];
223
+ body: ReadableStream | null;
224
+ }
225
+
226
+ /**
227
+ * Every method a hosting sibling must answer. Checked as a set at first
228
+ * contact: a stub that has the probe but not the router is a deployment skew,
229
+ * and finding that out mid-process is finding it out too late.
230
+ */
231
+ const PROCESS_PEER_METHODS = [
232
+ '_rpcProcessHostProbe',
233
+ '_rpcHostProcess',
234
+ '_rpcAwaitHostedOpen',
235
+ '_rpcAwaitHostedBoot',
236
+ '_rpcRouteHostedHttp',
237
+ '_rpcCancelHostProcess',
238
+ ] as const;
239
+
240
+ /** The host-process surface a sibling session DO exposes. */
241
+ interface ProcessPeerStub {
242
+ _rpcProcessHostProbe(): Promise<{ isolateToken: string }>;
243
+ _rpcHostProcess(boot: ResidentBootSpec, opts: HostProcessOpts): Promise<{ ok: boolean }>;
244
+ _rpcAwaitHostedOpen(workerKey: string): Promise<{ ok: boolean }>;
245
+ _rpcAwaitHostedBoot(workerKey: string): Promise<{ payload: unknown }>;
246
+ _rpcRouteHostedHttp(workerKey: string, request: HostedHttpRequest): Promise<HostedHttpResponse>;
247
+ _rpcCancelHostProcess(workerKey: string): Promise<{ cancelled: boolean }>;
248
+ fetch(request: Request): Promise<Response>;
249
+ }
250
+
251
+ /**
252
+ * Which hosted process a fetched upgrade is for. An upgrade cannot travel as
253
+ * RPC arguments, so the two values `_rpcRouteHostedHttp` would have taken ride
254
+ * as headers on the peer fetch instead.
255
+ *
256
+ * The key alone is guessable from a pid, so it is not enough on its own; the
257
+ * capability is minted per `open()` and known only to the coordinator that
258
+ * opened the process and the peer that hosts it. The receiving session strips
259
+ * both before the request reaches the process.
260
+ */
261
+ export const HOSTED_WEBSOCKET_KEY_HEADER = 'x-nimbus-hosted-websocket';
262
+ export const HOSTED_WEBSOCKET_CAPABILITY_HEADER = 'x-nimbus-hosted-websocket-capability';
263
+
264
+ interface PeerNamespace {
265
+ idFromName(name: string): unknown;
266
+ get(id: unknown): unknown;
267
+ }
268
+
269
+ function peerNamespace(env: unknown): PeerNamespace {
270
+ const ns = (typeof env === 'object' || typeof env === 'function') && env !== null
271
+ ? Reflect.get(env, 'NIMBUS_SESSION')
272
+ : undefined;
273
+ if ((typeof ns !== 'object' && typeof ns !== 'function') || ns === null
274
+ || typeof Reflect.get(ns, 'idFromName') !== 'function'
275
+ || typeof Reflect.get(ns, 'get') !== 'function') {
276
+ throw new BindingError(
277
+ 'ProcessFabric: env.NIMBUS_SESSION binding missing or invalid. '
278
+ + "NIMBUS_PROCESS_HOST='peer' hosts every resident process on a sibling "
279
+ + 'Durable Object; add the binding via durable_objects.bindings in wrangler.jsonc.',
280
+ );
281
+ }
282
+ return ns as unknown as PeerNamespace;
283
+ }
284
+
285
+ function processPeerStub(value: unknown, peerName: string): ProcessPeerStub {
286
+ if ((typeof value !== 'object' && typeof value !== 'function') || value === null) {
287
+ throw new BindingError(`ProcessFabric: NIMBUS_SESSION.get() returned no stub for peer '${peerName}'.`);
288
+ }
289
+ for (const method of PROCESS_PEER_METHODS) {
290
+ if (typeof Reflect.get(value, method) !== 'function') {
291
+ throw new BindingError(
292
+ `ProcessFabric: peer '${peerName}' does not expose ${method}(). `
293
+ + 'A sibling that answers some of the host-process surface and not the rest '
294
+ + 'would fail somewhere inside a running process instead of here.',
295
+ );
296
+ }
297
+ }
298
+ return value as unknown as ProcessPeerStub;
299
+ }
300
+
301
+ interface PeerPlacement {
302
+ stub: ProcessPeerStub;
303
+ peerName: string;
304
+ isolateToken: string;
305
+ }
306
+
307
+ class PeerProcessHost implements ProcessHost {
308
+ /**
309
+ * A peer buys independent CPU and its own storage budget, and pays for both
310
+ * with the image path: nothing crosses a Durable Object boundary by
311
+ * reference, so the whole session filesystem has to travel as bytes.
312
+ */
313
+ readonly imageDelivery: ProcessImageDelivery = {
314
+ reflink: 'impossible',
315
+ moduleCeilingBytes: DYNAMIC_WORKER_CODE_LIMIT_BYTES,
316
+ storageSharedWithSession: false,
317
+ };
318
+
319
+ private readonly ns: PeerNamespace;
320
+ private readonly env: ResidentFacetEnv;
321
+ private readonly coordDoId: string;
322
+ /** pid → the isolate token of the peer currently hosting that process. */
323
+ private readonly tokensInUse = new Map<number, string>();
324
+
325
+ constructor(private readonly ctx: DurableObjectState, env: unknown) {
326
+ this.ns = peerNamespace(env);
327
+ this.env = (env ?? {}) as ResidentFacetEnv;
328
+ this.coordDoId = ctx.id.toString();
329
+ }
330
+
331
+ /**
332
+ * Not placed on a sibling, and that is not a gap in this substrate.
333
+ * `peer` exists to buy a resident process independent CPU; a program that
334
+ * ends with the call it was started by has no residency to place, and its
335
+ * map is fully inline — so a hop would meet the RPC ceiling that by-path
336
+ * boot specs exist to avoid while buying nothing. It runs as a dynamic
337
+ * worker of the coordinator here exactly as it does on `facet`.
338
+ */
339
+ runOnce<T>(params: OneShotParams, consume: (response: Response) => Promise<T>): Promise<T> {
340
+ return runOneShotWorker(
341
+ this.ctx,
342
+ this.env,
343
+ { doId: this.coordDoId, pid: params.pid, writerId: params.writerId },
344
+ params,
345
+ consume,
346
+ );
347
+ }
348
+
349
+ async open(params: ProcessHostParams): Promise<HostedProcess> {
350
+ const placement = await this._place(params.pid);
351
+ this.tokensInUse.set(params.pid, placement.isolateToken);
352
+ // Minted per open, held only by this coordinator and the peer that hosts
353
+ // the process. The workerKey is derivable from a pid; this is not.
354
+ const webSocketCapability = crypto.randomUUID();
355
+
356
+ // Held open for the process's whole life: it is the lifecycle, and it is
357
+ // also what keeps the hosting DO resident. It settles when a `lifetime`
358
+ // runner exits or when a `boot` runner's host is cancelled, and rejects if
359
+ // the peer dies under either.
360
+ const hostLeg = placement.stub._rpcHostProcess(params.boot, {
361
+ coordinatorDoId: this.coordDoId,
362
+ pid: params.pid,
363
+ writerId: params.writerId,
364
+ workerKey: params.workerKey,
365
+ webSocketCapability,
366
+ startArgs: params.startArgs,
367
+ });
368
+ hostLeg.catch(() => {});
369
+ // The peer starts the runner as part of hosting it; this reads back that
370
+ // one boot payload without re-running anything, so `started` means exactly
371
+ // what it means on a facet. Racing the host leg is what turns a peer that
372
+ // died before the boot landed into a rejection rather than a hang — the
373
+ // peer that would have answered is the thing that is gone.
374
+ const booted = placement.stub._rpcAwaitHostedBoot(params.workerKey).then((r) => r.payload);
375
+ booted.catch(() => {});
376
+ const started = Promise.race([booted, hostLeg.then(() => booted)]);
377
+ started.catch(() => {});
378
+ // Do not return a handle for a process that was never opened. Opening a
379
+ // facet of one's own DO either throws or does not, before any handle
380
+ // exists; this is that same moment, one hop away.
381
+ try {
382
+ await Promise.race([
383
+ placement.stub._rpcAwaitHostedOpen(params.workerKey),
384
+ hostLeg.then(() => ({ ok: true })),
385
+ ]);
386
+ } catch (error) {
387
+ this.tokensInUse.delete(params.pid);
388
+ // Awaited, not fired off: a spawn that rejects must mean nothing was
389
+ // left running, which is what a throw from `openResidentFacet` means on
390
+ // the other substrate.
391
+ try { await this._cancel(params.workerKey, placement.peerName); }
392
+ finally { disposeRpcResource(placement.stub); }
393
+ throw error;
394
+ }
395
+
396
+ let released = false;
397
+ return {
398
+ started,
399
+ // The held leg IS the process's residency here. It settles cleanly when
400
+ // the coordinator releases; anything else is the host going away under a
401
+ // process that was up, and the fabric ends the process on it.
402
+ lost: hostLeg.then(() => new Promise<never>(() => {})),
403
+ handleHttpRequest: (request: Request) =>
404
+ routeThroughPeer(placement.stub, params.workerKey, request),
405
+ handleWebSocketRequest: (request: Request) =>
406
+ routeWebSocketThroughPeer(placement.stub, params.workerKey, webSocketCapability, request),
407
+ release: async () => {
408
+ if (released) return;
409
+ released = true;
410
+ this.tokensInUse.delete(params.pid);
411
+ try {
412
+ await this._cancel(params.workerKey, placement.peerName);
413
+ } finally {
414
+ disposeRpcResource(placement.stub);
415
+ }
416
+ },
417
+ describe: () =>
418
+ `peer '${placement.peerName}' (isolate ${placement.isolateToken.slice(0, 8)})`
419
+ + `; ${describeImageDelivery(this.imageDelivery)}`,
420
+ };
421
+ }
422
+
423
+ /**
424
+ * Probe successive sibling names until one reports an isolate token distinct
425
+ * from this coordinator's and from every peer already hosting a process. A
426
+ * peer that co-located bought nothing — it shares the CPU it was chosen to
427
+ * escape — so placement verifies rather than assumes.
428
+ */
429
+ private async _place(pid: number): Promise<PeerPlacement> {
430
+ const denied = new Set<string>([isolateToken(), ...this.tokensInUse.values()]);
431
+ for (let attempt = 0; attempt < PEER_PLACEMENT_MAX_ATTEMPTS - 1; attempt++) {
432
+ const candidate = await this._probePlacement(pid, attempt);
433
+ if (!denied.has(candidate.isolateToken)) return candidate;
434
+ disposeRpcResource(candidate.stub);
435
+ }
436
+ // Every attempt co-located, which happens in single-process topologies. Use
437
+ // the last one anyway: it runs the process correctly, it just shares the
438
+ // CPU it was chosen to escape, and the placement line names the isolate it
439
+ // landed in so that is visible rather than assumed.
440
+ return this._probePlacement(pid, PEER_PLACEMENT_MAX_ATTEMPTS - 1);
441
+ }
442
+
443
+ /** One sibling name, resolved and probed. Leaks nothing on failure. */
444
+ private async _probePlacement(pid: number, attempt: number): Promise<PeerPlacement> {
445
+ const peerName = `${this.coordDoId}:proc:${pid}:${attempt}`;
446
+ let resource: unknown;
447
+ try {
448
+ resource = this.ns.get(this.ns.idFromName(peerName));
449
+ const stub = processPeerStub(resource, peerName);
450
+ const probe = await this._probe(stub, peerName);
451
+ return { stub, peerName, isolateToken: probe.isolateToken };
452
+ } catch (error) {
453
+ disposeRpcResource(resource);
454
+ throw error;
455
+ }
456
+ }
457
+
458
+ /**
459
+ * First contact with a possibly-cold sibling DO: retry transient platform
460
+ * resets with the same bounded policy the fanout peers ship. Non-transient
461
+ * failures propagate on the first hit.
462
+ */
463
+ private async _probe(stub: ProcessPeerStub, peerName: string): Promise<{ isolateToken: string }> {
464
+ for (let attempt = 0; ; attempt++) {
465
+ try {
466
+ const probe = await stub._rpcProcessHostProbe();
467
+ if (!probe || typeof probe.isolateToken !== 'string' || probe.isolateToken.length === 0) {
468
+ throw new Error(`ProcessFabric: peer '${peerName}' returned no isolate token`);
469
+ }
470
+ return probe;
471
+ } catch (err) {
472
+ if (attempt < PEER_TRANSIENT_RESET_RETRIES && isTransientDoReset(err)) {
473
+ await new Promise((r) => setTimeout(
474
+ r, PEER_RETRY_BACKOFF_MS[Math.min(attempt, PEER_RETRY_BACKOFF_MS.length - 1)],
475
+ ));
476
+ continue;
477
+ }
478
+ throw err;
479
+ }
480
+ }
481
+ }
482
+
483
+ /**
484
+ * A fresh stub to the hosting peer fires `_rpcCancelHostProcess`, which
485
+ * releases the peer's facet — the exact teardown a local facet gets — and
486
+ * only answers once it has. Awaiting it is what makes "released" mean the
487
+ * same thing on both substrates, so the writer identity is retired at the
488
+ * same point in the process's life either way. Also handed to `waitUntil`,
489
+ * so a kill nobody awaited still completes.
490
+ */
491
+ private _cancel(workerKey: string, peerName: string): Promise<void> {
492
+ let stub: ProcessPeerStub;
493
+ try {
494
+ stub = processPeerStub(this.ns.get(this.ns.idFromName(peerName)), peerName);
495
+ } catch {
496
+ return Promise.resolve();
497
+ }
498
+ const cancelled = Promise.resolve(stub._rpcCancelHostProcess(workerKey))
499
+ .then(() => undefined)
500
+ .catch(() => { /* peer already gone — the held leg is severed either way */ })
501
+ .finally(() => disposeRpcResource(stub));
502
+ this.ctx.waitUntil(cancelled);
503
+ return cancelled;
504
+ }
505
+ }
506
+
507
+ async function routeThroughPeer(
508
+ stub: ProcessPeerStub,
509
+ workerKey: string,
510
+ request: Request,
511
+ ): Promise<Response> {
512
+ const result = await stub._rpcRouteHostedHttp(workerKey, {
513
+ method: request.method,
514
+ url: request.url,
515
+ headers: headerPairs(request.headers),
516
+ body: request.method === 'GET' || request.method === 'HEAD' ? null : request.body,
517
+ });
518
+ const responseHeaders = new Headers();
519
+ for (const [key, value] of result.headers) responseHeaders.append(key, value);
520
+ return new Response(result.body, {
521
+ status: result.status,
522
+ statusText: result.statusText,
523
+ headers: responseHeaders,
524
+ });
525
+ }
526
+
527
+ /**
528
+ * The upgrade hop. `stub.fetch` is a service-binding fetch, so the peer's
529
+ * `Response` — socket and all — is handed back rather than reconstructed,
530
+ * which is the whole reason this is not an RPC.
531
+ */
532
+ function routeWebSocketThroughPeer(
533
+ stub: ProcessPeerStub,
534
+ workerKey: string,
535
+ capability: string,
536
+ request: Request,
537
+ ): Promise<Response> {
538
+ const headers = new Headers(request.headers);
539
+ headers.set(HOSTED_WEBSOCKET_KEY_HEADER, workerKey);
540
+ headers.set(HOSTED_WEBSOCKET_CAPABILITY_HEADER, capability);
541
+ return stub.fetch(new Request(request.url, { method: request.method, headers }));
542
+ }
543
+
544
+ /**
545
+ * Headers as pairs, with every `Set-Cookie` kept separate.
546
+ *
547
+ * Iterating a `Headers` combines same-named fields into one comma-joined
548
+ * value, and for `Set-Cookie` that is not reversible — `append` cannot split
549
+ * `a=1; Path=/, b=2; Path=/` back into two cookies, and a browser reading the
550
+ * merged form sets one malformed cookie instead of two. Every other field
551
+ * combines by comma legally, so only this one needs the separate accessor.
552
+ * A user's server setting two cookies must not depend on which substrate its
553
+ * process happened to run on.
554
+ */
555
+ export function headerPairs(headers: Headers): [string, string][] {
556
+ const pairs: [string, string][] = [];
557
+ headers.forEach((value, key) => {
558
+ if (key.toLowerCase() !== 'set-cookie') pairs.push([key, value]);
559
+ });
560
+ const getSetCookie = (headers as Headers & { getSetCookie?: () => string[] }).getSetCookie;
561
+ const cookies = typeof getSetCookie === 'function'
562
+ ? getSetCookie.call(headers)
563
+ : (headers.get('set-cookie') ? [headers.get('set-cookie') as string] : []);
564
+ for (const cookie of cookies) pairs.push(['set-cookie', cookie]);
565
+ return pairs;
566
+ }
@@ -0,0 +1,56 @@
1
+ export class ParallelError extends Error {
2
+ constructor(message: string) {
3
+ super(message);
4
+ this.name = 'ParallelError';
5
+ }
6
+ }
7
+
8
+ export class SerializationError extends ParallelError {
9
+ constructor(message: string) {
10
+ super(message);
11
+ this.name = 'SerializationError';
12
+ }
13
+ }
14
+
15
+ export class ExecutionError extends ParallelError {
16
+ readonly remoteMessage: string;
17
+ readonly remoteStack?: string;
18
+
19
+ constructor(message: string, remoteStack?: string) {
20
+ super(message);
21
+ this.name = 'ExecutionError';
22
+ this.remoteMessage = message;
23
+ this.remoteStack = remoteStack;
24
+ }
25
+ }
26
+
27
+ export class TimeoutError extends ParallelError {
28
+ readonly deadlineMs: number;
29
+
30
+ constructor(deadlineMs: number) {
31
+ super(`Task exceeded ${deadlineMs}ms deadline`);
32
+ this.name = 'TimeoutError';
33
+ this.deadlineMs = deadlineMs;
34
+ }
35
+ }
36
+
37
+ export class RetryExhaustedError extends ParallelError {
38
+ readonly lastError: Error;
39
+ readonly attempts: number;
40
+
41
+ constructor(attempts: number, lastError: Error) {
42
+ super(
43
+ `Task failed after ${attempts} attempt(s): ${lastError.message}`,
44
+ );
45
+ this.name = 'RetryExhaustedError';
46
+ this.attempts = attempts;
47
+ this.lastError = lastError;
48
+ }
49
+ }
50
+
51
+ export class BindingError extends ParallelError {
52
+ constructor(message: string) {
53
+ super(message);
54
+ this.name = 'BindingError';
55
+ }
56
+ }
@@ -0,0 +1,37 @@
1
+ import { SerializationError } from './errors.js';
2
+
3
+ export function serializeFunction(fn: Function): string {
4
+ if (typeof fn !== 'function') {
5
+ throw new SerializationError(
6
+ `Expected a function, got ${typeof fn}`,
7
+ );
8
+ }
9
+
10
+ const source = fn.toString();
11
+
12
+ if (source.includes('[native code]')) {
13
+ throw new SerializationError(
14
+ `Cannot serialize native function: ${fn.name || '(anonymous)'}. ` +
15
+ 'Only user-defined functions can be dispatched to remote isolates.',
16
+ );
17
+ }
18
+
19
+ // `this` has no receiver in the remote isolate — reject it early.
20
+ if (/\bthis\b/.test(source)) {
21
+ throw new SerializationError(
22
+ `Function "${fn.name || '(anonymous)'}" references \`this\`, which is ` +
23
+ 'not available in a remote isolate. Pass values as explicit arguments instead.',
24
+ );
25
+ }
26
+
27
+ return source;
28
+ }
29
+
30
+ // djb2 hash — fast, deterministic, not cryptographic. Used only for loader cache key differentiation.
31
+ export function hashSource(source: string): string {
32
+ let hash = 5381;
33
+ for (let i = 0; i < source.length; i++) {
34
+ hash = ((hash << 5) + hash + source.charCodeAt(i)) | 0;
35
+ }
36
+ return (hash >>> 0).toString(36);
37
+ }