eutaxy 0.15.1 → 0.16.1

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 (34) hide show
  1. package/README.md +6 -6
  2. package/dist/aws.d.mts +2 -2
  3. package/dist/aws.d.mts.map +1 -1
  4. package/dist/aws.mjs +53 -79
  5. package/dist/aws.mjs.map +1 -1
  6. package/dist/bin.mjs +1 -1
  7. package/dist/{cli-DT4lxaPK.mjs → cli-KACykdzJ.mjs} +206 -169
  8. package/dist/cli-KACykdzJ.mjs.map +1 -0
  9. package/dist/cli.mjs +1 -1
  10. package/dist/cloudflare.d.mts +9 -7
  11. package/dist/cloudflare.d.mts.map +1 -1
  12. package/dist/cloudflare.mjs +2 -2
  13. package/dist/{delivery-invariants-DzMy3iPs.d.mts → delivery-invariants-B8ZZnCZg.d.mts} +2 -2
  14. package/dist/{delivery-invariants-DzMy3iPs.d.mts.map → delivery-invariants-B8ZZnCZg.d.mts.map} +1 -1
  15. package/dist/delivery-invariants-BfRnb9yR.mjs +44 -0
  16. package/dist/delivery-invariants-BfRnb9yR.mjs.map +1 -0
  17. package/dist/{explore-B52m-wmk.d.mts → explore-DlwIUowm.d.mts} +2 -2
  18. package/dist/{explore-B52m-wmk.d.mts.map → explore-DlwIUowm.d.mts.map} +1 -1
  19. package/dist/index.d.mts +2 -2
  20. package/dist/index.mjs +2 -2
  21. package/dist/{platform-Ba1Kvdza.d.mts → platform-DPJTjpSr.d.mts} +56 -4
  22. package/dist/{platform-Ba1Kvdza.d.mts.map → platform-DPJTjpSr.d.mts.map} +1 -1
  23. package/dist/{src-wa0JZa-T.mjs → src-DWRaG5aV.mjs} +2 -2
  24. package/dist/{src-wa0JZa-T.mjs.map → src-DWRaG5aV.mjs.map} +1 -1
  25. package/dist/{src-CPuihHZh.mjs → src-dkn6Illb.mjs} +1145 -165
  26. package/dist/src-dkn6Illb.mjs.map +1 -0
  27. package/dist/{workerd-DvhVDnQW.mjs → workerd-9Tt0BV-3.mjs} +848 -673
  28. package/dist/workerd-9Tt0BV-3.mjs.map +1 -0
  29. package/package.json +1 -1
  30. package/dist/cli-DT4lxaPK.mjs.map +0 -1
  31. package/dist/delivery-invariants-Dr658H1W.mjs +0 -67
  32. package/dist/delivery-invariants-Dr658H1W.mjs.map +0 -1
  33. package/dist/src-CPuihHZh.mjs.map +0 -1
  34. package/dist/workerd-DvhVDnQW.mjs.map +0 -1
@@ -1,6 +1,6 @@
1
- import { A as readFaults, E as validateScenario, I as getPath, L as canonicalJson, S as virtualEpoch, T as defaultBounds, _ as toResponse, a as explore, b as realTick, c as hostInvocation, d as InjectedEffectError, f as findResponse, g as replyOf, h as parseBody, i as proxiedSide, j as writeFaults, k as decisionFaults, l as runInvocation, m as isRedirect, n as DifferentialStuck, p as installScriptedFetch, r as compareSides, t as observeCore, u as CrashSignal, v as withoutNetwork, w as toJson, x as settleOn, y as patchGlobals } from "./src-CPuihHZh.mjs";
2
- import { a as redelivery, i as invocationOf, n as atLeastOncePerMessage$1 } from "./delivery-invariants-Dr658H1W.mjs";
3
- import { c as checkSpecModule, s as emitRegressionTest, t as renderJson, y as describeVerdict } from "./src-wa0JZa-T.mjs";
1
+ import { A as writeFaults, C as toJson, F as getPath, I as invocationOf, L as redelivery, O as decisionFaults, R as canonicalJson, T as validateScenario, _ as replyOf, a as explore, b as realTick, c as decide, d as runInvocation, f as CrashSignal, g as parseBody, h as isRedirect, i as rawRun, k as readFaults, l as hostInvocation, m as findResponse, n as compareSides, p as InjectedEffectError, r as proxiedSide, t as observeCore, u as note, v as toResponse, w as defaultBounds, x as virtualEpoch, y as withoutNetwork } from "./src-dkn6Illb.mjs";
2
+ import { n as atLeastOncePerMessage$1 } from "./delivery-invariants-BfRnb9yR.mjs";
3
+ import { c as checkSpecModule, s as emitRegressionTest, t as renderJson, y as describeVerdict } from "./src-DWRaG5aV.mjs";
4
4
  // packages/cli/src/regression.ts
5
5
  /**
6
6
  * Identifiers for binding names: a qualified name (`orders/DB`) becomes
@@ -105,13 +105,13 @@ function executionContext(background, failures, props = {}) {
105
105
  async function drainBackground(hooks, inv, invocation, target, background) {
106
106
  if (background.length === 0 || inv.isCrashed()) return false;
107
107
  try {
108
- hooks.effectSync({
108
+ note(hooks, {
109
109
  invocation,
110
110
  target,
111
111
  op: "background",
112
112
  args: { pending: background.length },
113
113
  allowed: CUT_OFF
114
- }, () => null, () => null);
114
+ });
115
115
  await Promise.race([hooks.settle(Promise.all(background), invocation), inv.crashed]);
116
116
  return inv.isCrashed();
117
117
  } catch (err) {
@@ -119,6 +119,303 @@ async function drainBackground(hooks, inv, invocation, target, background) {
119
119
  return true;
120
120
  }
121
121
  }
122
+ // packages/cloudflare/src/proxy-context.ts
123
+ /** The effect point of a proxied call: the invocation running now, the binding's target, the call. */
124
+ function pointAt(ctx, target, op, args, allowed) {
125
+ return {
126
+ invocation: ctx.currentInvocation(),
127
+ target,
128
+ op,
129
+ args,
130
+ allowed
131
+ };
132
+ }
133
+ /** Report why the run cannot be trusted and refuse the call with the same reason. */
134
+ function refuse(ctx, reason) {
135
+ ctx.hooks.unsupported(reason);
136
+ throw new Error(`eutaxy: ${reason}`);
137
+ }
138
+ // packages/cloudflare/src/services.ts
139
+ /**
140
+ * Service bindings with the callee scripted. A Worker reaches a peer through
141
+ * `env.BINDING`, by RPC method or by `fetch()`; Cloudflare routes the call on
142
+ * the same thread and retries nothing (Workers, service bindings). The real
143
+ * binding is never called here: the scenario's `service()` setup scripts the
144
+ * replies, and each call is one effect with the faults of a Durable Object
145
+ * stub call, where `crash_before` and `error` mean the call never reached
146
+ * the callee, `ambiguous` that it acted and the answer was lost, and
147
+ * `crash_after` that the caller died after it. The stub itself (callable
148
+ * methods, awaited properties, `fetch`, the pipelining guards) is shared
149
+ * with the callee that runs for real (`callees.ts`).
150
+ */
151
+ /** Marks of the other kinds of binding, which a service binding's duck type must not carry. */
152
+ const otherKinds = [
153
+ "prepare",
154
+ "idFromName",
155
+ "head",
156
+ "createBatch"
157
+ ];
158
+ /**
159
+ * Whether an env value is a service binding (the runtime's `Fetcher`). In
160
+ * workerd it is an RPC stub whose every property read yields a callable, so
161
+ * duck typing alone would take it for any other kind: the runtime's class is
162
+ * checked first, and the duck type (fetch and connect, none of the other
163
+ * kinds' marks) serves test doubles.
164
+ */
165
+ function isServiceBinding(value) {
166
+ if (typeof value !== "object" || value === null) return false;
167
+ const fetcher = globalThis.Fetcher;
168
+ if (typeof fetcher === "function" && value instanceof fetcher) return true;
169
+ if ((Object.getPrototypeOf(value)?.constructor)?.name === "Fetcher") return true;
170
+ const v = value;
171
+ return typeof v["fetch"] === "function" && typeof v["connect"] === "function" && otherKinds.every((k) => typeof v[k] !== "function");
172
+ }
173
+ /** The built-in error classes RPC carries across as themselves (workerd keeps the type). */
174
+ const builtInErrors = {
175
+ Error,
176
+ EvalError,
177
+ RangeError,
178
+ ReferenceError,
179
+ SyntaxError,
180
+ TypeError,
181
+ URIError
182
+ };
183
+ /**
184
+ * The error the caller sees for a `throws` reply, `"<Name>: <message>"`: a
185
+ * built-in error class is that class, so `instanceof` holds as it does over
186
+ * RPC; any other name is an `Error` carrying the name.
187
+ */
188
+ function scriptedError(spec) {
189
+ const at = spec.indexOf(": ");
190
+ if (at < 0) return new Error(spec);
191
+ const name = spec.slice(0, at);
192
+ const message = spec.slice(at + 2);
193
+ const builtIn = builtInErrors[name];
194
+ if (builtIn) return new builtIn(message);
195
+ const error = new Error(message);
196
+ error.name = name;
197
+ return error;
198
+ }
199
+ /** Read a request for the log without consuming it: the callee may still read the body. */
200
+ async function recordRequest(request) {
201
+ const method = request.method.toUpperCase();
202
+ const headers = {};
203
+ request.headers.forEach((value, name) => {
204
+ headers[name.toLowerCase()] = value;
205
+ });
206
+ const body = parseBody(await request.clone().text());
207
+ return {
208
+ url: request.url,
209
+ method,
210
+ headers,
211
+ body
212
+ };
213
+ }
214
+ /**
215
+ * The stub a Worker sees under a service binding's name: methods callable
216
+ * and awaitable, `fetch`, and the guards against what is not modelled
217
+ * (promise pipelining, `connect()`), with the answers supplied.
218
+ */
219
+ function serviceStub(binding, ctx, answers) {
220
+ const unsupported = (what) => refuse(ctx, `service binding ${binding}: ${what}`);
221
+ /**
222
+ * The promise a call returns. On the real stub it is an RPC promise that
223
+ * pipelines property reads (`stub.charge().id`); this one is not, so a read
224
+ * on it makes the run UNSUPPORTED instead of yielding undefined.
225
+ */
226
+ const pipelineGuard = (promise, method) => new Proxy(promise, { get(target, prop) {
227
+ if (typeof prop === "symbol" || prop === "then" || prop === "catch" || prop === "finally") {
228
+ const value = Reflect.get(target, prop, target);
229
+ return typeof value === "function" ? value.bind(target) : value;
230
+ }
231
+ ctx.hooks.unsupported(`service binding ${binding}: RPC promise pipelining (reading .${prop} on ${method}()'s promise) is not supported; await the call first`);
232
+ } });
233
+ /** One call: `stub.method(...)`, or `await stub.property` (an RPC getter). */
234
+ const call = (method) => {
235
+ const invoke = (...args) => pipelineGuard(answers.call(method, args), method);
236
+ const awaitable = (onFulfilled, onRejected) => answers.property(method).then(onFulfilled, onRejected);
237
+ return new Proxy(invoke, { get(fn, key) {
238
+ if (key === "then") return awaitable;
239
+ if (typeof key === "symbol") return Reflect.get(fn, key);
240
+ ctx.hooks.unsupported(`service binding ${binding}: RPC promise pipelining (reading .${method}.${key}) is not supported; await .${method} first`);
241
+ } });
242
+ };
243
+ const fetchThrough = async (input, init) => answers.fetch(new Request(input, init));
244
+ return new Proxy({}, { get(_stub, prop) {
245
+ if (prop === "then" || typeof prop === "symbol") return void 0;
246
+ if (prop === "fetch") return fetchThrough;
247
+ if (prop === "connect") return () => unsupported("connect() (a raw TCP socket) is not modelled");
248
+ return call(prop);
249
+ } });
250
+ }
251
+ /** The scripted stub a Worker sees under a service binding's name. */
252
+ function proxyService(binding, ctx, script) {
253
+ const target = `Service:${binding}`;
254
+ const point = (op, args) => pointAt(ctx, target, op, args, writeFaults);
255
+ const unsupported = (what) => refuse(ctx, `service binding ${binding}: ${what}`);
256
+ /** The scripted reply to a method, by name; a method the script lacks cannot be answered. */
257
+ const replyTo = (method) => {
258
+ if (script.methods === void 0) return { returns: null };
259
+ if (!Object.hasOwn(script.methods, method)) return unsupported(`no scripted reply for method ${method}; add it to the service(${JSON.stringify(binding)}) setup's methods`);
260
+ return script.methods[method];
261
+ };
262
+ const answer = (method) => {
263
+ const reply = replyTo(method);
264
+ if ("throws" in reply) throw scriptedError(reply.throws);
265
+ return structuredClone(reply.returns);
266
+ };
267
+ const summarize = (value) => ({ value: toJson(value) });
268
+ return serviceStub(binding, ctx, {
269
+ call: (method, args) => ctx.hooks.effect(point(method, { args: args.map((a) => toJson(a)) }), async () => answer(method), summarize),
270
+ property: (method) => ctx.hooks.effect(point(method, { property: true }), async () => answer(method), summarize),
271
+ async fetch(request) {
272
+ const url = new URL(request.url);
273
+ const { method, headers, body } = await recordRequest(request);
274
+ const reply = await ctx.hooks.effect(point(method, {
275
+ url: request.url,
276
+ method,
277
+ headers,
278
+ body
279
+ }), async () => {
280
+ const found = findResponse({
281
+ name: binding,
282
+ host: url.host,
283
+ guarantees: {},
284
+ ...script.fetch === void 0 ? {} : { responses: script.fetch }
285
+ }, method, url.pathname);
286
+ if (found === void 0) return unsupported(`no scripted reply for fetch ${method} ${url.pathname}; add it to the service(${JSON.stringify(binding)}) setup's fetch`);
287
+ const reply = replyOf(found);
288
+ if (isRedirect(reply.status) && request.redirect !== "manual") return unsupported(`the scripted reply to ${method} ${url.pathname} is a ${reply.status} redirect, which the runtime would follow; script the final reply or fetch with redirect: "manual"`);
289
+ return reply;
290
+ }, (r) => ({ status: r.status }));
291
+ return toResponse(reply);
292
+ }
293
+ });
294
+ }
295
+ // packages/cloudflare/src/object-access.ts
296
+ /** The host an object's code runs as (`EffectOptions.host`): its namespace's target and its name. */
297
+ function hostOf(target, object) {
298
+ return `${target}/${object}`;
299
+ }
300
+ /** Where a class's `method` is defined along `instance`'s prototype chain. */
301
+ function owner(instance, method) {
302
+ for (let o = instance; o !== null; o = Object.getPrototypeOf(o)) if (Object.hasOwn(o, method)) return o;
303
+ }
304
+ /** The host each instance's code runs as, set each time a call enters it. */
305
+ const hostOfInstance = /* @__PURE__ */ new WeakMap();
306
+ const hostingWrappers = /* @__PURE__ */ new WeakSet();
307
+ /**
308
+ * Have the object's `method` run as the host's code (`RunHooks.hostedCode`)
309
+ * when the runtime calls it next: the runtime carries no async context into
310
+ * an object's code, so the method is wrapped where its class defines it, and
311
+ * the wrapper looks the instance's host up; code the method spawns and does
312
+ * not await carries the object's identity too.
313
+ */
314
+ function hostMethod(hooks, host, instance, method) {
315
+ if (instance === null || typeof instance !== "object") return;
316
+ hostOfInstance.set(instance, {
317
+ hooks,
318
+ host
319
+ });
320
+ const where = owner(instance, method);
321
+ if (!where) return;
322
+ const descriptor = Object.getOwnPropertyDescriptor(where, method);
323
+ if (!descriptor?.configurable) return;
324
+ const hosted = (original) => function(...args) {
325
+ const of = this !== null && typeof this === "object" ? hostOfInstance.get(this) : void 0;
326
+ const call = () => original.apply(this, args);
327
+ return of ? of.hooks.hostedCode(of.host, call, method) : call();
328
+ };
329
+ if (typeof descriptor.value === "function" && descriptor.writable) {
330
+ if (hostingWrappers.has(descriptor.value)) return;
331
+ const wrapper = hosted(descriptor.value);
332
+ hostingWrappers.add(wrapper);
333
+ Object.defineProperty(where, method, {
334
+ ...descriptor,
335
+ value: wrapper
336
+ });
337
+ } else if (typeof descriptor.get === "function") {
338
+ if (hostingWrappers.has(descriptor.get)) return;
339
+ const wrapper = hosted(descriptor.get);
340
+ hostingWrappers.add(wrapper);
341
+ Object.defineProperty(where, method, {
342
+ ...descriptor,
343
+ get: wrapper
344
+ });
345
+ }
346
+ }
347
+ /** Who each guarded instance is and the run it belongs to, set each time a call enters it. */
348
+ const guardOfInstance = /* @__PURE__ */ new WeakMap();
349
+ /**
350
+ * Keep an object's calls on its own service bindings from passing for the
351
+ * scenario's. The runtime hands an object the Worker's real `env`, where a
352
+ * service binding is never the scenario's script or callee: a call through
353
+ * it would reach whatever the isolate holds under that name and fail or
354
+ * answer outside the simulation, unseen. So the instance's `env` is put
355
+ * behind a view under which every call on a service binding ends the run
356
+ * `UNSUPPORTED` with the reason. Reading the binding does nothing; the
357
+ * object's other bindings are its own to use, unrecorded, as before. An
358
+ * `env` the class keeps elsewhere than `this.env` (a private field, a
359
+ * closure of its constructor) is out of reach.
360
+ */
361
+ function guardEnv(hooks, binding, object, instance) {
362
+ if (instance === null || typeof instance !== "object") return;
363
+ const guarded = guardOfInstance.has(instance);
364
+ guardOfInstance.set(instance, {
365
+ hooks,
366
+ binding,
367
+ object
368
+ });
369
+ if (guarded) return;
370
+ const descriptor = Object.getOwnPropertyDescriptor(instance, "env");
371
+ const env = descriptor?.value;
372
+ if (!descriptor?.writable || env === null || typeof env !== "object") return;
373
+ const refuse = (name) => {
374
+ const of = guardOfInstance.get(instance) ?? {
375
+ hooks,
376
+ binding,
377
+ object
378
+ };
379
+ const reason = `Durable Object ${of.binding} ${of.object} called the service binding ${name} through its own env: an object's own binding calls are outside the simulation, so no service() script or callee() answers them`;
380
+ of.hooks.unsupported(reason);
381
+ throw new Error(`eutaxy: ${reason}`);
382
+ };
383
+ const stubs = /* @__PURE__ */ new Map();
384
+ const stubFor = (name) => {
385
+ let stub = stubs.get(name);
386
+ if (!stub) {
387
+ const refused = Object.assign(async () => refuse(name), { then: (onFulfilled, onRejected) => refused().then(onFulfilled, onRejected) });
388
+ stub = new Proxy({}, { get: (_t, prop) => prop === "then" || typeof prop === "symbol" ? void 0 : refused });
389
+ stubs.set(name, stub);
390
+ }
391
+ return stub;
392
+ };
393
+ instance.env = new Proxy(env, { get(target, prop) {
394
+ const value = Reflect.get(target, prop, target);
395
+ return typeof prop === "string" && isServiceBinding(value) ? stubFor(prop) : value;
396
+ } });
397
+ }
398
+ /**
399
+ * One effect of `inv` performed inside the object `id` of `binding`: `perform`
400
+ * runs as the effect, which hosts what the object does; a fault that
401
+ * abandons it resets the object, and a crash evicts the instance. The
402
+ * invocation's outcome.
403
+ */
404
+ async function hostedInObject(hooks, inv, objects, binding, id, object, point, perform, summarize) {
405
+ const { status } = await runInvocation(hooks, inv, () => hooks.effect({
406
+ ...point,
407
+ hostsEffects: true
408
+ }, perform, summarize, {
409
+ host: hostOf(`DO:${binding}`, object),
410
+ onAbandon: () => objects.abort(binding, id),
411
+ mayPark: () => objects.mayPark(binding, id)
412
+ }));
413
+ if (status === "crashed") {
414
+ await objects.evict(binding, id);
415
+ hooks.hostReset(hostOf(`DO:${binding}`, object));
416
+ }
417
+ return status;
418
+ }
122
419
  // packages/cloudflare/src/alarms.ts
123
420
  /**
124
421
  * Durable Object alarms in virtual time. Eutaxy takes over each object's
@@ -295,6 +592,23 @@ async function takeOverAlarms(storage, alarm) {
295
592
  };
296
593
  }
297
594
  /**
595
+ * Run an object's `alarm()` handler inside it, after taking over its alarms
596
+ * (the instance may be new since the alarm was set).
597
+ */
598
+ async function runAlarm(hooks, d, id, object, info, gen) {
599
+ await d.objects.run(d.binding, id, object, async (instance) => {
600
+ const entry = d.book.entry(id);
601
+ if (entry.gen !== gen) return;
602
+ entry.time = null;
603
+ const handler = instance.alarm;
604
+ if (typeof handler !== "function") {
605
+ hooks.unsupported(`Durable Object ${d.binding} ${object} set an alarm but has no alarm() handler`);
606
+ return;
607
+ }
608
+ await hooks.hostedCode(hostOf(`DO:${d.binding}`, object), () => handler.call(instance, info));
609
+ });
610
+ }
611
+ /**
298
612
  * Fire an alarm event: skip it when the object's alarm has since moved or
299
613
  * been deleted, run `alarm()` as one effect otherwise, and schedule a retry
300
614
  * with backoff when the handler fails, crashes, or a fault says it did.
@@ -330,7 +644,7 @@ async function deliverAlarm(event, hooks, maxRedeliveries, d) {
330
644
  retryCount: a.retryCount,
331
645
  isRetry: a.retryCount > 0
332
646
  };
333
- const { status } = await runInvocation(hooks, inv, () => hooks.effect({
647
+ const status = await hostedInObject(hooks, inv, d.objects, d.binding, a.id, a.object, {
334
648
  invocation,
335
649
  target: `DO:${d.binding}`,
336
650
  op: "alarm",
@@ -338,16 +652,11 @@ async function deliverAlarm(event, hooks, maxRedeliveries, d) {
338
652
  object: a.object,
339
653
  retryCount: a.retryCount
340
654
  },
341
- allowed: readFaults,
342
- hostsEffects: true
655
+ allowed: readFaults
343
656
  }, async () => {
344
- await d.runAlarm(a.id, a.object, info, a.gen);
657
+ await runAlarm(hooks, d, a.id, a.object, info, a.gen);
345
658
  return null;
346
- }, () => null, {
347
- onAbandon: () => d.abort(a.id),
348
- mayPark: () => d.mayPark(a.id)
349
- }));
350
- if (status === "crashed") await d.evict(a.id);
659
+ }, () => null);
351
660
  if (status !== "completed") {
352
661
  const next = redelivery(event, maxRetries, { maxRedeliveries });
353
662
  if (next) {
@@ -546,21 +855,16 @@ function summarize(result) {
546
855
  }
547
856
  function proxyNamespace(real, binding, ctx, state, helpers, isReset) {
548
857
  const target = `DO:${binding}`;
549
- const { names, touched, alarms: book } = state;
858
+ const { names } = state;
550
859
  const nameOf = (id) => names.get(id.toString()) ?? id.toString();
551
860
  function stubFor(stub, id, object) {
552
- /** Make sure the call may reach the object, and take over its alarms first. */
553
- async function reach(real) {
861
+ /** Make sure the call may reach the object, take over its alarms first, and host the method about to run. */
862
+ async function reach(real, method) {
554
863
  if (!helpers) ctx.hooks.unsupported(`Durable Object binding ${binding} needs the Cloudflare test helpers (pass durableObjects to createCloudflarePlatform)`);
555
864
  else if (!isReset()) ctx.hooks.unsupported(`Durable Object binding ${binding} has no durableObject setup, so its objects are not reset between runs; add durableObject(${JSON.stringify(binding)}) to the scenario's setup`);
556
- else {
557
- touched.add(id);
558
- await typed(helpers).runInDurableObject(real, (_instance, live) => {
559
- watchGate(live);
560
- state.states.set(id, live);
561
- return takeOverAlarms(live.storage, alarmControl(book, binding, id, object, () => ctx.hooks));
562
- });
563
- }
865
+ else await enterObject(real, binding, ctx, helpers, state, id, object, async (instance) => {
866
+ if (method !== void 0) hostMethod(ctx.hooks, hostOf(target, object), instance, method);
867
+ });
564
868
  }
565
869
  /** A result passed back to the Worker; one that is not plain data cannot be followed. */
566
870
  function plain(result) {
@@ -591,6 +895,7 @@ function proxyNamespace(real, binding, ctx, state, helpers, isReset) {
591
895
  allowed: writeFaults,
592
896
  hostsEffects: true
593
897
  }, perform, summarize, {
898
+ host: hostOf(target, object),
594
899
  onAbandon: () => state.abort(id),
595
900
  mayPark: () => state.mayPark(id)
596
901
  });
@@ -602,7 +907,7 @@ function proxyNamespace(real, binding, ctx, state, helpers, isReset) {
602
907
  object,
603
908
  args: args.map(argument)
604
909
  }, async () => {
605
- await reach(real);
910
+ await reach(real, prop);
606
911
  const method = real[prop];
607
912
  if (typeof method !== "function") throw new TypeError(`${binding} stub has no ${prop}`);
608
913
  const result = await Reflect.apply(method, real, args);
@@ -619,7 +924,7 @@ function proxyNamespace(real, binding, ctx, state, helpers, isReset) {
619
924
  object,
620
925
  property: true
621
926
  }, async () => {
622
- await reach(real);
927
+ await reach(real, prop);
623
928
  return plain(await real[prop]);
624
929
  });
625
930
  const awaitable = (onFulfilled, onRejected) => read().then(onFulfilled, onRejected);
@@ -677,33 +982,23 @@ async function runInObject(real, binding, ctx, helpers, state, id, object, fn) {
677
982
  ctx.hooks.unsupported(`Durable Object binding ${binding} needs the Cloudflare test helpers`);
678
983
  return;
679
984
  }
985
+ return enterObject(real.get(real.idFromString(id)), binding, ctx, helpers, state, id, object, fn);
986
+ }
987
+ /**
988
+ * Enter an object through a stub for a call or an event of its own: the
989
+ * object is marked reached, its gate watched, its state kept for the run,
990
+ * its alarms taken over, then `fn` runs with the instance and its state.
991
+ */
992
+ function enterObject(stub, binding, ctx, helpers, state, id, object, fn) {
680
993
  state.touched.add(id);
681
- return typed(helpers).runInDurableObject(real.get(real.idFromString(id)), async (instance, live) => {
994
+ return typed(helpers).runInDurableObject(stub, async (instance, live) => {
682
995
  watchGate(live);
683
996
  state.states.set(id, live);
684
997
  await takeOverAlarms(live.storage, alarmControl(state.alarms, binding, id, object, () => ctx.hooks));
998
+ guardEnv(ctx.hooks, binding, object, instance);
685
999
  return fn(instance, live);
686
1000
  });
687
1001
  }
688
- /**
689
- * Run an object's `alarm()` handler inside it, after taking over its alarms
690
- * (the instance may be new since the alarm was set).
691
- */
692
- function alarmRunner(real, binding, ctx, helpers, state) {
693
- return async (id, object, info, gen) => {
694
- await runInObject(real, binding, ctx, helpers, state, id, object, async (instance) => {
695
- const entry = state.alarms.entry(id);
696
- if (entry.gen !== gen) return;
697
- entry.time = null;
698
- const handler = instance.alarm;
699
- if (typeof handler !== "function") {
700
- ctx.hooks.unsupported(`Durable Object ${binding} ${object} set an alarm but has no alarm() handler`);
701
- return;
702
- }
703
- await handler.call(instance, info);
704
- });
705
- };
706
- }
707
1002
  /** The objects to reset: every id the namespace has created, plus the setup's named ones. */
708
1003
  async function objectIds(real, helpers, names, seeded) {
709
1004
  const ids = /* @__PURE__ */ new Map();
@@ -760,12 +1055,12 @@ async function clearAndSeed(real, helpers, names, objects, sql) {
760
1055
  * The tables are the seeded objects and those a call reached, never objects
761
1056
  * only earlier runs created, so a snapshot depends on this run alone.
762
1057
  */
763
- async function snapshotNamespace(real, helpers, names, touched, objects, sql, seededSql, onIndirect, onUnsupported) {
764
- const { value, requested } = await withoutNetwork(() => readTables(real, helpers, names, touched, objects, sql, seededSql, onIndirect, onUnsupported));
1058
+ async function snapshotNamespace(real, helpers, names, touched, objects, sql, seededSql, onIndirect, onUnsupported, all = false) {
1059
+ const { value, requested } = await withoutNetwork(() => readTables(real, helpers, names, touched, objects, sql, seededSql, onIndirect, onUnsupported, all));
765
1060
  if (requested) onUnsupported("a Durable Object made a request while its storage was being snapshotted");
766
1061
  return value;
767
1062
  }
768
- async function readTables(real, helpers, names, touched, objects, sql, seededSql, onIndirect, onUnsupported) {
1063
+ async function readTables(real, helpers, names, touched, objects, sql, seededSql, onIndirect, onUnsupported, all) {
769
1064
  const out = {};
770
1065
  const define = (table, rows) => {
771
1066
  if (Object.hasOwn(out, table)) throw new Error(`snapshot key ${table} named twice`);
@@ -779,15 +1074,16 @@ async function readTables(real, helpers, names, touched, objects, sql, seededSql
779
1074
  const seeded = seededNames(objects, sql);
780
1075
  for (const id of await objectIds(real, helpers, names, seeded)) {
781
1076
  const name = names.get(id.toString()) ?? id.toString();
782
- if (!touched.has(id.toString())) {
1077
+ const read = all || touched.has(id.toString());
1078
+ if (!read) {
783
1079
  if (await typed(helpers).evictDurableObject(real.get(id)).then(() => true, () => false)) onIndirect(name);
784
1080
  if (!seeded.includes(name)) continue;
785
1081
  }
786
1082
  let entries;
787
1083
  const tables = [];
788
- if (touched.has(id.toString())) {
1084
+ if (read) {
789
1085
  const read = await typed(helpers).runInDurableObject(real.get(id), (_instance, state) => {
790
- if (!takenOver.has(state.storage)) onUnsupported(`Durable Object ${name} was reset during the run and reconstructed for the snapshot; its constructor ran outside the simulation`);
1086
+ if (!all && !takenOver.has(state.storage)) onUnsupported(`Durable Object ${name} was reset during the run and reconstructed for the snapshot; its constructor ran outside the simulation`);
791
1087
  const surface = sqlOf(state.storage);
792
1088
  const sqlTables = surface ? readSqlTables(surface) : [];
793
1089
  return Promise.resolve(state.storage.list()).then((kv) => ({
@@ -911,24 +1207,48 @@ function startCaller(event, hooks, spec, policy, target, gaveUp) {
911
1207
  ...next,
912
1208
  ...resendAt > Date.now() ? { at: resendAt } : {}
913
1209
  });
914
- } else hooks.effectSync({
1210
+ } else note(hooks, {
915
1211
  invocation: hooks.bookkeeping(),
916
1212
  target,
917
1213
  op: "gave_up",
918
1214
  args: gaveUp,
919
1215
  allowed: []
920
- }, () => null, () => null);
1216
+ });
921
1217
  };
922
1218
  const deadlineTimer = lateAt === void 0 ? void 0 : setTimeout(() => giveUp(lateAt), deadline);
923
- return {
924
- responseFaults: deadline === void 0 ? RESPOND : RESPOND_WITH_DEADLINE,
925
- isLate: () => lateAt !== void 0 && Date.now() > lateAt,
926
- settle(accepted, late) {
927
- if (deadlineTimer !== void 0) clearTimeout(deadlineTimer);
928
- if (accepted) decided = true;
929
- else giveUp(late && lateAt !== void 0 ? lateAt : Date.now());
930
- }
1219
+ const responseFaults = deadline === void 0 ? RESPOND : RESPOND_WITH_DEADLINE;
1220
+ const isLate = () => lateAt !== void 0 && Date.now() > lateAt;
1221
+ /** The caller decides as soon as it has an answer or gives up, before background work ends. */
1222
+ const settle = (accepted, late) => {
1223
+ if (deadlineTimer !== void 0) clearTimeout(deadlineTimer);
1224
+ if (accepted) decided = true;
1225
+ else giveUp(late && lateAt !== void 0 ? lateAt : Date.now());
931
1226
  };
1227
+ return { respond(invocation, args, answer) {
1228
+ let late = isLate();
1229
+ let accepted = false;
1230
+ let crashed = false;
1231
+ const record = (allowed, value) => {
1232
+ hooks.effectSync({
1233
+ invocation,
1234
+ target,
1235
+ op: "response",
1236
+ args,
1237
+ allowed
1238
+ }, () => value, (v) => v);
1239
+ };
1240
+ if (answer.kind === "answered") try {
1241
+ record(responseFaults, answer.value);
1242
+ accepted = answer.accepted;
1243
+ } catch (err) {
1244
+ if (err instanceof CrashSignal) crashed = true;
1245
+ else if (err instanceof InjectedEffectError) late = true;
1246
+ else throw err;
1247
+ }
1248
+ else if (answer.kind === "errored") record([], answer.value);
1249
+ settle(accepted && !late, late);
1250
+ return crashed;
1251
+ } };
932
1252
  }
933
1253
  // packages/cloudflare/src/cron.ts
934
1254
  const fields = [
@@ -1807,45 +2127,25 @@ async function deliverCall(event, hooks, spec, drive, invocation, cls, env) {
1807
2127
  });
1808
2128
  const ran = await runInvocation(hooks, inv, () => callMethod(cls, call, executionContext(background), env));
1809
2129
  let status = ran.status;
1810
- let late = caller.isLate();
1811
- let answer = null;
2130
+ let answer = { kind: "none" };
1812
2131
  if (ran.status === "completed") {
1813
2132
  if (!isPlainData(ran.value)) hooks.unsupported(`Rpc ${call.method}: the result is not plain data (a stub, a function or a stream); RPC capabilities are not modelled`);
1814
- const s = {
1815
- ok: true,
1816
- value: toJson(ran.value)
2133
+ answer = {
2134
+ kind: "answered",
2135
+ value: {
2136
+ ok: true,
2137
+ value: toJson(ran.value)
2138
+ },
2139
+ accepted: true
1817
2140
  };
1818
- try {
1819
- hooks.effectSync({
1820
- invocation,
1821
- target,
1822
- op: "response",
1823
- args,
1824
- allowed: caller.responseFaults
1825
- }, () => s, (v) => v);
1826
- answer = s;
1827
- } catch (err) {
1828
- if (err instanceof CrashSignal) status = "crashed";
1829
- else if (err instanceof InjectedEffectError) {
1830
- answer = s;
1831
- late = true;
1832
- } else throw err;
1833
- }
1834
- } else if (ran.status === "errored") {
1835
- const s = {
2141
+ } else if (ran.status === "errored") answer = {
2142
+ kind: "errored",
2143
+ value: {
1836
2144
  ok: false,
1837
2145
  error: describeError(ran.error)
1838
- };
1839
- hooks.effectSync({
1840
- invocation,
1841
- target,
1842
- op: "response",
1843
- args,
1844
- allowed: []
1845
- }, () => s, (v) => v);
1846
- answer = s;
1847
- }
1848
- caller.settle(answer !== null && !late && answer.ok, late);
2146
+ }
2147
+ };
2148
+ if (caller.respond(invocation, args, answer)) status = "crashed";
1849
2149
  if (await drainBackground(hooks, inv, invocation, target, background)) status = "crashed";
1850
2150
  return {
1851
2151
  status,
@@ -1854,207 +2154,36 @@ async function deliverCall(event, hooks, spec, drive, invocation, cls, env) {
1854
2154
  }
1855
2155
  /**
1856
2156
  * The class an RPC drive calls: the named export, or the Worker's default
1857
- * export (the class passed as the handler, or `exports.default`). Not
1858
- * necessarily a class: the platform reports what it found instead.
1859
- */
1860
- function entrypointClass(handler, exports, entrypoint) {
1861
- if (entrypoint !== void 0) return exports?.[entrypoint];
1862
- return typeof handler === "function" ? handler : exports?.["default"];
1863
- }
1864
- /**
1865
- * The method RPC exposes under a name: one the class or a superclass defines
1866
- * on its prototype. An instance property, even a function, and Object's own
1867
- * methods are not callable (workerd: "The RPC receiver does not implement the
1868
- * method").
1869
- */
1870
- function rpcMethod(instance, name) {
1871
- for (let proto = Object.getPrototypeOf(instance); proto !== null && proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) {
1872
- const own = Object.getOwnPropertyDescriptor(proto, name);
1873
- if (!own) continue;
1874
- return typeof own.value === "function" && name !== "constructor" ? own.value : void 0;
1875
- }
1876
- }
1877
- /**
1878
- * Construct the entrypoint for one call and invoke the method, as the
1879
- * runtime does per call. The arguments are copied, as RPC copies them: a
1880
- * method that mutates one changes neither the scenario nor a later attempt.
1881
- */
1882
- function callMethod(cls, call, ctx, env) {
1883
- const instance = constructEntrypoint(cls, "WorkerEntrypoint", ctx, env);
1884
- const method = rpcMethod(instance, call.method);
1885
- if (!method) throw new TypeError(`The RPC receiver does not implement the method "${call.method}".`);
1886
- return method.apply(instance, structuredClone(call.args));
1887
- }
1888
- // packages/cloudflare/src/services.ts
1889
- /**
1890
- * Service bindings with the callee scripted. A Worker reaches a peer through
1891
- * `env.BINDING`, by RPC method or by `fetch()`; Cloudflare routes the call on
1892
- * the same thread and retries nothing (Workers, service bindings). The real
1893
- * binding is never called here: the scenario's `service()` setup scripts the
1894
- * replies, and each call is one effect with the faults of a Durable Object
1895
- * stub call, where `crash_before` and `error` mean the call never reached
1896
- * the callee, `ambiguous` that it acted and the answer was lost, and
1897
- * `crash_after` that the caller died after it. The stub itself (callable
1898
- * methods, awaited properties, `fetch`, the pipelining guards) is shared
1899
- * with the callee that runs for real (`callees.ts`).
1900
- */
1901
- /** Marks of the other kinds of binding, which a service binding's duck type must not carry. */
1902
- const otherKinds = [
1903
- "prepare",
1904
- "idFromName",
1905
- "head",
1906
- "createBatch"
1907
- ];
1908
- /**
1909
- * Whether an env value is a service binding (the runtime's `Fetcher`). In
1910
- * workerd it is an RPC stub whose every property read yields a callable, so
1911
- * duck typing alone would take it for any other kind: the runtime's class is
1912
- * checked first, and the duck type (fetch and connect, none of the other
1913
- * kinds' marks) serves test doubles.
1914
- */
1915
- function isServiceBinding(value) {
1916
- if (typeof value !== "object" || value === null) return false;
1917
- const fetcher = globalThis.Fetcher;
1918
- if (typeof fetcher === "function" && value instanceof fetcher) return true;
1919
- if ((Object.getPrototypeOf(value)?.constructor)?.name === "Fetcher") return true;
1920
- const v = value;
1921
- return typeof v["fetch"] === "function" && typeof v["connect"] === "function" && otherKinds.every((k) => typeof v[k] !== "function");
1922
- }
1923
- /** The built-in error classes RPC carries across as themselves (workerd keeps the type). */
1924
- const builtInErrors = {
1925
- Error,
1926
- EvalError,
1927
- RangeError,
1928
- ReferenceError,
1929
- SyntaxError,
1930
- TypeError,
1931
- URIError
1932
- };
1933
- /**
1934
- * The error the caller sees for a `throws` reply, `"<Name>: <message>"`: a
1935
- * built-in error class is that class, so `instanceof` holds as it does over
1936
- * RPC; any other name is an `Error` carrying the name.
1937
- */
1938
- function scriptedError(spec) {
1939
- const at = spec.indexOf(": ");
1940
- if (at < 0) return new Error(spec);
1941
- const name = spec.slice(0, at);
1942
- const message = spec.slice(at + 2);
1943
- const builtIn = builtInErrors[name];
1944
- if (builtIn) return new builtIn(message);
1945
- const error = new Error(message);
1946
- error.name = name;
1947
- return error;
1948
- }
1949
- /** Read a request for the log without consuming it: the callee may still read the body. */
1950
- async function recordRequest(request) {
1951
- const method = request.method.toUpperCase();
1952
- const headers = {};
1953
- request.headers.forEach((value, name) => {
1954
- headers[name.toLowerCase()] = value;
1955
- });
1956
- const body = parseBody(await request.clone().text());
1957
- return {
1958
- url: request.url,
1959
- method,
1960
- headers,
1961
- body
1962
- };
1963
- }
1964
- /**
1965
- * The stub a Worker sees under a service binding's name: methods callable
1966
- * and awaitable, `fetch`, and the guards against what is not modelled
1967
- * (promise pipelining, `connect()`), with the answers supplied.
1968
- */
1969
- function serviceStub(binding, ctx, answers) {
1970
- const unsupported = (what) => {
1971
- const reason = `service binding ${binding}: ${what}`;
1972
- ctx.hooks.unsupported(reason);
1973
- throw new Error(`eutaxy: ${reason}`);
1974
- };
1975
- /**
1976
- * The promise a call returns. On the real stub it is an RPC promise that
1977
- * pipelines property reads (`stub.charge().id`); this one is not, so a read
1978
- * on it makes the run UNSUPPORTED instead of yielding undefined.
1979
- */
1980
- const pipelineGuard = (promise, method) => new Proxy(promise, { get(target, prop) {
1981
- if (typeof prop === "symbol" || prop === "then" || prop === "catch" || prop === "finally") {
1982
- const value = Reflect.get(target, prop, target);
1983
- return typeof value === "function" ? value.bind(target) : value;
1984
- }
1985
- ctx.hooks.unsupported(`service binding ${binding}: RPC promise pipelining (reading .${prop} on ${method}()'s promise) is not supported; await the call first`);
1986
- } });
1987
- /** One call: `stub.method(...)`, or `await stub.property` (an RPC getter). */
1988
- const call = (method) => {
1989
- const invoke = (...args) => pipelineGuard(answers.call(method, args), method);
1990
- const awaitable = (onFulfilled, onRejected) => answers.property(method).then(onFulfilled, onRejected);
1991
- return new Proxy(invoke, { get(fn, key) {
1992
- if (key === "then") return awaitable;
1993
- if (typeof key === "symbol") return Reflect.get(fn, key);
1994
- ctx.hooks.unsupported(`service binding ${binding}: RPC promise pipelining (reading .${method}.${key}) is not supported; await .${method} first`);
1995
- } });
1996
- };
1997
- const fetchThrough = async (input, init) => answers.fetch(new Request(input, init));
1998
- return new Proxy({}, { get(_stub, prop) {
1999
- if (prop === "then" || typeof prop === "symbol") return void 0;
2000
- if (prop === "fetch") return fetchThrough;
2001
- if (prop === "connect") return () => unsupported("connect() (a raw TCP socket) is not modelled");
2002
- return call(prop);
2003
- } });
2004
- }
2005
- /** The scripted stub a Worker sees under a service binding's name. */
2006
- function proxyService(binding, ctx, script) {
2007
- const target = `Service:${binding}`;
2008
- const point = (op, args) => ({
2009
- invocation: ctx.currentInvocation(),
2010
- target,
2011
- op,
2012
- args,
2013
- allowed: writeFaults
2014
- });
2015
- const unsupported = (what) => {
2016
- const reason = `service binding ${binding}: ${what}`;
2017
- ctx.hooks.unsupported(reason);
2018
- throw new Error(`eutaxy: ${reason}`);
2019
- };
2020
- /** The scripted reply to a method, by name; a method the script lacks cannot be answered. */
2021
- const replyTo = (method) => {
2022
- if (script.methods === void 0) return { returns: null };
2023
- if (!Object.hasOwn(script.methods, method)) return unsupported(`no scripted reply for method ${method}; add it to the service(${JSON.stringify(binding)}) setup's methods`);
2024
- return script.methods[method];
2025
- };
2026
- const answer = (method) => {
2027
- const reply = replyTo(method);
2028
- if ("throws" in reply) throw scriptedError(reply.throws);
2029
- return structuredClone(reply.returns);
2030
- };
2031
- const summarize = (value) => ({ value: toJson(value) });
2032
- return serviceStub(binding, ctx, {
2033
- call: (method, args) => ctx.hooks.effect(point(method, { args: args.map((a) => toJson(a)) }), async () => answer(method), summarize),
2034
- property: (method) => ctx.hooks.effect(point(method, { property: true }), async () => answer(method), summarize),
2035
- async fetch(request) {
2036
- const url = new URL(request.url);
2037
- const { method, headers, body } = await recordRequest(request);
2038
- const reply = await ctx.hooks.effect(point(method, {
2039
- url: request.url,
2040
- method,
2041
- headers,
2042
- body
2043
- }), async () => {
2044
- const found = findResponse({
2045
- name: binding,
2046
- host: url.host,
2047
- guarantees: {},
2048
- ...script.fetch === void 0 ? {} : { responses: script.fetch }
2049
- }, method, url.pathname);
2050
- if (found === void 0) return unsupported(`no scripted reply for fetch ${method} ${url.pathname}; add it to the service(${JSON.stringify(binding)}) setup's fetch`);
2051
- const reply = replyOf(found);
2052
- if (isRedirect(reply.status) && request.redirect !== "manual") return unsupported(`the scripted reply to ${method} ${url.pathname} is a ${reply.status} redirect, which the runtime would follow; script the final reply or fetch with redirect: "manual"`);
2053
- return reply;
2054
- }, (r) => ({ status: r.status }));
2055
- return toResponse(reply);
2056
- }
2057
- });
2157
+ * export (the class passed as the handler, or `exports.default`). Not
2158
+ * necessarily a class: the platform reports what it found instead.
2159
+ */
2160
+ function entrypointClass(handler, exports, entrypoint) {
2161
+ if (entrypoint !== void 0) return exports?.[entrypoint];
2162
+ return typeof handler === "function" ? handler : exports?.["default"];
2163
+ }
2164
+ /**
2165
+ * The method RPC exposes under a name: one the class or a superclass defines
2166
+ * on its prototype. An instance property, even a function, and Object's own
2167
+ * methods are not callable (workerd: "The RPC receiver does not implement the
2168
+ * method").
2169
+ */
2170
+ function rpcMethod(instance, name) {
2171
+ for (let proto = Object.getPrototypeOf(instance); proto !== null && proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) {
2172
+ const own = Object.getOwnPropertyDescriptor(proto, name);
2173
+ if (!own) continue;
2174
+ return typeof own.value === "function" && name !== "constructor" ? own.value : void 0;
2175
+ }
2176
+ }
2177
+ /**
2178
+ * Construct the entrypoint for one call and invoke the method, as the
2179
+ * runtime does per call. The arguments are copied, as RPC copies them: a
2180
+ * method that mutates one changes neither the scenario nor a later attempt.
2181
+ */
2182
+ function callMethod(cls, call, ctx, env) {
2183
+ const instance = constructEntrypoint(cls, "WorkerEntrypoint", ctx, env);
2184
+ const method = rpcMethod(instance, call.method);
2185
+ if (!method) throw new TypeError(`The RPC receiver does not implement the method "${call.method}".`);
2186
+ return method.apply(instance, structuredClone(call.args));
2058
2187
  }
2059
2188
  // packages/cloudflare/src/callees.ts
2060
2189
  /**
@@ -2191,18 +2320,8 @@ function proxyCallee(binding, ctx, setup, module, env, state) {
2191
2320
  const view = calleeEnv(module.name, env);
2192
2321
  const entrypointName = setup.entrypoint ?? module.entrypoint;
2193
2322
  const props = module.props ?? {};
2194
- const unsupported = (what) => {
2195
- const reason = `callee ${binding}: ${what}`;
2196
- ctx.hooks.unsupported(reason);
2197
- throw new Error(`eutaxy: ${reason}`);
2198
- };
2199
- const point = (op, args) => ({
2200
- invocation: ctx.currentInvocation(),
2201
- target,
2202
- op,
2203
- args,
2204
- allowed: callFaults
2205
- });
2323
+ const unsupported = (what) => refuse(ctx, `callee ${binding}: ${what}`);
2324
+ const point = (op, args) => pointAt(ctx, target, op, args, callFaults);
2206
2325
  /** The hosted invocation's id: the n-th call of a method from one caller invocation is `#n`. */
2207
2326
  const invocationId = (method) => {
2208
2327
  const key = `${ctx.currentInvocation()}/${binding}.${method}`;
@@ -2325,15 +2444,6 @@ async function expectHolds(spec, platform, options) {
2325
2444
  function isD1(value) {
2326
2445
  return typeof value === "object" && value !== null && typeof value.prepare === "function" && typeof value.batch === "function";
2327
2446
  }
2328
- function point(ctx, target, op, args, allowed) {
2329
- return {
2330
- invocation: ctx.currentInvocation(),
2331
- target,
2332
- op,
2333
- args,
2334
- allowed
2335
- };
2336
- }
2337
2447
  function metaOf(result) {
2338
2448
  return {
2339
2449
  changes: result.meta.changes ?? 0,
@@ -2367,22 +2477,22 @@ var StatementProxy = class StatementProxy {
2367
2477
  return new StatementProxy(this.real.bind(...values), this.target, this.ctx, this.sql, values);
2368
2478
  }
2369
2479
  run() {
2370
- return this.ctx.hooks.effect(point(this.ctx, this.target, "run", this.args(), writeFaults), () => this.real.run(), (r) => metaOf(r));
2480
+ return this.ctx.hooks.effect(pointAt(this.ctx, this.target, "run", this.args(), writeFaults), () => this.real.run(), (r) => metaOf(r));
2371
2481
  }
2372
2482
  all() {
2373
- return this.ctx.hooks.effect(point(this.ctx, this.target, "all", this.args(), readFaults), () => this.real.all(), (r) => ({
2483
+ return this.ctx.hooks.effect(pointAt(this.ctx, this.target, "all", this.args(), readFaults), () => this.real.all(), (r) => ({
2374
2484
  rows: r.results.length,
2375
2485
  changes: r.meta.changes ?? 0
2376
2486
  }));
2377
2487
  }
2378
2488
  first(colName) {
2379
- return this.ctx.hooks.effect(point(this.ctx, this.target, "first", {
2489
+ return this.ctx.hooks.effect(pointAt(this.ctx, this.target, "first", {
2380
2490
  ...this.args(),
2381
2491
  column: colName ?? null
2382
2492
  }, readFaults), () => colName === void 0 ? this.real.first() : this.real.first(colName), (r) => ({ row: toJson(r) }));
2383
2493
  }
2384
2494
  raw(options) {
2385
- return this.ctx.hooks.effect(point(this.ctx, this.target, "raw", this.args(), readFaults), () => options ? this.real.raw(options) : this.real.raw(), (r) => ({ rows: r.length }));
2495
+ return this.ctx.hooks.effect(pointAt(this.ctx, this.target, "raw", this.args(), readFaults), () => options ? this.real.raw(options) : this.real.raw(), (r) => ({ rows: r.length }));
2386
2496
  }
2387
2497
  };
2388
2498
  /** Wrap a D1 binding. Methods not modelled fall through to the real binding and mark the run unsupported. */
@@ -2398,13 +2508,13 @@ function proxyD1(real, binding, ctx) {
2398
2508
  sql: s.sql,
2399
2509
  params: toJson(s.params)
2400
2510
  } : "<unproxied statement>") };
2401
- return ctx.hooks.effect(point(ctx, target, "batch", args, writeFaults), () => real.batch(unwrapped), (rs) => ({
2511
+ return ctx.hooks.effect(pointAt(ctx, target, "batch", args, writeFaults), () => real.batch(unwrapped), (rs) => ({
2402
2512
  changes: rs.reduce((n, r) => n + (r.meta.changes ?? 0), 0),
2403
2513
  statements: rs.length
2404
2514
  }));
2405
2515
  },
2406
2516
  exec(sql) {
2407
- return ctx.hooks.effect(point(ctx, target, "exec", { sql }, writeFaults), () => real.exec(sql), (r) => ({
2517
+ return ctx.hooks.effect(pointAt(ctx, target, "exec", { sql }, writeFaults), () => real.exec(sql), (r) => ({
2408
2518
  count: r.count,
2409
2519
  duration: 0
2410
2520
  }));
@@ -2662,18 +2772,8 @@ function putArgs(options) {
2662
2772
  }
2663
2773
  function proxyR2(real, binding, ctx, book) {
2664
2774
  const target = `R2:${binding}`;
2665
- const point = (op, args, allowed) => ({
2666
- invocation: ctx.currentInvocation(),
2667
- target,
2668
- op,
2669
- args,
2670
- allowed
2671
- });
2672
- const notModelled = (what) => {
2673
- const reason = `R2 ${binding}: ${what} is not modelled`;
2674
- ctx.hooks.unsupported(reason);
2675
- throw new Error(`eutaxy: ${reason}`);
2676
- };
2775
+ const point = (op, args, allowed) => pointAt(ctx, target, op, args, allowed);
2776
+ const notModelled = (what) => refuse(ctx, `R2 ${binding}: ${what} is not modelled`);
2677
2777
  /** Date conditions compare the store's real upload time, not the stand-in the Worker saw. */
2678
2778
  const checkConditions = (onlyIf) => {
2679
2779
  if (onlyIf instanceof Headers ? ["if-modified-since", "if-unmodified-since"].some((h) => onlyIf.has(h)) : typeof onlyIf === "object" && onlyIf !== null && ("uploadedBefore" in onlyIf || "uploadedAfter" in onlyIf)) ctx.hooks.unsupported(`R2 ${binding}: conditions on the upload time are not modelled`);
@@ -2798,12 +2898,16 @@ async function snapshotR2(real) {
2798
2898
  */
2799
2899
  /** The `EventRef.source` of a Workflow instance's run. */
2800
2900
  const workflowSource = "workflow";
2801
- /** Before a step's callback: the engine restarts before the step runs. */
2802
- const STEP_START = ["crash_before"];
2901
+ /**
2902
+ * Before a step's callback: the engine restarts before the step runs
2903
+ * (`crash_before`), or the attempt outlives its timeout from its start
2904
+ * (`ambiguous`): counted as failed and retried while it runs on late.
2905
+ */
2906
+ const STEP_START = ["crash_before", "ambiguous"];
2803
2907
  /**
2804
2908
  * After it: the engine restarts after the step ran but before its result
2805
2909
  * was persisted (`crash_after`), or the attempt ran and counted as failed,
2806
- * as a timeout does (`ambiguous`).
2910
+ * as a timeout just after its work does (`ambiguous`).
2807
2911
  */
2808
2912
  const STEP_RESULT = ["crash_after", "ambiguous"];
2809
2913
  /**
@@ -2860,11 +2964,7 @@ function isWorkflowBinding(value) {
2860
2964
  /** The binding's proxy: instances live in the registry and run as events, never in the real engine. */
2861
2965
  function proxyWorkflow(binding, ctx, registry) {
2862
2966
  const target = `Workflow:${binding}`;
2863
- const unsupported = (what) => {
2864
- const reason = `Workflow ${binding}: ${what} is not modelled`;
2865
- ctx.hooks.unsupported(reason);
2866
- throw new Error(`eutaxy: ${reason}`);
2867
- };
2967
+ const unsupported = (what) => refuse(ctx, `Workflow ${binding}: ${what} is not modelled`);
2868
2968
  const handle = (id) => ({
2869
2969
  id,
2870
2970
  status: () => ctx.hooks.effect({
@@ -3202,21 +3302,69 @@ async function deliverWorkflow(event, hooks, d) {
3202
3302
  count,
3203
3303
  attempt
3204
3304
  };
3205
- await hooks.effect({
3206
- invocation,
3207
- target,
3208
- op: "step",
3209
- args,
3210
- allowed: STEP_START
3211
- }, async () => null, () => null);
3305
+ let lateAtStart = false;
3306
+ try {
3307
+ await hooks.effect({
3308
+ invocation,
3309
+ target,
3310
+ op: "step",
3311
+ args,
3312
+ allowed: STEP_START
3313
+ }, async () => null, () => null);
3314
+ } catch (err) {
3315
+ if (!(err instanceof InjectedEffectError)) throw err;
3316
+ lateAtStart = true;
3317
+ }
3212
3318
  instance.attempts.set(k, attempt);
3213
3319
  let failed = false;
3214
3320
  let thrown;
3215
3321
  let value;
3216
3322
  let returned;
3217
- try {
3218
- returned = { value: await fn(stepContext) };
3219
- } catch (err) {
3323
+ const timeoutMs = durationMs(resolved.timeout);
3324
+ const started = hooks.attempt(invocation, () => {
3325
+ try {
3326
+ return Promise.resolve(fn(stepContext));
3327
+ } catch (err) {
3328
+ return Promise.reject(err);
3329
+ }
3330
+ }, lateAtStart ? 0 : timeoutMs);
3331
+ const settled = started.value.then((v) => ({
3332
+ ok: true,
3333
+ value: v
3334
+ }), (error) => ({
3335
+ ok: false,
3336
+ error
3337
+ }));
3338
+ const outcome = lateAtStart ? "late" : await Promise.race([settled, started.late.then(() => "late")]);
3339
+ if (outcome === "late") {
3340
+ if (!lateAtStart) note(hooks, {
3341
+ invocation,
3342
+ target,
3343
+ op: "step_timeout",
3344
+ args: {
3345
+ ...args,
3346
+ timeoutMs
3347
+ },
3348
+ allowed: []
3349
+ });
3350
+ failed = true;
3351
+ thrown = Object.assign(/* @__PURE__ */ new Error(`Execution timed out after ${timeoutMs}ms`), { name: "WorkflowTimeoutError" });
3352
+ background.push(settled.then((o) => {
3353
+ if (inv.isCrashed()) return;
3354
+ note(hooks, {
3355
+ invocation,
3356
+ target,
3357
+ op: "late_result",
3358
+ args: {
3359
+ ...args,
3360
+ outcome: o.ok ? "returned" : "threw"
3361
+ },
3362
+ allowed: []
3363
+ });
3364
+ }));
3365
+ } else if (outcome.ok) returned = { value: outcome.value };
3366
+ else {
3367
+ const err = outcome.error;
3220
3368
  if (err instanceof CrashSignal || inv.isCrashed()) throw err;
3221
3369
  failed = true;
3222
3370
  thrown = err;
@@ -3344,20 +3492,20 @@ async function deliverWorkflow(event, hooks, d) {
3344
3492
  }
3345
3493
  if (existing !== void 0 && Date.now() >= existing) {
3346
3494
  const error = Object.assign(/* @__PURE__ */ new Error(`Execution timed out after ${timeoutMs}ms`), { name: "WorkflowTimeoutError" });
3347
- hooks.effectSync({
3495
+ note(hooks, {
3348
3496
  invocation,
3349
3497
  target,
3350
3498
  op: "wait_timeout",
3351
3499
  args,
3352
3500
  allowed: []
3353
- }, () => null, () => null);
3501
+ });
3354
3502
  instance.persisted.set(k, failure(error));
3355
3503
  throw error;
3356
3504
  }
3357
3505
  const deadline = existing ?? Date.now() + timeoutMs;
3358
3506
  if (existing === void 0) {
3359
3507
  instance.deadlines.set(k, deadline);
3360
- hooks.effectSync({
3508
+ note(hooks, {
3361
3509
  invocation,
3362
3510
  target,
3363
3511
  op: "wait",
@@ -3366,7 +3514,7 @@ async function deliverWorkflow(event, hooks, d) {
3366
3514
  timeoutMs
3367
3515
  },
3368
3516
  allowed: []
3369
- }, () => null, () => null);
3517
+ });
3370
3518
  }
3371
3519
  const gen = ++instance.waitGen;
3372
3520
  instance.waiting = {
@@ -3407,7 +3555,7 @@ async function deliverWorkflow(event, hooks, d) {
3407
3555
  return;
3408
3556
  }
3409
3557
  instance.deadlines.set(k, Date.now() + ms);
3410
- hooks.effectSync({
3558
+ note(hooks, {
3411
3559
  invocation,
3412
3560
  target,
3413
3561
  op: "sleep",
@@ -3418,7 +3566,7 @@ async function deliverWorkflow(event, hooks, d) {
3418
3566
  ...until === void 0 ? {} : { until }
3419
3567
  },
3420
3568
  allowed: []
3421
- }, () => null, () => null);
3569
+ });
3422
3570
  await sleep(ms);
3423
3571
  instance.persisted.set(k, {
3424
3572
  ok: true,
@@ -3465,6 +3613,10 @@ async function deliverWorkflow(event, hooks, d) {
3465
3613
  value: void 0
3466
3614
  };
3467
3615
  let status = result.status;
3616
+ const restart = () => status === "crashed" && instance.status === "running" && event.attempt <= d.maxFaultsPerRun ? [{
3617
+ ...event,
3618
+ attempt: event.attempt + 1
3619
+ }] : [];
3468
3620
  if (suspending !== void 0 && result.status === "completed") {
3469
3621
  instance.status = "waiting";
3470
3622
  const suspended = suspending;
@@ -3473,10 +3625,7 @@ async function deliverWorkflow(event, hooks, d) {
3473
3625
  instance.status = "running";
3474
3626
  instance.waiting = void 0;
3475
3627
  }
3476
- const followUps = status === "crashed" ? instance.status === "running" && event.attempt <= d.maxFaultsPerRun ? [{
3477
- ...event,
3478
- attempt: event.attempt + 1
3479
- }] : [] : [{
3628
+ const followUps = status === "crashed" ? restart() : [{
3480
3629
  id: `workflow:${d.binding}:${instance.id}:timeout-${suspended.gen}`,
3481
3630
  attempt: 1,
3482
3631
  source: workflowSource,
@@ -3495,7 +3644,7 @@ async function deliverWorkflow(event, hooks, d) {
3495
3644
  if (result.status === "completed") {
3496
3645
  instance.status = "complete";
3497
3646
  instance.output = result.value;
3498
- hooks.effectSync({
3647
+ note(hooks, {
3499
3648
  invocation,
3500
3649
  target,
3501
3650
  op: "complete",
@@ -3504,7 +3653,7 @@ async function deliverWorkflow(event, hooks, d) {
3504
3653
  output: toJson(instance.output)
3505
3654
  },
3506
3655
  allowed: []
3507
- }, () => null, () => null);
3656
+ });
3508
3657
  } else if (result.status === "errored") {
3509
3658
  instance.status = "errored";
3510
3659
  const e = result.error;
@@ -3515,7 +3664,7 @@ async function deliverWorkflow(event, hooks, d) {
3515
3664
  name: "Error",
3516
3665
  message: String(e)
3517
3666
  };
3518
- hooks.effectSync({
3667
+ note(hooks, {
3519
3668
  invocation,
3520
3669
  target,
3521
3670
  op: "errored",
@@ -3524,16 +3673,12 @@ async function deliverWorkflow(event, hooks, d) {
3524
3673
  error: `${instance.error.name}: ${instance.error.message}`
3525
3674
  },
3526
3675
  allowed: []
3527
- }, () => null, () => null);
3676
+ });
3528
3677
  }
3529
3678
  if (await drainBackground(hooks, inv, invocation, target, background)) status = "crashed";
3530
- const followUps = status === "crashed" && instance.status === "running" && event.attempt <= d.maxFaultsPerRun ? [{
3531
- ...event,
3532
- attempt: event.attempt + 1
3533
- }] : [];
3534
3679
  return {
3535
3680
  status,
3536
- followUps
3681
+ followUps: restart()
3537
3682
  };
3538
3683
  }
3539
3684
  /** The delay before the next attempt (Workflows, Sleeping and retrying; a delay function is called). */
@@ -3640,13 +3785,14 @@ function durableObjectBinding(deps) {
3640
3785
  if (!helpers) throw new Error("Durable Object setup needs the Cloudflare test helpers: createCloudflarePlatform({ ..., durableObjects: await import(\"cloudflare:test\") })");
3641
3786
  return helpers;
3642
3787
  };
3788
+ const objects = {
3789
+ run: (binding, id, object, fn) => runInObject(namespace(binding), binding, ctx, helpers, stateFor(binding), id, object, fn),
3790
+ abort: (binding, id) => stateFor(binding).abort(id),
3791
+ mayPark: (binding, id) => stateFor(binding).mayPark(id),
3792
+ evict: (binding, id) => evictObject(namespace(binding), helpers, id)
3793
+ };
3643
3794
  return {
3644
- objects: {
3645
- run: (binding, id, object, fn) => runInObject(namespace(binding), binding, ctx, helpers, stateFor(binding), id, object, fn),
3646
- abort: (binding, id) => stateFor(binding).abort(id),
3647
- mayPark: (binding, id) => stateFor(binding).mayPark(id),
3648
- evict: (binding, id) => evictObject(namespace(binding), helpers, id)
3649
- },
3795
+ objects,
3650
3796
  kind: "durable_object",
3651
3797
  target: "DO",
3652
3798
  is: isDurableObjectNamespace,
@@ -3670,7 +3816,7 @@ function durableObjectBinding(deps) {
3670
3816
  },
3671
3817
  async snapshot(step, real, unsupported) {
3672
3818
  const binding = step.binding;
3673
- return snapshotNamespace(namespace(binding, real), required(), stateFor(binding).names, stateFor(binding).touched, step.objects, step.sql ?? {}, stateFor(binding).seededSql, (object) => unsupported(`Durable Object ${binding} ${object} was reached without a call Eutaxy saw (through another object's binding); calls between objects are not proxied yet`), unsupported);
3819
+ return snapshotNamespace(namespace(binding, real), required(), stateFor(binding).names, stateFor(binding).touched, step.objects, step.sql ?? {}, stateFor(binding).seededSql, (object) => unsupported(`Durable Object ${binding} ${object} was reached without a call Eutaxy saw (through another object's binding); calls between objects are not proxied yet`), unsupported, deps.snapshotAll === true);
3674
3820
  },
3675
3821
  source: alarmSource,
3676
3822
  async deliver(event, hooks, spec) {
@@ -3679,17 +3825,14 @@ function durableObjectBinding(deps) {
3679
3825
  binding,
3680
3826
  book: stateFor(binding).alarms,
3681
3827
  limit: alarmLimits.get(binding) ?? 3,
3682
- runAlarm: alarmRunner(namespace(binding), binding, ctx, helpers, stateFor(binding)),
3683
- abort: (id) => stateFor(binding).abort(id),
3684
- mayPark: (id) => stateFor(binding).mayPark(id),
3685
- evict: (id) => evictObject(namespace(binding), helpers, id),
3686
- bookkeep: (op, args) => hooks.effectSync({
3828
+ objects,
3829
+ bookkeep: (op, args) => note(hooks, {
3687
3830
  invocation: hooks.bookkeeping(),
3688
3831
  target: `DO:${binding}`,
3689
3832
  op,
3690
3833
  args,
3691
3834
  allowed: []
3692
- }, () => null, () => null)
3835
+ })
3693
3836
  });
3694
3837
  }
3695
3838
  };
@@ -3935,52 +4078,28 @@ async function deliverRequest(event, hooks, spec, drive, invocation, worker) {
3935
4078
  if (!(value instanceof Response)) throw new TypeError("the fetch handler returned something that is not a Response");
3936
4079
  return value;
3937
4080
  });
3938
- const response = handled.status === "completed" ? handled.value : void 0;
3939
4081
  let status = handled.status;
3940
- let summary = null;
3941
- let read = "errored";
3942
- if (status === "completed" && response) {
3943
- const body = await runInvocation(hooks, inv, () => summarizeResponse(response));
3944
- read = body.status === "completed" ? body.value : body.status;
3945
- if (read === "crashed" || read === "errored") status = read;
4082
+ let answer = { kind: "none" };
4083
+ if (handled.status === "completed") {
4084
+ const body = await runInvocation(hooks, inv, () => summarizeResponse(handled.value));
4085
+ if (body.status === "completed") {
4086
+ const sent = body.value;
4087
+ answer = {
4088
+ kind: "answered",
4089
+ value: sent,
4090
+ accepted: drive.retryOn === "5xx" ? sent.status < 500 : sent.ok
4091
+ };
4092
+ } else status = body.status;
3946
4093
  }
3947
- let late = caller.isLate();
3948
- const allowed = caller.responseFaults;
3949
- if (status === "completed" && typeof read === "object") {
3950
- const s = read;
3951
- try {
3952
- hooks.effectSync({
3953
- invocation,
3954
- target,
3955
- op: "response",
3956
- args,
3957
- allowed
3958
- }, () => s, (v) => v);
3959
- summary = s;
3960
- } catch (err) {
3961
- if (err instanceof CrashSignal) status = "crashed";
3962
- else if (err instanceof InjectedEffectError) {
3963
- summary = s;
3964
- late = true;
3965
- } else throw err;
3966
- }
3967
- } else if (status === "errored") {
3968
- const s = {
4094
+ if (status === "errored") answer = {
4095
+ kind: "errored",
4096
+ value: {
3969
4097
  status: 500,
3970
4098
  ok: false,
3971
4099
  body: ""
3972
- };
3973
- hooks.effectSync({
3974
- invocation,
3975
- target,
3976
- op: "response",
3977
- args,
3978
- allowed: []
3979
- }, () => s, (v) => v);
3980
- summary = s;
3981
- }
3982
- const accepted = summary !== null && !late && (drive.retryOn === "5xx" ? summary.status < 500 : summary.ok);
3983
- caller.settle(accepted, late);
4100
+ }
4101
+ };
4102
+ if (caller.respond(invocation, args, answer)) status = "crashed";
3984
4103
  if (await drainBackground(hooks, inv, invocation, target, background)) status = "crashed";
3985
4104
  return {
3986
4105
  status,
@@ -4000,31 +4119,35 @@ async function deliverMessage$1(event, hooks, spec, drive, invocation, worker, m
4000
4119
  /** Cloudflare honours the first ack or retry decision per message; later ones are ignored. */
4001
4120
  const state = { decision: null };
4002
4121
  const background = [];
4003
- /** Records the call; the result says whether it took effect (the first decision wins). */
4004
- const decide = (op, args) => {
4005
- hooks.effectSync({
4006
- invocation,
4007
- target: queueTarget,
4008
- op,
4009
- args,
4010
- allowed: decisionFaults
4011
- }, () => {
4012
- if (state.decision !== null) return false;
4013
- state.decision = op;
4014
- return true;
4015
- }, (effective) => ({ effective }));
4122
+ const decisionPoint = (op, args) => ({
4123
+ invocation,
4124
+ target: queueTarget,
4125
+ op,
4126
+ args,
4127
+ allowed: decisionFaults
4128
+ });
4129
+ /** The first decision wins; a later one is recorded as not effective. */
4130
+ const take = (op) => () => {
4131
+ if (state.decision !== null) return false;
4132
+ state.decision = op;
4133
+ return true;
4134
+ };
4135
+ const effective = (e) => ({ effective: e });
4136
+ /** Records the handler's call; the result says whether it took effect. */
4137
+ const record = (op, args) => {
4138
+ hooks.effectSync(decisionPoint(op, args), take(op), effective);
4016
4139
  };
4017
4140
  const message = {
4018
4141
  id: event.id,
4019
4142
  timestamp: /* @__PURE__ */ new Date(),
4020
4143
  body: cloneJson(event.data),
4021
4144
  attempts: event.attempt,
4022
- ack: () => decide("ack", {
4145
+ ack: () => record("ack", {
4023
4146
  messageId: event.id,
4024
4147
  implicit: false,
4025
4148
  body: event.data
4026
4149
  }),
4027
- retry: () => decide("retry", {
4150
+ retry: () => record("retry", {
4028
4151
  messageId: event.id,
4029
4152
  body: event.data
4030
4153
  })
@@ -4043,22 +4166,20 @@ async function deliverMessage$1(event, hooks, spec, drive, invocation, worker, m
4043
4166
  const handler = worker.handler.queue;
4044
4167
  if (!handler) throw new Error("the Worker has no queue() handler");
4045
4168
  let status = (await runInvocation(hooks, inv, () => handler.call(worker.handler, batch, worker.env, execution))).status;
4046
- if (status === "completed" && state.decision === null) try {
4047
- decide("ack", {
4169
+ if (status === "completed" && state.decision === null) {
4170
+ const implicit = decisionPoint("ack", {
4048
4171
  messageId: event.id,
4049
4172
  implicit: true,
4050
4173
  body: event.data
4051
4174
  });
4052
- } catch (err) {
4053
- if (err instanceof CrashSignal) status = "crashed";
4054
- else throw err;
4175
+ if (decide(hooks, implicit, take("ack"), effective) === "crashed") status = "crashed";
4055
4176
  }
4056
4177
  if (await drainBackground(hooks, inv, invocation, queueTarget, background)) status = "crashed";
4057
4178
  const followUps = [];
4058
4179
  if (state.decision !== "ack") {
4059
4180
  const next = redelivery(event, maxRetries, spec.bounds);
4060
4181
  if (next) followUps.push(next);
4061
- else hooks.effectSync({
4182
+ else note(hooks, {
4062
4183
  invocation: hooks.bookkeeping(),
4063
4184
  target: queueTarget,
4064
4185
  op: "dead_letter",
@@ -4067,7 +4188,7 @@ async function deliverMessage$1(event, hooks, spec, drive, invocation, worker, m
4067
4188
  attempts: event.attempt
4068
4189
  },
4069
4190
  allowed: []
4070
- }, () => null, () => null);
4191
+ });
4071
4192
  }
4072
4193
  return {
4073
4194
  status,
@@ -4116,7 +4237,7 @@ async function deliverTick(event, hooks, spec, drive, invocation, worker) {
4116
4237
  if (status !== "completed" && !noRetry) {
4117
4238
  const next = redelivery(event, drive.retries, spec.bounds);
4118
4239
  if (next) followUps.push(next);
4119
- else hooks.effectSync({
4240
+ else note(hooks, {
4120
4241
  invocation: hooks.bookkeeping(),
4121
4242
  target,
4122
4243
  op: "gave_up",
@@ -4125,7 +4246,7 @@ async function deliverTick(event, hooks, spec, drive, invocation, worker) {
4125
4246
  attempts: event.attempt
4126
4247
  },
4127
4248
  allowed: []
4128
- }, () => null, () => null);
4249
+ });
4129
4250
  }
4130
4251
  return {
4131
4252
  status,
@@ -4346,7 +4467,7 @@ var Connections = class {
4346
4467
  record(hooks) {
4347
4468
  const bookkeeping = () => hooks.bookkeeping();
4348
4469
  for (const [connection, c] of this.open) {
4349
- for (const data of this.frames.get(connection) ?? []) hooks.effectSync({
4470
+ for (const data of this.frames.get(connection) ?? []) note(hooks, {
4350
4471
  invocation: bookkeeping(),
4351
4472
  target: `WebSocket:${connection}`,
4352
4473
  op: "message",
@@ -4355,8 +4476,8 @@ var Connections = class {
4355
4476
  data
4356
4477
  },
4357
4478
  allowed: []
4358
- }, () => null, () => null);
4359
- if (c.closed) hooks.effectSync({
4479
+ });
4480
+ if (c.closed) note(hooks, {
4360
4481
  invocation: bookkeeping(),
4361
4482
  target: `WebSocket:${connection}`,
4362
4483
  op: "close",
@@ -4366,7 +4487,7 @@ var Connections = class {
4366
4487
  reason: c.closed.reason
4367
4488
  },
4368
4489
  allowed: []
4369
- }, () => null, () => null);
4490
+ });
4370
4491
  }
4371
4492
  this.frames.clear();
4372
4493
  }
@@ -4581,13 +4702,12 @@ async function deliverMessage(event, hooks, c, data, deps) {
4581
4702
  };
4582
4703
  }
4583
4704
  const { binding, id, object } = conn.upgrade;
4584
- const { status } = await runInvocation(hooks, inv, () => hooks.effect({
4705
+ const status = await hostedInObject(hooks, inv, deps.objects, binding, id, object, {
4585
4706
  invocation,
4586
4707
  target,
4587
4708
  op: "send",
4588
4709
  args,
4589
- allowed: readFaults,
4590
- hostsEffects: true
4710
+ allowed: readFaults
4591
4711
  }, async () => {
4592
4712
  await deps.objects.run(binding, id, object, async (instance, live) => {
4593
4713
  const { lost } = deps.connections.rebind(conn.upgrade, live);
@@ -4605,17 +4725,13 @@ async function deliverMessage(event, hooks, c, data, deps) {
4605
4725
  return;
4606
4726
  }
4607
4727
  const end = conn.server ?? server;
4608
- await handler.call(instance, end, frameText(data.data));
4728
+ await hooks.hostedCode(hostOf(`DO:${binding}`, object), () => handler.call(instance, end, frameText(data.data)));
4609
4729
  conn.identity = identityOf(end, live);
4610
4730
  });
4611
4731
  await settleFrames();
4612
4732
  return { delivered: true };
4613
- }, (v) => v, {
4614
- onAbandon: () => deps.objects.abort(binding, id),
4615
- mayPark: () => deps.objects.mayPark(binding, id)
4616
- }));
4733
+ }, (v) => v);
4617
4734
  if (status === "crashed") {
4618
- await deps.objects.evict(binding, id);
4619
4735
  const rebuild = hooks.startInvocation(`${invocation}/rebuild`);
4620
4736
  await runInvocation(hooks, rebuild, () => hooks.effect({
4621
4737
  invocation: rebuild.id,
@@ -4646,24 +4762,31 @@ async function deliverMessage(event, hooks, c, data, deps) {
4646
4762
  * documented by Cloudflare, and for requests the caller's retry policy
4647
4763
  * declared in the drive.
4648
4764
  */
4765
+ /**
4766
+ * Whether an env value is a binding and not a var: something with methods.
4767
+ * A JSON var is plain data, whose only methods are `Object.prototype`'s or
4768
+ * an array's, so those do not count; a test double written as an object
4769
+ * literal counts by the functions it holds itself.
4770
+ */
4649
4771
  function isBindingLike(value) {
4650
4772
  if (typeof value === "function") return true;
4651
- if (typeof value !== "object" || value === null) return false;
4773
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
4652
4774
  const proto = Object.getPrototypeOf(value);
4653
- return [...Object.getOwnPropertyNames(value), ...Object.getOwnPropertyNames(proto ?? {})].some((k) => k !== "constructor" && typeof value[k] === "function");
4775
+ const inherited = proto === null || proto === Object.prototype ? {} : proto;
4776
+ return [...Object.getOwnPropertyNames(value), ...Object.getOwnPropertyNames(inherited)].some((k) => k !== "constructor" && typeof value[k] === "function");
4654
4777
  }
4655
4778
  const assumptions = [
4656
4779
  "platform model: Cloudflare Queues at-least-once delivery; the first ack or retry decision per message wins; unacked messages are redelivered up to max_retries then dead-lettered",
4657
- "D1 statements run against Miniflare's SQLite; each run/first/all/raw/batch/exec is one effect",
4780
+ "D1 statements run against Miniflare's SQLite; each run/first/all/raw/batch/exec is one effect; SQL that reads the time or draws randomness itself (CURRENT_TIMESTAMP, strftime('now'), random()) reads SQLite's own clock and generator, not the virtual ones, so a value it stores differs from run to run",
4658
4781
  "message.timestamp is the virtual clock's time at delivery",
4659
- "only D1, Durable Object, R2, Workflow and scripted service bindings are proxied; touching any other binding makes the run UNSUPPORTED",
4782
+ "only D1, Durable Object, R2, Workflow and scripted service bindings are proxied; a call on any other binding makes the run UNSUPPORTED (reading one off env does not)",
4660
4783
  "service bindings are scripted callees unless the scenario names a callee for them: the Worker behind a scripted binding is never called; each RPC method call or fetch() through it is one effect answered from the scenario's service() setup, where crash_before and error mean the call never reached the callee, ambiguous that it acted and the answer was lost, and crash_after that the caller died after it (developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/); Cloudflare does not retry such a call",
4661
4784
  "a binding named as an alias of another (the same database, the same Durable Object namespace, in two Workers' configs) is that binding: its effects and snapshot carry the other's name, and a callee's Workflow runs the callee's class with the callee's env",
4662
4785
  "a service binding with a callee() setup runs that Worker's real code in the caller's simulation, in the same isolate, as Cloudflare runs both Workers on one thread (developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/): each RPC method call or fetch() through it is one effect hosting the callee's invocation (<caller invocation>/<binding>.<method>), which constructs the entrypoint anew with a fresh ExecutionContext and the callee's env (its bindings under <worker name>/<binding>) and answers with the return value, plain data by copy, or the Response as it is; what the callee throws reaches the caller as a new error with its name, message and serializable own properties, a built-in class as itself (developers.cloudflare.com/workers/runtime-apis/rpc/error-handling/); the callee's waitUntil work finishes before its answer crosses; crash_before means the call never reached the callee, ambiguous that it acted and the answer was lost, crash_after that the caller died after it, and a fault that crashes the callee ends its invocation and throws an Error to the caller; Cloudflare retries nothing",
4663
4786
  "R2 buckets are Miniflare's real ones, emptied and seeded before each run and snapshotted after it; R2 is strongly consistent and the last writer wins (developers.cloudflare.com/r2/reference/consistency/); each put, delete, get, head and list is one effect, a body is read inside its get, and an object's version and upload time are stand-ins so traces repeat; multipart uploads and conditions on the upload time are not modelled",
4664
- "Durable Objects are the real objects workerd runs (storage, transactions, input and output gates are the runtime's own); each stub call is one effect: crash_before or error means it never reached the object, ambiguous means the object committed and the caller lost the answer, crash_after means the caller died after it; in a concurrent run an object's own outbound I/O during a call is a turn, so another event may enter the object meanwhile (its input gate is open then), except while it holds the gate with blockConcurrencyWhile, when its effects run at once; storage operations are not turns (the input gate holds other events during them); the object's own binding calls are not recorded; objects are cleared, seeded and evicted before each run and their storage is snapshotted after it (developers.cloudflare.com/durable-objects/api/storage-api/)",
4787
+ "Durable Objects are the real objects workerd runs (storage, transactions, input and output gates are the runtime's own); each stub call is one effect: crash_before or error means it never reached the object, ambiguous means the object committed and the caller lost the answer, crash_after means the caller died after it; in a concurrent run an object's own outbound I/O during a call is a turn, so another event may enter the object meanwhile (its input gate is open then), except while it holds the gate with blockConcurrencyWhile, when its effects run at once; work an object starts and does not await (a promise left running, a timer, ctx.waitUntil) goes on after its answer as the object's own invocation, DO:<binding>/<object>/after, whose effects are turns of their own and take faults by their position in it, until nothing of it can move or a crash resets the object, which ends it with the instance (work that keeps setting timers is waited for up to 100 firings without settling, then the run is UNSUPPORTED); an object that awaits a timer of its own before answering is woken by it; an effect it issued before its answer and did not await, a timer it set and real work it started (Web Crypto) are its own once the call has answered: the caller's crash does not end them and a fault in them resets the object, not the caller; in a sequential run that work runs to rest before the next event (developers.cloudflare.com/durable-objects/concepts/durable-object-lifecycle/); storage operations are not turns (the input gate holds other events during them); the object's own binding calls are not recorded, and a call it makes on a service binding through this.env makes the run UNSUPPORTED, since no service() script or callee() answers inside the object; objects are cleared, seeded and evicted before each run and their storage is snapshotted after it (developers.cloudflare.com/durable-objects/api/storage-api/)",
4665
4788
  "Durable Object alarms are taken over so none is scheduled on the real clock and fire in virtual time: one alarm per object, a later setAlarm replaces it, setAlarm in a transaction applies on commit, the alarm survives eviction, alarm() is one effect (crash_before: it never ran; crash_after: it ran and counts as failed; error: it threw), and a failed alarm is retried after 2 s, 4 s, 8 s ... up to six retries and maxRedeliveries, with retryCount and isRetry (developers.cloudflare.com/durable-objects/api/base/#alarm); each object's alarm fires at most alarmsPerObject times per run (default 3)",
4666
- "Workflows are a model of the engine, never the local one, running the scenario's own class: create is one effect that queues the instance; each step.do attempt is two effect points around its callback, which runs as the instance's own code (step, crash_before: the engine restarts before it; step_result, crash_after: it ran and committed but its result was not persisted, so it runs again; ambiguous: the attempt ran but counted as failed, as a timeout does); a failed attempt is retried after its delay in virtual time (defaults 5 retries, 10 s, exponential, merged field by field with a step's config), up to its limit and maxRedeliveries, except a NonRetryableError; a restart re-runs run() from the start with the persisted step and sleep results, so code outside steps repeats; step timeouts are not measured (developers.cloudflare.com/workflows/build/rules-of-workflows/, /workflows/build/sleeping-and-retrying/)",
4789
+ "Workflows are a model of the engine, never the local one, running the scenario's own class: create is one effect that queues the instance; each step.do attempt is two effect points around its callback, which runs as the instance's own code (step, crash_before: the engine restarts before it; step_result, crash_after: it ran and committed but its result was not persisted, so it runs again; ambiguous at step: the attempt outlives its timeout from its start; ambiguous at step_result: it ran but counted as failed just after its work, as a timeout does); a failed attempt is retried after its delay in virtual time (defaults 5 retries, 10 s, exponential, merged field by field with a step's config), up to its limit and maxRedeliveries, except a NonRetryableError; a restart re-runs run() from the start with the persisted step and sleep results, so code outside steps repeats; a step's timeout is measured in virtual time (default 10 minutes), and an attempt that passes it is not stopped, as the engine cannot stop it either: it runs on as the late attempt while the step is retried or fails for good, its result dropped, and in a concurrent run its remaining effects land before, between or after the retry's or the recovery's (a sequential run lets it run first) (developers.cloudflare.com/workflows/build/rules-of-workflows/, /workflows/build/sleeping-and-retrying/)",
4667
4790
  "state invariants read a snapshot of every D1 binding named in setup, taken after the last event",
4668
4791
  "work passed to ctx.waitUntil runs after the handler returns and never affects acknowledgement or the response; a cut_off fault at that point loses work not yet started, and an effect in flight commits without its continuation",
4669
4792
  "concurrent invocations (maxConcurrentInvocations above 1) share one isolate's module state and bindings, and another may run while one awaits I/O (developers.cloudflare.com/workers/reference/how-workers-works/); queue consumers run concurrently up to max_concurrency (developers.cloudflare.com/queues/configuration/consumer-concurrency/)",
@@ -4724,6 +4847,42 @@ function createCloudflarePlatform(options) {
4724
4847
  ];
4725
4848
  const own = (prop) => typeof prop !== "string" || !prop.startsWith("__VITEST_POOL_WORKERS_");
4726
4849
  const aliasKeys = Object.keys(aliases).filter((a) => canonical(a) in env);
4850
+ /**
4851
+ * What the Worker sees under a binding of a kind the simulation does not
4852
+ * model: the binding with every method refused. Reading it does nothing,
4853
+ * as code that builds its dependencies from `env` on every call does;
4854
+ * the first call on it ends the run `UNSUPPORTED` and is never passed to
4855
+ * the real binding.
4856
+ */
4857
+ const standIns = /* @__PURE__ */ new Map();
4858
+ const unproxied = (name, real) => {
4859
+ let p = standIns.get(name);
4860
+ if (!p) {
4861
+ const refuseCall = () => refuse(ctx, `binding ${name} is not proxied`);
4862
+ p = new Proxy(typeof real === "function" ? refuseCall : {}, {
4863
+ get(_t, prop) {
4864
+ const value = Reflect.get(real, prop, real);
4865
+ return typeof value === "function" ? refuseCall : value;
4866
+ },
4867
+ has: (_t, prop) => Reflect.has(real, prop),
4868
+ ownKeys: () => Reflect.ownKeys(real),
4869
+ getOwnPropertyDescriptor(_t, prop) {
4870
+ const d = Reflect.getOwnPropertyDescriptor(real, prop);
4871
+ if (!d) return void 0;
4872
+ const value = Reflect.get(real, prop, real);
4873
+ return {
4874
+ value: typeof value === "function" ? refuseCall : value,
4875
+ enumerable: d.enumerable ?? false,
4876
+ configurable: true,
4877
+ writable: false
4878
+ };
4879
+ },
4880
+ apply: refuseCall
4881
+ });
4882
+ standIns.set(name, p);
4883
+ }
4884
+ return p;
4885
+ };
4727
4886
  const proxiedEnv = new Proxy(env, {
4728
4887
  get(target, prop, receiver) {
4729
4888
  if (!own(prop)) return void 0;
@@ -4735,8 +4894,7 @@ function createCloudflarePlatform(options) {
4735
4894
  const proxied = binding.proxy(name, value, ctx);
4736
4895
  if (proxied !== void 0) return proxied;
4737
4896
  }
4738
- if (isBindingLike(value)) ctx.hooks.unsupported(`binding ${name} is not proxied`);
4739
- return value;
4897
+ return isBindingLike(value) ? unproxied(name, value) : value;
4740
4898
  },
4741
4899
  has: (target, prop) => own(prop) && (Reflect.has(target, prop) || typeof prop === "string" && aliasKeys.includes(prop)),
4742
4900
  ownKeys: (target) => [.../* @__PURE__ */ new Set([...Reflect.ownKeys(target).filter(own), ...aliasKeys])],
@@ -4821,9 +4979,10 @@ function createCloudflarePlatform(options) {
4821
4979
  * Differential check: the same fault-free scenario run once through Eutaxy's
4822
4980
  * proxies and once against the raw bindings, with the queue model (or the
4823
4981
  * HTTP caller's retry policy) applied on the raw side itself. Any difference in the per-attempt decisions or in
4824
- * the final D1 and R2 state is a bug in the proxies or the platform model, not in
4982
+ * the final D1, R2 and Durable Object state is a bug in the proxies or the platform model, not in
4825
4983
  * the Worker. The raw side shares Eutaxy's *reading* of Cloudflare's queue
4826
- * semantics (core's redelivery rule among it); what it does not share is any proxy code.
4984
+ * semantics (core's redelivery rule among it) and the engine's raw loop; what
4985
+ * it does not share is any proxy code.
4827
4986
  */
4828
4987
  /**
4829
4988
  * The raw side's only wrapper: counts D1 calls in flight (so the settle loop
@@ -4900,16 +5059,69 @@ function countingR2(real, io, clock) {
4900
5059
  }
4901
5060
  /**
4902
5061
  * The bindings whose state the two sides compare: those a store holds and
4903
- * the real binding resets and reads back (D1, R2). Durable Objects and
4904
- * Workflows have no raw side.
5062
+ * the real binding resets and reads back (D1, R2, and Durable Objects when
5063
+ * the test helpers are given: the raw side reads every seeded object's
5064
+ * storage, since no proxy saw which were reached). Workflows have no raw
5065
+ * side.
4905
5066
  */
4906
5067
  function storedBindings(options) {
4907
- return [d1Binding(options.schemas), r2Binding()];
5068
+ const helpers = options.durableObjects;
5069
+ const env = options.env;
5070
+ return [
5071
+ d1Binding(options.schemas),
5072
+ r2Binding(),
5073
+ ...helpers ? [durableObjectBinding({
5074
+ ctx: {
5075
+ hooks: void 0,
5076
+ currentInvocation: () => "raw"
5077
+ },
5078
+ helpers,
5079
+ real: (name) => env[name],
5080
+ snapshotAll: true
5081
+ })] : []
5082
+ ];
5083
+ }
5084
+ /**
5085
+ * A Durable Object namespace whose stub calls count as I/O in flight: the
5086
+ * call crosses workerd, which the settle loop cannot otherwise see, and
5087
+ * advances the clock as the proxied call does. It records nothing.
5088
+ */
5089
+ function countingNamespace(real, io, clock) {
5090
+ const track = async (p) => {
5091
+ io.n++;
5092
+ try {
5093
+ return await p;
5094
+ } finally {
5095
+ io.n--;
5096
+ clock.advance(1);
5097
+ }
5098
+ };
5099
+ const countingStub = (stub) => new Proxy(stub, { get(t, prop, r) {
5100
+ const v = Reflect.get(t, prop, r);
5101
+ if (prop === "then" || prop === "id" || prop === "name" || typeof prop !== "string") return v;
5102
+ if (typeof v !== "function") return v;
5103
+ return new Proxy(v, {
5104
+ apply: (member, _self, a) => track(Promise.resolve(Reflect.apply(member, t, a))),
5105
+ get(member, key, receiver) {
5106
+ if (key === "then") {
5107
+ const read = track(Promise.resolve(member));
5108
+ return read.then.bind(read);
5109
+ }
5110
+ return Reflect.get(member, key, receiver);
5111
+ }
5112
+ });
5113
+ } });
5114
+ return new Proxy(real, { get(t, prop, r) {
5115
+ const v = Reflect.get(t, prop, r);
5116
+ if (prop === "get") return (...a) => countingStub(t.get(...a));
5117
+ if (prop === "getByName") return (name) => countingStub(t.getByName(name));
5118
+ return typeof v === "function" ? v.bind(t) : v;
5119
+ } });
4908
5120
  }
4909
- async function snapshotAll(spec, options) {
5121
+ async function snapshotAll(spec, options, stored) {
4910
5122
  const env = options.env;
4911
5123
  const out = {};
4912
- for (const [binding, setup] of ownedSetups(spec.setup, storedBindings(options))) {
5124
+ for (const [binding, setup] of ownedSetups(spec.setup, stored)) {
4913
5125
  const tables = await binding.snapshot(setup, env[setup.binding], (reason) => {
4914
5126
  throw new Error(`snapshot of ${setup.binding}: ${reason}`);
4915
5127
  });
@@ -4918,7 +5130,7 @@ async function snapshotAll(spec, options) {
4918
5130
  return out;
4919
5131
  }
4920
5132
  /** The Eutaxy side, keeping each delivery's status and the decision it made. */
4921
- async function eutaxySide(spec, options) {
5133
+ async function eutaxySide(spec, options, stored) {
4922
5134
  const { attempts, unsupported } = await proxiedSide(spec, createCloudflarePlatform(options), (event, result, entries) => {
4923
5135
  const invocation = invocationOf(event);
4924
5136
  const mine = entries.filter((e) => e.invocation === invocation);
@@ -4939,7 +5151,7 @@ async function eutaxySide(spec, options) {
4939
5151
  });
4940
5152
  return {
4941
5153
  attempts,
4942
- state: await snapshotAll(spec, options),
5154
+ state: await snapshotAll(spec, options, stored),
4943
5155
  unsupported
4944
5156
  };
4945
5157
  }
@@ -4949,212 +5161,175 @@ function flatten(state) {
4949
5161
  for (const [binding, tables] of Object.entries(state)) for (const [table, rows] of Object.entries(tables)) out[`${binding}.${table}`] = rows;
4950
5162
  return out;
4951
5163
  }
4952
- /** The next event as the engine picks it: the earliest due, the first inserted among equals. */
4953
- function takeEarliest(pending) {
4954
- let best = 0;
4955
- for (let i = 1; i < pending.length; i++) if ((pending[i]?.at ?? 0) < (pending[best]?.at ?? 0)) best = i;
4956
- return pending.splice(best, 1)[0];
4957
- }
4958
- /** The raw side: the handler called directly with the real bindings and plain message or Request objects. */
4959
- async function rawSide(spec, options) {
4960
- const env = options.env;
4961
- const drive = spec.drive;
4962
- const maxRetries = options.maxRetries ?? 3;
4963
- for (const [binding, setup] of ownedSetups(spec.setup, storedBindings(options))) await binding.reset(setup, env[setup.binding]);
4964
- const attempts = [];
4965
- const pending = [...driveEvents(drive)];
4966
- const patched = patchGlobals(0);
4967
- const unsupported = [];
4968
- const restoreFetch = installScriptedFetch(spec.externals, null, (r) => unsupported.push(r), () => patched.clock.advance(1));
4969
- const io = { n: 0 };
5164
+ /** The real bindings with each call counted as I/O in flight and the clock advanced as the proxies do. */
5165
+ function countingEnv(env, ctx) {
4970
5166
  const counting = /* @__PURE__ */ new Map();
4971
- const countedEnv = new Proxy(env, { get(target, prop, receiver) {
5167
+ return new Proxy(env, { get(target, prop, receiver) {
4972
5168
  const value = Reflect.get(target, prop, receiver);
4973
- if (typeof prop !== "string" || !(isD1(value) || isR2(value))) return value;
5169
+ if (typeof prop !== "string" || !(isD1(value) || isR2(value) || isDurableObjectNamespace(value))) return value;
4974
5170
  let c = counting.get(prop);
4975
5171
  if (!c) {
4976
- c = isD1(value) ? countingD1(value, io, patched.clock) : countingR2(value, io, patched.clock);
5172
+ c = isD1(value) ? countingD1(value, ctx.io, ctx.clock) : isR2(value) ? countingR2(value, ctx.io, ctx.clock) : countingNamespace(value, ctx.io, ctx.clock);
4977
5173
  counting.set(prop, c);
4978
5174
  }
4979
5175
  return c;
4980
5176
  } });
4981
- const settle = (p) => settleOn(p, {
4982
- clock: patched.clock,
4983
- inFlight: () => io.n,
4984
- crashed: () => false,
4985
- stuck: () => {
4986
- throw new DifferentialStuck();
4987
- }
4988
- });
4989
- try {
4990
- const handlers = typeof options.handler === "function" ? {} : options.handler;
4991
- if (drive.kind === "websocket") throw new Error("runDifferential has no raw side for a websocket drive: its messages are delivered inside the object");
4992
- if (drive.kind === "rpc") {
4993
- const cls = entrypointClass(options.handler, options.exports, drive.entrypoint);
4994
- if (typeof cls !== "function") throw new Error("the Worker has no WorkerEntrypoint class");
4995
- while (pending.length > 0) {
4996
- const event = takeEarliest(pending);
4997
- const call = event.data;
4998
- const background = [];
4999
- let status;
5000
- let result;
5001
- try {
5002
- const value = await settle(Promise.resolve().then(() => callMethod(cls, call, executionContext(background), countedEnv)));
5003
- result = {
5004
- ok: true,
5005
- value: toJson(value)
5006
- };
5007
- status = "completed";
5008
- } catch (err) {
5009
- if (err instanceof CrashSignal || err instanceof DifferentialStuck) throw err;
5010
- result = {
5011
- ok: false,
5012
- error: describeError(err)
5013
- };
5014
- status = "errored";
5015
- }
5016
- await settle(Promise.all(background));
5017
- attempts.push({
5018
- event: event.id,
5019
- attempt: event.attempt,
5020
- status,
5021
- decision: null,
5022
- result
5023
- });
5024
- const next = status === "completed" ? null : redelivery(event, drive.retries, spec.bounds);
5025
- if (next) pending.push(next);
5026
- }
5027
- } else if (drive.kind === "cron") {
5028
- const handler = handlers.scheduled;
5029
- if (!handler) throw new Error("the Worker has no scheduled() handler");
5030
- while (pending.length > 0) {
5031
- const event = takeEarliest(pending);
5032
- const tick = event.data;
5033
- if (event.at !== void 0 && event.at > patched.clock.now()) patched.clock.advance(event.at - patched.clock.now());
5034
- const background = [];
5035
- const failures = [];
5036
- let noRetry = false;
5037
- const controller = {
5038
- scheduledTime: tick.scheduledTime,
5039
- cron: tick.cron,
5040
- noRetry: () => {
5041
- noRetry = true;
5042
- }
5043
- };
5044
- let status;
5045
- try {
5046
- await settle(Promise.resolve().then(() => handler.call(handlers, controller, countedEnv, executionContext(background, failures))));
5047
- status = "completed";
5048
- } catch (err) {
5049
- if (err instanceof CrashSignal || err instanceof DifferentialStuck) throw err;
5050
- status = "errored";
5051
- }
5052
- await settle(Promise.all(background));
5053
- if (status === "completed" && failures.length > 0) status = "errored";
5054
- attempts.push({
5055
- event: event.id,
5056
- attempt: event.attempt,
5057
- status,
5058
- decision: noRetry ? "no_retry" : null
5059
- });
5060
- const next = status === "completed" || noRetry ? null : redelivery(event, drive.retries, spec.bounds);
5061
- if (next) pending.push(next);
5177
+ }
5178
+ function rawCall(ctx, drive, options, env) {
5179
+ const cls = entrypointClass(options.handler, options.exports, drive.entrypoint);
5180
+ if (typeof cls !== "function") throw new Error("the Worker has no WorkerEntrypoint class");
5181
+ return async (event) => {
5182
+ const call = event.data;
5183
+ const background = [];
5184
+ const ran = await ctx.call(async () => toJson(await callMethod(cls, call, executionContext(background), env)));
5185
+ await ctx.settle(Promise.all(background));
5186
+ const result = ran.status === "completed" ? {
5187
+ ok: true,
5188
+ value: ran.value
5189
+ } : {
5190
+ ok: false,
5191
+ error: describeError(ran.error)
5192
+ };
5193
+ return {
5194
+ record: {
5195
+ event: event.id,
5196
+ attempt: event.attempt,
5197
+ status: ran.status,
5198
+ decision: null,
5199
+ result
5200
+ },
5201
+ handled: ran.status === "completed"
5202
+ };
5203
+ };
5204
+ }
5205
+ function rawTick(ctx, _drive, handlers, env) {
5206
+ const handler = handlers.scheduled;
5207
+ if (!handler) throw new Error("the Worker has no scheduled() handler");
5208
+ return async (event) => {
5209
+ const tick = event.data;
5210
+ const background = [];
5211
+ const failures = [];
5212
+ let noRetry = false;
5213
+ const controller = {
5214
+ scheduledTime: tick.scheduledTime,
5215
+ cron: tick.cron,
5216
+ noRetry: () => {
5217
+ noRetry = true;
5062
5218
  }
5063
- } else if (drive.kind === "http") {
5064
- const handler = handlers.fetch;
5065
- if (!handler) throw new Error("the Worker has no fetch() handler");
5066
- while (pending.length > 0) {
5067
- const event = takeEarliest(pending);
5068
- const req = event.data;
5069
- const background = [];
5070
- let status;
5071
- let response = 500;
5072
- try {
5073
- const r = await settle(Promise.resolve().then(() => handler.call(handlers, requestFor(req), countedEnv, executionContext(background))));
5074
- await settle(r.clone().text());
5075
- response = r.status;
5076
- status = "completed";
5077
- } catch (err) {
5078
- if (err instanceof CrashSignal || err instanceof DifferentialStuck) throw err;
5079
- status = "errored";
5080
- }
5081
- await settle(Promise.all(background));
5082
- attempts.push({
5083
- event: event.id,
5084
- attempt: event.attempt,
5085
- status,
5086
- decision: null,
5087
- response
5088
- });
5089
- const next = (drive.retryOn === "5xx" ? response < 500 : response >= 200 && response < 300) ? null : redelivery(event, drive.retries, spec.bounds);
5090
- if (next) pending.push(next);
5219
+ };
5220
+ const ran = await ctx.call(() => handler.call(handlers, controller, env, executionContext(background, failures)));
5221
+ await ctx.settle(Promise.all(background));
5222
+ const status = ran.status === "completed" && failures.length === 0 ? "completed" : "errored";
5223
+ return {
5224
+ record: {
5225
+ event: event.id,
5226
+ attempt: event.attempt,
5227
+ status,
5228
+ decision: noRetry ? "no_retry" : null
5229
+ },
5230
+ handled: status === "completed" || noRetry
5231
+ };
5232
+ };
5233
+ }
5234
+ function rawRequest(ctx, drive, handlers, env) {
5235
+ const handler = handlers.fetch;
5236
+ if (!handler) throw new Error("the Worker has no fetch() handler");
5237
+ return async (event) => {
5238
+ const req = event.data;
5239
+ const background = [];
5240
+ const ran = await ctx.call(async () => {
5241
+ const r = await handler.call(handlers, requestFor(req), env, executionContext(background));
5242
+ await r.clone().text();
5243
+ return r.status;
5244
+ });
5245
+ await ctx.settle(Promise.all(background));
5246
+ const response = ran.status === "completed" ? ran.value : 500;
5247
+ const accepted = drive.retryOn === "5xx" ? response < 500 : response >= 200 && response < 300;
5248
+ return {
5249
+ record: {
5250
+ event: event.id,
5251
+ attempt: event.attempt,
5252
+ status: ran.status,
5253
+ decision: null,
5254
+ response
5255
+ },
5256
+ handled: accepted
5257
+ };
5258
+ };
5259
+ }
5260
+ function rawMessage(ctx, drive, handlers, env) {
5261
+ const handler = handlers.queue;
5262
+ if (!handler) throw new Error("the Worker has no queue() handler");
5263
+ return async (event) => {
5264
+ let decision = null;
5265
+ const background = [];
5266
+ const message = {
5267
+ id: event.id,
5268
+ timestamp: /* @__PURE__ */ new Date(),
5269
+ body: cloneJson(event.data),
5270
+ attempts: event.attempt,
5271
+ ack: () => {
5272
+ decision ??= "ack";
5273
+ },
5274
+ retry: () => {
5275
+ decision ??= "retry";
5091
5276
  }
5092
- } else {
5093
- const handler = handlers.queue;
5094
- if (!handler) throw new Error("the Worker has no queue() handler");
5095
- while (pending.length > 0) {
5096
- const event = takeEarliest(pending);
5097
- let decision = null;
5098
- const background = [];
5099
- const message = {
5100
- id: event.id,
5101
- timestamp: /* @__PURE__ */ new Date(),
5102
- body: JSON.parse(JSON.stringify(event.data)),
5103
- attempts: event.attempt,
5104
- ack: () => {
5105
- decision ??= "ack";
5106
- },
5107
- retry: () => {
5108
- decision ??= "retry";
5109
- }
5110
- };
5111
- const batch = {
5112
- queue: drive.queue,
5113
- messages: [message],
5114
- metadata: { metrics: {
5115
- backlogCount: 0,
5116
- backlogBytes: 0
5117
- } },
5118
- ackAll: () => message.ack(),
5119
- retryAll: () => message.retry()
5120
- };
5121
- const ctx = executionContext(background);
5122
- let status;
5123
- try {
5124
- await settle(Promise.resolve().then(() => handler.call(handlers, batch, countedEnv, ctx)));
5125
- status = "completed";
5126
- } catch (err) {
5127
- if (err instanceof CrashSignal || err instanceof DifferentialStuck) throw err;
5128
- status = "errored";
5277
+ };
5278
+ const batch = {
5279
+ queue: drive.queue,
5280
+ messages: [message],
5281
+ metadata: { metrics: {
5282
+ backlogCount: 0,
5283
+ backlogBytes: 0
5284
+ } },
5285
+ ackAll: () => message.ack(),
5286
+ retryAll: () => message.retry()
5287
+ };
5288
+ const ran = await ctx.call(() => handler.call(handlers, batch, env, executionContext(background)));
5289
+ if (ran.status === "completed") decision ??= "ack";
5290
+ await ctx.settle(Promise.all(background));
5291
+ return {
5292
+ record: {
5293
+ event: event.id,
5294
+ attempt: event.attempt,
5295
+ status: ran.status,
5296
+ decision
5297
+ },
5298
+ handled: decision === "ack"
5299
+ };
5300
+ };
5301
+ }
5302
+ /** The raw side: the engine's raw loop, each attempt calling the handler directly with the real bindings. */
5303
+ async function rawSide(spec, options, stored) {
5304
+ const env = options.env;
5305
+ const drive = spec.drive;
5306
+ if (drive.kind === "websocket") throw new Error("runDifferential has no raw side for a websocket drive: its messages are delivered inside the object");
5307
+ for (const [binding, setup] of ownedSetups(spec.setup, stored)) await binding.reset(setup, env[setup.binding]);
5308
+ const handlers = typeof options.handler === "function" ? {} : options.handler;
5309
+ return {
5310
+ attempts: await rawRun(spec, {
5311
+ events: driveEvents(drive),
5312
+ limit: drive.kind === "queue" ? options.maxRetries ?? 3 : drive.retries,
5313
+ install: (ctx) => {
5314
+ const counted = countingEnv(env, ctx);
5315
+ switch (drive.kind) {
5316
+ case "rpc": return { attempt: rawCall(ctx, drive, options, counted) };
5317
+ case "cron": return { attempt: rawTick(ctx, drive, handlers, counted) };
5318
+ case "http": return { attempt: rawRequest(ctx, drive, handlers, counted) };
5319
+ case "queue": return { attempt: rawMessage(ctx, drive, handlers, counted) };
5129
5320
  }
5130
- if (status === "completed") decision ??= "ack";
5131
- await settle(Promise.all(background));
5132
- attempts.push({
5133
- event: event.id,
5134
- attempt: event.attempt,
5135
- status,
5136
- decision
5137
- });
5138
- const next = decision === "ack" ? null : redelivery(event, maxRetries, spec.bounds);
5139
- if (next) pending.push(next);
5140
5321
  }
5141
- }
5142
- } finally {
5143
- restoreFetch();
5144
- patched.restore();
5145
- }
5146
- if (unsupported.length > 0) throw new DifferentialStuck(`raw side: ${unsupported.join("; ")}`);
5147
- return {
5148
- attempts,
5149
- state: await snapshotAll(spec, options)
5322
+ }),
5323
+ state: await snapshotAll(spec, options, stored)
5150
5324
  };
5151
5325
  }
5152
5326
  /** Run both sides and compare. The Eutaxy side runs first; both start from the schema. */
5153
5327
  async function runDifferential(spec, options) {
5154
5328
  if ((spec.drive.kind === "http" || spec.drive.kind === "rpc") && ("delaysMs" in spec.drive || "deadlineMs" in spec.drive)) throw new Error("runDifferential does not model the caller's delaysMs or deadlineMs yet");
5155
5329
  if (spec.setup.some((s) => s.kind === "callee")) throw new Error("runDifferential keeps to the binding proxies: a scenario with a callee() has no raw side; script the service for the differential entry");
5156
- const { unsupported, ...eutaxy } = await eutaxySide(spec, options);
5157
- const raw = await rawSide(spec, options);
5330
+ const stored = storedBindings(options);
5331
+ const { unsupported, ...eutaxy } = await eutaxySide(spec, options, stored);
5332
+ const raw = await rawSide(spec, options, stored);
5158
5333
  const differences = compareSides({
5159
5334
  attempts: eutaxy.attempts,
5160
5335
  state: flatten(eutaxy.state)
@@ -5273,8 +5448,8 @@ async function checkInWorkerd(input) {
5273
5448
  ...input.extraSql
5274
5449
  });
5275
5450
  const load = input.modules[globKey(scenario.worker.entry)];
5276
- if (!load) throw new Error(`worker entry ${scenario.worker.entry} not found next to the scenario`);
5277
- const worker = await load();
5451
+ if (!input.worker && !load) throw new Error(`worker entry ${scenario.worker.entry} not found next to the scenario`);
5452
+ const worker = input.worker ?? await load?.();
5278
5453
  const platform = createCloudflarePlatform({
5279
5454
  env: input.env,
5280
5455
  handler: worker.default,
@@ -5325,4 +5500,4 @@ async function checkInWorkerd(input) {
5325
5500
  }
5326
5501
  export { r2Bucket as A, webSocketReceived as B, external as C, implies as D, httpResponse as E, rpc as F, cloudflareRegressionTest as G, workflow as H, rpcResponse as I, service as L, r2Rows as M, references as N, queue as O, refines as P, serviceCall as R, everyRow as S, http as T, workflowRows as U, websocket as V, workflowStep as W, d1Write as _, createCloudflarePlatform as a, durableObjectRows as b, expectHolds as c, callee as d, cron as f, d1Schema as g, d1Rows as h, runDifferential as i, r2Op as j, queueAck as k, calleeEnv as l, d1Read as m, globKey as n, snapshotD1 as o, d1Param as p, specKey as r, check as s, checkInWorkerd as t, atLeastOncePerMessage as u, defineScenario as v, fetchCall as w, durableObjectTable as x, durableObject as y, unique as z };
5327
5502
 
5328
- //# sourceMappingURL=workerd-DvhVDnQW.mjs.map
5503
+ //# sourceMappingURL=workerd-9Tt0BV-3.mjs.map