eutaxy 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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-CzGCMudc.mjs → cli-DbLlYHTY.mjs} +406 -196
  8. package/dist/cli-DbLlYHTY.mjs.map +1 -0
  9. package/dist/cli.mjs +1 -1
  10. package/dist/cloudflare.d.mts +7 -7
  11. package/dist/cloudflare.d.mts.map +1 -1
  12. package/dist/cloudflare.mjs +2 -2
  13. package/dist/delivery-invariants-90c5xBcd.mjs +44 -0
  14. package/dist/delivery-invariants-90c5xBcd.mjs.map +1 -0
  15. package/dist/{delivery-invariants-DzMy3iPs.d.mts → delivery-invariants-B8ZZnCZg.d.mts} +2 -2
  16. package/dist/{delivery-invariants-DzMy3iPs.d.mts.map → delivery-invariants-B8ZZnCZg.d.mts.map} +1 -1
  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-ud5wEfnx.mjs → src-CmHdPsZy.mjs} +1297 -388
  24. package/dist/src-CmHdPsZy.mjs.map +1 -0
  25. package/dist/{src-nwQA9Xwr.mjs → src-Dz9Wn2vL.mjs} +2 -2
  26. package/dist/{src-nwQA9Xwr.mjs.map → src-Dz9Wn2vL.mjs.map} +1 -1
  27. package/dist/{workerd-Be43_PZo.mjs → workerd-D9cUGjYv.mjs} +571 -483
  28. package/dist/workerd-D9cUGjYv.mjs.map +1 -0
  29. package/package.json +3 -3
  30. package/dist/cli-CzGCMudc.mjs.map +0 -1
  31. package/dist/delivery-invariants-BCtvzAfW.mjs +0 -67
  32. package/dist/delivery-invariants-BCtvzAfW.mjs.map +0 -1
  33. package/dist/src-ud5wEfnx.mjs.map +0 -1
  34. package/dist/workerd-Be43_PZo.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-ud5wEfnx.mjs";
2
- import { a as redelivery, i as invocationOf, n as atLeastOncePerMessage$1 } from "./delivery-invariants-BCtvzAfW.mjs";
3
- import { c as checkSpecModule, s as emitRegressionTest, t as renderJson, y as describeVerdict } from "./src-nwQA9Xwr.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-CmHdPsZy.mjs";
2
+ import { n as atLeastOncePerMessage$1 } from "./delivery-invariants-90c5xBcd.mjs";
3
+ import { c as checkSpecModule, s as emitRegressionTest, t as renderJson, y as describeVerdict } from "./src-Dz9Wn2vL.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,79 @@ async function drainBackground(hooks, inv, invocation, target, background) {
119
119
  return true;
120
120
  }
121
121
  }
122
+ // packages/cloudflare/src/object-access.ts
123
+ /** The host an object's code runs as (`EffectOptions.host`): its namespace's target and its name. */
124
+ function hostOf(target, object) {
125
+ return `${target}/${object}`;
126
+ }
127
+ /** Where a class's `method` is defined along `instance`'s prototype chain. */
128
+ function owner(instance, method) {
129
+ for (let o = instance; o !== null; o = Object.getPrototypeOf(o)) if (Object.hasOwn(o, method)) return o;
130
+ }
131
+ /** The host each instance's code runs as, set each time a call enters it. */
132
+ const hostOfInstance = /* @__PURE__ */ new WeakMap();
133
+ const hostingWrappers = /* @__PURE__ */ new WeakSet();
134
+ /**
135
+ * Have the object's `method` run as the host's code (`RunHooks.hostedCode`)
136
+ * when the runtime calls it next: the runtime carries no async context into
137
+ * an object's code, so the method is wrapped where its class defines it, and
138
+ * the wrapper looks the instance's host up; code the method spawns and does
139
+ * not await carries the object's identity too.
140
+ */
141
+ function hostMethod(hooks, host, instance, method) {
142
+ if (instance === null || typeof instance !== "object") return;
143
+ hostOfInstance.set(instance, {
144
+ hooks,
145
+ host
146
+ });
147
+ const where = owner(instance, method);
148
+ if (!where) return;
149
+ const descriptor = Object.getOwnPropertyDescriptor(where, method);
150
+ if (!descriptor?.configurable) return;
151
+ const hosted = (original) => function(...args) {
152
+ const of = this !== null && typeof this === "object" ? hostOfInstance.get(this) : void 0;
153
+ const call = () => original.apply(this, args);
154
+ return of ? of.hooks.hostedCode(of.host, call, method) : call();
155
+ };
156
+ if (typeof descriptor.value === "function" && descriptor.writable) {
157
+ if (hostingWrappers.has(descriptor.value)) return;
158
+ const wrapper = hosted(descriptor.value);
159
+ hostingWrappers.add(wrapper);
160
+ Object.defineProperty(where, method, {
161
+ ...descriptor,
162
+ value: wrapper
163
+ });
164
+ } else if (typeof descriptor.get === "function") {
165
+ if (hostingWrappers.has(descriptor.get)) return;
166
+ const wrapper = hosted(descriptor.get);
167
+ hostingWrappers.add(wrapper);
168
+ Object.defineProperty(where, method, {
169
+ ...descriptor,
170
+ get: wrapper
171
+ });
172
+ }
173
+ }
174
+ /**
175
+ * One effect of `inv` performed inside the object `id` of `binding`: `perform`
176
+ * runs as the effect, which hosts what the object does; a fault that
177
+ * abandons it resets the object, and a crash evicts the instance. The
178
+ * invocation's outcome.
179
+ */
180
+ async function hostedInObject(hooks, inv, objects, binding, id, object, point, perform, summarize) {
181
+ const { status } = await runInvocation(hooks, inv, () => hooks.effect({
182
+ ...point,
183
+ hostsEffects: true
184
+ }, perform, summarize, {
185
+ host: hostOf(`DO:${binding}`, object),
186
+ onAbandon: () => objects.abort(binding, id),
187
+ mayPark: () => objects.mayPark(binding, id)
188
+ }));
189
+ if (status === "crashed") {
190
+ await objects.evict(binding, id);
191
+ hooks.hostReset(hostOf(`DO:${binding}`, object));
192
+ }
193
+ return status;
194
+ }
122
195
  // packages/cloudflare/src/alarms.ts
123
196
  /**
124
197
  * Durable Object alarms in virtual time. Eutaxy takes over each object's
@@ -295,6 +368,23 @@ async function takeOverAlarms(storage, alarm) {
295
368
  };
296
369
  }
297
370
  /**
371
+ * Run an object's `alarm()` handler inside it, after taking over its alarms
372
+ * (the instance may be new since the alarm was set).
373
+ */
374
+ async function runAlarm(hooks, d, id, object, info, gen) {
375
+ await d.objects.run(d.binding, id, object, async (instance) => {
376
+ const entry = d.book.entry(id);
377
+ if (entry.gen !== gen) return;
378
+ entry.time = null;
379
+ const handler = instance.alarm;
380
+ if (typeof handler !== "function") {
381
+ hooks.unsupported(`Durable Object ${d.binding} ${object} set an alarm but has no alarm() handler`);
382
+ return;
383
+ }
384
+ await hooks.hostedCode(hostOf(`DO:${d.binding}`, object), () => handler.call(instance, info));
385
+ });
386
+ }
387
+ /**
298
388
  * Fire an alarm event: skip it when the object's alarm has since moved or
299
389
  * been deleted, run `alarm()` as one effect otherwise, and schedule a retry
300
390
  * with backoff when the handler fails, crashes, or a fault says it did.
@@ -330,7 +420,7 @@ async function deliverAlarm(event, hooks, maxRedeliveries, d) {
330
420
  retryCount: a.retryCount,
331
421
  isRetry: a.retryCount > 0
332
422
  };
333
- const { status } = await runInvocation(hooks, inv, () => hooks.effect({
423
+ const status = await hostedInObject(hooks, inv, d.objects, d.binding, a.id, a.object, {
334
424
  invocation,
335
425
  target: `DO:${d.binding}`,
336
426
  op: "alarm",
@@ -338,16 +428,11 @@ async function deliverAlarm(event, hooks, maxRedeliveries, d) {
338
428
  object: a.object,
339
429
  retryCount: a.retryCount
340
430
  },
341
- allowed: readFaults,
342
- hostsEffects: true
431
+ allowed: readFaults
343
432
  }, async () => {
344
- await d.runAlarm(a.id, a.object, info, a.gen);
433
+ await runAlarm(hooks, d, a.id, a.object, info, a.gen);
345
434
  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);
435
+ }, () => null);
351
436
  if (status !== "completed") {
352
437
  const next = redelivery(event, maxRetries, { maxRedeliveries });
353
438
  if (next) {
@@ -546,21 +631,16 @@ function summarize(result) {
546
631
  }
547
632
  function proxyNamespace(real, binding, ctx, state, helpers, isReset) {
548
633
  const target = `DO:${binding}`;
549
- const { names, touched, alarms: book } = state;
634
+ const { names } = state;
550
635
  const nameOf = (id) => names.get(id.toString()) ?? id.toString();
551
636
  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) {
637
+ /** Make sure the call may reach the object, take over its alarms first, and host the method about to run. */
638
+ async function reach(real, method) {
554
639
  if (!helpers) ctx.hooks.unsupported(`Durable Object binding ${binding} needs the Cloudflare test helpers (pass durableObjects to createCloudflarePlatform)`);
555
640
  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
- }
641
+ else await enterObject(real, binding, ctx, helpers, state, id, object, async (instance) => {
642
+ if (method !== void 0) hostMethod(ctx.hooks, hostOf(target, object), instance, method);
643
+ });
564
644
  }
565
645
  /** A result passed back to the Worker; one that is not plain data cannot be followed. */
566
646
  function plain(result) {
@@ -591,6 +671,7 @@ function proxyNamespace(real, binding, ctx, state, helpers, isReset) {
591
671
  allowed: writeFaults,
592
672
  hostsEffects: true
593
673
  }, perform, summarize, {
674
+ host: hostOf(target, object),
594
675
  onAbandon: () => state.abort(id),
595
676
  mayPark: () => state.mayPark(id)
596
677
  });
@@ -602,7 +683,7 @@ function proxyNamespace(real, binding, ctx, state, helpers, isReset) {
602
683
  object,
603
684
  args: args.map(argument)
604
685
  }, async () => {
605
- await reach(real);
686
+ await reach(real, prop);
606
687
  const method = real[prop];
607
688
  if (typeof method !== "function") throw new TypeError(`${binding} stub has no ${prop}`);
608
689
  const result = await Reflect.apply(method, real, args);
@@ -619,7 +700,7 @@ function proxyNamespace(real, binding, ctx, state, helpers, isReset) {
619
700
  object,
620
701
  property: true
621
702
  }, async () => {
622
- await reach(real);
703
+ await reach(real, prop);
623
704
  return plain(await real[prop]);
624
705
  });
625
706
  const awaitable = (onFulfilled, onRejected) => read().then(onFulfilled, onRejected);
@@ -640,8 +721,11 @@ function proxyNamespace(real, binding, ctx, state, helpers, isReset) {
640
721
  case "idFromName": return idFromName;
641
722
  case "idFromString": return (hex) => target.idFromString(hex);
642
723
  case "newUniqueId": return (options) => {
643
- ctx.hooks.unsupported(`${binding}.newUniqueId() is random and differs on replay; use idFromName`);
644
- return target.newUniqueId(options);
724
+ if (options?.jurisdiction !== void 0) {
725
+ ctx.hooks.unsupported(`${binding}.newUniqueId({ jurisdiction }) ids are not proxied or reset; use newUniqueId() without one`);
726
+ return target.newUniqueId(options);
727
+ }
728
+ return idFromName(`eutaxy:unique:${crypto.randomUUID()}`);
645
729
  };
646
730
  case "get": return (id, options) => stubFor(target.get(id, options), id.toString(), nameOf(id));
647
731
  case "getByName": return (name) => {
@@ -674,33 +758,22 @@ async function runInObject(real, binding, ctx, helpers, state, id, object, fn) {
674
758
  ctx.hooks.unsupported(`Durable Object binding ${binding} needs the Cloudflare test helpers`);
675
759
  return;
676
760
  }
761
+ return enterObject(real.get(real.idFromString(id)), binding, ctx, helpers, state, id, object, fn);
762
+ }
763
+ /**
764
+ * Enter an object through a stub for a call or an event of its own: the
765
+ * object is marked reached, its gate watched, its state kept for the run,
766
+ * its alarms taken over, then `fn` runs with the instance and its state.
767
+ */
768
+ function enterObject(stub, binding, ctx, helpers, state, id, object, fn) {
677
769
  state.touched.add(id);
678
- return typed(helpers).runInDurableObject(real.get(real.idFromString(id)), async (instance, live) => {
770
+ return typed(helpers).runInDurableObject(stub, async (instance, live) => {
679
771
  watchGate(live);
680
772
  state.states.set(id, live);
681
773
  await takeOverAlarms(live.storage, alarmControl(state.alarms, binding, id, object, () => ctx.hooks));
682
774
  return fn(instance, live);
683
775
  });
684
776
  }
685
- /**
686
- * Run an object's `alarm()` handler inside it, after taking over its alarms
687
- * (the instance may be new since the alarm was set).
688
- */
689
- function alarmRunner(real, binding, ctx, helpers, state) {
690
- return async (id, object, info, gen) => {
691
- await runInObject(real, binding, ctx, helpers, state, id, object, async (instance) => {
692
- const entry = state.alarms.entry(id);
693
- if (entry.gen !== gen) return;
694
- entry.time = null;
695
- const handler = instance.alarm;
696
- if (typeof handler !== "function") {
697
- ctx.hooks.unsupported(`Durable Object ${binding} ${object} set an alarm but has no alarm() handler`);
698
- return;
699
- }
700
- await handler.call(instance, info);
701
- });
702
- };
703
- }
704
777
  /** The objects to reset: every id the namespace has created, plus the setup's named ones. */
705
778
  async function objectIds(real, helpers, names, seeded) {
706
779
  const ids = /* @__PURE__ */ new Map();
@@ -757,12 +830,12 @@ async function clearAndSeed(real, helpers, names, objects, sql) {
757
830
  * The tables are the seeded objects and those a call reached, never objects
758
831
  * only earlier runs created, so a snapshot depends on this run alone.
759
832
  */
760
- async function snapshotNamespace(real, helpers, names, touched, objects, sql, seededSql, onIndirect, onUnsupported) {
761
- const { value, requested } = await withoutNetwork(() => readTables(real, helpers, names, touched, objects, sql, seededSql, onIndirect, onUnsupported));
833
+ async function snapshotNamespace(real, helpers, names, touched, objects, sql, seededSql, onIndirect, onUnsupported, all = false) {
834
+ const { value, requested } = await withoutNetwork(() => readTables(real, helpers, names, touched, objects, sql, seededSql, onIndirect, onUnsupported, all));
762
835
  if (requested) onUnsupported("a Durable Object made a request while its storage was being snapshotted");
763
836
  return value;
764
837
  }
765
- async function readTables(real, helpers, names, touched, objects, sql, seededSql, onIndirect, onUnsupported) {
838
+ async function readTables(real, helpers, names, touched, objects, sql, seededSql, onIndirect, onUnsupported, all) {
766
839
  const out = {};
767
840
  const define = (table, rows) => {
768
841
  if (Object.hasOwn(out, table)) throw new Error(`snapshot key ${table} named twice`);
@@ -776,15 +849,16 @@ async function readTables(real, helpers, names, touched, objects, sql, seededSql
776
849
  const seeded = seededNames(objects, sql);
777
850
  for (const id of await objectIds(real, helpers, names, seeded)) {
778
851
  const name = names.get(id.toString()) ?? id.toString();
779
- if (!touched.has(id.toString())) {
852
+ const read = all || touched.has(id.toString());
853
+ if (!read) {
780
854
  if (await typed(helpers).evictDurableObject(real.get(id)).then(() => true, () => false)) onIndirect(name);
781
855
  if (!seeded.includes(name)) continue;
782
856
  }
783
857
  let entries;
784
858
  const tables = [];
785
- if (touched.has(id.toString())) {
859
+ if (read) {
786
860
  const read = await typed(helpers).runInDurableObject(real.get(id), (_instance, state) => {
787
- 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`);
861
+ 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`);
788
862
  const surface = sqlOf(state.storage);
789
863
  const sqlTables = surface ? readSqlTables(surface) : [];
790
864
  return Promise.resolve(state.storage.list()).then((kv) => ({
@@ -864,6 +938,22 @@ function entrypointHandler(cls) {
864
938
  };
865
939
  return out;
866
940
  }
941
+ // packages/cloudflare/src/proxy-context.ts
942
+ /** The effect point of a proxied call: the invocation running now, the binding's target, the call. */
943
+ function pointAt(ctx, target, op, args, allowed) {
944
+ return {
945
+ invocation: ctx.currentInvocation(),
946
+ target,
947
+ op,
948
+ args,
949
+ allowed
950
+ };
951
+ }
952
+ /** Report why the run cannot be trusted and refuse the call with the same reason. */
953
+ function refuse(ctx, reason) {
954
+ ctx.hooks.unsupported(reason);
955
+ throw new Error(`eutaxy: ${reason}`);
956
+ }
867
957
  // packages/cloudflare/src/caller.ts
868
958
  /**
869
959
  * The caller of an inbound request or RPC call. Cloudflare retries neither,
@@ -908,24 +998,48 @@ function startCaller(event, hooks, spec, policy, target, gaveUp) {
908
998
  ...next,
909
999
  ...resendAt > Date.now() ? { at: resendAt } : {}
910
1000
  });
911
- } else hooks.effectSync({
1001
+ } else note(hooks, {
912
1002
  invocation: hooks.bookkeeping(),
913
1003
  target,
914
1004
  op: "gave_up",
915
1005
  args: gaveUp,
916
1006
  allowed: []
917
- }, () => null, () => null);
1007
+ });
918
1008
  };
919
1009
  const deadlineTimer = lateAt === void 0 ? void 0 : setTimeout(() => giveUp(lateAt), deadline);
920
- return {
921
- responseFaults: deadline === void 0 ? RESPOND : RESPOND_WITH_DEADLINE,
922
- isLate: () => lateAt !== void 0 && Date.now() > lateAt,
923
- settle(accepted, late) {
924
- if (deadlineTimer !== void 0) clearTimeout(deadlineTimer);
925
- if (accepted) decided = true;
926
- else giveUp(late && lateAt !== void 0 ? lateAt : Date.now());
927
- }
1010
+ const responseFaults = deadline === void 0 ? RESPOND : RESPOND_WITH_DEADLINE;
1011
+ const isLate = () => lateAt !== void 0 && Date.now() > lateAt;
1012
+ /** The caller decides as soon as it has an answer or gives up, before background work ends. */
1013
+ const settle = (accepted, late) => {
1014
+ if (deadlineTimer !== void 0) clearTimeout(deadlineTimer);
1015
+ if (accepted) decided = true;
1016
+ else giveUp(late && lateAt !== void 0 ? lateAt : Date.now());
928
1017
  };
1018
+ return { respond(invocation, args, answer) {
1019
+ let late = isLate();
1020
+ let accepted = false;
1021
+ let crashed = false;
1022
+ const record = (allowed, value) => {
1023
+ hooks.effectSync({
1024
+ invocation,
1025
+ target,
1026
+ op: "response",
1027
+ args,
1028
+ allowed
1029
+ }, () => value, (v) => v);
1030
+ };
1031
+ if (answer.kind === "answered") try {
1032
+ record(responseFaults, answer.value);
1033
+ accepted = answer.accepted;
1034
+ } catch (err) {
1035
+ if (err instanceof CrashSignal) crashed = true;
1036
+ else if (err instanceof InjectedEffectError) late = true;
1037
+ else throw err;
1038
+ }
1039
+ else if (answer.kind === "errored") record([], answer.value);
1040
+ settle(accepted && !late, late);
1041
+ return crashed;
1042
+ } };
929
1043
  }
930
1044
  // packages/cloudflare/src/cron.ts
931
1045
  const fields = [
@@ -1804,45 +1918,25 @@ async function deliverCall(event, hooks, spec, drive, invocation, cls, env) {
1804
1918
  });
1805
1919
  const ran = await runInvocation(hooks, inv, () => callMethod(cls, call, executionContext(background), env));
1806
1920
  let status = ran.status;
1807
- let late = caller.isLate();
1808
- let answer = null;
1921
+ let answer = { kind: "none" };
1809
1922
  if (ran.status === "completed") {
1810
1923
  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`);
1811
- const s = {
1812
- ok: true,
1813
- value: toJson(ran.value)
1924
+ answer = {
1925
+ kind: "answered",
1926
+ value: {
1927
+ ok: true,
1928
+ value: toJson(ran.value)
1929
+ },
1930
+ accepted: true
1814
1931
  };
1815
- try {
1816
- hooks.effectSync({
1817
- invocation,
1818
- target,
1819
- op: "response",
1820
- args,
1821
- allowed: caller.responseFaults
1822
- }, () => s, (v) => v);
1823
- answer = s;
1824
- } catch (err) {
1825
- if (err instanceof CrashSignal) status = "crashed";
1826
- else if (err instanceof InjectedEffectError) {
1827
- answer = s;
1828
- late = true;
1829
- } else throw err;
1830
- }
1831
- } else if (ran.status === "errored") {
1832
- const s = {
1932
+ } else if (ran.status === "errored") answer = {
1933
+ kind: "errored",
1934
+ value: {
1833
1935
  ok: false,
1834
1936
  error: describeError(ran.error)
1835
- };
1836
- hooks.effectSync({
1837
- invocation,
1838
- target,
1839
- op: "response",
1840
- args,
1841
- allowed: []
1842
- }, () => s, (v) => v);
1843
- answer = s;
1844
- }
1845
- caller.settle(answer !== null && !late && answer.ok, late);
1937
+ }
1938
+ };
1939
+ if (caller.respond(invocation, args, answer)) status = "crashed";
1846
1940
  if (await drainBackground(hooks, inv, invocation, target, background)) status = "crashed";
1847
1941
  return {
1848
1942
  status,
@@ -1964,11 +2058,7 @@ async function recordRequest(request) {
1964
2058
  * (promise pipelining, `connect()`), with the answers supplied.
1965
2059
  */
1966
2060
  function serviceStub(binding, ctx, answers) {
1967
- const unsupported = (what) => {
1968
- const reason = `service binding ${binding}: ${what}`;
1969
- ctx.hooks.unsupported(reason);
1970
- throw new Error(`eutaxy: ${reason}`);
1971
- };
2061
+ const unsupported = (what) => refuse(ctx, `service binding ${binding}: ${what}`);
1972
2062
  /**
1973
2063
  * The promise a call returns. On the real stub it is an RPC promise that
1974
2064
  * pipelines property reads (`stub.charge().id`); this one is not, so a read
@@ -2002,18 +2092,8 @@ function serviceStub(binding, ctx, answers) {
2002
2092
  /** The scripted stub a Worker sees under a service binding's name. */
2003
2093
  function proxyService(binding, ctx, script) {
2004
2094
  const target = `Service:${binding}`;
2005
- const point = (op, args) => ({
2006
- invocation: ctx.currentInvocation(),
2007
- target,
2008
- op,
2009
- args,
2010
- allowed: writeFaults
2011
- });
2012
- const unsupported = (what) => {
2013
- const reason = `service binding ${binding}: ${what}`;
2014
- ctx.hooks.unsupported(reason);
2015
- throw new Error(`eutaxy: ${reason}`);
2016
- };
2095
+ const point = (op, args) => pointAt(ctx, target, op, args, writeFaults);
2096
+ const unsupported = (what) => refuse(ctx, `service binding ${binding}: ${what}`);
2017
2097
  /** The scripted reply to a method, by name; a method the script lacks cannot be answered. */
2018
2098
  const replyTo = (method) => {
2019
2099
  if (script.methods === void 0) return { returns: null };
@@ -2188,18 +2268,8 @@ function proxyCallee(binding, ctx, setup, module, env, state) {
2188
2268
  const view = calleeEnv(module.name, env);
2189
2269
  const entrypointName = setup.entrypoint ?? module.entrypoint;
2190
2270
  const props = module.props ?? {};
2191
- const unsupported = (what) => {
2192
- const reason = `callee ${binding}: ${what}`;
2193
- ctx.hooks.unsupported(reason);
2194
- throw new Error(`eutaxy: ${reason}`);
2195
- };
2196
- const point = (op, args) => ({
2197
- invocation: ctx.currentInvocation(),
2198
- target,
2199
- op,
2200
- args,
2201
- allowed: callFaults
2202
- });
2271
+ const unsupported = (what) => refuse(ctx, `callee ${binding}: ${what}`);
2272
+ const point = (op, args) => pointAt(ctx, target, op, args, callFaults);
2203
2273
  /** The hosted invocation's id: the n-th call of a method from one caller invocation is `#n`. */
2204
2274
  const invocationId = (method) => {
2205
2275
  const key = `${ctx.currentInvocation()}/${binding}.${method}`;
@@ -2322,15 +2392,6 @@ async function expectHolds(spec, platform, options) {
2322
2392
  function isD1(value) {
2323
2393
  return typeof value === "object" && value !== null && typeof value.prepare === "function" && typeof value.batch === "function";
2324
2394
  }
2325
- function point(ctx, target, op, args, allowed) {
2326
- return {
2327
- invocation: ctx.currentInvocation(),
2328
- target,
2329
- op,
2330
- args,
2331
- allowed
2332
- };
2333
- }
2334
2395
  function metaOf(result) {
2335
2396
  return {
2336
2397
  changes: result.meta.changes ?? 0,
@@ -2364,22 +2425,22 @@ var StatementProxy = class StatementProxy {
2364
2425
  return new StatementProxy(this.real.bind(...values), this.target, this.ctx, this.sql, values);
2365
2426
  }
2366
2427
  run() {
2367
- return this.ctx.hooks.effect(point(this.ctx, this.target, "run", this.args(), writeFaults), () => this.real.run(), (r) => metaOf(r));
2428
+ return this.ctx.hooks.effect(pointAt(this.ctx, this.target, "run", this.args(), writeFaults), () => this.real.run(), (r) => metaOf(r));
2368
2429
  }
2369
2430
  all() {
2370
- return this.ctx.hooks.effect(point(this.ctx, this.target, "all", this.args(), readFaults), () => this.real.all(), (r) => ({
2431
+ return this.ctx.hooks.effect(pointAt(this.ctx, this.target, "all", this.args(), readFaults), () => this.real.all(), (r) => ({
2371
2432
  rows: r.results.length,
2372
2433
  changes: r.meta.changes ?? 0
2373
2434
  }));
2374
2435
  }
2375
2436
  first(colName) {
2376
- return this.ctx.hooks.effect(point(this.ctx, this.target, "first", {
2437
+ return this.ctx.hooks.effect(pointAt(this.ctx, this.target, "first", {
2377
2438
  ...this.args(),
2378
2439
  column: colName ?? null
2379
2440
  }, readFaults), () => colName === void 0 ? this.real.first() : this.real.first(colName), (r) => ({ row: toJson(r) }));
2380
2441
  }
2381
2442
  raw(options) {
2382
- 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 }));
2443
+ 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 }));
2383
2444
  }
2384
2445
  };
2385
2446
  /** Wrap a D1 binding. Methods not modelled fall through to the real binding and mark the run unsupported. */
@@ -2395,13 +2456,13 @@ function proxyD1(real, binding, ctx) {
2395
2456
  sql: s.sql,
2396
2457
  params: toJson(s.params)
2397
2458
  } : "<unproxied statement>") };
2398
- return ctx.hooks.effect(point(ctx, target, "batch", args, writeFaults), () => real.batch(unwrapped), (rs) => ({
2459
+ return ctx.hooks.effect(pointAt(ctx, target, "batch", args, writeFaults), () => real.batch(unwrapped), (rs) => ({
2399
2460
  changes: rs.reduce((n, r) => n + (r.meta.changes ?? 0), 0),
2400
2461
  statements: rs.length
2401
2462
  }));
2402
2463
  },
2403
2464
  exec(sql) {
2404
- return ctx.hooks.effect(point(ctx, target, "exec", { sql }, writeFaults), () => real.exec(sql), (r) => ({
2465
+ return ctx.hooks.effect(pointAt(ctx, target, "exec", { sql }, writeFaults), () => real.exec(sql), (r) => ({
2405
2466
  count: r.count,
2406
2467
  duration: 0
2407
2468
  }));
@@ -2659,18 +2720,8 @@ function putArgs(options) {
2659
2720
  }
2660
2721
  function proxyR2(real, binding, ctx, book) {
2661
2722
  const target = `R2:${binding}`;
2662
- const point = (op, args, allowed) => ({
2663
- invocation: ctx.currentInvocation(),
2664
- target,
2665
- op,
2666
- args,
2667
- allowed
2668
- });
2669
- const notModelled = (what) => {
2670
- const reason = `R2 ${binding}: ${what} is not modelled`;
2671
- ctx.hooks.unsupported(reason);
2672
- throw new Error(`eutaxy: ${reason}`);
2673
- };
2723
+ const point = (op, args, allowed) => pointAt(ctx, target, op, args, allowed);
2724
+ const notModelled = (what) => refuse(ctx, `R2 ${binding}: ${what} is not modelled`);
2674
2725
  /** Date conditions compare the store's real upload time, not the stand-in the Worker saw. */
2675
2726
  const checkConditions = (onlyIf) => {
2676
2727
  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`);
@@ -2795,12 +2846,16 @@ async function snapshotR2(real) {
2795
2846
  */
2796
2847
  /** The `EventRef.source` of a Workflow instance's run. */
2797
2848
  const workflowSource = "workflow";
2798
- /** Before a step's callback: the engine restarts before the step runs. */
2799
- const STEP_START = ["crash_before"];
2849
+ /**
2850
+ * Before a step's callback: the engine restarts before the step runs
2851
+ * (`crash_before`), or the attempt outlives its timeout from its start
2852
+ * (`ambiguous`): counted as failed and retried while it runs on late.
2853
+ */
2854
+ const STEP_START = ["crash_before", "ambiguous"];
2800
2855
  /**
2801
2856
  * After it: the engine restarts after the step ran but before its result
2802
2857
  * was persisted (`crash_after`), or the attempt ran and counted as failed,
2803
- * as a timeout does (`ambiguous`).
2858
+ * as a timeout just after its work does (`ambiguous`).
2804
2859
  */
2805
2860
  const STEP_RESULT = ["crash_after", "ambiguous"];
2806
2861
  /**
@@ -2857,11 +2912,7 @@ function isWorkflowBinding(value) {
2857
2912
  /** The binding's proxy: instances live in the registry and run as events, never in the real engine. */
2858
2913
  function proxyWorkflow(binding, ctx, registry) {
2859
2914
  const target = `Workflow:${binding}`;
2860
- const unsupported = (what) => {
2861
- const reason = `Workflow ${binding}: ${what} is not modelled`;
2862
- ctx.hooks.unsupported(reason);
2863
- throw new Error(`eutaxy: ${reason}`);
2864
- };
2915
+ const unsupported = (what) => refuse(ctx, `Workflow ${binding}: ${what} is not modelled`);
2865
2916
  const handle = (id) => ({
2866
2917
  id,
2867
2918
  status: () => ctx.hooks.effect({
@@ -3199,21 +3250,69 @@ async function deliverWorkflow(event, hooks, d) {
3199
3250
  count,
3200
3251
  attempt
3201
3252
  };
3202
- await hooks.effect({
3203
- invocation,
3204
- target,
3205
- op: "step",
3206
- args,
3207
- allowed: STEP_START
3208
- }, async () => null, () => null);
3253
+ let lateAtStart = false;
3254
+ try {
3255
+ await hooks.effect({
3256
+ invocation,
3257
+ target,
3258
+ op: "step",
3259
+ args,
3260
+ allowed: STEP_START
3261
+ }, async () => null, () => null);
3262
+ } catch (err) {
3263
+ if (!(err instanceof InjectedEffectError)) throw err;
3264
+ lateAtStart = true;
3265
+ }
3209
3266
  instance.attempts.set(k, attempt);
3210
3267
  let failed = false;
3211
3268
  let thrown;
3212
3269
  let value;
3213
3270
  let returned;
3214
- try {
3215
- returned = { value: await fn(stepContext) };
3216
- } catch (err) {
3271
+ const timeoutMs = durationMs(resolved.timeout);
3272
+ const started = hooks.attempt(invocation, () => {
3273
+ try {
3274
+ return Promise.resolve(fn(stepContext));
3275
+ } catch (err) {
3276
+ return Promise.reject(err);
3277
+ }
3278
+ }, lateAtStart ? 0 : timeoutMs);
3279
+ const settled = started.value.then((v) => ({
3280
+ ok: true,
3281
+ value: v
3282
+ }), (error) => ({
3283
+ ok: false,
3284
+ error
3285
+ }));
3286
+ const outcome = lateAtStart ? "late" : await Promise.race([settled, started.late.then(() => "late")]);
3287
+ if (outcome === "late") {
3288
+ if (!lateAtStart) note(hooks, {
3289
+ invocation,
3290
+ target,
3291
+ op: "step_timeout",
3292
+ args: {
3293
+ ...args,
3294
+ timeoutMs
3295
+ },
3296
+ allowed: []
3297
+ });
3298
+ failed = true;
3299
+ thrown = Object.assign(/* @__PURE__ */ new Error(`Execution timed out after ${timeoutMs}ms`), { name: "WorkflowTimeoutError" });
3300
+ background.push(settled.then((o) => {
3301
+ if (inv.isCrashed()) return;
3302
+ note(hooks, {
3303
+ invocation,
3304
+ target,
3305
+ op: "late_result",
3306
+ args: {
3307
+ ...args,
3308
+ outcome: o.ok ? "returned" : "threw"
3309
+ },
3310
+ allowed: []
3311
+ });
3312
+ }));
3313
+ } else if (outcome.ok) returned = { value: outcome.value };
3314
+ else {
3315
+ const err = outcome.error;
3217
3316
  if (err instanceof CrashSignal || inv.isCrashed()) throw err;
3218
3317
  failed = true;
3219
3318
  thrown = err;
@@ -3341,20 +3440,20 @@ async function deliverWorkflow(event, hooks, d) {
3341
3440
  }
3342
3441
  if (existing !== void 0 && Date.now() >= existing) {
3343
3442
  const error = Object.assign(/* @__PURE__ */ new Error(`Execution timed out after ${timeoutMs}ms`), { name: "WorkflowTimeoutError" });
3344
- hooks.effectSync({
3443
+ note(hooks, {
3345
3444
  invocation,
3346
3445
  target,
3347
3446
  op: "wait_timeout",
3348
3447
  args,
3349
3448
  allowed: []
3350
- }, () => null, () => null);
3449
+ });
3351
3450
  instance.persisted.set(k, failure(error));
3352
3451
  throw error;
3353
3452
  }
3354
3453
  const deadline = existing ?? Date.now() + timeoutMs;
3355
3454
  if (existing === void 0) {
3356
3455
  instance.deadlines.set(k, deadline);
3357
- hooks.effectSync({
3456
+ note(hooks, {
3358
3457
  invocation,
3359
3458
  target,
3360
3459
  op: "wait",
@@ -3363,7 +3462,7 @@ async function deliverWorkflow(event, hooks, d) {
3363
3462
  timeoutMs
3364
3463
  },
3365
3464
  allowed: []
3366
- }, () => null, () => null);
3465
+ });
3367
3466
  }
3368
3467
  const gen = ++instance.waitGen;
3369
3468
  instance.waiting = {
@@ -3404,7 +3503,7 @@ async function deliverWorkflow(event, hooks, d) {
3404
3503
  return;
3405
3504
  }
3406
3505
  instance.deadlines.set(k, Date.now() + ms);
3407
- hooks.effectSync({
3506
+ note(hooks, {
3408
3507
  invocation,
3409
3508
  target,
3410
3509
  op: "sleep",
@@ -3415,7 +3514,7 @@ async function deliverWorkflow(event, hooks, d) {
3415
3514
  ...until === void 0 ? {} : { until }
3416
3515
  },
3417
3516
  allowed: []
3418
- }, () => null, () => null);
3517
+ });
3419
3518
  await sleep(ms);
3420
3519
  instance.persisted.set(k, {
3421
3520
  ok: true,
@@ -3462,6 +3561,10 @@ async function deliverWorkflow(event, hooks, d) {
3462
3561
  value: void 0
3463
3562
  };
3464
3563
  let status = result.status;
3564
+ const restart = () => status === "crashed" && instance.status === "running" && event.attempt <= d.maxFaultsPerRun ? [{
3565
+ ...event,
3566
+ attempt: event.attempt + 1
3567
+ }] : [];
3465
3568
  if (suspending !== void 0 && result.status === "completed") {
3466
3569
  instance.status = "waiting";
3467
3570
  const suspended = suspending;
@@ -3470,10 +3573,7 @@ async function deliverWorkflow(event, hooks, d) {
3470
3573
  instance.status = "running";
3471
3574
  instance.waiting = void 0;
3472
3575
  }
3473
- const followUps = status === "crashed" ? instance.status === "running" && event.attempt <= d.maxFaultsPerRun ? [{
3474
- ...event,
3475
- attempt: event.attempt + 1
3476
- }] : [] : [{
3576
+ const followUps = status === "crashed" ? restart() : [{
3477
3577
  id: `workflow:${d.binding}:${instance.id}:timeout-${suspended.gen}`,
3478
3578
  attempt: 1,
3479
3579
  source: workflowSource,
@@ -3492,7 +3592,7 @@ async function deliverWorkflow(event, hooks, d) {
3492
3592
  if (result.status === "completed") {
3493
3593
  instance.status = "complete";
3494
3594
  instance.output = result.value;
3495
- hooks.effectSync({
3595
+ note(hooks, {
3496
3596
  invocation,
3497
3597
  target,
3498
3598
  op: "complete",
@@ -3501,7 +3601,7 @@ async function deliverWorkflow(event, hooks, d) {
3501
3601
  output: toJson(instance.output)
3502
3602
  },
3503
3603
  allowed: []
3504
- }, () => null, () => null);
3604
+ });
3505
3605
  } else if (result.status === "errored") {
3506
3606
  instance.status = "errored";
3507
3607
  const e = result.error;
@@ -3512,7 +3612,7 @@ async function deliverWorkflow(event, hooks, d) {
3512
3612
  name: "Error",
3513
3613
  message: String(e)
3514
3614
  };
3515
- hooks.effectSync({
3615
+ note(hooks, {
3516
3616
  invocation,
3517
3617
  target,
3518
3618
  op: "errored",
@@ -3521,16 +3621,12 @@ async function deliverWorkflow(event, hooks, d) {
3521
3621
  error: `${instance.error.name}: ${instance.error.message}`
3522
3622
  },
3523
3623
  allowed: []
3524
- }, () => null, () => null);
3624
+ });
3525
3625
  }
3526
3626
  if (await drainBackground(hooks, inv, invocation, target, background)) status = "crashed";
3527
- const followUps = status === "crashed" && instance.status === "running" && event.attempt <= d.maxFaultsPerRun ? [{
3528
- ...event,
3529
- attempt: event.attempt + 1
3530
- }] : [];
3531
3627
  return {
3532
3628
  status,
3533
- followUps
3629
+ followUps: restart()
3534
3630
  };
3535
3631
  }
3536
3632
  /** The delay before the next attempt (Workflows, Sleeping and retrying; a delay function is called). */
@@ -3637,13 +3733,14 @@ function durableObjectBinding(deps) {
3637
3733
  if (!helpers) throw new Error("Durable Object setup needs the Cloudflare test helpers: createCloudflarePlatform({ ..., durableObjects: await import(\"cloudflare:test\") })");
3638
3734
  return helpers;
3639
3735
  };
3736
+ const objects = {
3737
+ run: (binding, id, object, fn) => runInObject(namespace(binding), binding, ctx, helpers, stateFor(binding), id, object, fn),
3738
+ abort: (binding, id) => stateFor(binding).abort(id),
3739
+ mayPark: (binding, id) => stateFor(binding).mayPark(id),
3740
+ evict: (binding, id) => evictObject(namespace(binding), helpers, id)
3741
+ };
3640
3742
  return {
3641
- objects: {
3642
- run: (binding, id, object, fn) => runInObject(namespace(binding), binding, ctx, helpers, stateFor(binding), id, object, fn),
3643
- abort: (binding, id) => stateFor(binding).abort(id),
3644
- mayPark: (binding, id) => stateFor(binding).mayPark(id),
3645
- evict: (binding, id) => evictObject(namespace(binding), helpers, id)
3646
- },
3743
+ objects,
3647
3744
  kind: "durable_object",
3648
3745
  target: "DO",
3649
3746
  is: isDurableObjectNamespace,
@@ -3667,7 +3764,7 @@ function durableObjectBinding(deps) {
3667
3764
  },
3668
3765
  async snapshot(step, real, unsupported) {
3669
3766
  const binding = step.binding;
3670
- 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);
3767
+ 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);
3671
3768
  },
3672
3769
  source: alarmSource,
3673
3770
  async deliver(event, hooks, spec) {
@@ -3676,17 +3773,14 @@ function durableObjectBinding(deps) {
3676
3773
  binding,
3677
3774
  book: stateFor(binding).alarms,
3678
3775
  limit: alarmLimits.get(binding) ?? 3,
3679
- runAlarm: alarmRunner(namespace(binding), binding, ctx, helpers, stateFor(binding)),
3680
- abort: (id) => stateFor(binding).abort(id),
3681
- mayPark: (id) => stateFor(binding).mayPark(id),
3682
- evict: (id) => evictObject(namespace(binding), helpers, id),
3683
- bookkeep: (op, args) => hooks.effectSync({
3776
+ objects,
3777
+ bookkeep: (op, args) => note(hooks, {
3684
3778
  invocation: hooks.bookkeeping(),
3685
3779
  target: `DO:${binding}`,
3686
3780
  op,
3687
3781
  args,
3688
3782
  allowed: []
3689
- }, () => null, () => null)
3783
+ })
3690
3784
  });
3691
3785
  }
3692
3786
  };
@@ -3927,53 +4021,33 @@ async function deliverRequest(event, hooks, spec, drive, invocation, worker) {
3927
4021
  requestId: event.id,
3928
4022
  attempts: event.attempt
3929
4023
  });
3930
- const handled = await runInvocation(hooks, inv, () => handler.call(worker.handler, requestFor(req), worker.env, executionContext(background)));
3931
- const response = handled.status === "completed" ? handled.value : void 0;
4024
+ const handled = await runInvocation(hooks, inv, async () => {
4025
+ const value = await handler.call(worker.handler, requestFor(req), worker.env, executionContext(background));
4026
+ if (!(value instanceof Response)) throw new TypeError("the fetch handler returned something that is not a Response");
4027
+ return value;
4028
+ });
3932
4029
  let status = handled.status;
3933
- let summary = null;
3934
- let read = "errored";
3935
- if (status === "completed" && response) {
3936
- const body = await runInvocation(hooks, inv, () => summarizeResponse(response));
3937
- read = body.status === "completed" ? body.value : body.status;
3938
- if (read === "crashed" || read === "errored") status = read;
4030
+ let answer = { kind: "none" };
4031
+ if (handled.status === "completed") {
4032
+ const body = await runInvocation(hooks, inv, () => summarizeResponse(handled.value));
4033
+ if (body.status === "completed") {
4034
+ const sent = body.value;
4035
+ answer = {
4036
+ kind: "answered",
4037
+ value: sent,
4038
+ accepted: drive.retryOn === "5xx" ? sent.status < 500 : sent.ok
4039
+ };
4040
+ } else status = body.status;
3939
4041
  }
3940
- let late = caller.isLate();
3941
- const allowed = caller.responseFaults;
3942
- if (status === "completed" && typeof read === "object") {
3943
- const s = read;
3944
- try {
3945
- hooks.effectSync({
3946
- invocation,
3947
- target,
3948
- op: "response",
3949
- args,
3950
- allowed
3951
- }, () => s, (v) => v);
3952
- summary = s;
3953
- } catch (err) {
3954
- if (err instanceof CrashSignal) status = "crashed";
3955
- else if (err instanceof InjectedEffectError) {
3956
- summary = s;
3957
- late = true;
3958
- } else throw err;
3959
- }
3960
- } else if (status === "errored") {
3961
- const s = {
4042
+ if (status === "errored") answer = {
4043
+ kind: "errored",
4044
+ value: {
3962
4045
  status: 500,
3963
4046
  ok: false,
3964
4047
  body: ""
3965
- };
3966
- hooks.effectSync({
3967
- invocation,
3968
- target,
3969
- op: "response",
3970
- args,
3971
- allowed: []
3972
- }, () => s, (v) => v);
3973
- summary = s;
3974
- }
3975
- const accepted = summary !== null && !late && (drive.retryOn === "5xx" ? summary.status < 500 : summary.ok);
3976
- caller.settle(accepted, late);
4048
+ }
4049
+ };
4050
+ if (caller.respond(invocation, args, answer)) status = "crashed";
3977
4051
  if (await drainBackground(hooks, inv, invocation, target, background)) status = "crashed";
3978
4052
  return {
3979
4053
  status,
@@ -3993,31 +4067,35 @@ async function deliverMessage$1(event, hooks, spec, drive, invocation, worker, m
3993
4067
  /** Cloudflare honours the first ack or retry decision per message; later ones are ignored. */
3994
4068
  const state = { decision: null };
3995
4069
  const background = [];
3996
- /** Records the call; the result says whether it took effect (the first decision wins). */
3997
- const decide = (op, args) => {
3998
- hooks.effectSync({
3999
- invocation,
4000
- target: queueTarget,
4001
- op,
4002
- args,
4003
- allowed: decisionFaults
4004
- }, () => {
4005
- if (state.decision !== null) return false;
4006
- state.decision = op;
4007
- return true;
4008
- }, (effective) => ({ effective }));
4070
+ const decisionPoint = (op, args) => ({
4071
+ invocation,
4072
+ target: queueTarget,
4073
+ op,
4074
+ args,
4075
+ allowed: decisionFaults
4076
+ });
4077
+ /** The first decision wins; a later one is recorded as not effective. */
4078
+ const take = (op) => () => {
4079
+ if (state.decision !== null) return false;
4080
+ state.decision = op;
4081
+ return true;
4082
+ };
4083
+ const effective = (e) => ({ effective: e });
4084
+ /** Records the handler's call; the result says whether it took effect. */
4085
+ const record = (op, args) => {
4086
+ hooks.effectSync(decisionPoint(op, args), take(op), effective);
4009
4087
  };
4010
4088
  const message = {
4011
4089
  id: event.id,
4012
4090
  timestamp: /* @__PURE__ */ new Date(),
4013
4091
  body: cloneJson(event.data),
4014
4092
  attempts: event.attempt,
4015
- ack: () => decide("ack", {
4093
+ ack: () => record("ack", {
4016
4094
  messageId: event.id,
4017
4095
  implicit: false,
4018
4096
  body: event.data
4019
4097
  }),
4020
- retry: () => decide("retry", {
4098
+ retry: () => record("retry", {
4021
4099
  messageId: event.id,
4022
4100
  body: event.data
4023
4101
  })
@@ -4036,22 +4114,20 @@ async function deliverMessage$1(event, hooks, spec, drive, invocation, worker, m
4036
4114
  const handler = worker.handler.queue;
4037
4115
  if (!handler) throw new Error("the Worker has no queue() handler");
4038
4116
  let status = (await runInvocation(hooks, inv, () => handler.call(worker.handler, batch, worker.env, execution))).status;
4039
- if (status === "completed" && state.decision === null) try {
4040
- decide("ack", {
4117
+ if (status === "completed" && state.decision === null) {
4118
+ const implicit = decisionPoint("ack", {
4041
4119
  messageId: event.id,
4042
4120
  implicit: true,
4043
4121
  body: event.data
4044
4122
  });
4045
- } catch (err) {
4046
- if (err instanceof CrashSignal) status = "crashed";
4047
- else throw err;
4123
+ if (decide(hooks, implicit, take("ack"), effective) === "crashed") status = "crashed";
4048
4124
  }
4049
4125
  if (await drainBackground(hooks, inv, invocation, queueTarget, background)) status = "crashed";
4050
4126
  const followUps = [];
4051
4127
  if (state.decision !== "ack") {
4052
4128
  const next = redelivery(event, maxRetries, spec.bounds);
4053
4129
  if (next) followUps.push(next);
4054
- else hooks.effectSync({
4130
+ else note(hooks, {
4055
4131
  invocation: hooks.bookkeeping(),
4056
4132
  target: queueTarget,
4057
4133
  op: "dead_letter",
@@ -4060,7 +4136,7 @@ async function deliverMessage$1(event, hooks, spec, drive, invocation, worker, m
4060
4136
  attempts: event.attempt
4061
4137
  },
4062
4138
  allowed: []
4063
- }, () => null, () => null);
4139
+ });
4064
4140
  }
4065
4141
  return {
4066
4142
  status,
@@ -4109,7 +4185,7 @@ async function deliverTick(event, hooks, spec, drive, invocation, worker) {
4109
4185
  if (status !== "completed" && !noRetry) {
4110
4186
  const next = redelivery(event, drive.retries, spec.bounds);
4111
4187
  if (next) followUps.push(next);
4112
- else hooks.effectSync({
4188
+ else note(hooks, {
4113
4189
  invocation: hooks.bookkeeping(),
4114
4190
  target,
4115
4191
  op: "gave_up",
@@ -4118,7 +4194,7 @@ async function deliverTick(event, hooks, spec, drive, invocation, worker) {
4118
4194
  attempts: event.attempt
4119
4195
  },
4120
4196
  allowed: []
4121
- }, () => null, () => null);
4197
+ });
4122
4198
  }
4123
4199
  return {
4124
4200
  status,
@@ -4339,7 +4415,7 @@ var Connections = class {
4339
4415
  record(hooks) {
4340
4416
  const bookkeeping = () => hooks.bookkeeping();
4341
4417
  for (const [connection, c] of this.open) {
4342
- for (const data of this.frames.get(connection) ?? []) hooks.effectSync({
4418
+ for (const data of this.frames.get(connection) ?? []) note(hooks, {
4343
4419
  invocation: bookkeeping(),
4344
4420
  target: `WebSocket:${connection}`,
4345
4421
  op: "message",
@@ -4348,8 +4424,8 @@ var Connections = class {
4348
4424
  data
4349
4425
  },
4350
4426
  allowed: []
4351
- }, () => null, () => null);
4352
- if (c.closed) hooks.effectSync({
4427
+ });
4428
+ if (c.closed) note(hooks, {
4353
4429
  invocation: bookkeeping(),
4354
4430
  target: `WebSocket:${connection}`,
4355
4431
  op: "close",
@@ -4359,7 +4435,7 @@ var Connections = class {
4359
4435
  reason: c.closed.reason
4360
4436
  },
4361
4437
  allowed: []
4362
- }, () => null, () => null);
4438
+ });
4363
4439
  }
4364
4440
  this.frames.clear();
4365
4441
  }
@@ -4574,13 +4650,12 @@ async function deliverMessage(event, hooks, c, data, deps) {
4574
4650
  };
4575
4651
  }
4576
4652
  const { binding, id, object } = conn.upgrade;
4577
- const { status } = await runInvocation(hooks, inv, () => hooks.effect({
4653
+ const status = await hostedInObject(hooks, inv, deps.objects, binding, id, object, {
4578
4654
  invocation,
4579
4655
  target,
4580
4656
  op: "send",
4581
4657
  args,
4582
- allowed: readFaults,
4583
- hostsEffects: true
4658
+ allowed: readFaults
4584
4659
  }, async () => {
4585
4660
  await deps.objects.run(binding, id, object, async (instance, live) => {
4586
4661
  const { lost } = deps.connections.rebind(conn.upgrade, live);
@@ -4598,17 +4673,13 @@ async function deliverMessage(event, hooks, c, data, deps) {
4598
4673
  return;
4599
4674
  }
4600
4675
  const end = conn.server ?? server;
4601
- await handler.call(instance, end, frameText(data.data));
4676
+ await hooks.hostedCode(hostOf(`DO:${binding}`, object), () => handler.call(instance, end, frameText(data.data)));
4602
4677
  conn.identity = identityOf(end, live);
4603
4678
  });
4604
4679
  await settleFrames();
4605
4680
  return { delivered: true };
4606
- }, (v) => v, {
4607
- onAbandon: () => deps.objects.abort(binding, id),
4608
- mayPark: () => deps.objects.mayPark(binding, id)
4609
- }));
4681
+ }, (v) => v);
4610
4682
  if (status === "crashed") {
4611
- await deps.objects.evict(binding, id);
4612
4683
  const rebuild = hooks.startInvocation(`${invocation}/rebuild`);
4613
4684
  await runInvocation(hooks, rebuild, () => hooks.effect({
4614
4685
  invocation: rebuild.id,
@@ -4654,7 +4725,7 @@ const assumptions = [
4654
4725
  "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",
4655
4726
  "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",
4656
4727
  "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",
4657
- "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/)",
4728
+ "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; objects are cleared, seeded and evicted before each run and their storage is snapshotted after it (developers.cloudflare.com/durable-objects/api/storage-api/)",
4658
4729
  "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)",
4659
4730
  "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/)",
4660
4731
  "state invariants read a snapshot of every D1 binding named in setup, taken after the last event",
@@ -4814,9 +4885,10 @@ function createCloudflarePlatform(options) {
4814
4885
  * Differential check: the same fault-free scenario run once through Eutaxy's
4815
4886
  * proxies and once against the raw bindings, with the queue model (or the
4816
4887
  * HTTP caller's retry policy) applied on the raw side itself. Any difference in the per-attempt decisions or in
4817
- * the final D1 and R2 state is a bug in the proxies or the platform model, not in
4888
+ * the final D1, R2 and Durable Object state is a bug in the proxies or the platform model, not in
4818
4889
  * the Worker. The raw side shares Eutaxy's *reading* of Cloudflare's queue
4819
- * semantics (core's redelivery rule among it); what it does not share is any proxy code.
4890
+ * semantics (core's redelivery rule among it) and the engine's raw loop; what
4891
+ * it does not share is any proxy code.
4820
4892
  */
4821
4893
  /**
4822
4894
  * The raw side's only wrapper: counts D1 calls in flight (so the settle loop
@@ -4893,16 +4965,69 @@ function countingR2(real, io, clock) {
4893
4965
  }
4894
4966
  /**
4895
4967
  * The bindings whose state the two sides compare: those a store holds and
4896
- * the real binding resets and reads back (D1, R2). Durable Objects and
4897
- * Workflows have no raw side.
4968
+ * the real binding resets and reads back (D1, R2, and Durable Objects when
4969
+ * the test helpers are given: the raw side reads every seeded object's
4970
+ * storage, since no proxy saw which were reached). Workflows have no raw
4971
+ * side.
4898
4972
  */
4899
4973
  function storedBindings(options) {
4900
- return [d1Binding(options.schemas), r2Binding()];
4974
+ const helpers = options.durableObjects;
4975
+ const env = options.env;
4976
+ return [
4977
+ d1Binding(options.schemas),
4978
+ r2Binding(),
4979
+ ...helpers ? [durableObjectBinding({
4980
+ ctx: {
4981
+ hooks: void 0,
4982
+ currentInvocation: () => "raw"
4983
+ },
4984
+ helpers,
4985
+ real: (name) => env[name],
4986
+ snapshotAll: true
4987
+ })] : []
4988
+ ];
4989
+ }
4990
+ /**
4991
+ * A Durable Object namespace whose stub calls count as I/O in flight: the
4992
+ * call crosses workerd, which the settle loop cannot otherwise see, and
4993
+ * advances the clock as the proxied call does. It records nothing.
4994
+ */
4995
+ function countingNamespace(real, io, clock) {
4996
+ const track = async (p) => {
4997
+ io.n++;
4998
+ try {
4999
+ return await p;
5000
+ } finally {
5001
+ io.n--;
5002
+ clock.advance(1);
5003
+ }
5004
+ };
5005
+ const countingStub = (stub) => new Proxy(stub, { get(t, prop, r) {
5006
+ const v = Reflect.get(t, prop, r);
5007
+ if (prop === "then" || prop === "id" || prop === "name" || typeof prop !== "string") return v;
5008
+ if (typeof v !== "function") return v;
5009
+ return new Proxy(v, {
5010
+ apply: (member, _self, a) => track(Promise.resolve(Reflect.apply(member, t, a))),
5011
+ get(member, key, receiver) {
5012
+ if (key === "then") {
5013
+ const read = track(Promise.resolve(member));
5014
+ return read.then.bind(read);
5015
+ }
5016
+ return Reflect.get(member, key, receiver);
5017
+ }
5018
+ });
5019
+ } });
5020
+ return new Proxy(real, { get(t, prop, r) {
5021
+ const v = Reflect.get(t, prop, r);
5022
+ if (prop === "get") return (...a) => countingStub(t.get(...a));
5023
+ if (prop === "getByName") return (name) => countingStub(t.getByName(name));
5024
+ return typeof v === "function" ? v.bind(t) : v;
5025
+ } });
4901
5026
  }
4902
- async function snapshotAll(spec, options) {
5027
+ async function snapshotAll(spec, options, stored) {
4903
5028
  const env = options.env;
4904
5029
  const out = {};
4905
- for (const [binding, setup] of ownedSetups(spec.setup, storedBindings(options))) {
5030
+ for (const [binding, setup] of ownedSetups(spec.setup, stored)) {
4906
5031
  const tables = await binding.snapshot(setup, env[setup.binding], (reason) => {
4907
5032
  throw new Error(`snapshot of ${setup.binding}: ${reason}`);
4908
5033
  });
@@ -4911,7 +5036,7 @@ async function snapshotAll(spec, options) {
4911
5036
  return out;
4912
5037
  }
4913
5038
  /** The Eutaxy side, keeping each delivery's status and the decision it made. */
4914
- async function eutaxySide(spec, options) {
5039
+ async function eutaxySide(spec, options, stored) {
4915
5040
  const { attempts, unsupported } = await proxiedSide(spec, createCloudflarePlatform(options), (event, result, entries) => {
4916
5041
  const invocation = invocationOf(event);
4917
5042
  const mine = entries.filter((e) => e.invocation === invocation);
@@ -4932,7 +5057,7 @@ async function eutaxySide(spec, options) {
4932
5057
  });
4933
5058
  return {
4934
5059
  attempts,
4935
- state: await snapshotAll(spec, options),
5060
+ state: await snapshotAll(spec, options, stored),
4936
5061
  unsupported
4937
5062
  };
4938
5063
  }
@@ -4942,212 +5067,175 @@ function flatten(state) {
4942
5067
  for (const [binding, tables] of Object.entries(state)) for (const [table, rows] of Object.entries(tables)) out[`${binding}.${table}`] = rows;
4943
5068
  return out;
4944
5069
  }
4945
- /** The next event as the engine picks it: the earliest due, the first inserted among equals. */
4946
- function takeEarliest(pending) {
4947
- let best = 0;
4948
- for (let i = 1; i < pending.length; i++) if ((pending[i]?.at ?? 0) < (pending[best]?.at ?? 0)) best = i;
4949
- return pending.splice(best, 1)[0];
4950
- }
4951
- /** The raw side: the handler called directly with the real bindings and plain message or Request objects. */
4952
- async function rawSide(spec, options) {
4953
- const env = options.env;
4954
- const drive = spec.drive;
4955
- const maxRetries = options.maxRetries ?? 3;
4956
- for (const [binding, setup] of ownedSetups(spec.setup, storedBindings(options))) await binding.reset(setup, env[setup.binding]);
4957
- const attempts = [];
4958
- const pending = [...driveEvents(drive)];
4959
- const patched = patchGlobals(0);
4960
- const unsupported = [];
4961
- const restoreFetch = installScriptedFetch(spec.externals, null, (r) => unsupported.push(r), () => patched.clock.advance(1));
4962
- const io = { n: 0 };
5070
+ /** The real bindings with each call counted as I/O in flight and the clock advanced as the proxies do. */
5071
+ function countingEnv(env, ctx) {
4963
5072
  const counting = /* @__PURE__ */ new Map();
4964
- const countedEnv = new Proxy(env, { get(target, prop, receiver) {
5073
+ return new Proxy(env, { get(target, prop, receiver) {
4965
5074
  const value = Reflect.get(target, prop, receiver);
4966
- if (typeof prop !== "string" || !(isD1(value) || isR2(value))) return value;
5075
+ if (typeof prop !== "string" || !(isD1(value) || isR2(value) || isDurableObjectNamespace(value))) return value;
4967
5076
  let c = counting.get(prop);
4968
5077
  if (!c) {
4969
- c = isD1(value) ? countingD1(value, io, patched.clock) : countingR2(value, io, patched.clock);
5078
+ c = isD1(value) ? countingD1(value, ctx.io, ctx.clock) : isR2(value) ? countingR2(value, ctx.io, ctx.clock) : countingNamespace(value, ctx.io, ctx.clock);
4970
5079
  counting.set(prop, c);
4971
5080
  }
4972
5081
  return c;
4973
5082
  } });
4974
- const settle = (p) => settleOn(p, {
4975
- clock: patched.clock,
4976
- inFlight: () => io.n,
4977
- crashed: () => false,
4978
- stuck: () => {
4979
- throw new DifferentialStuck();
4980
- }
4981
- });
4982
- try {
4983
- const handlers = typeof options.handler === "function" ? {} : options.handler;
4984
- if (drive.kind === "websocket") throw new Error("runDifferential has no raw side for a websocket drive: its messages are delivered inside the object");
4985
- if (drive.kind === "rpc") {
4986
- const cls = entrypointClass(options.handler, options.exports, drive.entrypoint);
4987
- if (typeof cls !== "function") throw new Error("the Worker has no WorkerEntrypoint class");
4988
- while (pending.length > 0) {
4989
- const event = takeEarliest(pending);
4990
- const call = event.data;
4991
- const background = [];
4992
- let status;
4993
- let result;
4994
- try {
4995
- const value = await settle(Promise.resolve().then(() => callMethod(cls, call, executionContext(background), countedEnv)));
4996
- result = {
4997
- ok: true,
4998
- value: toJson(value)
4999
- };
5000
- status = "completed";
5001
- } catch (err) {
5002
- if (err instanceof CrashSignal || err instanceof DifferentialStuck) throw err;
5003
- result = {
5004
- ok: false,
5005
- error: describeError(err)
5006
- };
5007
- status = "errored";
5008
- }
5009
- await settle(Promise.all(background));
5010
- attempts.push({
5011
- event: event.id,
5012
- attempt: event.attempt,
5013
- status,
5014
- decision: null,
5015
- result
5016
- });
5017
- const next = status === "completed" ? null : redelivery(event, drive.retries, spec.bounds);
5018
- if (next) pending.push(next);
5019
- }
5020
- } else if (drive.kind === "cron") {
5021
- const handler = handlers.scheduled;
5022
- if (!handler) throw new Error("the Worker has no scheduled() handler");
5023
- while (pending.length > 0) {
5024
- const event = takeEarliest(pending);
5025
- const tick = event.data;
5026
- if (event.at !== void 0 && event.at > patched.clock.now()) patched.clock.advance(event.at - patched.clock.now());
5027
- const background = [];
5028
- const failures = [];
5029
- let noRetry = false;
5030
- const controller = {
5031
- scheduledTime: tick.scheduledTime,
5032
- cron: tick.cron,
5033
- noRetry: () => {
5034
- noRetry = true;
5035
- }
5036
- };
5037
- let status;
5038
- try {
5039
- await settle(Promise.resolve().then(() => handler.call(handlers, controller, countedEnv, executionContext(background, failures))));
5040
- status = "completed";
5041
- } catch (err) {
5042
- if (err instanceof CrashSignal || err instanceof DifferentialStuck) throw err;
5043
- status = "errored";
5044
- }
5045
- await settle(Promise.all(background));
5046
- if (status === "completed" && failures.length > 0) status = "errored";
5047
- attempts.push({
5048
- event: event.id,
5049
- attempt: event.attempt,
5050
- status,
5051
- decision: noRetry ? "no_retry" : null
5052
- });
5053
- const next = status === "completed" || noRetry ? null : redelivery(event, drive.retries, spec.bounds);
5054
- if (next) pending.push(next);
5083
+ }
5084
+ function rawCall(ctx, drive, options, env) {
5085
+ const cls = entrypointClass(options.handler, options.exports, drive.entrypoint);
5086
+ if (typeof cls !== "function") throw new Error("the Worker has no WorkerEntrypoint class");
5087
+ return async (event) => {
5088
+ const call = event.data;
5089
+ const background = [];
5090
+ const ran = await ctx.call(async () => toJson(await callMethod(cls, call, executionContext(background), env)));
5091
+ await ctx.settle(Promise.all(background));
5092
+ const result = ran.status === "completed" ? {
5093
+ ok: true,
5094
+ value: ran.value
5095
+ } : {
5096
+ ok: false,
5097
+ error: describeError(ran.error)
5098
+ };
5099
+ return {
5100
+ record: {
5101
+ event: event.id,
5102
+ attempt: event.attempt,
5103
+ status: ran.status,
5104
+ decision: null,
5105
+ result
5106
+ },
5107
+ handled: ran.status === "completed"
5108
+ };
5109
+ };
5110
+ }
5111
+ function rawTick(ctx, _drive, handlers, env) {
5112
+ const handler = handlers.scheduled;
5113
+ if (!handler) throw new Error("the Worker has no scheduled() handler");
5114
+ return async (event) => {
5115
+ const tick = event.data;
5116
+ const background = [];
5117
+ const failures = [];
5118
+ let noRetry = false;
5119
+ const controller = {
5120
+ scheduledTime: tick.scheduledTime,
5121
+ cron: tick.cron,
5122
+ noRetry: () => {
5123
+ noRetry = true;
5055
5124
  }
5056
- } else if (drive.kind === "http") {
5057
- const handler = handlers.fetch;
5058
- if (!handler) throw new Error("the Worker has no fetch() handler");
5059
- while (pending.length > 0) {
5060
- const event = takeEarliest(pending);
5061
- const req = event.data;
5062
- const background = [];
5063
- let status;
5064
- let response = 500;
5065
- try {
5066
- const r = await settle(Promise.resolve().then(() => handler.call(handlers, requestFor(req), countedEnv, executionContext(background))));
5067
- await settle(r.clone().text());
5068
- response = r.status;
5069
- status = "completed";
5070
- } catch (err) {
5071
- if (err instanceof CrashSignal || err instanceof DifferentialStuck) throw err;
5072
- status = "errored";
5073
- }
5074
- await settle(Promise.all(background));
5075
- attempts.push({
5076
- event: event.id,
5077
- attempt: event.attempt,
5078
- status,
5079
- decision: null,
5080
- response
5081
- });
5082
- const next = (drive.retryOn === "5xx" ? response < 500 : response >= 200 && response < 300) ? null : redelivery(event, drive.retries, spec.bounds);
5083
- if (next) pending.push(next);
5125
+ };
5126
+ const ran = await ctx.call(() => handler.call(handlers, controller, env, executionContext(background, failures)));
5127
+ await ctx.settle(Promise.all(background));
5128
+ const status = ran.status === "completed" && failures.length === 0 ? "completed" : "errored";
5129
+ return {
5130
+ record: {
5131
+ event: event.id,
5132
+ attempt: event.attempt,
5133
+ status,
5134
+ decision: noRetry ? "no_retry" : null
5135
+ },
5136
+ handled: status === "completed" || noRetry
5137
+ };
5138
+ };
5139
+ }
5140
+ function rawRequest(ctx, drive, handlers, env) {
5141
+ const handler = handlers.fetch;
5142
+ if (!handler) throw new Error("the Worker has no fetch() handler");
5143
+ return async (event) => {
5144
+ const req = event.data;
5145
+ const background = [];
5146
+ const ran = await ctx.call(async () => {
5147
+ const r = await handler.call(handlers, requestFor(req), env, executionContext(background));
5148
+ await r.clone().text();
5149
+ return r.status;
5150
+ });
5151
+ await ctx.settle(Promise.all(background));
5152
+ const response = ran.status === "completed" ? ran.value : 500;
5153
+ const accepted = drive.retryOn === "5xx" ? response < 500 : response >= 200 && response < 300;
5154
+ return {
5155
+ record: {
5156
+ event: event.id,
5157
+ attempt: event.attempt,
5158
+ status: ran.status,
5159
+ decision: null,
5160
+ response
5161
+ },
5162
+ handled: accepted
5163
+ };
5164
+ };
5165
+ }
5166
+ function rawMessage(ctx, drive, handlers, env) {
5167
+ const handler = handlers.queue;
5168
+ if (!handler) throw new Error("the Worker has no queue() handler");
5169
+ return async (event) => {
5170
+ let decision = null;
5171
+ const background = [];
5172
+ const message = {
5173
+ id: event.id,
5174
+ timestamp: /* @__PURE__ */ new Date(),
5175
+ body: cloneJson(event.data),
5176
+ attempts: event.attempt,
5177
+ ack: () => {
5178
+ decision ??= "ack";
5179
+ },
5180
+ retry: () => {
5181
+ decision ??= "retry";
5084
5182
  }
5085
- } else {
5086
- const handler = handlers.queue;
5087
- if (!handler) throw new Error("the Worker has no queue() handler");
5088
- while (pending.length > 0) {
5089
- const event = takeEarliest(pending);
5090
- let decision = null;
5091
- const background = [];
5092
- const message = {
5093
- id: event.id,
5094
- timestamp: /* @__PURE__ */ new Date(),
5095
- body: JSON.parse(JSON.stringify(event.data)),
5096
- attempts: event.attempt,
5097
- ack: () => {
5098
- decision ??= "ack";
5099
- },
5100
- retry: () => {
5101
- decision ??= "retry";
5102
- }
5103
- };
5104
- const batch = {
5105
- queue: drive.queue,
5106
- messages: [message],
5107
- metadata: { metrics: {
5108
- backlogCount: 0,
5109
- backlogBytes: 0
5110
- } },
5111
- ackAll: () => message.ack(),
5112
- retryAll: () => message.retry()
5113
- };
5114
- const ctx = executionContext(background);
5115
- let status;
5116
- try {
5117
- await settle(Promise.resolve().then(() => handler.call(handlers, batch, countedEnv, ctx)));
5118
- status = "completed";
5119
- } catch (err) {
5120
- if (err instanceof CrashSignal || err instanceof DifferentialStuck) throw err;
5121
- status = "errored";
5183
+ };
5184
+ const batch = {
5185
+ queue: drive.queue,
5186
+ messages: [message],
5187
+ metadata: { metrics: {
5188
+ backlogCount: 0,
5189
+ backlogBytes: 0
5190
+ } },
5191
+ ackAll: () => message.ack(),
5192
+ retryAll: () => message.retry()
5193
+ };
5194
+ const ran = await ctx.call(() => handler.call(handlers, batch, env, executionContext(background)));
5195
+ if (ran.status === "completed") decision ??= "ack";
5196
+ await ctx.settle(Promise.all(background));
5197
+ return {
5198
+ record: {
5199
+ event: event.id,
5200
+ attempt: event.attempt,
5201
+ status: ran.status,
5202
+ decision
5203
+ },
5204
+ handled: decision === "ack"
5205
+ };
5206
+ };
5207
+ }
5208
+ /** The raw side: the engine's raw loop, each attempt calling the handler directly with the real bindings. */
5209
+ async function rawSide(spec, options, stored) {
5210
+ const env = options.env;
5211
+ const drive = spec.drive;
5212
+ if (drive.kind === "websocket") throw new Error("runDifferential has no raw side for a websocket drive: its messages are delivered inside the object");
5213
+ for (const [binding, setup] of ownedSetups(spec.setup, stored)) await binding.reset(setup, env[setup.binding]);
5214
+ const handlers = typeof options.handler === "function" ? {} : options.handler;
5215
+ return {
5216
+ attempts: await rawRun(spec, {
5217
+ events: driveEvents(drive),
5218
+ limit: drive.kind === "queue" ? options.maxRetries ?? 3 : drive.retries,
5219
+ install: (ctx) => {
5220
+ const counted = countingEnv(env, ctx);
5221
+ switch (drive.kind) {
5222
+ case "rpc": return { attempt: rawCall(ctx, drive, options, counted) };
5223
+ case "cron": return { attempt: rawTick(ctx, drive, handlers, counted) };
5224
+ case "http": return { attempt: rawRequest(ctx, drive, handlers, counted) };
5225
+ case "queue": return { attempt: rawMessage(ctx, drive, handlers, counted) };
5122
5226
  }
5123
- if (status === "completed") decision ??= "ack";
5124
- await settle(Promise.all(background));
5125
- attempts.push({
5126
- event: event.id,
5127
- attempt: event.attempt,
5128
- status,
5129
- decision
5130
- });
5131
- const next = decision === "ack" ? null : redelivery(event, maxRetries, spec.bounds);
5132
- if (next) pending.push(next);
5133
5227
  }
5134
- }
5135
- } finally {
5136
- restoreFetch();
5137
- patched.restore();
5138
- }
5139
- if (unsupported.length > 0) throw new DifferentialStuck(`raw side: ${unsupported.join("; ")}`);
5140
- return {
5141
- attempts,
5142
- state: await snapshotAll(spec, options)
5228
+ }),
5229
+ state: await snapshotAll(spec, options, stored)
5143
5230
  };
5144
5231
  }
5145
5232
  /** Run both sides and compare. The Eutaxy side runs first; both start from the schema. */
5146
5233
  async function runDifferential(spec, options) {
5147
5234
  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");
5148
5235
  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");
5149
- const { unsupported, ...eutaxy } = await eutaxySide(spec, options);
5150
- const raw = await rawSide(spec, options);
5236
+ const stored = storedBindings(options);
5237
+ const { unsupported, ...eutaxy } = await eutaxySide(spec, options, stored);
5238
+ const raw = await rawSide(spec, options, stored);
5151
5239
  const differences = compareSides({
5152
5240
  attempts: eutaxy.attempts,
5153
5241
  state: flatten(eutaxy.state)
@@ -5318,4 +5406,4 @@ async function checkInWorkerd(input) {
5318
5406
  }
5319
5407
  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 };
5320
5408
 
5321
- //# sourceMappingURL=workerd-Be43_PZo.mjs.map
5409
+ //# sourceMappingURL=workerd-D9cUGjYv.mjs.map