eutaxy 0.4.0 → 0.5.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.
@@ -1,7 +1,7 @@
1
1
  import { i as canonicalJson } from "./src-s6uYyC0B.mjs";
2
- import { a as Run, d as validateScenario, i as CrashSignal, l as settleOn, m as getPath, o as installScriptedFetch, s as patchGlobals, t as explore, u as defaultBounds } from "./src-Brt0dfNL.mjs";
2
+ import { _ as getPath, a as CrashSignal, c as installScriptedFetch, f as settleOn, l as withoutNetwork, m as validateScenario, n as explore, o as InjectedEffectError, p as defaultBounds, s as Run, u as patchGlobals } from "./src-C19_yfMM.mjs";
3
3
  import { t as describeVerdict } from "./verdict-evEM5Gxx.mjs";
4
- import { n as cloudflareRegressionTest } from "./src-BGdIBGkN.mjs";
4
+ import { n as cloudflareRegressionTest } from "./src-BD3jkjgG.mjs";
5
5
  // packages/cloudflare/src/check.ts
6
6
  /** Explore a scenario on a platform and return its verdict. */
7
7
  function check(spec, platform, options = { seed: spec.name }) {
@@ -227,11 +227,869 @@ async function snapshotD1(real) {
227
227
  for (const { name } of tables.results) out[name] = (await real.prepare(`SELECT * FROM "${name.replace(/"/g, "\"\"")}"`).all()).results.map((r) => toJson(r)).map((j) => [canonicalJson(j), j]).sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0).map(([, j]) => j);
228
228
  return out;
229
229
  }
230
+ // packages/cloudflare/src/alarms.ts
231
+ /** `EventRef.source` of an alarm event. */
232
+ const alarmSource = "durable_object_alarm";
233
+ /** Crash before: the handler never ran. Crash after: it ran and committed, but counts as failed. */
234
+ const ALARM = [
235
+ "crash_before",
236
+ "crash_after",
237
+ "error"
238
+ ];
239
+ /** Cloudflare retries a failed alarm handler up to six times, after 2 s, 4 s, 8 s, ... */
240
+ const maxRetries = 6;
241
+ const firstRetryMs = 2e3;
242
+ /** The alarms of one namespace's objects; the platform clears it before each run. */
243
+ var AlarmBook = class {
244
+ entries = /* @__PURE__ */ new Map();
245
+ clear() {
246
+ this.entries.clear();
247
+ }
248
+ entry(id) {
249
+ let e = this.entries.get(id);
250
+ if (!e) {
251
+ e = {
252
+ time: null,
253
+ seq: 0,
254
+ gen: 0,
255
+ firings: 0
256
+ };
257
+ this.entries.set(id, e);
258
+ }
259
+ return e;
260
+ }
261
+ };
262
+ /** One alarm control per object: setting schedules an event at the alarm's virtual time. */
263
+ function alarmControl(book, binding, id, object, hooks) {
264
+ const entry = book.entry(id);
265
+ return {
266
+ get: () => entry.time,
267
+ set: (time) => {
268
+ entry.time = time;
269
+ entry.seq++;
270
+ entry.gen = entry.seq;
271
+ const data = {
272
+ binding,
273
+ gen: entry.gen,
274
+ id,
275
+ object,
276
+ time,
277
+ retryCount: 0
278
+ };
279
+ const now = Date.now();
280
+ hooks().enqueue({
281
+ id: `alarm:${binding}:${object}:${entry.seq}`,
282
+ attempt: 1,
283
+ source: alarmSource,
284
+ data,
285
+ ...time > now ? { at: time } : {}
286
+ });
287
+ },
288
+ delete: () => {
289
+ entry.time = null;
290
+ entry.seq++;
291
+ entry.gen = entry.seq;
292
+ },
293
+ unsupported: (reason) => hooks().unsupported(`Durable Object ${binding} ${object}: ${reason}`)
294
+ };
295
+ }
296
+ /** Storage objects whose alarm methods Eutaxy has taken over (one per live instance). */
297
+ const takenOver = /* @__PURE__ */ new WeakSet();
298
+ const timeOf = (time) => typeof time === "number" ? time : time.getTime();
299
+ /** Storage objects whose alarm was read before Eutaxy took them over (in a constructor). */
300
+ const readBeforeTakeover = /* @__PURE__ */ new WeakSet();
301
+ /** Storage prototypes whose getAlarm records such reads. */
302
+ const watched = /* @__PURE__ */ new WeakSet();
303
+ /**
304
+ * Record reads of the native alarm on storage not yet taken over: a rebuilt
305
+ * object's constructor reads native storage, where Eutaxy's pending alarm is
306
+ * not. The wrapper only records; it returns what the native method returns.
307
+ */
308
+ function watchReads(storage) {
309
+ const proto = Object.getPrototypeOf(storage);
310
+ if (!proto || watched.has(proto) || typeof proto.getAlarm !== "function") return;
311
+ watched.add(proto);
312
+ const native = proto.getAlarm;
313
+ proto.getAlarm = function(...args) {
314
+ if (!takenOver.has(this)) readBeforeTakeover.add(this);
315
+ return native.apply(this, args);
316
+ };
317
+ }
318
+ /**
319
+ * Replace an object's alarm methods so no real alarm is ever scheduled. An
320
+ * alarm the object set before the takeover (in its constructor) is moved
321
+ * over: deleted from the runtime and set on the control, unless an alarm is
322
+ * still pending, which the constructor could not see in native storage
323
+ * (Eutaxy keeps it): then the pending one stays and the run is UNSUPPORTED.
324
+ */
325
+ async function takeOverAlarms(storage, alarm) {
326
+ if (takenOver.has(storage)) return;
327
+ watchReads(storage);
328
+ takenOver.add(storage);
329
+ if (readBeforeTakeover.has(storage) && alarm.get() !== null) alarm.unsupported("its constructor read the alarm while one was pending; natively it would have seen that alarm, so constructors that read the alarm are not modelled");
330
+ const existing = await storage.getAlarm();
331
+ if (existing !== null) {
332
+ await storage.deleteAlarm();
333
+ if (alarm.get() === null) alarm.set(existing);
334
+ else alarm.unsupported("its constructor set an alarm while one was pending; natively it would have seen that alarm, so constructors that read the alarm are not modelled");
335
+ }
336
+ const s = storage;
337
+ let inSync = false;
338
+ const outsideSync = (op) => {
339
+ if (inSync) alarm.unsupported(`${op} inside transactionSync() is not modelled`);
340
+ };
341
+ Object.assign(s, {
342
+ setAlarm: async (time) => {
343
+ outsideSync("setAlarm");
344
+ alarm.set(timeOf(time));
345
+ },
346
+ getAlarm: async () => alarm.get(),
347
+ deleteAlarm: async () => {
348
+ outsideSync("deleteAlarm");
349
+ alarm.delete();
350
+ }
351
+ });
352
+ if (typeof s["transactionSync"] === "function") {
353
+ const transactionSync = s["transactionSync"].bind(storage);
354
+ s["transactionSync"] = (callback) => {
355
+ inSync = true;
356
+ try {
357
+ return transactionSync(callback);
358
+ } finally {
359
+ inSync = false;
360
+ }
361
+ };
362
+ }
363
+ const transaction = s["transaction"].bind(storage);
364
+ s["transaction"] = async (callback) => {
365
+ let pending;
366
+ let rolledBack = false;
367
+ const held = {
368
+ setAlarm: async (time) => {
369
+ pending = { time: timeOf(time) };
370
+ },
371
+ getAlarm: async () => pending ? pending.time : alarm.get(),
372
+ deleteAlarm: async () => {
373
+ pending = { time: null };
374
+ }
375
+ };
376
+ const result = await transaction((txn) => {
377
+ pending = void 0;
378
+ rolledBack = false;
379
+ return callback(new Proxy(txn, { get(target, prop) {
380
+ if (typeof prop === "string" && prop in held) return held[prop];
381
+ const value = target[prop];
382
+ if (prop === "rollback" && typeof value === "function") return (...args) => {
383
+ rolledBack = true;
384
+ return value.apply(target, args);
385
+ };
386
+ return typeof value === "function" ? value.bind(target) : value;
387
+ } }));
388
+ });
389
+ if (pending && !rolledBack) {
390
+ if (pending.time === null) alarm.delete();
391
+ else alarm.set(pending.time);
392
+ }
393
+ return result;
394
+ };
395
+ }
396
+ /**
397
+ * Fire an alarm event: skip it when the object's alarm has since moved or
398
+ * been deleted, run `alarm()` as one effect otherwise, and schedule a retry
399
+ * with backoff when the handler fails, crashes, or a fault says it did.
400
+ */
401
+ async function deliverAlarm(event, hooks, maxRedeliveries, d) {
402
+ const a = event.data;
403
+ const entry = d.book.entry(a.id);
404
+ if (entry.gen !== a.gen) return {
405
+ status: "completed",
406
+ followUps: []
407
+ };
408
+ if (a.retryCount === 0) {
409
+ if (entry.time !== a.time) return {
410
+ status: "completed",
411
+ followUps: []
412
+ };
413
+ if (entry.firings >= d.limit) {
414
+ entry.time = null;
415
+ d.bookkeep("alarm_not_fired", {
416
+ object: a.object,
417
+ firings: entry.firings
418
+ });
419
+ return {
420
+ status: "completed",
421
+ followUps: []
422
+ };
423
+ }
424
+ entry.firings++;
425
+ }
426
+ const invocation = `${event.id}#${event.attempt}`;
427
+ const inv = hooks.startInvocation(invocation);
428
+ const info = {
429
+ retryCount: a.retryCount,
430
+ isRetry: a.retryCount > 0
431
+ };
432
+ const outcome = hooks.effect({
433
+ invocation,
434
+ target: `DO:${d.binding}`,
435
+ op: "alarm",
436
+ args: {
437
+ object: a.object,
438
+ retryCount: a.retryCount
439
+ },
440
+ allowed: ALARM,
441
+ hostsEffects: true
442
+ }, async () => {
443
+ await d.runAlarm(a.id, a.object, info, a.gen);
444
+ return null;
445
+ }, () => null, {
446
+ onAbandon: () => d.abort(a.id),
447
+ mayPark: () => d.mayPark(a.id)
448
+ }).then(() => "completed", (err) => err instanceof CrashSignal ? "crashed" : "errored");
449
+ const status = await Promise.race([hooks.settle(outcome, invocation), inv.crashed.then(() => "crashed")]);
450
+ if (status === "crashed") await d.evict(a.id);
451
+ if (status !== "completed") {
452
+ if (a.retryCount < maxRetries && a.retryCount < maxRedeliveries) {
453
+ const retryAt = Date.now() + firstRetryMs * 2 ** a.retryCount;
454
+ const data = {
455
+ ...a,
456
+ retryCount: a.retryCount + 1
457
+ };
458
+ if (entry.gen === a.gen) entry.time = retryAt;
459
+ hooks.enqueue({
460
+ ...event,
461
+ attempt: event.attempt + 1,
462
+ data,
463
+ at: retryAt
464
+ });
465
+ } else {
466
+ if (entry.gen === a.gen) entry.time = null;
467
+ d.bookkeep("alarm_gave_up", {
468
+ object: a.object,
469
+ retries: a.retryCount
470
+ });
471
+ }
472
+ }
473
+ return {
474
+ status,
475
+ followUps: []
476
+ };
477
+ }
478
+ // packages/cloudflare/src/durable-objects.ts
479
+ const CALL = [
480
+ "crash_before",
481
+ "crash_after",
482
+ "ambiguous",
483
+ "error"
484
+ ];
485
+ const typed = (helpers) => helpers;
486
+ function isDurableObjectNamespace(value) {
487
+ return typeof value === "object" && value !== null && typeof value.idFromName === "function" && typeof value.get === "function";
488
+ }
489
+ /** How deep each object state is inside blockConcurrencyWhile, while it is. */
490
+ const gateDepth = /* @__PURE__ */ new WeakMap();
491
+ /** Object-state prototypes whose blockConcurrencyWhile records that depth. */
492
+ const gateWatched = /* @__PURE__ */ new WeakSet();
493
+ /**
494
+ * Record when an object holds its input gate with blockConcurrencyWhile,
495
+ * on the state prototype so constructors are covered too; the wrapper only
496
+ * records and calls the native method.
497
+ */
498
+ function watchGate(state) {
499
+ const proto = Object.getPrototypeOf(state);
500
+ if (!proto || gateWatched.has(proto) || typeof proto.blockConcurrencyWhile !== "function") return;
501
+ gateWatched.add(proto);
502
+ const native = proto.blockConcurrencyWhile;
503
+ proto.blockConcurrencyWhile = function(callback) {
504
+ return native.call(this, async () => {
505
+ gateDepth.set(this, (gateDepth.get(this) ?? 0) + 1);
506
+ try {
507
+ return await callback();
508
+ } finally {
509
+ gateDepth.set(this, (gateDepth.get(this) ?? 1) - 1);
510
+ }
511
+ });
512
+ };
513
+ }
514
+ /** Whether the object is inside blockConcurrencyWhile now. */
515
+ function gateHeld(state) {
516
+ return state !== void 0 && (gateDepth.get(state) ?? 0) > 0;
517
+ }
518
+ /** What Eutaxy keeps about one namespace during a run; the platform clears it before each run. */
519
+ var BindingState = class {
520
+ /** Names learned this run (seeded ones come back with the setup), so traces never depend on earlier runs. */
521
+ names = /* @__PURE__ */ new Map();
522
+ /** Ids of the objects a call or an alarm reached this run. */
523
+ touched = /* @__PURE__ */ new Set();
524
+ /** The objects' alarms in virtual time. */
525
+ alarms = new AlarmBook();
526
+ /** Each reached object's live state, so an invocation that crashes inside it can reset it. */
527
+ states = /* @__PURE__ */ new Map();
528
+ /** Whether the object's own effects may wait for a turn: not while it holds its input gate. */
529
+ mayPark(id) {
530
+ return !gateHeld(this.states.get(id));
531
+ }
532
+ clear() {
533
+ this.names.clear();
534
+ this.touched.clear();
535
+ this.alarms.clear();
536
+ this.states.clear();
537
+ }
538
+ /**
539
+ * Reset an object the way a crash does, with `ctx.abort()`, which
540
+ * application code cannot catch: the runtime ends the requests inside it.
541
+ * Called where an injected crash happens inside the object's own work,
542
+ * which is the one place abort() works (from outside, workerd refuses).
543
+ */
544
+ abort(id) {
545
+ const state = this.states.get(id);
546
+ this.states.delete(id);
547
+ try {
548
+ state?.abort("Eutaxy: the invocation crashed inside this object");
549
+ } catch {}
550
+ }
551
+ };
552
+ /** The storage's own alarm deletion, even after Eutaxy replaced the method on it. */
553
+ async function deleteRealAlarm(storage) {
554
+ const proto = Object.getPrototypeOf(storage);
555
+ await (Object.hasOwn(storage, "deleteAlarm") ? proto.deleteAlarm : storage.deleteAlarm)?.call(storage);
556
+ }
557
+ /** An RPC argument as effect-log data; a Request becomes its method and URL. */
558
+ function argument(value) {
559
+ if (value instanceof Request) return {
560
+ method: value.method,
561
+ url: value.url
562
+ };
563
+ return toJson(value);
564
+ }
565
+ /**
566
+ * Whether a result is data the caller holds by value. Anything else (an RPC
567
+ * capability, an object with methods) would let later calls bypass the
568
+ * proxy, so it makes the run UNSUPPORTED.
569
+ */
570
+ function isPlainData(value, depth = 0) {
571
+ if (value === null || value === void 0) return true;
572
+ if (typeof value === "function") return false;
573
+ if (typeof value !== "object") return true;
574
+ if (depth > 8) return false;
575
+ if (value instanceof Response || value instanceof Date) return true;
576
+ if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) return true;
577
+ const proto = Object.getPrototypeOf(value);
578
+ if (Array.isArray(value)) return value.every((v) => isPlainData(v, depth + 1));
579
+ if (proto !== Object.prototype && proto !== null) return false;
580
+ return Object.values(value).every((v) => isPlainData(v, depth + 1));
581
+ }
582
+ /** An RPC result as effect-log data; a Response becomes its status. */
583
+ function summarize(result) {
584
+ if (result instanceof Response) return {
585
+ status: result.status,
586
+ ok: result.ok
587
+ };
588
+ return toJson(result);
589
+ }
590
+ function proxyNamespace(real, binding, ctx, state, helpers, isReset) {
591
+ const target = `DO:${binding}`;
592
+ const { names, touched, alarms: book } = state;
593
+ const nameOf = (id) => names.get(id.toString()) ?? id.toString();
594
+ function stubFor(stub, id, object) {
595
+ /** Make sure the call may reach the object, and take over its alarms first. */
596
+ async function reach(real) {
597
+ if (!helpers) ctx.hooks.unsupported(`Durable Object binding ${binding} needs the Cloudflare test helpers (pass durableObjects to createCloudflarePlatform)`);
598
+ 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`);
599
+ else {
600
+ touched.add(id);
601
+ await typed(helpers).runInDurableObject(real, (_instance, live) => {
602
+ watchGate(live);
603
+ state.states.set(id, live);
604
+ return takeOverAlarms(live.storage, alarmControl(book, binding, id, object, () => ctx.hooks));
605
+ });
606
+ }
607
+ }
608
+ /** A result passed back to the Worker; one that is not plain data cannot be followed. */
609
+ function plain(result) {
610
+ if (!isPlainData(result)) ctx.hooks.unsupported(`Durable Object ${binding} ${object} returned something that is not plain data (an RPC capability or an object with methods); calls on it would bypass Eutaxy`);
611
+ return result;
612
+ }
613
+ /**
614
+ * The promise a call returns. On a real stub it is an RPC promise that
615
+ * pipelines property reads (`stub.getData().value`); this one is not, so
616
+ * a read on it makes the run UNSUPPORTED instead of yielding undefined.
617
+ */
618
+ function pipelineGuard(promise) {
619
+ return new Proxy(promise, { get(target, prop) {
620
+ if (typeof prop === "symbol" || prop === "then" || prop === "catch" || prop === "finally") {
621
+ const value = Reflect.get(target, prop, target);
622
+ return typeof value === "function" ? value.bind(target) : value;
623
+ }
624
+ ctx.hooks.unsupported(`Durable Object ${binding} ${object}: RPC promise pipelining (reading .${prop} on a call's promise) is not supported; await the call first`);
625
+ } });
626
+ }
627
+ /** One effect on the object: a method call, or awaiting an RPC property. */
628
+ function onObject(op, args, perform) {
629
+ return ctx.hooks.effect({
630
+ invocation: ctx.currentInvocation(),
631
+ target,
632
+ op,
633
+ args,
634
+ allowed: CALL,
635
+ hostsEffects: true
636
+ }, perform, summarize, {
637
+ onAbandon: () => state.abort(id),
638
+ mayPark: () => state.mayPark(id)
639
+ });
640
+ }
641
+ return new Proxy(stub, { get(real, prop, receiver) {
642
+ if (prop === "then") return void 0;
643
+ if (typeof prop !== "string" || prop === "id" || prop === "name") return Reflect.get(real, prop, receiver);
644
+ const call = (...args) => pipelineGuard(onObject(prop, {
645
+ object,
646
+ args: args.map(argument)
647
+ }, async () => {
648
+ await reach(real);
649
+ const method = real[prop];
650
+ if (typeof method !== "function") throw new TypeError(`${binding} stub has no ${prop}`);
651
+ return plain(await Reflect.apply(method, real, args));
652
+ }));
653
+ const read = () => onObject(prop, {
654
+ object,
655
+ property: true
656
+ }, async () => {
657
+ await reach(real);
658
+ return plain(await real[prop]);
659
+ });
660
+ const awaitable = (onFulfilled, onRejected) => read().then(onFulfilled, onRejected);
661
+ return new Proxy(call, { get(target, key) {
662
+ if (key === "then") return awaitable;
663
+ if (typeof key === "symbol") return Reflect.get(target, key);
664
+ ctx.hooks.unsupported(`Durable Object ${binding} ${object}: RPC promise pipelining (reading .${prop}.${key}) is not supported; await .${prop} first`);
665
+ } });
666
+ } });
667
+ }
668
+ function idFromName(name) {
669
+ const id = real.idFromName(name);
670
+ names.set(id.toString(), name);
671
+ return id;
672
+ }
673
+ return new Proxy(real, { get(target, prop, receiver) {
674
+ switch (prop) {
675
+ case "idFromName": return idFromName;
676
+ case "idFromString": return (hex) => target.idFromString(hex);
677
+ case "newUniqueId": return (options) => {
678
+ ctx.hooks.unsupported(`${binding}.newUniqueId() is random and differs on replay; use idFromName`);
679
+ return target.newUniqueId(options);
680
+ };
681
+ case "get": return (id, options) => stubFor(target.get(id, options), id.toString(), nameOf(id));
682
+ case "getByName": return (name) => {
683
+ const id = idFromName(name);
684
+ return stubFor(target.get(id), id.toString(), name);
685
+ };
686
+ case "jurisdiction": return (jurisdiction) => {
687
+ ctx.hooks.unsupported(`${binding}.jurisdiction() namespaces are not proxied or reset; use the namespace itself`);
688
+ return target.jurisdiction(jurisdiction);
689
+ };
690
+ default: {
691
+ const value = Reflect.get(target, prop, receiver);
692
+ return typeof value === "function" ? value.bind(target) : value;
693
+ }
694
+ }
695
+ } });
696
+ }
697
+ /**
698
+ * Run an object's `alarm()` handler inside it, after taking over its alarms
699
+ * (the instance may be new since the alarm was set).
700
+ */
701
+ /** Drop an object's instance from outside it; one that is not running has nothing to drop. */
702
+ async function evictObject(real, helpers, id) {
703
+ if (!helpers) return;
704
+ await typed(helpers).evictDurableObject(real.get(real.idFromString(id))).catch(() => {});
705
+ }
706
+ function alarmRunner(real, binding, ctx, helpers, state) {
707
+ return async (id, object, info, gen) => {
708
+ if (!helpers) {
709
+ ctx.hooks.unsupported(`Durable Object binding ${binding} needs the Cloudflare test helpers`);
710
+ return;
711
+ }
712
+ state.touched.add(id);
713
+ await typed(helpers).runInDurableObject(real.get(real.idFromString(id)), async (instance, live) => {
714
+ watchGate(live);
715
+ state.states.set(id, live);
716
+ await takeOverAlarms(live.storage, alarmControl(state.alarms, binding, id, object, () => ctx.hooks));
717
+ const entry = state.alarms.entry(id);
718
+ if (entry.gen !== gen) return;
719
+ entry.time = null;
720
+ const handler = instance.alarm;
721
+ if (typeof handler !== "function") {
722
+ ctx.hooks.unsupported(`Durable Object ${binding} ${object} set an alarm but has no alarm() handler`);
723
+ return;
724
+ }
725
+ await handler.call(instance, info);
726
+ });
727
+ };
728
+ }
729
+ /** The objects to reset: every id the namespace has created, plus the setup's named ones. */
730
+ async function objectIds(real, helpers, names, seeded) {
731
+ const ids = /* @__PURE__ */ new Map();
732
+ for (const id of await typed(helpers).listDurableObjectIds(real)) ids.set(id.toString(), id);
733
+ for (const name of seeded) {
734
+ const id = real.idFromName(name);
735
+ names.set(id.toString(), name);
736
+ ids.set(id.toString(), id);
737
+ }
738
+ return [...ids.values()].sort((a, b) => a.toString() < b.toString() ? -1 : 1);
739
+ }
740
+ /**
741
+ * Clear every object of the namespace, write the seeded entries, and evict
742
+ * them all, so each run's first call constructs the object from storage.
743
+ */
744
+ async function resetNamespace(real, helpers, names, objects) {
745
+ const { requested } = await withoutNetwork(() => clearAndSeed(real, helpers, names, objects));
746
+ if (requested) throw new Error("a Durable Object constructor made a request during reset; constructors run outside the simulation there, so objects whose constructor does I/O are not supported");
747
+ }
748
+ async function clearAndSeed(real, helpers, names, objects) {
749
+ const ids = await objectIds(real, helpers, names, Object.keys(objects));
750
+ for (const id of ids) {
751
+ const stub = real.get(id);
752
+ const name = names.get(id.toString());
753
+ const entries = name !== void 0 && Object.hasOwn(objects, name) ? objects[name] : void 0;
754
+ await typed(helpers).runInDurableObject(stub, async (_instance, state) => {
755
+ watchGate(state);
756
+ await state.storage.deleteAll();
757
+ await deleteRealAlarm(state.storage);
758
+ if (entries && Object.keys(entries).length > 0) await state.storage.put(entries);
759
+ });
760
+ await typed(helpers).evictDurableObject(stub);
761
+ }
762
+ }
763
+ /**
764
+ * Each object's storage as rows `{ key, value }`, sorted by key, one table
765
+ * per object name. An object no call reached this run still holds exactly
766
+ * its seed (reset left it evicted), so its rows come from the seed and it is
767
+ * not constructed: its constructor would run outside the simulation. Such an
768
+ * object that is running anyway was reached some other way (through another
769
+ * object's own binding): `onIndirect` is told, and the seed is not its state.
770
+ * The tables are the seeded objects and those a call reached, never objects
771
+ * only earlier runs created, so a snapshot depends on this run alone.
772
+ */
773
+ async function snapshotNamespace(real, helpers, names, touched, objects, onIndirect, onUnsupported) {
774
+ const { value, requested } = await withoutNetwork(() => readTables(real, helpers, names, touched, objects, onIndirect, onUnsupported));
775
+ if (requested) onUnsupported("a Durable Object made a request while its storage was being snapshotted");
776
+ return value;
777
+ }
778
+ async function readTables(real, helpers, names, touched, objects, onIndirect, onUnsupported) {
779
+ const out = {};
780
+ for (const id of await objectIds(real, helpers, names, Object.keys(objects))) {
781
+ const name = names.get(id.toString()) ?? id.toString();
782
+ if (!touched.has(id.toString())) {
783
+ if (await typed(helpers).evictDurableObject(real.get(id)).then(() => true, () => false)) onIndirect(name);
784
+ if (!Object.hasOwn(objects, name)) continue;
785
+ }
786
+ const entries = touched.has(id.toString()) ? [...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`);
788
+ return state.storage.list();
789
+ })] : Object.entries(Object.hasOwn(objects, name) ? objects[name] ?? {} : {});
790
+ Object.defineProperty(out, name, {
791
+ value: entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, value]) => ({
792
+ key,
793
+ value: toJson(value)
794
+ })),
795
+ enumerable: true,
796
+ writable: true,
797
+ configurable: true
798
+ });
799
+ }
800
+ return out;
801
+ }
802
+ // packages/cloudflare/src/scenario.ts
803
+ /**
804
+ * Typed construction of scenario specs for Cloudflare Workers. Everything here
805
+ * produces the plain-data `ScenarioSpec` from core; this module only knows the
806
+ * Cloudflare shapes (queues, D1 bindings) and the effect conventions the
807
+ * proxies follow.
808
+ */
809
+ function http(requests, options = {}) {
810
+ return {
811
+ kind: "http",
812
+ requests: requests.map((r, i) => ({
813
+ id: r.id ?? `req-${i + 1}`,
814
+ method: (r.method ?? (r.body === void 0 ? "GET" : "POST")).toUpperCase(),
815
+ path: r.path,
816
+ headers: r.headers ?? {},
817
+ ...r.body === void 0 ? {} : { body: r.body }
818
+ })),
819
+ retries: options.retries ?? 3,
820
+ retryOn: options.retryOn ?? "non-2xx",
821
+ ...options.delaysMs === void 0 ? {} : { delaysMs: [...options.delaysMs] },
822
+ ...options.deadlineMs === void 0 ? {} : { deadlineMs: options.deadlineMs }
823
+ };
824
+ }
825
+ /** The virtual delay before resend number `resend` (1 for the first), per the drive's caller. */
826
+ function retryDelayMs(drive, resend) {
827
+ const delays = drive.delaysMs ?? [];
828
+ return delays[Math.min(resend, delays.length) - 1] ?? 0;
829
+ }
830
+ function durableObject(binding, objects = {}, options = {}) {
831
+ return {
832
+ kind: "durable_object",
833
+ binding,
834
+ objects,
835
+ ...options.alarmsPerObject === void 0 ? {} : { alarmsPerObject: options.alarmsPerObject }
836
+ };
837
+ }
838
+ /**
839
+ * The storage of one object (by the name its id was made from) as rows
840
+ * `{ key, value }`, for state invariants.
841
+ */
842
+ function durableObjectRows(binding, object, where) {
843
+ const target = `DO:${binding}`;
844
+ return where ? {
845
+ target,
846
+ table: object,
847
+ where
848
+ } : {
849
+ target,
850
+ table: object
851
+ };
852
+ }
853
+ function queue(name, messages) {
854
+ return {
855
+ kind: "queue",
856
+ queue: name,
857
+ messages: messages.map((m, i) => ({
858
+ id: m.id ?? `msg-${i + 1}`,
859
+ body: m.body
860
+ }))
861
+ };
862
+ }
863
+ function d1Schema(binding, schemaFile) {
864
+ return {
865
+ kind: "d1",
866
+ binding,
867
+ schemaFile
868
+ };
869
+ }
870
+ /**
871
+ * Effect conventions for D1 (what the proxies record):
872
+ * call payload { args: { sql, params } }
873
+ * result payload { args: { sql, params }, result: { changes, lastRowId } }
874
+ * A committed write is a `result` whose `result.changes` is at least 1.
875
+ */
876
+ function d1Write(binding, op = "run") {
877
+ return {
878
+ target: `D1:${binding}`,
879
+ op,
880
+ kind: "result",
881
+ atLeast: { "result.changes": 1 }
882
+ };
883
+ }
884
+ /** Reads of a D1 binding: `first` (result payload `{ row }`), `all` or `raw`. */
885
+ function d1Read(binding, op = "first") {
886
+ return {
887
+ target: `D1:${binding}`,
888
+ op,
889
+ kind: "result"
890
+ };
891
+ }
892
+ /** Dot path to the Nth bound parameter of a D1 statement, in an effect payload. */
893
+ function d1Param(index) {
894
+ return `args.params.${index}`;
895
+ }
896
+ /**
897
+ * The shell follows the core function `decision` (see the `refines`
898
+ * invariant): every selected effect carries out the latest decision of its
899
+ * invocation, agrees with it on `follows`, and, with `state`, was not made
900
+ * stale by another invocation's write between the read it rests on and the
901
+ * effect. The core function's module must be listed in the scenario's
902
+ * `specs`, which is what records its calls.
903
+ */
904
+ function refines(name, decision, effect, options = {}) {
905
+ return {
906
+ kind: "refines",
907
+ name,
908
+ decision,
909
+ effect,
910
+ ...options
911
+ };
912
+ }
913
+ function atMostOncePerKey(name, effect, key) {
914
+ return {
915
+ kind: "atMostOncePerKey",
916
+ name,
917
+ effect,
918
+ key
919
+ };
920
+ }
921
+ function atLeastOnce(name, effect, key, expected) {
922
+ return {
923
+ kind: "atLeastOnce",
924
+ name,
925
+ effect,
926
+ key,
927
+ expected
928
+ };
929
+ }
930
+ /**
931
+ * Every message's (or request's) `bodyKey` value must appear at least once
932
+ * as `key` in a selected effect: nothing the drive delivered may be lost.
933
+ */
934
+ function atLeastOncePerMessage(name, drive, effect, key, bodyKey) {
935
+ const expected = [];
936
+ const items = drive.kind === "queue" ? drive.messages.map((m) => ({
937
+ id: m.id,
938
+ body: m.body
939
+ })) : drive.requests.map((r) => ({
940
+ id: r.id,
941
+ body: r.body ?? null
942
+ }));
943
+ for (const m of items) {
944
+ const v = getPath(m.body, bodyKey);
945
+ if (v === void 0) throw new Error(`${drive.kind} event ${m.id} has no ${JSON.stringify(bodyKey)} in its body`);
946
+ expected.push(v);
947
+ }
948
+ const perMessage = { bodyKey: drive.kind === "queue" ? bodyKey : bodyKey === "" ? "body" : `body.${bodyKey}` };
949
+ return {
950
+ ...atLeastOnce(name, effect, key, expected),
951
+ perMessage
952
+ };
953
+ }
954
+ /**
955
+ * Selects the responses the Worker returned for a path (`ok` narrows to 2xx
956
+ * or to everything else). One `result` per attempt: a crash before the
957
+ * response leaves none, a thrown error records status 500.
958
+ */
959
+ function httpResponse(path, options = {}) {
960
+ return {
961
+ target: `Http:${path}`,
962
+ op: "response",
963
+ kind: "result",
964
+ ...options.ok === void 0 ? {} : { where: { "result.ok": options.ok } }
965
+ };
966
+ }
967
+ /** Rows of a D1 table in the end-of-run snapshot, optionally filtered. */
968
+ function d1Rows(binding, table, where) {
969
+ return where ? {
970
+ target: `D1:${binding}`,
971
+ table,
972
+ where
973
+ } : {
974
+ target: `D1:${binding}`,
975
+ table
976
+ };
977
+ }
978
+ /** Every row the query selects satisfies all conditions. */
979
+ function everyRow(name, query, holds) {
980
+ return {
981
+ kind: "everyRow",
982
+ name,
983
+ query,
984
+ holds
985
+ };
986
+ }
987
+ /** No two rows the query selects share the value at `path` (a column, or a dot path into the row). */
988
+ function unique(name, query, path) {
989
+ return {
990
+ kind: "unique",
991
+ name,
992
+ query,
993
+ path
994
+ };
995
+ }
996
+ /** Every selected effect has a row whose column equals the effect's key. */
997
+ function implies(name, when, key, state, column) {
998
+ return {
999
+ kind: "implies",
1000
+ name,
1001
+ when,
1002
+ key,
1003
+ state,
1004
+ column
1005
+ };
1006
+ }
1007
+ /** Selects the acknowledgement that took effect for each message (explicit or implicit; not one ignored after a retry). */
1008
+ function queueAck(queueName) {
1009
+ return {
1010
+ target: `Queue:${queueName}`,
1011
+ op: "ack",
1012
+ kind: "result",
1013
+ where: { "result.effective": true }
1014
+ };
1015
+ }
1016
+ /**
1017
+ * Declare an external service: requests to `host` are answered from
1018
+ * `responses` (every request gets 200 and an empty body when omitted), and
1019
+ * `dedupeBy` names the header whose value makes repeated requests
1020
+ * idempotent at that service.
1021
+ */
1022
+ function external(name, host, options = {}) {
1023
+ return {
1024
+ name,
1025
+ host,
1026
+ guarantees: options.dedupeBy ? { dedupeBy: options.dedupeBy } : {},
1027
+ ...options.responses ? { responses: options.responses } : {}
1028
+ };
1029
+ }
1030
+ /**
1031
+ * Selects the requests to an external that took effect: a request replayed
1032
+ * under a dedupe key the external had already seen is not counted.
1033
+ */
1034
+ function fetchCall(externalName, method) {
1035
+ return {
1036
+ target: `Fetch:${externalName}`,
1037
+ ...method ? { op: method.toUpperCase() } : {},
1038
+ kind: "result",
1039
+ where: { "result.effective": true }
1040
+ };
1041
+ }
1042
+ function validateHttpDrive(drive) {
1043
+ const errors = [];
1044
+ if (drive.requests.length === 0) errors.push("http drive needs at least one request");
1045
+ const ids = /* @__PURE__ */ new Set();
1046
+ drive.requests.forEach((r, i) => {
1047
+ if (!r.path.startsWith("/")) errors.push(`requests[${i}].path must start with "/"`);
1048
+ if (!r.method) errors.push(`requests[${i}].method must not be empty`);
1049
+ if (ids.has(r.id)) errors.push(`duplicate request id ${JSON.stringify(r.id)}`);
1050
+ ids.add(r.id);
1051
+ if ((r.method === "GET" || r.method === "HEAD") && r.body !== void 0) errors.push(`requests[${i}] is a ${r.method} and cannot carry a body`);
1052
+ });
1053
+ if (!(Number.isInteger(drive.retries) && drive.retries >= 0)) errors.push("http drive retries must be a non-negative integer");
1054
+ (drive.delaysMs ?? []).forEach((d, i) => {
1055
+ if (!(Number.isInteger(d) && d >= 0)) errors.push(`http drive delaysMs[${i}] must be a non-negative integer`);
1056
+ });
1057
+ if (drive.deadlineMs !== void 0 && !(Number.isInteger(drive.deadlineMs) && drive.deadlineMs > 0)) errors.push("http drive deadlineMs must be a positive integer");
1058
+ return errors;
1059
+ }
1060
+ /** Build and validate a scenario spec; throws with every problem listed. */
1061
+ function defineScenario(input) {
1062
+ const drive = input.drive.kind === "http" ? input.drive : "messages" in input.drive && input.drive.messages.every((m) => "id" in m && typeof m.id === "string") ? input.drive : queue(input.drive.queue, input.drive.messages);
1063
+ const spec = {
1064
+ version: 1,
1065
+ name: input.name,
1066
+ platform: "cloudflare",
1067
+ worker: input.worker,
1068
+ drive,
1069
+ setup: input.setup ?? [],
1070
+ externals: input.externals ?? [],
1071
+ invariants: input.invariants,
1072
+ bounds: {
1073
+ ...defaultBounds,
1074
+ ...input.bounds
1075
+ },
1076
+ ...input.specs ? { specs: input.specs } : {}
1077
+ };
1078
+ const errors = [...validateScenario(spec), ...drive.kind === "http" ? validateHttpDrive(drive) : []];
1079
+ if (errors.length > 0) throw new Error(`invalid scenario ${JSON.stringify(input.name)}:\n- ${errors.join("\n- ")}`);
1080
+ return spec;
1081
+ }
230
1082
  // packages/cloudflare/src/platform.ts
231
1083
  const ACK = ["crash_before", "crash_after"];
232
1084
  const CUT_OFF = ["cut_off"];
233
1085
  /** The response point: a crash before it is a response the caller never saw. */
234
1086
  const RESPOND = ["crash_before"];
1087
+ /**
1088
+ * With a caller deadline the answer can also arrive too late: `ambiguous`
1089
+ * here means it was sent, the caller counted it as failed, and the handler
1090
+ * carried on.
1091
+ */
1092
+ const RESPOND_WITH_DEADLINE = ["crash_before", "ambiguous"];
235
1093
  /** The URL inbound requests are addressed to; handlers read only the path. */
236
1094
  const requestOrigin = "https://worker.test";
237
1095
  /** Build the `Request` a drive entry describes. */
@@ -281,24 +1139,50 @@ const assumptions = [
281
1139
  "platform model: Cloudflare Queues at-least-once delivery; the first ack or retry decision per message wins; unacked messages are redelivered up to max_retries then dead-lettered",
282
1140
  "D1 statements run against Miniflare's SQLite; each run/first/all/raw/batch/exec is one effect",
283
1141
  "message.timestamp is the virtual clock's time at delivery",
284
- "only D1 bindings are proxied; touching any other binding makes the run UNSUPPORTED",
1142
+ "only D1 and Durable Object bindings are proxied; touching any other binding makes the run UNSUPPORTED",
1143
+ "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/)",
1144
+ "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)",
285
1145
  "state invariants read a snapshot of every D1 binding named in setup, taken after the last event",
286
1146
  "work passed to ctx.waitUntil runs after the handler returns and never affects acknowledgement or the response; a cut_off fault at that point loses work not yet started, and an effect in flight commits without its continuation",
287
- "inbound requests: one invocation per attempt; an uncaught exception is a 500 response; the drive's caller resends a request it got no acceptable response for (crash before the response, or a status its retryOn policy rejects) up to its retries"
1147
+ "concurrent invocations (maxConcurrentInvocations above 1) share one isolate's module state and bindings, and another may run while one awaits I/O (developers.cloudflare.com/workers/reference/how-workers-works/); queue consumers run concurrently up to max_concurrency (developers.cloudflare.com/queues/configuration/consumer-concurrency/)",
1148
+ "inbound requests: one invocation per attempt; an uncaught exception is a 500 response; the drive's caller resends a request it got no acceptable response for (crash before the response, an answer after its deadlineMs, or a status its retryOn policy rejects) up to its retries, each resend after its delaysMs entry of virtual time; the handler's own time is virtual, so a late answer is the ambiguous fault at the response point or an answer later than deadlineMs in virtual time"
288
1149
  ];
289
1150
  function createCloudflarePlatform(options) {
290
1151
  const env = options.env;
291
1152
  const maxRetries = options.maxRetries ?? 3;
292
- let currentInvocation = "";
293
1153
  let hooksRef = null;
294
1154
  const ctx = {
295
1155
  get hooks() {
296
1156
  if (!hooksRef) throw new Error("no run in progress");
297
1157
  return hooksRef;
298
1158
  },
299
- currentInvocation: () => currentInvocation
1159
+ currentInvocation: () => ctx.hooks.running()
300
1160
  };
301
1161
  const d1Proxies = /* @__PURE__ */ new Map();
1162
+ const doProxies = /* @__PURE__ */ new Map();
1163
+ /** The Durable Object bindings the current scenario's setup resets before each run. */
1164
+ let resetBindings = /* @__PURE__ */ new Set();
1165
+ /** Per binding, what the current run knows about its objects. */
1166
+ const bindingStates = /* @__PURE__ */ new Map();
1167
+ const stateFor = (binding) => {
1168
+ let state = bindingStates.get(binding);
1169
+ if (!state) {
1170
+ state = new BindingState();
1171
+ bindingStates.set(binding, state);
1172
+ }
1173
+ return state;
1174
+ };
1175
+ /** Per binding, alarm firings allowed per object in the current run. */
1176
+ let alarmLimits = /* @__PURE__ */ new Map();
1177
+ const namespace = (binding) => {
1178
+ const real = env[binding];
1179
+ if (!isDurableObjectNamespace(real)) throw new Error(`env.${binding} is not a Durable Object namespace`);
1180
+ return real;
1181
+ };
1182
+ const helpers = () => {
1183
+ if (!options.durableObjects) throw new Error("Durable Object setup needs the Cloudflare test helpers: createCloudflarePlatform({ ..., durableObjects: await import(\"cloudflare:test\") })");
1184
+ return options.durableObjects;
1185
+ };
302
1186
  const proxiedEnv = new Proxy(env, { get(target, prop, receiver) {
303
1187
  const value = Reflect.get(target, prop, receiver);
304
1188
  if (typeof prop !== "string") return value;
@@ -310,6 +1194,14 @@ function createCloudflarePlatform(options) {
310
1194
  }
311
1195
  return p;
312
1196
  }
1197
+ if (isDurableObjectNamespace(value)) {
1198
+ let p = doProxies.get(prop);
1199
+ if (!p) {
1200
+ p = proxyNamespace(value, prop, ctx, stateFor(prop), options.durableObjects, () => resetBindings.has(prop));
1201
+ doProxies.set(prop, p);
1202
+ }
1203
+ return p;
1204
+ }
313
1205
  if (isBindingLike(value)) ctx.hooks.unsupported(`binding ${prop} is not proxied`);
314
1206
  return value;
315
1207
  } });
@@ -319,7 +1211,7 @@ function createCloudflarePlatform(options) {
319
1211
  let id = platformInvocations.get(hooks);
320
1212
  if (id === void 0) {
321
1213
  id = "platform";
322
- hooks.startInvocation(id);
1214
+ hooks.startInvocation(id, { bookkeeping: true });
323
1215
  platformInvocations.set(hooks, id);
324
1216
  }
325
1217
  return id;
@@ -327,8 +1219,17 @@ function createCloudflarePlatform(options) {
327
1219
  return {
328
1220
  name: "cloudflare",
329
1221
  assumptions,
1222
+ concurrent: true,
330
1223
  async reset(spec) {
1224
+ resetBindings = new Set(spec.setup.filter((s) => s.kind === "durable_object").map((s) => String(s["binding"])));
1225
+ for (const state of bindingStates.values()) state.clear();
1226
+ alarmLimits = new Map(spec.setup.filter((s) => s.kind === "durable_object").map((s) => [String(s["binding"]), s.alarmsPerObject ?? 3]));
331
1227
  for (const step of spec.setup) {
1228
+ if (step.kind === "durable_object") {
1229
+ const setup = step;
1230
+ await resetNamespace(namespace(setup.binding), helpers(), stateFor(setup.binding).names, setup.objects);
1231
+ continue;
1232
+ }
332
1233
  if (step.kind !== "d1") continue;
333
1234
  const binding = String(step["binding"]);
334
1235
  const schema = options.schemas[binding];
@@ -357,6 +1258,13 @@ function createCloudflarePlatform(options) {
357
1258
  },
358
1259
  async finish(spec, hooks) {
359
1260
  for (const step of spec.setup) {
1261
+ if (step.kind === "durable_object") {
1262
+ const setup = step;
1263
+ const binding = setup.binding;
1264
+ const tables = await snapshotNamespace(namespace(binding), helpers(), stateFor(binding).names, stateFor(binding).touched, setup.objects, (object) => hooks.unsupported(`Durable Object ${binding} ${object} was reached without a call Eutaxy saw (through another object's binding); calls between objects are not proxied yet`), (reason) => hooks.unsupported(reason));
1265
+ hooks.snapshot(platformInvocation(hooks), `DO:${binding}`, { tables });
1266
+ continue;
1267
+ }
360
1268
  if (step.kind !== "d1") continue;
361
1269
  const binding = String(step["binding"]);
362
1270
  const real = env[binding];
@@ -382,12 +1290,26 @@ function createCloudflarePlatform(options) {
382
1290
  const drive = spec.drive;
383
1291
  const invocation = `${event.id}#${event.attempt}`;
384
1292
  hooksRef = hooks;
385
- currentInvocation = invocation;
386
- try {
387
- return drive.kind === "http" ? await deliverRequest(event, hooks, spec, drive, invocation) : await deliverMessage(event, hooks, spec, drive, invocation);
388
- } finally {
389
- currentInvocation = "";
1293
+ if (event.source === "durable_object_alarm") {
1294
+ const binding = String(event.data.binding ?? "");
1295
+ return deliverAlarm(event, hooks, spec.bounds.maxRedeliveries, {
1296
+ binding,
1297
+ book: stateFor(binding).alarms,
1298
+ limit: alarmLimits.get(binding) ?? 3,
1299
+ runAlarm: alarmRunner(namespace(binding), binding, ctx, options.durableObjects, stateFor(binding)),
1300
+ abort: (id) => stateFor(binding).abort(id),
1301
+ mayPark: (id) => stateFor(binding).mayPark(id),
1302
+ evict: (id) => evictObject(namespace(binding), options.durableObjects, id),
1303
+ bookkeep: (op, args) => hooks.effectSync({
1304
+ invocation: platformInvocation(hooks),
1305
+ target: `DO:${binding}`,
1306
+ op,
1307
+ args,
1308
+ allowed: []
1309
+ }, () => null, () => null)
1310
+ });
390
1311
  }
1312
+ return drive.kind === "http" ? await deliverRequest(event, hooks, spec, drive, invocation) : await deliverMessage(event, hooks, spec, drive, invocation);
391
1313
  }
392
1314
  };
393
1315
  /** The `ExecutionContext` handed to a handler; `waitUntil` work is collected to run after it returns. */
@@ -425,6 +1347,7 @@ function createCloudflarePlatform(options) {
425
1347
  const req = event.data;
426
1348
  const target = `Http:${req.path}`;
427
1349
  const inv = hooks.startInvocation(invocation);
1350
+ const started = Date.now();
428
1351
  const background = [];
429
1352
  const handler = options.handler.fetch;
430
1353
  if (!handler) throw new Error("the Worker has no fetch() handler");
@@ -433,6 +1356,33 @@ function createCloudflarePlatform(options) {
433
1356
  method: req.method,
434
1357
  path: req.path
435
1358
  };
1359
+ const deadline = drive.deadlineMs;
1360
+ const lateAt = deadline === void 0 ? void 0 : started + deadline;
1361
+ /** The caller decides once: it accepts the answer, or gives up at `at` and resends or stops. */
1362
+ let decided = false;
1363
+ const giveUp = (at) => {
1364
+ if (decided) return;
1365
+ decided = true;
1366
+ const redeliveries = event.attempt - 1;
1367
+ if (redeliveries < drive.retries && redeliveries < spec.bounds.maxRedeliveries) {
1368
+ const resendAt = Math.max(at + retryDelayMs(drive, event.attempt), Date.now());
1369
+ hooks.enqueue({
1370
+ ...event,
1371
+ attempt: event.attempt + 1,
1372
+ ...resendAt > Date.now() ? { at: resendAt } : {}
1373
+ });
1374
+ } else hooks.effectSync({
1375
+ invocation: platformInvocation(hooks),
1376
+ target,
1377
+ op: "gave_up",
1378
+ args: {
1379
+ requestId: event.id,
1380
+ attempts: event.attempt
1381
+ },
1382
+ allowed: []
1383
+ }, () => null, () => null);
1384
+ };
1385
+ const deadlineTimer = deadline === void 0 || lateAt === void 0 ? void 0 : setTimeout(() => giveUp(lateAt), deadline);
436
1386
  let response;
437
1387
  const outcome = Promise.resolve().then(() => handler.call(options.handler, requestFor(req), proxiedEnv, executionContext(background))).then((r) => {
438
1388
  response = r;
@@ -445,6 +1395,8 @@ function createCloudflarePlatform(options) {
445
1395
  read = await Promise.race([hooks.settle(summarizeResponse(response), invocation).then((s) => s, (err) => err instanceof CrashSignal ? "crashed" : "errored"), inv.crashed.then(() => "crashed")]);
446
1396
  if (read === "crashed" || read === "errored") status = read;
447
1397
  }
1398
+ let late = lateAt !== void 0 && Date.now() > lateAt;
1399
+ const allowed = deadline === void 0 ? RESPOND : RESPOND_WITH_DEADLINE;
448
1400
  if (status === "completed" && typeof read === "object") {
449
1401
  const s = read;
450
1402
  try {
@@ -453,12 +1405,15 @@ function createCloudflarePlatform(options) {
453
1405
  target,
454
1406
  op: "response",
455
1407
  args,
456
- allowed: RESPOND
1408
+ allowed
457
1409
  }, () => s, (v) => v);
458
1410
  summary = s;
459
1411
  } catch (err) {
460
1412
  if (err instanceof CrashSignal) status = "crashed";
461
- else throw err;
1413
+ else if (err instanceof InjectedEffectError) {
1414
+ summary = s;
1415
+ late = true;
1416
+ } else throw err;
462
1417
  }
463
1418
  } else if (status === "errored") {
464
1419
  const s = {
@@ -475,29 +1430,13 @@ function createCloudflarePlatform(options) {
475
1430
  }, () => s, (v) => v);
476
1431
  summary = s;
477
1432
  }
1433
+ if (deadlineTimer !== void 0) clearTimeout(deadlineTimer);
1434
+ if (summary !== null && !late && (drive.retryOn === "5xx" ? summary.status < 500 : summary.ok)) decided = true;
1435
+ else giveUp(late && lateAt !== void 0 ? lateAt : Date.now());
478
1436
  if (await drainBackground(hooks, inv, invocation, target, background)) status = "crashed";
479
- const accepted = summary !== null && (drive.retryOn === "5xx" ? summary.status < 500 : summary.ok);
480
- const followUps = [];
481
- if (!accepted) {
482
- const redeliveries = event.attempt - 1;
483
- if (redeliveries < drive.retries && redeliveries < spec.bounds.maxRedeliveries) followUps.push({
484
- ...event,
485
- attempt: event.attempt + 1
486
- });
487
- else hooks.effectSync({
488
- invocation: platformInvocation(hooks),
489
- target,
490
- op: "gave_up",
491
- args: {
492
- requestId: event.id,
493
- attempts: event.attempt
494
- },
495
- allowed: []
496
- }, () => null, () => null);
497
- }
498
1437
  return {
499
1438
  status,
500
- followUps
1439
+ followUps: []
501
1440
  };
502
1441
  }
503
1442
  async function deliverMessage(event, hooks, spec, drive, invocation) {
@@ -660,7 +1599,10 @@ async function eutaxySide(spec, options) {
660
1599
  seed: 0,
661
1600
  faults: []
662
1601
  },
663
- bounds: spec.bounds,
1602
+ bounds: {
1603
+ ...spec.bounds,
1604
+ maxConcurrentInvocations: 1
1605
+ },
664
1606
  faultProbability: 0
665
1607
  });
666
1608
  const attempts = [];
@@ -683,7 +1625,7 @@ async function eutaxySide(spec, options) {
683
1625
  decision: decision ?? null,
684
1626
  ...response ? { response: getPath(response.payload, "result.status") } : {}
685
1627
  });
686
- pending.push(...result.followUps);
1628
+ pending.push(...run.takeQueued(), ...result.followUps);
687
1629
  }
688
1630
  } finally {
689
1631
  run.uninstall();
@@ -843,6 +1785,7 @@ async function rawSide(spec, options) {
843
1785
  }
844
1786
  /** Run both sides and compare. The Eutaxy side runs first; both start from the schema. */
845
1787
  async function runDifferential(spec, options) {
1788
+ if (spec.drive.kind === "http" && ("delaysMs" in spec.drive || "deadlineMs" in spec.drive)) throw new Error("runDifferential does not model the caller's delaysMs or deadlineMs yet");
846
1789
  const { unsupported, ...eutaxy } = await eutaxySide(spec, options);
847
1790
  const raw = await rawSide(spec, options);
848
1791
  const differences = [];
@@ -867,217 +1810,6 @@ async function runDifferential(spec, options) {
867
1810
  unsupported
868
1811
  };
869
1812
  }
870
- // packages/cloudflare/src/scenario.ts
871
- /**
872
- * Typed construction of scenario specs for Cloudflare Workers. Everything here
873
- * produces the plain-data `ScenarioSpec` from core; this module only knows the
874
- * Cloudflare shapes (queues, D1 bindings) and the effect conventions the
875
- * proxies follow.
876
- */
877
- function http(requests, options = {}) {
878
- return {
879
- kind: "http",
880
- requests: requests.map((r, i) => ({
881
- id: r.id ?? `req-${i + 1}`,
882
- method: (r.method ?? (r.body === void 0 ? "GET" : "POST")).toUpperCase(),
883
- path: r.path,
884
- headers: r.headers ?? {},
885
- ...r.body === void 0 ? {} : { body: r.body }
886
- })),
887
- retries: options.retries ?? 3,
888
- retryOn: options.retryOn ?? "non-2xx"
889
- };
890
- }
891
- function queue(name, messages) {
892
- return {
893
- kind: "queue",
894
- queue: name,
895
- messages: messages.map((m, i) => ({
896
- id: m.id ?? `msg-${i + 1}`,
897
- body: m.body
898
- }))
899
- };
900
- }
901
- function d1Schema(binding, schemaFile) {
902
- return {
903
- kind: "d1",
904
- binding,
905
- schemaFile
906
- };
907
- }
908
- /**
909
- * Effect conventions for D1 (what the proxies record):
910
- * call payload { args: { sql, params } }
911
- * result payload { args: { sql, params }, result: { changes, lastRowId } }
912
- * A committed write is a `result` whose `result.changes` is at least 1.
913
- */
914
- function d1Write(binding, op = "run") {
915
- return {
916
- target: `D1:${binding}`,
917
- op,
918
- kind: "result",
919
- atLeast: { "result.changes": 1 }
920
- };
921
- }
922
- /** Dot path to the Nth bound parameter of a D1 statement, in an effect payload. */
923
- function d1Param(index) {
924
- return `args.params.${index}`;
925
- }
926
- function atMostOncePerKey(name, effect, key) {
927
- return {
928
- kind: "atMostOncePerKey",
929
- name,
930
- effect,
931
- key
932
- };
933
- }
934
- function atLeastOnce(name, effect, key, expected) {
935
- return {
936
- kind: "atLeastOnce",
937
- name,
938
- effect,
939
- key,
940
- expected
941
- };
942
- }
943
- /**
944
- * Every message's (or request's) `bodyKey` value must appear at least once
945
- * as `key` in a selected effect: nothing the drive delivered may be lost.
946
- */
947
- function atLeastOncePerMessage(name, drive, effect, key, bodyKey) {
948
- const expected = [];
949
- const items = drive.kind === "queue" ? drive.messages.map((m) => ({
950
- id: m.id,
951
- body: m.body
952
- })) : drive.requests.map((r) => ({
953
- id: r.id,
954
- body: r.body ?? null
955
- }));
956
- for (const m of items) {
957
- const v = getPath(m.body, bodyKey);
958
- if (v === void 0) throw new Error(`${drive.kind} event ${m.id} has no ${JSON.stringify(bodyKey)} in its body`);
959
- expected.push(v);
960
- }
961
- const perMessage = { bodyKey: drive.kind === "queue" ? bodyKey : bodyKey === "" ? "body" : `body.${bodyKey}` };
962
- return {
963
- ...atLeastOnce(name, effect, key, expected),
964
- perMessage
965
- };
966
- }
967
- /**
968
- * Selects the responses the Worker returned for a path (`ok` narrows to 2xx
969
- * or to everything else). One `result` per attempt: a crash before the
970
- * response leaves none, a thrown error records status 500.
971
- */
972
- function httpResponse(path, options = {}) {
973
- return {
974
- target: `Http:${path}`,
975
- op: "response",
976
- kind: "result",
977
- ...options.ok === void 0 ? {} : { where: { "result.ok": options.ok } }
978
- };
979
- }
980
- /** Rows of a D1 table in the end-of-run snapshot, optionally filtered. */
981
- function d1Rows(binding, table, where) {
982
- return where ? {
983
- target: `D1:${binding}`,
984
- table,
985
- where
986
- } : {
987
- target: `D1:${binding}`,
988
- table
989
- };
990
- }
991
- /** Every row the query selects satisfies all conditions. */
992
- function everyRow(name, query, holds) {
993
- return {
994
- kind: "everyRow",
995
- name,
996
- query,
997
- holds
998
- };
999
- }
1000
- /** Every selected effect has a row whose column equals the effect's key. */
1001
- function implies(name, when, key, state, column) {
1002
- return {
1003
- kind: "implies",
1004
- name,
1005
- when,
1006
- key,
1007
- state,
1008
- column
1009
- };
1010
- }
1011
- /** Selects the acknowledgement that took effect for each message (explicit or implicit; not one ignored after a retry). */
1012
- function queueAck(queueName) {
1013
- return {
1014
- target: `Queue:${queueName}`,
1015
- op: "ack",
1016
- kind: "result",
1017
- where: { "result.effective": true }
1018
- };
1019
- }
1020
- /**
1021
- * Declare an external service: requests to `host` are answered from
1022
- * `responses` (every request gets 200 and an empty body when omitted), and
1023
- * `dedupeBy` names the header whose value makes repeated requests
1024
- * idempotent at that service.
1025
- */
1026
- function external(name, host, options = {}) {
1027
- return {
1028
- name,
1029
- host,
1030
- guarantees: options.dedupeBy ? { dedupeBy: options.dedupeBy } : {},
1031
- ...options.responses ? { responses: options.responses } : {}
1032
- };
1033
- }
1034
- /**
1035
- * Selects the requests to an external that took effect: a request replayed
1036
- * under a dedupe key the external had already seen is not counted.
1037
- */
1038
- function fetchCall(externalName, method) {
1039
- return {
1040
- target: `Fetch:${externalName}`,
1041
- ...method ? { op: method.toUpperCase() } : {},
1042
- kind: "result",
1043
- where: { "result.effective": true }
1044
- };
1045
- }
1046
- function validateHttpDrive(drive) {
1047
- const errors = [];
1048
- if (drive.requests.length === 0) errors.push("http drive needs at least one request");
1049
- const ids = /* @__PURE__ */ new Set();
1050
- drive.requests.forEach((r, i) => {
1051
- if (!r.path.startsWith("/")) errors.push(`requests[${i}].path must start with "/"`);
1052
- if (!r.method) errors.push(`requests[${i}].method must not be empty`);
1053
- if (ids.has(r.id)) errors.push(`duplicate request id ${JSON.stringify(r.id)}`);
1054
- ids.add(r.id);
1055
- if ((r.method === "GET" || r.method === "HEAD") && r.body !== void 0) errors.push(`requests[${i}] is a ${r.method} and cannot carry a body`);
1056
- });
1057
- if (!(Number.isInteger(drive.retries) && drive.retries >= 0)) errors.push("http drive retries must be a non-negative integer");
1058
- return errors;
1059
- }
1060
- /** Build and validate a scenario spec; throws with every problem listed. */
1061
- function defineScenario(input) {
1062
- const drive = input.drive.kind === "http" ? input.drive : "messages" in input.drive && input.drive.messages.every((m) => "id" in m && typeof m.id === "string") ? input.drive : queue(input.drive.queue, input.drive.messages);
1063
- const spec = {
1064
- version: 1,
1065
- name: input.name,
1066
- platform: "cloudflare",
1067
- worker: input.worker,
1068
- drive,
1069
- setup: input.setup ?? [],
1070
- externals: input.externals ?? [],
1071
- invariants: input.invariants,
1072
- bounds: {
1073
- ...defaultBounds,
1074
- ...input.bounds
1075
- }
1076
- };
1077
- const errors = [...validateScenario(spec), ...drive.kind === "http" ? validateHttpDrive(drive) : []];
1078
- if (errors.length > 0) throw new Error(`invalid scenario ${JSON.stringify(input.name)}:\n- ${errors.join("\n- ")}`);
1079
- return spec;
1080
- }
1081
- export { atLeastOnce, atLeastOncePerMessage, atMostOncePerKey, check, cloudflareRegressionTest, createCloudflarePlatform, d1Param, d1Rows, d1Schema, d1Write, defineScenario, everyRow, expectHolds, external, fetchCall, http, httpResponse, implies, queue, queueAck, runDifferential, snapshotD1 };
1813
+ export { atLeastOnce, atLeastOncePerMessage, atMostOncePerKey, check, cloudflareRegressionTest, createCloudflarePlatform, d1Param, d1Read, d1Rows, d1Schema, d1Write, defineScenario, durableObject, durableObjectRows, everyRow, expectHolds, external, fetchCall, http, httpResponse, implies, queue, queueAck, refines, runDifferential, snapshotD1, unique };
1082
1814
 
1083
1815
  //# sourceMappingURL=cloudflare.mjs.map