@nimbus-sh/fabric 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +98 -11
  2. package/dist/bindings.d.ts +31 -33
  3. package/dist/bindings.d.ts.map +1 -1
  4. package/dist/bindings.js +108 -97
  5. package/dist/budgets.d.ts +102 -29
  6. package/dist/budgets.d.ts.map +1 -1
  7. package/dist/budgets.js +266 -44
  8. package/dist/do-calls.d.ts +20 -0
  9. package/dist/do-calls.d.ts.map +1 -1
  10. package/dist/do-calls.js +24 -11
  11. package/dist/fanout.d.ts +40 -32
  12. package/dist/fanout.d.ts.map +1 -1
  13. package/dist/fanout.js +48 -51
  14. package/dist/fenced-work.d.ts +3 -3
  15. package/dist/fenced-work.js +3 -3
  16. package/dist/host-wasm.d.ts +29 -0
  17. package/dist/host-wasm.d.ts.map +1 -0
  18. package/dist/host-wasm.js +31 -0
  19. package/dist/image-store.d.ts +1 -1
  20. package/dist/image-store.d.ts.map +1 -1
  21. package/dist/image-store.js +33 -1
  22. package/dist/inner-do-env.d.ts +83 -0
  23. package/dist/inner-do-env.d.ts.map +1 -0
  24. package/dist/inner-do-env.js +181 -0
  25. package/dist/isolate-pool.d.ts +40 -23
  26. package/dist/isolate-pool.d.ts.map +1 -1
  27. package/dist/isolate-pool.js +105 -55
  28. package/dist/process-fabric.d.ts +26 -11
  29. package/dist/process-fabric.d.ts.map +1 -1
  30. package/dist/process-fabric.js +44 -0
  31. package/dist/timers.d.ts +12 -0
  32. package/dist/timers.d.ts.map +1 -1
  33. package/dist/timers.js +44 -9
  34. package/dist/vendor/types.d.ts +11 -5
  35. package/dist/vendor/types.d.ts.map +1 -1
  36. package/dist/workerd-facet-host.d.ts.map +1 -1
  37. package/dist/workerd-facet-host.js +35 -30
  38. package/package.json +4 -4
  39. package/src/bindings.ts +121 -98
  40. package/src/budgets.ts +311 -53
  41. package/src/do-calls.ts +45 -11
  42. package/src/fanout.ts +62 -53
  43. package/src/fenced-work.ts +3 -3
  44. package/src/host-wasm.ts +41 -0
  45. package/src/image-store.ts +29 -2
  46. package/src/inner-do-env.ts +213 -0
  47. package/src/isolate-pool.ts +145 -75
  48. package/src/process-fabric.ts +55 -13
  49. package/src/timers.ts +45 -9
  50. package/src/vendor/types.ts +11 -5
  51. package/src/workerd-facet-host.ts +36 -31
package/dist/do-calls.js CHANGED
@@ -41,6 +41,7 @@
41
41
  */
42
42
  import { classifyDoCall, isRetryableDoCall } from '@nimbus-sh/platform/oom-classify.js';
43
43
  import { disposeRpcResource } from '@nimbus-sh/platform/rpc-dispose.js';
44
+ import { untraced } from '@nimbus-sh/platform/tracing.js';
44
45
  /** Total attempts. Two retries is what a dropped connection or a deploy
45
46
  * bounce needs; beyond that the object is not coming back inside this
46
47
  * request (the consumer's measured bound). */
@@ -87,7 +88,7 @@ export class DoCallError extends Error {
87
88
  export function idempotent(operation, stub, call, policy = {}) {
88
89
  const maxAttempts = policy.maxAttempts ?? MAX_ATTEMPTS;
89
90
  const baseDelayMs = policy.baseDelayMs ?? BASE_DELAY_MS;
90
- const { hedgeAfterMs, retryWindowMs } = policy;
91
+ const { hedgeAfterMs, retryWindowMs, span = untraced } = policy;
91
92
  const startedAt = Date.now();
92
93
  // The executor form: fabric's library target predates Promise.withResolvers.
93
94
  return new Promise((resolve, reject) => {
@@ -99,7 +100,9 @@ export function idempotent(operation, stub, call, policy = {}) {
99
100
  // An attempt was shed as overloaded: nothing is repeated after it.
100
101
  let refused = false;
101
102
  let settled = false;
102
- const settle = (answer) => {
103
+ // Attempts a hedge started rather than a retry or the first send.
104
+ let hedged = 0;
105
+ const settle = (outcome, answeredBy, answer) => {
103
106
  if (settled)
104
107
  return;
105
108
  settled = true;
@@ -107,6 +110,12 @@ export function idempotent(operation, stub, call, policy = {}) {
107
110
  clearTimeout(timer);
108
111
  hedges.clear();
109
112
  answer();
113
+ span.set({
114
+ 'do_call.attempts': started,
115
+ 'do_call.hedges': hedged,
116
+ 'do_call.answered_by': answeredBy,
117
+ 'do_call.outcome': outcome,
118
+ });
110
119
  };
111
120
  /** May another attempt start at `at`? */
112
121
  const canRepeat = (at) => !settled && !refused && started < maxAttempts
@@ -114,13 +123,20 @@ export function idempotent(operation, stub, call, policy = {}) {
114
123
  /** `error` ended an attempt that will not be repeated: the call's answer, once nothing else is live. */
115
124
  const exhausted = (error) => {
116
125
  if (live === 0)
117
- settle(() => reject(error));
126
+ settle(refused ? 'overloaded' : 'exhausted', undefined, () => reject(error));
118
127
  };
119
128
  /** A failed attempt, numbered: repeat it after its backoff, or let it stand. */
120
129
  const failed = async (number, error) => {
121
130
  if (settled)
122
131
  return;
123
132
  const classification = classifyDoCall(error);
133
+ if (!isRetryableDoCall(classification) && classification !== 'overloaded') {
134
+ // The call ran and its answer is this error — ENOENT is a read's answer as much as bytes are.
135
+ settle('callee_error', number, () => reject(error));
136
+ return;
137
+ }
138
+ // A lost attempt: the call's span says which, and why.
139
+ span.exception(error, classification, `attempt ${number} of ${maxAttempts}: `);
124
140
  if (classification === 'overloaded') {
125
141
  // A shed call is no answer: nothing more is sent, and an attempt
126
142
  // still in flight may yet answer.
@@ -128,11 +144,6 @@ export function idempotent(operation, stub, call, policy = {}) {
128
144
  exhausted(error);
129
145
  return;
130
146
  }
131
- if (!isRetryableDoCall(classification)) {
132
- // The call ran and its answer is this error — ENOENT is a read's answer as much as bytes are.
133
- settle(() => reject(error));
134
- return;
135
- }
136
147
  const delayMs = Math.floor(Math.random() * 2 ** number * baseDelayMs);
137
148
  if (!canRepeat(Date.now() + delayMs)) {
138
149
  exhausted(error);
@@ -163,8 +174,10 @@ export function idempotent(operation, stub, call, policy = {}) {
163
174
  const hedge = hedgeAfterMs === undefined ? undefined : setTimeout(() => {
164
175
  if (hedge !== undefined)
165
176
  hedges.delete(hedge);
166
- if (canRepeat(Date.now()))
177
+ if (canRepeat(Date.now())) {
178
+ hedged++;
167
179
  attempt();
180
+ }
168
181
  }, hedgeAfterMs);
169
182
  if (hedge !== undefined)
170
183
  hedges.add(hedge);
@@ -193,11 +206,11 @@ export function idempotent(operation, stub, call, policy = {}) {
193
206
  disposeRpcResource(result);
194
207
  return;
195
208
  }
196
- settle(() => resolve(result));
209
+ settle('answered', number, () => resolve(result));
197
210
  };
198
211
  /** Start an attempt. Whatever it throws outside the call itself fails the call. */
199
212
  const attempt = () => {
200
- run().catch((error) => settle(() => reject(error)));
213
+ run().catch((error) => settle('caller_error', undefined, () => reject(error)));
201
214
  };
202
215
  attempt();
203
216
  });
package/dist/fanout.d.ts CHANGED
@@ -1,17 +1,21 @@
1
1
  /**
2
2
  * Two-tier fan-out primitive for work that must execute in Worker Loader
3
- * facets without tripping workerd's per-DO dynamic-worker ceiling.
3
+ * isolates within the Durable Object's Dynamic Worker budget.
4
4
  *
5
- * A single Durable Object method can drive at most four concurrent
6
- * Worker Loader fetches before extra dispatches serialize or fail. Small
7
- * batches therefore run in the coordinator DO through IsolatePool.
8
- * Wider batches are sharded across sibling NimbusSession DOs, each of
9
- * which owns its own four-loader budget.
5
+ * A Durable Object may have `DO_DYNAMIC_WORKER_LIMIT` distinct Dynamic
6
+ * Workers with in-flight requests, shared across every concurrent request to
7
+ * it (budgets.ts). A batch the coordinator's remaining headroom can hold —
8
+ * the limit less the workers it already has in flight (resident processes,
9
+ * the esbuild facet, a git network op) and other fan-outs' claims — runs in
10
+ * the coordinator through IsolatePool, one Dynamic Worker per task. Only a
11
+ * batch wider than that headroom is sharded across sibling NimbusSession
12
+ * DOs, each of which spends its own budget.
10
13
  *
11
- * Routing is deterministic: each task has a stable key, and the key maps
12
- * to a sibling DO shard. There is no silent fallback to width-1 execution;
13
- * missing LOADER or NIMBUS_SESSION bindings fail loudly so install and
14
- * runtime operations do not appear successful after partial dispatch.
14
+ * Routing is deterministic for a given headroom: each task has a stable key,
15
+ * and the key maps to a sibling DO shard. There is no silent fallback to
16
+ * width-1 execution; missing LOADER or NIMBUS_SESSION bindings fail loudly so
17
+ * install and runtime operations do not appear successful after partial
18
+ * dispatch.
15
19
  */
16
20
  import { type FacetTaskFn } from './isolate-pool.js';
17
21
  import type { WorkerLoader } from './vendor/types.js';
@@ -22,14 +26,16 @@ export interface FanoutEnv {
22
26
  LOADER?: WorkerLoader;
23
27
  NIMBUS_SESSION?: unknown;
24
28
  }
25
- /**
26
- * Threshold at which routing switches from coordinator-local loaders to
27
- * sibling Durable Objects.
28
- *
29
- * Set to **5** so the in-DO path stays below the V8 4-loaders-per-method
30
- * cap by construction. width < 5 stays local; width >= 5 uses sibling DOs.
31
- */
32
- export declare const IN_DO_THRESHOLD = 5;
29
+ /** Where one `submitMany` ran. */
30
+ export type FanoutTopology = 'in-do' | 'peer-do';
31
+ /** The routing decision for one `submitMany`, as its caller may log it. */
32
+ export interface FanoutRoute {
33
+ topology: FanoutTopology;
34
+ /** Tasks in the batch — the Dynamic Workers an in-DO run spends. */
35
+ tasks: number;
36
+ /** The coordinator's Dynamic Worker headroom when the batch was routed. */
37
+ headroom: number;
38
+ }
33
39
  /**
34
40
  * Hard cap on concurrent peer DOs per single submitMany call. Throughput stays
35
41
  * flat through this width while keeping per-request scheduler pressure bounded.
@@ -134,12 +140,14 @@ export interface FanoutOptions {
134
140
  * Not called on the in-DO path, which has no phases.
135
141
  */
136
142
  onDispatchPhase?: (width: number, elapsedMs: number) => void;
143
+ /** Called once per non-empty submitMany with the route it took. */
144
+ onRoute?: (route: FanoutRoute) => void;
137
145
  /**
138
146
  * Cap on peer DOs this pool will spread one submitMany across. Defaults to
139
147
  * MAX_PEER_FANOUT. Tasks beyond the cap bucket into the peers that exist and
140
148
  * run through their in-peer pool, so lowering it trades peers for barriers
141
- * without lowering total concurrency: each peer runs its bucket at
142
- * concurrency 4, so N peers still resolve 4N tasks at once.
149
+ * without lowering total concurrency: each peer runs its bucket as wide as
150
+ * its own Dynamic Worker headroom allows.
143
151
  *
144
152
  * A caller sets this when its per-task work is small enough that a peer per
145
153
  * task buys nothing but round-trips — one task per peer costs ⌈tasks/
@@ -149,7 +157,7 @@ export interface FanoutOptions {
149
157
  }
150
158
  /**
151
159
  * Two-tier fan-out pool. Constructed by the supervisor DO; routes
152
- * each `submitMany` call automatically based on width.
160
+ * each `submitMany` call on the coordinator's live Dynamic Worker headroom.
153
161
  *
154
162
  * Lifetime: cheap to construct (no async init). Multiple submitMany
155
163
  * calls share NO state — each is dispatched fresh. The class
@@ -167,16 +175,16 @@ export declare class Fanout {
167
175
  * Dispatch `tasks` across the appropriate topology and return
168
176
  * results in input order.
169
177
  *
170
- * Routing:
171
- * tasks.length < 5 -> coordinator-local IsolatePool
172
- * tasks.length >= 5 -> sibling NimbusSession DOs
178
+ * Routing, against the coordinator's Dynamic Worker headroom at call time:
179
+ * tasks.length <= headroom -> coordinator-local IsolatePool, one Dynamic
180
+ * Worker per task, the width claimed on the
181
+ * ledger until the batch settles
182
+ * tasks.length > headroom -> sibling NimbusSession DOs
173
183
  *
174
- * Backpressure: if `tasks.length > MAX_PEER_FANOUT (32)`, tasks
175
- * are sharded modulo `MAX_PEER_FANOUT` and each shard's bucket
176
- * runs serially inside its assigned peer DO via the in-peer
177
- * IsolatePool's concurrency (capped at 4 there too). A
178
- * single submitMany call returns when ALL tasks complete (or any
179
- * throws).
184
+ * Peer shards: tasks hash onto min(tasks, maxPeers ?? MAX_PEER_FANOUT)
185
+ * peers and each peer runs its bucket through its own IsolatePool, as
186
+ * wide as that peer's headroom allows. A single submitMany call returns
187
+ * when ALL tasks complete (or any throws).
180
188
  *
181
189
  * `fn` is the user function executed per task. It runs INSIDE a
182
190
  * Worker Loader isolate (in the in-DO path) or inside a peer DO's
@@ -185,8 +193,8 @@ export declare class Fanout {
185
193
  * the vendored serializeFunction (same as IsolatePool#prepare).
186
194
  */
187
195
  submitMany<A, R>(tasks: FanoutTask<A>[], fn: FacetTaskFn<A, R>): Promise<R[]>;
188
- /** Report which topology a task count uses without dispatching. */
189
- topologyFor(taskCount: number): 'in-do' | 'peer-do' | 'empty';
196
+ /** The topology a task count would take against the headroom right now. */
197
+ topologyFor(taskCount: number): FanoutTopology | 'empty';
190
198
  /**
191
199
  * Compute the deterministic peer-DO id for a task key and peer count.
192
200
  *
@@ -1 +1 @@
1
- {"version":3,"file":"fanout.d.ts","sourceRoot":"","sources":["../src/fanout.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAIH,OAAO,EAAe,KAAK,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAIlE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAOtD;;+EAE+E;AAC/E,MAAM,WAAW,SAAS;IACxB,MAAM,CAAC,EAAE,YAAY,CAAC;IACtB,cAAc,CAAC,EAAE,OAAO,CAAC;CAC1B;AAED;;;;;;GAMG;AACH,eAAO,MAAM,eAAe,IAAI,CAAC;AAEjC;;;GAGG;AACH,eAAO,MAAM,eAAe,KAAK,CAAC;AAElC;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,4BAA4B,IAAI,CAAC;AAC9C,eAAO,MAAM,qBAAqB,UAAmB,CAAC;AAEtD;;;;;GAKG;AACH,eAAO,MAAM,wBAAwB,UAAqB,CAAC;AAE3D;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,iBAAiB,IAAI,CAAC;AAEnC,uCAAuC;AACvC,MAAM,WAAW,UAAU,CAAC,CAAC;IAC3B;;;OAGG;IACH,GAAG,EAAE,MAAM,CAAC;IACZ,sCAAsC;IACtC,IAAI,EAAE,CAAC,CAAC;CACT;AAED,8CAA8C;AAC9C,MAAM,WAAW,aAAa;IAC5B;;;;;OAKG;IACH,GAAG,EAAE,MAAM,CAAC;IACZ;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;OAGG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;IAC1C;;;OAGG;IACH,aAAa,CAAC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G,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,CAUrE"}
package/dist/fanout.js CHANGED
@@ -1,33 +1,30 @@
1
1
  /**
2
2
  * Two-tier fan-out primitive for work that must execute in Worker Loader
3
- * facets without tripping workerd's per-DO dynamic-worker ceiling.
3
+ * isolates within the Durable Object's Dynamic Worker budget.
4
4
  *
5
- * A single Durable Object method can drive at most four concurrent
6
- * Worker Loader fetches before extra dispatches serialize or fail. Small
7
- * batches therefore run in the coordinator DO through IsolatePool.
8
- * Wider batches are sharded across sibling NimbusSession DOs, each of
9
- * which owns its own four-loader budget.
5
+ * A Durable Object may have `DO_DYNAMIC_WORKER_LIMIT` distinct Dynamic
6
+ * Workers with in-flight requests, shared across every concurrent request to
7
+ * it (budgets.ts). A batch the coordinator's remaining headroom can hold —
8
+ * the limit less the workers it already has in flight (resident processes,
9
+ * the esbuild facet, a git network op) and other fan-outs' claims — runs in
10
+ * the coordinator through IsolatePool, one Dynamic Worker per task. Only a
11
+ * batch wider than that headroom is sharded across sibling NimbusSession
12
+ * DOs, each of which spends its own budget.
10
13
  *
11
- * Routing is deterministic: each task has a stable key, and the key maps
12
- * to a sibling DO shard. There is no silent fallback to width-1 execution;
13
- * missing LOADER or NIMBUS_SESSION bindings fail loudly so install and
14
- * runtime operations do not appear successful after partial dispatch.
14
+ * Routing is deterministic for a given headroom: each task has a stable key,
15
+ * and the key maps to a sibling DO shard. There is no silent fallback to
16
+ * width-1 execution; missing LOADER or NIMBUS_SESSION bindings fail loudly so
17
+ * install and runtime operations do not appear successful after partial
18
+ * dispatch.
15
19
  */
16
20
  import { serializeFunction } from './vendor/serialize.js';
17
21
  import { BindingError } from './vendor/errors.js';
18
22
  import { IsolatePool } from './isolate-pool.js';
23
+ import { claimDynamicWorkers, dynamicWorkerHeadroom } from './budgets.js';
19
24
  import { hostRoute } from './composition.js';
20
25
  import { disposeRpcResource } from '@nimbus-sh/platform/rpc-dispose.js';
21
26
  import { classifyDoCall, describeError, isRetryableDoCall } from '@nimbus-sh/platform/oom-classify.js';
22
27
  import { hostNamespaceBinding, hostOpDispatch, } from './host-dispatch.js';
23
- /**
24
- * Threshold at which routing switches from coordinator-local loaders to
25
- * sibling Durable Objects.
26
- *
27
- * Set to **5** so the in-DO path stays below the V8 4-loaders-per-method
28
- * cap by construction. width < 5 stays local; width >= 5 uses sibling DOs.
29
- */
30
- export const IN_DO_THRESHOLD = 5;
31
28
  /**
32
29
  * Hard cap on concurrent peer DOs per single submitMany call. Throughput stays
33
30
  * flat through this width while keeping per-request scheduler pressure bounded.
@@ -78,7 +75,7 @@ function isPeerResult(value) {
78
75
  }
79
76
  /**
80
77
  * Two-tier fan-out pool. Constructed by the supervisor DO; routes
81
- * each `submitMany` call automatically based on width.
78
+ * each `submitMany` call on the coordinator's live Dynamic Worker headroom.
82
79
  *
83
80
  * Lifetime: cheap to construct (no async init). Multiple submitMany
84
81
  * calls share NO state — each is dispatched fresh. The class
@@ -112,16 +109,16 @@ export class Fanout {
112
109
  * Dispatch `tasks` across the appropriate topology and return
113
110
  * results in input order.
114
111
  *
115
- * Routing:
116
- * tasks.length < 5 -> coordinator-local IsolatePool
117
- * tasks.length >= 5 -> sibling NimbusSession DOs
112
+ * Routing, against the coordinator's Dynamic Worker headroom at call time:
113
+ * tasks.length <= headroom -> coordinator-local IsolatePool, one Dynamic
114
+ * Worker per task, the width claimed on the
115
+ * ledger until the batch settles
116
+ * tasks.length > headroom -> sibling NimbusSession DOs
118
117
  *
119
- * Backpressure: if `tasks.length > MAX_PEER_FANOUT (32)`, tasks
120
- * are sharded modulo `MAX_PEER_FANOUT` and each shard's bucket
121
- * runs serially inside its assigned peer DO via the in-peer
122
- * IsolatePool's concurrency (capped at 4 there too). A
123
- * single submitMany call returns when ALL tasks complete (or any
124
- * throws).
118
+ * Peer shards: tasks hash onto min(tasks, maxPeers ?? MAX_PEER_FANOUT)
119
+ * peers and each peer runs its bucket through its own IsolatePool, as
120
+ * wide as that peer's headroom allows. A single submitMany call returns
121
+ * when ALL tasks complete (or any throws).
125
122
  *
126
123
  * `fn` is the user function executed per task. It runs INSIDE a
127
124
  * Worker Loader isolate (in the in-DO path) or inside a peer DO's
@@ -132,16 +129,23 @@ export class Fanout {
132
129
  async submitMany(tasks, fn) {
133
130
  if (tasks.length === 0)
134
131
  return [];
135
- if (tasks.length < IN_DO_THRESHOLD) {
136
- return this._dispatchInDo(tasks, fn);
132
+ const headroom = dynamicWorkerHeadroom(this.ctx);
133
+ const claim = claimDynamicWorkers(this.ctx, tasks.length);
134
+ this.opts.onRoute?.({ topology: claim ? 'in-do' : 'peer-do', tasks: tasks.length, headroom });
135
+ if (!claim)
136
+ return this._dispatchPeerDo(tasks, fn);
137
+ try {
138
+ return await this._dispatchInDo(tasks, fn, claim);
139
+ }
140
+ finally {
141
+ claim.release();
137
142
  }
138
- return this._dispatchPeerDo(tasks, fn);
139
143
  }
140
- /** Report which topology a task count uses without dispatching. */
144
+ /** The topology a task count would take against the headroom right now. */
141
145
  topologyFor(taskCount) {
142
146
  if (taskCount === 0)
143
147
  return 'empty';
144
- return taskCount < IN_DO_THRESHOLD ? 'in-do' : 'peer-do';
148
+ return taskCount <= dynamicWorkerHeadroom(this.ctx) ? 'in-do' : 'peer-do';
145
149
  }
146
150
  /**
147
151
  * Compute the deterministic peer-DO id for a task key and peer count.
@@ -155,14 +159,12 @@ export class Fanout {
155
159
  return `nbf:${this.opts.tag}:${this.coordDoIdShort}:${shard}`;
156
160
  }
157
161
  // ── Private: in-DO dispatch (in-DO fanout) ──────────────────────────────
158
- async _dispatchInDo(tasks, fn) {
159
- // Use the existing IsolatePool. Concurrency = task count
160
- // (capped at 4 by constructor — tasks.length is already < 5
161
- // here, so the cap won't bite). Each task = one pool.submit;
162
- // pool.map runs them with stable-slot reuse.
163
- const concurrency = Math.min(tasks.length, IN_DO_THRESHOLD - 1);
162
+ async _dispatchInDo(tasks, fn, claim) {
163
+ // One slot — one Dynamic Worker — per task; submitMany has claimed
164
+ // that width on the ledger, and the pool's dispatches are held inside it.
164
165
  const pool = new IsolatePool(this.env, this.ctx, {
165
- concurrency,
166
+ concurrency: tasks.length,
167
+ claim,
166
168
  timeoutMs: this.opts.timeoutMs,
167
169
  tag: this.opts.tag,
168
170
  preamble: this.opts.preamble,
@@ -172,9 +174,6 @@ export class Fanout {
172
174
  supervisorPid: this.opts.supervisorPid,
173
175
  });
174
176
  try {
175
- // pool.map runs the function over `items` with concurrency-bounded
176
- // slot reuse. Each slot is one warm loader isolate; we get exactly
177
- // `concurrency` loader isolates total — well under the 4-cap.
178
177
  const items = tasks.map((t) => t.args);
179
178
  const results = await pool.map(fn, items);
180
179
  // pool.map returns Array<R | null> (null on per-item failure with
@@ -200,10 +199,9 @@ export class Fanout {
200
199
  // loader isolates (keyed on fnHash) reuse across calls with
201
200
  // identical fns.
202
201
  const fnSource = serializeFunction(fn);
203
- // Cap peer count at MAX_PEER_FANOUT. Tasks beyond N=32 are
204
- // bucketed into existing shards — each shard's peer DO then
205
- // runs its bucket through its in-DO IsolatePool.map
206
- // (concurrency capped at 4 there).
202
+ // Cap peer count at maxPeers (default MAX_PEER_FANOUT). Tasks beyond
203
+ // it bucket into existing shards; each peer runs its bucket through
204
+ // its own IsolatePool, as wide as its own headroom allows.
207
205
  const peerCount = Math.min(tasks.length, this.opts.maxPeers ?? MAX_PEER_FANOUT);
208
206
  // Group tasks by deterministic shard. Same key → same shard, so
209
207
  // tests can predict which peer handles which task.
@@ -242,10 +240,9 @@ export class Fanout {
242
240
  const peerStub = ns.get(id);
243
241
  try {
244
242
  const dispatch = hostOpDispatch(peerStub, `Fanout peer ${siblingName}`);
245
- // Each peer DO RPC call uses ONE LOADER worker on its side.
246
- // Supervisor → peer DO is a stub.fetch / RPC method call,
247
- // NOT an env.LOADER.get(); that's the cap-sidestep that
248
- // makes peer-DO fanout work.
243
+ // A peer DO call is a Durable Object RPC, not a Dynamic Worker:
244
+ // it spends none of this coordinator's budget, and the peer
245
+ // spends its own.
249
246
  const rpcResp = await dispatch({
250
247
  op: 'fanoutExecute',
251
248
  args: [
@@ -195,9 +195,9 @@ export declare class FencedWork<R extends FencedWorkRecord> {
195
195
  * Runs once per instance — re-calls in the same instance are no-ops — and
196
196
  * re-drives every row whose pid is `> 0` and at or below `generationBase()`
197
197
  * with `attempt < FENCED_WORK_MAX_ATTEMPT`; the rest are abandoned. What the
198
- * re-drive resolver receives is the journalled recipe and nothing else:
199
- * env and credentials are never written to storage, so the resolver's
200
- * embedder re-resolves them rather than reading them back.
198
+ * re-drive resolver receives is the journalled record and nothing else: a
199
+ * host keeps env and secrets out of it, so the resolver's embedder
200
+ * re-resolves them rather than reading them back.
201
201
  */
202
202
  recoverInterrupted(): Promise<void>;
203
203
  /**
@@ -183,9 +183,9 @@ export class FencedWork {
183
183
  * Runs once per instance — re-calls in the same instance are no-ops — and
184
184
  * re-drives every row whose pid is `> 0` and at or below `generationBase()`
185
185
  * with `attempt < FENCED_WORK_MAX_ATTEMPT`; the rest are abandoned. What the
186
- * re-drive resolver receives is the journalled recipe and nothing else:
187
- * env and credentials are never written to storage, so the resolver's
188
- * embedder re-resolves them rather than reading them back.
186
+ * re-drive resolver receives is the journalled record and nothing else: a
187
+ * host keeps env and secrets out of it, so the resolver's embedder
188
+ * re-resolves them rather than reading them back.
189
189
  */
190
190
  async recoverInterrupted() {
191
191
  if (this.recovered)
@@ -0,0 +1,29 @@
1
+ /**
2
+ * host-wasm.ts — what the fabric knows about a WebAssembly.Module a host
3
+ * hands a dynamic worker already compiled.
4
+ *
5
+ * workerd accepts a compiled module in a Worker Loader module map and lets
6
+ * the dynamic worker share its compiled code (src/workerd/api/
7
+ * worker-loader.c++, extractWasmModuleContent), so a host that bundles a
8
+ * fixed wasm (esbuild's, say) hands that module over instead of fetching a
9
+ * second copy of the bytes and having the guest compile them again. Two
10
+ * things the fabric needs about a member are unreadable from JS for a
11
+ * Module:
12
+ * - its size: the module's wire bytes still count toward the 64 MiB
13
+ * dynamic-worker code limit (worker-loader.c++ sums every member), and
14
+ * assertModuleMapWithinCodeLimit must count them;
15
+ * - its identity: a pool folds its wasm into the loader cache key, and a
16
+ * Module has no bytes to fingerprint.
17
+ * The host that owns the module states both once, here.
18
+ */
19
+ export interface HostWasmIdentity {
20
+ /** A stable name for the module's content, e.g. `esbuild@0.24.2`. */
21
+ readonly id: string;
22
+ /** The module's wire bytes: what it costs the dynamic-worker code budget. */
23
+ readonly bytes: number;
24
+ }
25
+ /** Record what `module` is, and return it. */
26
+ export declare function describeHostWasm(module: WebAssembly.Module, identity: HostWasmIdentity): WebAssembly.Module;
27
+ /** What a host said `module` is, or undefined for a module nobody described. */
28
+ export declare function hostWasmIdentity(module: WebAssembly.Module): HostWasmIdentity | undefined;
29
+ //# sourceMappingURL=host-wasm.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host-wasm.d.ts","sourceRoot":"","sources":["../src/host-wasm.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,MAAM,WAAW,gBAAgB;IAC/B,qEAAqE;IACrE,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,6EAA6E;IAC7E,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;CACxB;AAID,8CAA8C;AAC9C,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,WAAW,CAAC,MAAM,EAAE,QAAQ,EAAE,gBAAgB,GAAG,WAAW,CAAC,MAAM,CAM3G;AAED,gFAAgF;AAChF,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,WAAW,CAAC,MAAM,GAAG,gBAAgB,GAAG,SAAS,CAEzF"}
@@ -0,0 +1,31 @@
1
+ /**
2
+ * host-wasm.ts — what the fabric knows about a WebAssembly.Module a host
3
+ * hands a dynamic worker already compiled.
4
+ *
5
+ * workerd accepts a compiled module in a Worker Loader module map and lets
6
+ * the dynamic worker share its compiled code (src/workerd/api/
7
+ * worker-loader.c++, extractWasmModuleContent), so a host that bundles a
8
+ * fixed wasm (esbuild's, say) hands that module over instead of fetching a
9
+ * second copy of the bytes and having the guest compile them again. Two
10
+ * things the fabric needs about a member are unreadable from JS for a
11
+ * Module:
12
+ * - its size: the module's wire bytes still count toward the 64 MiB
13
+ * dynamic-worker code limit (worker-loader.c++ sums every member), and
14
+ * assertModuleMapWithinCodeLimit must count them;
15
+ * - its identity: a pool folds its wasm into the loader cache key, and a
16
+ * Module has no bytes to fingerprint.
17
+ * The host that owns the module states both once, here.
18
+ */
19
+ const described = new WeakMap();
20
+ /** Record what `module` is, and return it. */
21
+ export function describeHostWasm(module, identity) {
22
+ if (!Number.isSafeInteger(identity.bytes) || identity.bytes <= 0) {
23
+ throw new RangeError(`describeHostWasm: '${identity.id}' needs its wire size in bytes, got ${identity.bytes}`);
24
+ }
25
+ described.set(module, identity);
26
+ return module;
27
+ }
28
+ /** What a host said `module` is, or undefined for a module nobody described. */
29
+ export function hostWasmIdentity(module) {
30
+ return described.get(module);
31
+ }
@@ -105,7 +105,7 @@ export declare class ImageStore {
105
105
  * Writing the sources here, once, is what lets the session stop holding
106
106
  * them: after this returns, the only thing it keeps is a path.
107
107
  */
108
- materialize(pid: number, images: AsyncIterable<readonly [string, string]> | Iterable<readonly [string, string]>, pacer: TurnBudget): Promise<Record<string, string>>;
108
+ materialize(pid: number, images: AsyncIterable<readonly [string, string | readonly string[]]> | Iterable<readonly [string, string | readonly string[]]>, pacer: TurnBudget): Promise<Record<string, string>>;
109
109
  /**
110
110
  * Drop every image no running process boots from.
111
111
  *
@@ -1 +1 @@
1
- {"version":3,"file":"image-store.d.ts","sourceRoot":"","sources":["../src/image-store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAIH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEnD;;;;;;;;;GASG;AACH,eAAO,MAAM,6BAA6B,QAA0D,CAAC;AAErG;;;;;GAKG;AACH,MAAM,WAAW,cAAc;IAC7B,iEAAiE;IACjE,MAAM,CAAC,GAAG,E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,CAAC,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,MAAM,EAAE,CAAC,CAAC,EAC9H,KAAK,EAAE,UAAU,GAChB,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAuDlC;;;;;;;;;;OAUG;IACH,OAAO,CAAC,KAAK;CAgBd"}
@@ -111,7 +111,7 @@ export class ImageStore {
111
111
  fs.mkdirp(FACET_IMAGE_DIR);
112
112
  let count = 0;
113
113
  for await (const [moduleName, source] of images) {
114
- const bytes = new TextEncoder().encode(source);
114
+ const bytes = typeof source === 'string' ? new TextEncoder().encode(source) : encodeParts(source);
115
115
  const path = facetImagePath(await facetImageDigest(bytes));
116
116
  paths[moduleName] = path;
117
117
  rooted.push(path);
@@ -190,3 +190,35 @@ export class ImageStore {
190
190
  }
191
191
  }
192
192
  }
193
+ /**
194
+ * UTF-8 bytes of an image given as ordered parts, encoded into one buffer a
195
+ * part at a time: joining the parts first would hold the whole image twice as
196
+ * text.
197
+ */
198
+ function encodeParts(parts) {
199
+ let length = 0;
200
+ for (const part of parts) {
201
+ for (let i = 0; i < part.length; i++) {
202
+ const code = part.charCodeAt(i);
203
+ if (code < 0x80)
204
+ length += 1;
205
+ else if (code < 0x800)
206
+ length += 2;
207
+ else if (code >= 0xd800 && code <= 0xdbff && (part.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {
208
+ length += 4;
209
+ i++;
210
+ }
211
+ else
212
+ length += 3;
213
+ }
214
+ }
215
+ const bytes = new Uint8Array(length);
216
+ const encoder = new TextEncoder();
217
+ let offset = 0;
218
+ for (const part of parts) {
219
+ const encoded = encoder.encode(part);
220
+ bytes.set(encoded, offset);
221
+ offset += encoded.byteLength;
222
+ }
223
+ return bytes;
224
+ }