eutaxy 0.15.1 → 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-DT4lxaPK.mjs → cli-DbLlYHTY.mjs} +180 -162
  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-CPuihHZh.mjs → src-CmHdPsZy.mjs} +1089 -159
  24. package/dist/src-CmHdPsZy.mjs.map +1 -0
  25. package/dist/{src-wa0JZa-T.mjs → src-Dz9Wn2vL.mjs} +2 -2
  26. package/dist/{src-wa0JZa-T.mjs.map → src-Dz9Wn2vL.mjs.map} +1 -1
  27. package/dist/{workerd-DvhVDnQW.mjs → workerd-D9cUGjYv.mjs} +561 -480
  28. package/dist/workerd-D9cUGjYv.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-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);
@@ -677,33 +758,22 @@ async function runInObject(real, binding, ctx, helpers, state, id, object, fn) {
677
758
  ctx.hooks.unsupported(`Durable Object binding ${binding} needs the Cloudflare test helpers`);
678
759
  return;
679
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) {
680
769
  state.touched.add(id);
681
- return typed(helpers).runInDurableObject(real.get(real.idFromString(id)), async (instance, live) => {
770
+ return typed(helpers).runInDurableObject(stub, async (instance, live) => {
682
771
  watchGate(live);
683
772
  state.states.set(id, live);
684
773
  await takeOverAlarms(live.storage, alarmControl(state.alarms, binding, id, object, () => ctx.hooks));
685
774
  return fn(instance, live);
686
775
  });
687
776
  }
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
777
  /** The objects to reset: every id the namespace has created, plus the setup's named ones. */
708
778
  async function objectIds(real, helpers, names, seeded) {
709
779
  const ids = /* @__PURE__ */ new Map();
@@ -760,12 +830,12 @@ async function clearAndSeed(real, helpers, names, objects, sql) {
760
830
  * The tables are the seeded objects and those a call reached, never objects
761
831
  * only earlier runs created, so a snapshot depends on this run alone.
762
832
  */
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));
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));
765
835
  if (requested) onUnsupported("a Durable Object made a request while its storage was being snapshotted");
766
836
  return value;
767
837
  }
768
- 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) {
769
839
  const out = {};
770
840
  const define = (table, rows) => {
771
841
  if (Object.hasOwn(out, table)) throw new Error(`snapshot key ${table} named twice`);
@@ -779,15 +849,16 @@ async function readTables(real, helpers, names, touched, objects, sql, seededSql
779
849
  const seeded = seededNames(objects, sql);
780
850
  for (const id of await objectIds(real, helpers, names, seeded)) {
781
851
  const name = names.get(id.toString()) ?? id.toString();
782
- if (!touched.has(id.toString())) {
852
+ const read = all || touched.has(id.toString());
853
+ if (!read) {
783
854
  if (await typed(helpers).evictDurableObject(real.get(id)).then(() => true, () => false)) onIndirect(name);
784
855
  if (!seeded.includes(name)) continue;
785
856
  }
786
857
  let entries;
787
858
  const tables = [];
788
- if (touched.has(id.toString())) {
859
+ if (read) {
789
860
  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`);
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`);
791
862
  const surface = sqlOf(state.storage);
792
863
  const sqlTables = surface ? readSqlTables(surface) : [];
793
864
  return Promise.resolve(state.storage.list()).then((kv) => ({
@@ -867,6 +938,22 @@ function entrypointHandler(cls) {
867
938
  };
868
939
  return out;
869
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
+ }
870
957
  // packages/cloudflare/src/caller.ts
871
958
  /**
872
959
  * The caller of an inbound request or RPC call. Cloudflare retries neither,
@@ -911,24 +998,48 @@ function startCaller(event, hooks, spec, policy, target, gaveUp) {
911
998
  ...next,
912
999
  ...resendAt > Date.now() ? { at: resendAt } : {}
913
1000
  });
914
- } else hooks.effectSync({
1001
+ } else note(hooks, {
915
1002
  invocation: hooks.bookkeeping(),
916
1003
  target,
917
1004
  op: "gave_up",
918
1005
  args: gaveUp,
919
1006
  allowed: []
920
- }, () => null, () => null);
1007
+ });
921
1008
  };
922
1009
  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
- }
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());
931
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
+ } };
932
1043
  }
933
1044
  // packages/cloudflare/src/cron.ts
934
1045
  const fields = [
@@ -1807,45 +1918,25 @@ async function deliverCall(event, hooks, spec, drive, invocation, cls, env) {
1807
1918
  });
1808
1919
  const ran = await runInvocation(hooks, inv, () => callMethod(cls, call, executionContext(background), env));
1809
1920
  let status = ran.status;
1810
- let late = caller.isLate();
1811
- let answer = null;
1921
+ let answer = { kind: "none" };
1812
1922
  if (ran.status === "completed") {
1813
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`);
1814
- const s = {
1815
- ok: true,
1816
- value: toJson(ran.value)
1924
+ answer = {
1925
+ kind: "answered",
1926
+ value: {
1927
+ ok: true,
1928
+ value: toJson(ran.value)
1929
+ },
1930
+ accepted: true
1817
1931
  };
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 = {
1932
+ } else if (ran.status === "errored") answer = {
1933
+ kind: "errored",
1934
+ value: {
1836
1935
  ok: false,
1837
1936
  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);
1937
+ }
1938
+ };
1939
+ if (caller.respond(invocation, args, answer)) status = "crashed";
1849
1940
  if (await drainBackground(hooks, inv, invocation, target, background)) status = "crashed";
1850
1941
  return {
1851
1942
  status,
@@ -1967,11 +2058,7 @@ async function recordRequest(request) {
1967
2058
  * (promise pipelining, `connect()`), with the answers supplied.
1968
2059
  */
1969
2060
  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
- };
2061
+ const unsupported = (what) => refuse(ctx, `service binding ${binding}: ${what}`);
1975
2062
  /**
1976
2063
  * The promise a call returns. On the real stub it is an RPC promise that
1977
2064
  * pipelines property reads (`stub.charge().id`); this one is not, so a read
@@ -2005,18 +2092,8 @@ function serviceStub(binding, ctx, answers) {
2005
2092
  /** The scripted stub a Worker sees under a service binding's name. */
2006
2093
  function proxyService(binding, ctx, script) {
2007
2094
  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
- };
2095
+ const point = (op, args) => pointAt(ctx, target, op, args, writeFaults);
2096
+ const unsupported = (what) => refuse(ctx, `service binding ${binding}: ${what}`);
2020
2097
  /** The scripted reply to a method, by name; a method the script lacks cannot be answered. */
2021
2098
  const replyTo = (method) => {
2022
2099
  if (script.methods === void 0) return { returns: null };
@@ -2191,18 +2268,8 @@ function proxyCallee(binding, ctx, setup, module, env, state) {
2191
2268
  const view = calleeEnv(module.name, env);
2192
2269
  const entrypointName = setup.entrypoint ?? module.entrypoint;
2193
2270
  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
- });
2271
+ const unsupported = (what) => refuse(ctx, `callee ${binding}: ${what}`);
2272
+ const point = (op, args) => pointAt(ctx, target, op, args, callFaults);
2206
2273
  /** The hosted invocation's id: the n-th call of a method from one caller invocation is `#n`. */
2207
2274
  const invocationId = (method) => {
2208
2275
  const key = `${ctx.currentInvocation()}/${binding}.${method}`;
@@ -2325,15 +2392,6 @@ async function expectHolds(spec, platform, options) {
2325
2392
  function isD1(value) {
2326
2393
  return typeof value === "object" && value !== null && typeof value.prepare === "function" && typeof value.batch === "function";
2327
2394
  }
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
2395
  function metaOf(result) {
2338
2396
  return {
2339
2397
  changes: result.meta.changes ?? 0,
@@ -2367,22 +2425,22 @@ var StatementProxy = class StatementProxy {
2367
2425
  return new StatementProxy(this.real.bind(...values), this.target, this.ctx, this.sql, values);
2368
2426
  }
2369
2427
  run() {
2370
- 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));
2371
2429
  }
2372
2430
  all() {
2373
- 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) => ({
2374
2432
  rows: r.results.length,
2375
2433
  changes: r.meta.changes ?? 0
2376
2434
  }));
2377
2435
  }
2378
2436
  first(colName) {
2379
- return this.ctx.hooks.effect(point(this.ctx, this.target, "first", {
2437
+ return this.ctx.hooks.effect(pointAt(this.ctx, this.target, "first", {
2380
2438
  ...this.args(),
2381
2439
  column: colName ?? null
2382
2440
  }, readFaults), () => colName === void 0 ? this.real.first() : this.real.first(colName), (r) => ({ row: toJson(r) }));
2383
2441
  }
2384
2442
  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 }));
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 }));
2386
2444
  }
2387
2445
  };
2388
2446
  /** Wrap a D1 binding. Methods not modelled fall through to the real binding and mark the run unsupported. */
@@ -2398,13 +2456,13 @@ function proxyD1(real, binding, ctx) {
2398
2456
  sql: s.sql,
2399
2457
  params: toJson(s.params)
2400
2458
  } : "<unproxied statement>") };
2401
- 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) => ({
2402
2460
  changes: rs.reduce((n, r) => n + (r.meta.changes ?? 0), 0),
2403
2461
  statements: rs.length
2404
2462
  }));
2405
2463
  },
2406
2464
  exec(sql) {
2407
- 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) => ({
2408
2466
  count: r.count,
2409
2467
  duration: 0
2410
2468
  }));
@@ -2662,18 +2720,8 @@ function putArgs(options) {
2662
2720
  }
2663
2721
  function proxyR2(real, binding, ctx, book) {
2664
2722
  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
- };
2723
+ const point = (op, args, allowed) => pointAt(ctx, target, op, args, allowed);
2724
+ const notModelled = (what) => refuse(ctx, `R2 ${binding}: ${what} is not modelled`);
2677
2725
  /** Date conditions compare the store's real upload time, not the stand-in the Worker saw. */
2678
2726
  const checkConditions = (onlyIf) => {
2679
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`);
@@ -2798,12 +2846,16 @@ async function snapshotR2(real) {
2798
2846
  */
2799
2847
  /** The `EventRef.source` of a Workflow instance's run. */
2800
2848
  const workflowSource = "workflow";
2801
- /** Before a step's callback: the engine restarts before the step runs. */
2802
- 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"];
2803
2855
  /**
2804
2856
  * After it: the engine restarts after the step ran but before its result
2805
2857
  * was persisted (`crash_after`), or the attempt ran and counted as failed,
2806
- * as a timeout does (`ambiguous`).
2858
+ * as a timeout just after its work does (`ambiguous`).
2807
2859
  */
2808
2860
  const STEP_RESULT = ["crash_after", "ambiguous"];
2809
2861
  /**
@@ -2860,11 +2912,7 @@ function isWorkflowBinding(value) {
2860
2912
  /** The binding's proxy: instances live in the registry and run as events, never in the real engine. */
2861
2913
  function proxyWorkflow(binding, ctx, registry) {
2862
2914
  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
- };
2915
+ const unsupported = (what) => refuse(ctx, `Workflow ${binding}: ${what} is not modelled`);
2868
2916
  const handle = (id) => ({
2869
2917
  id,
2870
2918
  status: () => ctx.hooks.effect({
@@ -3202,21 +3250,69 @@ async function deliverWorkflow(event, hooks, d) {
3202
3250
  count,
3203
3251
  attempt
3204
3252
  };
3205
- await hooks.effect({
3206
- invocation,
3207
- target,
3208
- op: "step",
3209
- args,
3210
- allowed: STEP_START
3211
- }, 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
+ }
3212
3266
  instance.attempts.set(k, attempt);
3213
3267
  let failed = false;
3214
3268
  let thrown;
3215
3269
  let value;
3216
3270
  let returned;
3217
- try {
3218
- returned = { value: await fn(stepContext) };
3219
- } 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;
3220
3316
  if (err instanceof CrashSignal || inv.isCrashed()) throw err;
3221
3317
  failed = true;
3222
3318
  thrown = err;
@@ -3344,20 +3440,20 @@ async function deliverWorkflow(event, hooks, d) {
3344
3440
  }
3345
3441
  if (existing !== void 0 && Date.now() >= existing) {
3346
3442
  const error = Object.assign(/* @__PURE__ */ new Error(`Execution timed out after ${timeoutMs}ms`), { name: "WorkflowTimeoutError" });
3347
- hooks.effectSync({
3443
+ note(hooks, {
3348
3444
  invocation,
3349
3445
  target,
3350
3446
  op: "wait_timeout",
3351
3447
  args,
3352
3448
  allowed: []
3353
- }, () => null, () => null);
3449
+ });
3354
3450
  instance.persisted.set(k, failure(error));
3355
3451
  throw error;
3356
3452
  }
3357
3453
  const deadline = existing ?? Date.now() + timeoutMs;
3358
3454
  if (existing === void 0) {
3359
3455
  instance.deadlines.set(k, deadline);
3360
- hooks.effectSync({
3456
+ note(hooks, {
3361
3457
  invocation,
3362
3458
  target,
3363
3459
  op: "wait",
@@ -3366,7 +3462,7 @@ async function deliverWorkflow(event, hooks, d) {
3366
3462
  timeoutMs
3367
3463
  },
3368
3464
  allowed: []
3369
- }, () => null, () => null);
3465
+ });
3370
3466
  }
3371
3467
  const gen = ++instance.waitGen;
3372
3468
  instance.waiting = {
@@ -3407,7 +3503,7 @@ async function deliverWorkflow(event, hooks, d) {
3407
3503
  return;
3408
3504
  }
3409
3505
  instance.deadlines.set(k, Date.now() + ms);
3410
- hooks.effectSync({
3506
+ note(hooks, {
3411
3507
  invocation,
3412
3508
  target,
3413
3509
  op: "sleep",
@@ -3418,7 +3514,7 @@ async function deliverWorkflow(event, hooks, d) {
3418
3514
  ...until === void 0 ? {} : { until }
3419
3515
  },
3420
3516
  allowed: []
3421
- }, () => null, () => null);
3517
+ });
3422
3518
  await sleep(ms);
3423
3519
  instance.persisted.set(k, {
3424
3520
  ok: true,
@@ -3465,6 +3561,10 @@ async function deliverWorkflow(event, hooks, d) {
3465
3561
  value: void 0
3466
3562
  };
3467
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
+ }] : [];
3468
3568
  if (suspending !== void 0 && result.status === "completed") {
3469
3569
  instance.status = "waiting";
3470
3570
  const suspended = suspending;
@@ -3473,10 +3573,7 @@ async function deliverWorkflow(event, hooks, d) {
3473
3573
  instance.status = "running";
3474
3574
  instance.waiting = void 0;
3475
3575
  }
3476
- const followUps = status === "crashed" ? instance.status === "running" && event.attempt <= d.maxFaultsPerRun ? [{
3477
- ...event,
3478
- attempt: event.attempt + 1
3479
- }] : [] : [{
3576
+ const followUps = status === "crashed" ? restart() : [{
3480
3577
  id: `workflow:${d.binding}:${instance.id}:timeout-${suspended.gen}`,
3481
3578
  attempt: 1,
3482
3579
  source: workflowSource,
@@ -3495,7 +3592,7 @@ async function deliverWorkflow(event, hooks, d) {
3495
3592
  if (result.status === "completed") {
3496
3593
  instance.status = "complete";
3497
3594
  instance.output = result.value;
3498
- hooks.effectSync({
3595
+ note(hooks, {
3499
3596
  invocation,
3500
3597
  target,
3501
3598
  op: "complete",
@@ -3504,7 +3601,7 @@ async function deliverWorkflow(event, hooks, d) {
3504
3601
  output: toJson(instance.output)
3505
3602
  },
3506
3603
  allowed: []
3507
- }, () => null, () => null);
3604
+ });
3508
3605
  } else if (result.status === "errored") {
3509
3606
  instance.status = "errored";
3510
3607
  const e = result.error;
@@ -3515,7 +3612,7 @@ async function deliverWorkflow(event, hooks, d) {
3515
3612
  name: "Error",
3516
3613
  message: String(e)
3517
3614
  };
3518
- hooks.effectSync({
3615
+ note(hooks, {
3519
3616
  invocation,
3520
3617
  target,
3521
3618
  op: "errored",
@@ -3524,16 +3621,12 @@ async function deliverWorkflow(event, hooks, d) {
3524
3621
  error: `${instance.error.name}: ${instance.error.message}`
3525
3622
  },
3526
3623
  allowed: []
3527
- }, () => null, () => null);
3624
+ });
3528
3625
  }
3529
3626
  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
3627
  return {
3535
3628
  status,
3536
- followUps
3629
+ followUps: restart()
3537
3630
  };
3538
3631
  }
3539
3632
  /** The delay before the next attempt (Workflows, Sleeping and retrying; a delay function is called). */
@@ -3640,13 +3733,14 @@ function durableObjectBinding(deps) {
3640
3733
  if (!helpers) throw new Error("Durable Object setup needs the Cloudflare test helpers: createCloudflarePlatform({ ..., durableObjects: await import(\"cloudflare:test\") })");
3641
3734
  return helpers;
3642
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
+ };
3643
3742
  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
- },
3743
+ objects,
3650
3744
  kind: "durable_object",
3651
3745
  target: "DO",
3652
3746
  is: isDurableObjectNamespace,
@@ -3670,7 +3764,7 @@ function durableObjectBinding(deps) {
3670
3764
  },
3671
3765
  async snapshot(step, real, unsupported) {
3672
3766
  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);
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);
3674
3768
  },
3675
3769
  source: alarmSource,
3676
3770
  async deliver(event, hooks, spec) {
@@ -3679,17 +3773,14 @@ function durableObjectBinding(deps) {
3679
3773
  binding,
3680
3774
  book: stateFor(binding).alarms,
3681
3775
  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({
3776
+ objects,
3777
+ bookkeep: (op, args) => note(hooks, {
3687
3778
  invocation: hooks.bookkeeping(),
3688
3779
  target: `DO:${binding}`,
3689
3780
  op,
3690
3781
  args,
3691
3782
  allowed: []
3692
- }, () => null, () => null)
3783
+ })
3693
3784
  });
3694
3785
  }
3695
3786
  };
@@ -3935,52 +4026,28 @@ async function deliverRequest(event, hooks, spec, drive, invocation, worker) {
3935
4026
  if (!(value instanceof Response)) throw new TypeError("the fetch handler returned something that is not a Response");
3936
4027
  return value;
3937
4028
  });
3938
- const response = handled.status === "completed" ? handled.value : void 0;
3939
4029
  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;
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;
3946
4041
  }
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 = {
4042
+ if (status === "errored") answer = {
4043
+ kind: "errored",
4044
+ value: {
3969
4045
  status: 500,
3970
4046
  ok: false,
3971
4047
  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);
4048
+ }
4049
+ };
4050
+ if (caller.respond(invocation, args, answer)) status = "crashed";
3984
4051
  if (await drainBackground(hooks, inv, invocation, target, background)) status = "crashed";
3985
4052
  return {
3986
4053
  status,
@@ -4000,31 +4067,35 @@ async function deliverMessage$1(event, hooks, spec, drive, invocation, worker, m
4000
4067
  /** Cloudflare honours the first ack or retry decision per message; later ones are ignored. */
4001
4068
  const state = { decision: null };
4002
4069
  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 }));
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);
4016
4087
  };
4017
4088
  const message = {
4018
4089
  id: event.id,
4019
4090
  timestamp: /* @__PURE__ */ new Date(),
4020
4091
  body: cloneJson(event.data),
4021
4092
  attempts: event.attempt,
4022
- ack: () => decide("ack", {
4093
+ ack: () => record("ack", {
4023
4094
  messageId: event.id,
4024
4095
  implicit: false,
4025
4096
  body: event.data
4026
4097
  }),
4027
- retry: () => decide("retry", {
4098
+ retry: () => record("retry", {
4028
4099
  messageId: event.id,
4029
4100
  body: event.data
4030
4101
  })
@@ -4043,22 +4114,20 @@ async function deliverMessage$1(event, hooks, spec, drive, invocation, worker, m
4043
4114
  const handler = worker.handler.queue;
4044
4115
  if (!handler) throw new Error("the Worker has no queue() handler");
4045
4116
  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", {
4117
+ if (status === "completed" && state.decision === null) {
4118
+ const implicit = decisionPoint("ack", {
4048
4119
  messageId: event.id,
4049
4120
  implicit: true,
4050
4121
  body: event.data
4051
4122
  });
4052
- } catch (err) {
4053
- if (err instanceof CrashSignal) status = "crashed";
4054
- else throw err;
4123
+ if (decide(hooks, implicit, take("ack"), effective) === "crashed") status = "crashed";
4055
4124
  }
4056
4125
  if (await drainBackground(hooks, inv, invocation, queueTarget, background)) status = "crashed";
4057
4126
  const followUps = [];
4058
4127
  if (state.decision !== "ack") {
4059
4128
  const next = redelivery(event, maxRetries, spec.bounds);
4060
4129
  if (next) followUps.push(next);
4061
- else hooks.effectSync({
4130
+ else note(hooks, {
4062
4131
  invocation: hooks.bookkeeping(),
4063
4132
  target: queueTarget,
4064
4133
  op: "dead_letter",
@@ -4067,7 +4136,7 @@ async function deliverMessage$1(event, hooks, spec, drive, invocation, worker, m
4067
4136
  attempts: event.attempt
4068
4137
  },
4069
4138
  allowed: []
4070
- }, () => null, () => null);
4139
+ });
4071
4140
  }
4072
4141
  return {
4073
4142
  status,
@@ -4116,7 +4185,7 @@ async function deliverTick(event, hooks, spec, drive, invocation, worker) {
4116
4185
  if (status !== "completed" && !noRetry) {
4117
4186
  const next = redelivery(event, drive.retries, spec.bounds);
4118
4187
  if (next) followUps.push(next);
4119
- else hooks.effectSync({
4188
+ else note(hooks, {
4120
4189
  invocation: hooks.bookkeeping(),
4121
4190
  target,
4122
4191
  op: "gave_up",
@@ -4125,7 +4194,7 @@ async function deliverTick(event, hooks, spec, drive, invocation, worker) {
4125
4194
  attempts: event.attempt
4126
4195
  },
4127
4196
  allowed: []
4128
- }, () => null, () => null);
4197
+ });
4129
4198
  }
4130
4199
  return {
4131
4200
  status,
@@ -4346,7 +4415,7 @@ var Connections = class {
4346
4415
  record(hooks) {
4347
4416
  const bookkeeping = () => hooks.bookkeeping();
4348
4417
  for (const [connection, c] of this.open) {
4349
- for (const data of this.frames.get(connection) ?? []) hooks.effectSync({
4418
+ for (const data of this.frames.get(connection) ?? []) note(hooks, {
4350
4419
  invocation: bookkeeping(),
4351
4420
  target: `WebSocket:${connection}`,
4352
4421
  op: "message",
@@ -4355,8 +4424,8 @@ var Connections = class {
4355
4424
  data
4356
4425
  },
4357
4426
  allowed: []
4358
- }, () => null, () => null);
4359
- if (c.closed) hooks.effectSync({
4427
+ });
4428
+ if (c.closed) note(hooks, {
4360
4429
  invocation: bookkeeping(),
4361
4430
  target: `WebSocket:${connection}`,
4362
4431
  op: "close",
@@ -4366,7 +4435,7 @@ var Connections = class {
4366
4435
  reason: c.closed.reason
4367
4436
  },
4368
4437
  allowed: []
4369
- }, () => null, () => null);
4438
+ });
4370
4439
  }
4371
4440
  this.frames.clear();
4372
4441
  }
@@ -4581,13 +4650,12 @@ async function deliverMessage(event, hooks, c, data, deps) {
4581
4650
  };
4582
4651
  }
4583
4652
  const { binding, id, object } = conn.upgrade;
4584
- const { status } = await runInvocation(hooks, inv, () => hooks.effect({
4653
+ const status = await hostedInObject(hooks, inv, deps.objects, binding, id, object, {
4585
4654
  invocation,
4586
4655
  target,
4587
4656
  op: "send",
4588
4657
  args,
4589
- allowed: readFaults,
4590
- hostsEffects: true
4658
+ allowed: readFaults
4591
4659
  }, async () => {
4592
4660
  await deps.objects.run(binding, id, object, async (instance, live) => {
4593
4661
  const { lost } = deps.connections.rebind(conn.upgrade, live);
@@ -4605,17 +4673,13 @@ async function deliverMessage(event, hooks, c, data, deps) {
4605
4673
  return;
4606
4674
  }
4607
4675
  const end = conn.server ?? server;
4608
- await handler.call(instance, end, frameText(data.data));
4676
+ await hooks.hostedCode(hostOf(`DO:${binding}`, object), () => handler.call(instance, end, frameText(data.data)));
4609
4677
  conn.identity = identityOf(end, live);
4610
4678
  });
4611
4679
  await settleFrames();
4612
4680
  return { delivered: true };
4613
- }, (v) => v, {
4614
- onAbandon: () => deps.objects.abort(binding, id),
4615
- mayPark: () => deps.objects.mayPark(binding, id)
4616
- }));
4681
+ }, (v) => v);
4617
4682
  if (status === "crashed") {
4618
- await deps.objects.evict(binding, id);
4619
4683
  const rebuild = hooks.startInvocation(`${invocation}/rebuild`);
4620
4684
  await runInvocation(hooks, rebuild, () => hooks.effect({
4621
4685
  invocation: rebuild.id,
@@ -4661,7 +4725,7 @@ const assumptions = [
4661
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",
4662
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",
4663
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",
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/)",
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/)",
4665
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)",
4666
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/)",
4667
4731
  "state invariants read a snapshot of every D1 binding named in setup, taken after the last event",
@@ -4821,9 +4885,10 @@ function createCloudflarePlatform(options) {
4821
4885
  * Differential check: the same fault-free scenario run once through Eutaxy's
4822
4886
  * proxies and once against the raw bindings, with the queue model (or the
4823
4887
  * 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
4888
+ * the final D1, R2 and Durable Object state is a bug in the proxies or the platform model, not in
4825
4889
  * 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.
4890
+ * semantics (core's redelivery rule among it) and the engine's raw loop; what
4891
+ * it does not share is any proxy code.
4827
4892
  */
4828
4893
  /**
4829
4894
  * The raw side's only wrapper: counts D1 calls in flight (so the settle loop
@@ -4900,16 +4965,69 @@ function countingR2(real, io, clock) {
4900
4965
  }
4901
4966
  /**
4902
4967
  * 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.
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.
4905
4972
  */
4906
4973
  function storedBindings(options) {
4907
- 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
+ } });
4908
5026
  }
4909
- async function snapshotAll(spec, options) {
5027
+ async function snapshotAll(spec, options, stored) {
4910
5028
  const env = options.env;
4911
5029
  const out = {};
4912
- for (const [binding, setup] of ownedSetups(spec.setup, storedBindings(options))) {
5030
+ for (const [binding, setup] of ownedSetups(spec.setup, stored)) {
4913
5031
  const tables = await binding.snapshot(setup, env[setup.binding], (reason) => {
4914
5032
  throw new Error(`snapshot of ${setup.binding}: ${reason}`);
4915
5033
  });
@@ -4918,7 +5036,7 @@ async function snapshotAll(spec, options) {
4918
5036
  return out;
4919
5037
  }
4920
5038
  /** The Eutaxy side, keeping each delivery's status and the decision it made. */
4921
- async function eutaxySide(spec, options) {
5039
+ async function eutaxySide(spec, options, stored) {
4922
5040
  const { attempts, unsupported } = await proxiedSide(spec, createCloudflarePlatform(options), (event, result, entries) => {
4923
5041
  const invocation = invocationOf(event);
4924
5042
  const mine = entries.filter((e) => e.invocation === invocation);
@@ -4939,7 +5057,7 @@ async function eutaxySide(spec, options) {
4939
5057
  });
4940
5058
  return {
4941
5059
  attempts,
4942
- state: await snapshotAll(spec, options),
5060
+ state: await snapshotAll(spec, options, stored),
4943
5061
  unsupported
4944
5062
  };
4945
5063
  }
@@ -4949,212 +5067,175 @@ function flatten(state) {
4949
5067
  for (const [binding, tables] of Object.entries(state)) for (const [table, rows] of Object.entries(tables)) out[`${binding}.${table}`] = rows;
4950
5068
  return out;
4951
5069
  }
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 };
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) {
4970
5072
  const counting = /* @__PURE__ */ new Map();
4971
- const countedEnv = new Proxy(env, { get(target, prop, receiver) {
5073
+ return new Proxy(env, { get(target, prop, receiver) {
4972
5074
  const value = Reflect.get(target, prop, receiver);
4973
- if (typeof prop !== "string" || !(isD1(value) || isR2(value))) return value;
5075
+ if (typeof prop !== "string" || !(isD1(value) || isR2(value) || isDurableObjectNamespace(value))) return value;
4974
5076
  let c = counting.get(prop);
4975
5077
  if (!c) {
4976
- 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);
4977
5079
  counting.set(prop, c);
4978
5080
  }
4979
5081
  return c;
4980
5082
  } });
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);
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;
5062
5124
  }
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);
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";
5091
5182
  }
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";
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) };
5129
5226
  }
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
5227
  }
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)
5228
+ }),
5229
+ state: await snapshotAll(spec, options, stored)
5150
5230
  };
5151
5231
  }
5152
5232
  /** Run both sides and compare. The Eutaxy side runs first; both start from the schema. */
5153
5233
  async function runDifferential(spec, options) {
5154
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");
5155
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");
5156
- const { unsupported, ...eutaxy } = await eutaxySide(spec, options);
5157
- 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);
5158
5239
  const differences = compareSides({
5159
5240
  attempts: eutaxy.attempts,
5160
5241
  state: flatten(eutaxy.state)
@@ -5325,4 +5406,4 @@ async function checkInWorkerd(input) {
5325
5406
  }
5326
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 };
5327
5408
 
5328
- //# sourceMappingURL=workerd-DvhVDnQW.mjs.map
5409
+ //# sourceMappingURL=workerd-D9cUGjYv.mjs.map