eutaxy 0.12.0 → 0.13.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,20 +1,21 @@
1
- import { A as writeFaults, C as toJson, F as getPath, I as canonicalJson, O as decisionFaults, T as validateScenario, _ as withoutNetwork, a as explore, b as settleOn, c as runInvocation, d as findResponse, f as installScriptedFetch, g as toResponse, h as replyOf, i as proxiedSide, k as readFaults, l as CrashSignal, m as parseBody, n as DifferentialStuck, p as isRedirect, r as compareSides, t as observeCore, u as InjectedEffectError, v as patchGlobals, w as defaultBounds, x as virtualEpoch } from "./src-DGh7w877.mjs";
2
- import { a as redelivery, i as invocationOf, n as atLeastOncePerMessage$1 } from "./delivery-invariants-Br29H7Rg.mjs";
3
- import { _ as endpointNumber, a as renderText, b as describeVerdict, c as aggregate, f as shrinkRefutation, g as endpointBigInt, h as conforms, i as renderSpecs, l as checkSpecModule, m as evaluate, n as renderSpecReport, r as renderSpecReportJson, s as emitRegressionTest, t as renderJson, v as render, y as describeType } from "./src-CWVQEhTr.mjs";
1
+ import { I as canonicalJson } from "./src-DGh7w877.mjs";
2
+ import { _ as render, a as renderText, c as checkSpecModule, d as shrinkRefutation, g as endpointNumber, h as endpointBigInt, i as renderSpecs, m as conforms, n as renderSpecReport, p as evaluate, r as renderSpecReportJson, v as describeType } from "./src-5pKRvj02.mjs";
4
3
  import { n as isSpec } from "./combinators-CVjxodAJ.mjs";
4
+ import { t as aggregate } from "./provers-DS44OeEm.mjs";
5
+ import { H as cloudflareRegressionTest, n as specKey } from "./workerd-BMJ-GKx8.mjs";
5
6
  import { createRequire, registerHooks } from "node:module";
6
- import { fork, spawn } from "node:child_process";
7
+ import { Readable } from "node:stream";
8
+ import { createHash, randomBytes } from "node:crypto";
7
9
  import { chmodSync, closeSync, copyFileSync, createReadStream, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, renameSync, rmSync, symlinkSync, writeFileSync, writeSync } from "node:fs";
10
+ import { homedir, tmpdir } from "node:os";
8
11
  import { basename, dirname, join, relative, resolve, sep } from "node:path";
12
+ import { createZstdDecompress, inflateRawSync } from "node:zlib";
13
+ import { fork, spawn } from "node:child_process";
9
14
  import { InternalSymbolName, ModifierFlags, NodeFlags, SyntaxKind, forEachLeadingCommentRange, forEachTrailingCommentRange } from "typescript/ast";
10
15
  import { createFileSystemLayer } from "typescript/fs";
11
16
  import { API, DiagnosticCategory, SymbolFlags, TypeFlags, TypeFormatFlags } from "typescript/sync";
12
17
  import * as is from "typescript/ast/is";
13
- import { homedir, tmpdir } from "node:os";
14
- import { createHash, randomBytes } from "node:crypto";
15
18
  import { fileURLToPath, pathToFileURL } from "node:url";
16
- import { Readable } from "node:stream";
17
- import { createZstdDecompress, inflateRawSync } from "node:zlib";
18
19
  import { createInterface } from "node:readline";
19
20
  // packages/cli/src/args.ts
20
21
  function parseArgs(argv, booleans = []) {
@@ -6023,45 +6024,6 @@ export default defineConfig({
6023
6024
  });
6024
6025
  `;
6025
6026
  }
6026
- // packages/cli/src/regression.ts
6027
- /** A Vitest regression test for a Cloudflare scenario, to run under the Cloudflare Vitest plugin. */
6028
- function cloudflareRegressionTest(verdict, options) {
6029
- const bindings = Object.keys(options.schemaPaths).sort();
6030
- const withExports = options.exports === true || options.workflows === true;
6031
- const imports = [
6032
- "import { createCloudflarePlatform } from \"eutaxy/cloudflare\";",
6033
- "import { env } from \"cloudflare:workers\";",
6034
- ...options.durableObjects ? ["import * as cloudflareTest from \"cloudflare:test\";"] : [],
6035
- `import scenario from ${JSON.stringify(options.scenarioPath)};`,
6036
- ...bindings.map((b) => `import schema_${b} from ${JSON.stringify(`${options.schemaPaths[b]}?raw`)};`),
6037
- withExports ? `import * as worker from ${JSON.stringify(options.workerPath)};` : `import handler from ${JSON.stringify(options.workerPath)};`,
6038
- ...(options.specModules ?? []).map((m, i) => `import * as core_${i} from ${JSON.stringify(m.path)};`)
6039
- ];
6040
- const schemas = `{ ${bindings.map((b) => `${b}: schema_${b}`).join(", ")} }`;
6041
- const retries = options.maxRetries === void 0 ? "" : `, maxRetries: ${options.maxRetries}`;
6042
- const objects = options.durableObjects ? ", durableObjects: cloudflareTest" : "";
6043
- return emitRegressionTest(verdict, {
6044
- imports,
6045
- platform: `createCloudflarePlatform({ env, ${withExports ? "handler: worker.default" : "handler"}, schemas: ${schemas}${retries}${objects}${withExports ? ", exports: worker" : ""} })`,
6046
- scenario: options.budgetMs === void 0 ? "scenario" : `{ ...scenario, bounds: { ...scenario.bounds, budgetMs: ${options.budgetMs} } }`,
6047
- ...options.expect ? { expect: options.expect } : {},
6048
- ...options.engineModule ? { engineModule: options.engineModule } : {},
6049
- ...options.specModules && options.specModules.length > 0 ? { observe: options.specModules.map((m, i) => ({
6050
- namespace: `core_${i}`,
6051
- functions: m.functions
6052
- })) } : {}
6053
- });
6054
- }
6055
- // packages/cli/src/keys.ts
6056
- /** How the two halves of `eutaxy check` name a module next to the scenario. Imports nothing, so workerd can load it. */
6057
- /** Normalize a module path from a scenario's `specs` to a key: "./domain.ts". */
6058
- function specKey(path) {
6059
- return `./${path.split("\\").join("/").replace(/^(\.\/)+/, "")}`;
6060
- }
6061
- /** The key Vite's `import.meta.glob` gives a path next to the scenario, seen from `.eutaxy/`. */
6062
- function globKey(path) {
6063
- return `.${specKey(path)}`;
6064
- }
6065
6027
  const skipDirs = /* @__PURE__ */ new Set([
6066
6028
  "node_modules",
6067
6029
  ".eutaxy",
@@ -6274,9 +6236,10 @@ async function runCheck(o) {
6274
6236
  o.stderr(`no wrangler config found next to the scenario; pass --wrangler <path>\n`);
6275
6237
  return exitCodes.error;
6276
6238
  }
6239
+ const stamp = `${process.pid}-${randomBytes(3).toString("hex")}`;
6277
6240
  const workDir = join(dir, ".eutaxy");
6278
- const testPath = join(workDir, `${name}.check.test.ts`);
6279
- const configPath = join(workDir, "vitest.config.mts");
6241
+ const testPath = join(workDir, `${name}.${stamp}.check.test.ts`);
6242
+ const configPath = join(workDir, `vitest.config.${stamp}.mts`);
6280
6243
  mkdirSync(workDir, { recursive: true });
6281
6244
  try {
6282
6245
  writeFileSync(testPath, checkTestSource({
@@ -6291,7 +6254,7 @@ async function runCheck(o) {
6291
6254
  mkdirSync(dirname(join(workDir, f.name)), { recursive: true });
6292
6255
  writeFileSync(join(workDir, f.name), f.source);
6293
6256
  }
6294
- const reportPath = join(workDir, "vitest-report.json");
6257
+ const reportPath = join(workDir, `vitest-report.${stamp}.json`);
6295
6258
  rmSync(reportPath, { force: true });
6296
6259
  writeFileSync(configPath, vitestConfigSource(wrangler, testPath, reportPath));
6297
6260
  const { code, output } = await runVitest(vitestBin(dir), configPath, dir);
@@ -6348,12 +6311,22 @@ async function runCheck(o) {
6348
6311
  if (verdict.kind !== "VIOLATED" && specs.some((v) => v.kind === "REFUTED" || v.kind === "CONFLICT")) return exitCodes.VIOLATED;
6349
6312
  return exitCodes[verdict.kind];
6350
6313
  } finally {
6351
- if (!o.keep) rmSync(workDir, {
6352
- recursive: true,
6353
- force: true
6354
- });
6314
+ if (!o.keep) cleanUp(workDir, stamp);
6355
6315
  }
6356
6316
  }
6317
+ /**
6318
+ * Remove this run's files; the shared ones and the directory go only when
6319
+ * no other run's files are left there (another check may still be using
6320
+ * them).
6321
+ */
6322
+ function cleanUp(workDir, stamp) {
6323
+ if (!existsSync(workDir)) return;
6324
+ for (const f of readdirSync(workDir)) if (f.includes(`.${stamp}.`)) rmSync(join(workDir, f), { force: true });
6325
+ if (!readdirSync(workDir).some((f) => /\.check\.test\.ts$|^vitest\.config\..*\.mts$|^vitest-report\./.test(f))) rmSync(workDir, {
6326
+ recursive: true,
6327
+ force: true
6328
+ });
6329
+ }
6357
6330
  // packages/cli/src/archive.ts
6358
6331
  /**
6359
6332
  * Reading the two archive formats the prover releases come in, with Node's
@@ -7079,7 +7052,7 @@ async function runReport(o) {
7079
7052
  }
7080
7053
  // packages/cli/src/version.ts
7081
7054
  /** The published package's version, as the MCP server reports it; the release tooling keeps it in step. */
7082
- const eutaxyVersion = "0.12.0";
7055
+ const eutaxyVersion = "0.13.0";
7083
7056
  // packages/cli/src/mcp.ts
7084
7057
  /**
7085
7058
  * `eutaxy mcp`: a Model Context Protocol server over stdio, so a coding
@@ -7724,3972 +7697,6 @@ async function main(argv, io) {
7724
7697
  stderr: io.stderr
7725
7698
  });
7726
7699
  }
7727
- // packages/cloudflare/src/check.ts
7728
- /** Explore a scenario on a platform and return its verdict. */
7729
- function check(spec, platform, options = { seed: spec.name }) {
7730
- return explore(spec, platform, options);
7731
- }
7732
- /** For use from a test: passes only when the scenario is BOUNDED. */
7733
- async function expectHolds(spec, platform, options) {
7734
- const verdict = await check(spec, platform, options);
7735
- if (verdict.kind !== "BOUNDED") throw new Error(describeVerdict(verdict));
7736
- }
7737
- // packages/cloudflare/src/d1.ts
7738
- /**
7739
- * The D1 binding proxy. Every statement execution is an effect point: the
7740
- * engine decides the fault, the real Miniflare-backed D1 performs the query,
7741
- * and the log records call, result and fault in the documented shape.
7742
- */
7743
- /** Whether a binding is a D1 database (what the proxies and the differential wrap). */
7744
- function isD1(value) {
7745
- return typeof value === "object" && value !== null && typeof value.prepare === "function" && typeof value.batch === "function";
7746
- }
7747
- function point(ctx, target, op, args, allowed) {
7748
- return {
7749
- invocation: ctx.currentInvocation(),
7750
- target,
7751
- op,
7752
- args,
7753
- allowed
7754
- };
7755
- }
7756
- function metaOf(result) {
7757
- return {
7758
- changes: result.meta.changes ?? 0,
7759
- lastRowId: result.meta.last_row_id ?? null
7760
- };
7761
- }
7762
- var StatementProxy = class StatementProxy {
7763
- real;
7764
- target;
7765
- ctx;
7766
- sql;
7767
- params;
7768
- constructor(real, target, ctx, sql, params) {
7769
- this.real = real;
7770
- this.target = target;
7771
- this.ctx = ctx;
7772
- this.sql = sql;
7773
- this.params = params;
7774
- }
7775
- /** The real statement, for `batch()`. */
7776
- get statement() {
7777
- return this.real;
7778
- }
7779
- args() {
7780
- return {
7781
- sql: this.sql,
7782
- params: toJson(this.params)
7783
- };
7784
- }
7785
- bind(...values) {
7786
- return new StatementProxy(this.real.bind(...values), this.target, this.ctx, this.sql, values);
7787
- }
7788
- run() {
7789
- return this.ctx.hooks.effect(point(this.ctx, this.target, "run", this.args(), writeFaults), () => this.real.run(), (r) => metaOf(r));
7790
- }
7791
- all() {
7792
- return this.ctx.hooks.effect(point(this.ctx, this.target, "all", this.args(), readFaults), () => this.real.all(), (r) => ({
7793
- rows: r.results.length,
7794
- changes: r.meta.changes ?? 0
7795
- }));
7796
- }
7797
- first(colName) {
7798
- return this.ctx.hooks.effect(point(this.ctx, this.target, "first", {
7799
- ...this.args(),
7800
- column: colName ?? null
7801
- }, readFaults), () => colName === void 0 ? this.real.first() : this.real.first(colName), (r) => ({ row: toJson(r) }));
7802
- }
7803
- raw(options) {
7804
- 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 }));
7805
- }
7806
- };
7807
- /** Wrap a D1 binding. Methods not modelled fall through to the real binding and mark the run unsupported. */
7808
- function proxyD1(real, binding, ctx) {
7809
- const target = `D1:${binding}`;
7810
- const modelled = {
7811
- prepare(sql) {
7812
- return new StatementProxy(real.prepare(sql), target, ctx, sql, []);
7813
- },
7814
- batch(statements) {
7815
- const unwrapped = statements.map((s) => s instanceof StatementProxy ? s.statement : s);
7816
- const args = { statements: statements.map((s) => s instanceof StatementProxy ? {
7817
- sql: s.sql,
7818
- params: toJson(s.params)
7819
- } : "<unproxied statement>") };
7820
- return ctx.hooks.effect(point(ctx, target, "batch", args, writeFaults), () => real.batch(unwrapped), (rs) => ({
7821
- changes: rs.reduce((n, r) => n + (r.meta.changes ?? 0), 0),
7822
- statements: rs.length
7823
- }));
7824
- },
7825
- exec(sql) {
7826
- return ctx.hooks.effect(point(ctx, target, "exec", { sql }, writeFaults), () => real.exec(sql), (r) => ({
7827
- count: r.count,
7828
- duration: 0
7829
- }));
7830
- }
7831
- };
7832
- return new Proxy(real, { get(obj, prop, receiver) {
7833
- if (prop in modelled) return modelled[prop];
7834
- const value = Reflect.get(obj, prop, receiver);
7835
- if (typeof value === "function") {
7836
- ctx.hooks.unsupported(`D1 ${binding}.${String(prop)} is not modelled`);
7837
- return value.bind(obj);
7838
- }
7839
- return value;
7840
- } });
7841
- }
7842
- /**
7843
- * Statements in a schema file. Splits on semicolons outside string literals,
7844
- * quoted identifiers and comments, and keeps CREATE TRIGGER bodies (and CASE
7845
- * expressions) whole by tracking BEGIN/CASE ... END nesting.
7846
- */
7847
- function splitSql(sql) {
7848
- const out = [];
7849
- let cur = "";
7850
- let depth = 0;
7851
- let i = 0;
7852
- const isWordChar = (c) => c !== void 0 && /[A-Za-z0-9_]/.test(c);
7853
- while (i < sql.length) {
7854
- const c = sql[i];
7855
- const next = sql[i + 1];
7856
- if (c === "-" && next === "-") {
7857
- while (i < sql.length && sql[i] !== "\n") i++;
7858
- continue;
7859
- }
7860
- if (c === "/" && next === "*") {
7861
- const end = sql.indexOf("*/", i + 2);
7862
- i = end === -1 ? sql.length : end + 2;
7863
- continue;
7864
- }
7865
- if (c === "'" || c === "\"" || c === "`" || c === "[") {
7866
- const close = c === "[" ? "]" : c;
7867
- let j = i + 1;
7868
- for (;;) {
7869
- const k = sql.indexOf(close, j);
7870
- if (k === -1) {
7871
- j = sql.length;
7872
- break;
7873
- }
7874
- if (close !== "]" && sql[k + 1] === close) {
7875
- j = k + 2;
7876
- continue;
7877
- }
7878
- j = k + 1;
7879
- break;
7880
- }
7881
- cur += sql.slice(i, j);
7882
- i = j;
7883
- continue;
7884
- }
7885
- if (isWordChar(c) && !isWordChar(sql[i - 1])) {
7886
- let j = i;
7887
- while (isWordChar(sql[j])) j++;
7888
- const word = sql.slice(i, j);
7889
- const upper = word.toUpperCase();
7890
- if (upper === "BEGIN" || upper === "CASE") depth++;
7891
- else if (upper === "END" && depth > 0) depth--;
7892
- cur += word;
7893
- i = j;
7894
- continue;
7895
- }
7896
- if (c === ";" && depth === 0) {
7897
- const statement = cur.trim();
7898
- if (statement.length > 0) out.push(statement);
7899
- cur = "";
7900
- i++;
7901
- continue;
7902
- }
7903
- cur += c;
7904
- i++;
7905
- }
7906
- const last = cur.trim();
7907
- if (last.length > 0) out.push(last);
7908
- return out;
7909
- }
7910
- /** Drop every user table and re-apply the schema, using the real binding (not an effect). */
7911
- async function resetD1(real, schema) {
7912
- const tables = await real.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '\\_cf\\_%' ESCAPE '\\'").all();
7913
- for (const { name } of tables.results) await real.prepare(`DROP TABLE IF EXISTS "${name.replace(/"/g, "\"\"")}"`).run();
7914
- for (const statement of splitSql(schema)) await real.prepare(statement).run();
7915
- }
7916
- /** Every user table's rows, sorted canonically, read through the real binding (not an effect). */
7917
- async function snapshotD1(real) {
7918
- const tables = await real.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '\\_cf\\_%' ESCAPE '\\' ORDER BY name").all();
7919
- const out = {};
7920
- 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);
7921
- return out;
7922
- }
7923
- // packages/cloudflare/src/background.ts
7924
- const CUT_OFF = ["cut_off"];
7925
- /**
7926
- * The `ExecutionContext` handed to a handler; `waitUntil` work is collected to
7927
- * run after it returns. A rejection is kept in `failures` when given: a
7928
- * scheduled invocation's status is that of its first failed `waitUntil`
7929
- * (Cloudflare, Scheduled handler); a queue or HTTP delivery's is not.
7930
- */
7931
- function executionContext(background, failures) {
7932
- return {
7933
- waitUntil: (promise) => {
7934
- background.push(promise.then(() => void 0, (error) => {
7935
- failures?.push(error);
7936
- }));
7937
- },
7938
- passThroughOnException: () => {},
7939
- props: {}
7940
- };
7941
- }
7942
- /**
7943
- * Background work extends the invocation but never changes the acknowledgement or the response.
7944
- * A cut-off here is the isolate dying after them: work not yet started is lost.
7945
- */
7946
- async function drainBackground(hooks, inv, invocation, target, background) {
7947
- if (background.length === 0 || inv.isCrashed()) return false;
7948
- try {
7949
- hooks.effectSync({
7950
- invocation,
7951
- target,
7952
- op: "background",
7953
- args: { pending: background.length },
7954
- allowed: CUT_OFF
7955
- }, () => null, () => null);
7956
- await Promise.race([hooks.settle(Promise.all(background), invocation), inv.crashed]);
7957
- return false;
7958
- } catch (err) {
7959
- if (!(err instanceof CrashSignal)) throw err;
7960
- return true;
7961
- }
7962
- }
7963
- // packages/cloudflare/src/alarms.ts
7964
- /**
7965
- * Durable Object alarms in virtual time. Eutaxy takes over each object's
7966
- * alarm methods (on its storage and inside transactions), so the runtime
7967
- * never schedules an alarm on the real clock, whose time is far ahead of
7968
- * the virtual one. A set alarm is kept per object, so it survives eviction
7969
- * as a real one does, and becomes an event due at its virtual time; when
7970
- * the run reaches it, the object's `alarm()` handler runs as one effect.
7971
- *
7972
- * Semantics, as Cloudflare documents them (developers.cloudflare.com/
7973
- * durable-objects/api/base/#alarm): an object has one alarm, a later
7974
- * `setAlarm` replaces it, execution is at least once, and a handler that
7975
- * throws is retried with exponential backoff starting at two seconds, up to
7976
- * six retries, with `{ retryCount, isRetry }`. `setAlarm` inside a
7977
- * transaction takes effect only if the transaction commits.
7978
- */
7979
- /** `EventRef.source` of an alarm event. */
7980
- const alarmSource = "durable_object_alarm";
7981
- /** Cloudflare retries a failed alarm handler up to six times, after 2 s, 4 s, 8 s, ... */
7982
- const maxRetries = 6;
7983
- const firstRetryMs = 2e3;
7984
- /** The alarms of one namespace's objects; the platform clears it before each run. */
7985
- var AlarmBook = class {
7986
- entries = /* @__PURE__ */ new Map();
7987
- clear() {
7988
- this.entries.clear();
7989
- }
7990
- entry(id) {
7991
- let e = this.entries.get(id);
7992
- if (!e) {
7993
- e = {
7994
- time: null,
7995
- seq: 0,
7996
- gen: 0,
7997
- firings: 0
7998
- };
7999
- this.entries.set(id, e);
8000
- }
8001
- return e;
8002
- }
8003
- };
8004
- /** One alarm control per object: setting schedules an event at the alarm's virtual time. */
8005
- function alarmControl(book, binding, id, object, hooks) {
8006
- const entry = book.entry(id);
8007
- return {
8008
- get: () => entry.time,
8009
- set: (time) => {
8010
- entry.time = time;
8011
- entry.seq++;
8012
- entry.gen = entry.seq;
8013
- const data = {
8014
- binding,
8015
- gen: entry.gen,
8016
- id,
8017
- object,
8018
- time,
8019
- retryCount: 0
8020
- };
8021
- const now = Date.now();
8022
- hooks().enqueue({
8023
- id: `alarm:${binding}:${object}:${entry.seq}`,
8024
- attempt: 1,
8025
- source: alarmSource,
8026
- data,
8027
- ...time > now ? { at: time } : {}
8028
- });
8029
- },
8030
- delete: () => {
8031
- entry.time = null;
8032
- entry.seq++;
8033
- entry.gen = entry.seq;
8034
- },
8035
- unsupported: (reason) => hooks().unsupported(`Durable Object ${binding} ${object}: ${reason}`)
8036
- };
8037
- }
8038
- /** Storage objects whose alarm methods Eutaxy has taken over (one per live instance). */
8039
- const takenOver = /* @__PURE__ */ new WeakSet();
8040
- const timeOf = (time) => typeof time === "number" ? time : time.getTime();
8041
- /** Storage objects whose alarm was read before Eutaxy took them over (in a constructor). */
8042
- const readBeforeTakeover = /* @__PURE__ */ new WeakSet();
8043
- /** Storage prototypes whose getAlarm records such reads. */
8044
- const watched = /* @__PURE__ */ new WeakSet();
8045
- /**
8046
- * Record reads of the native alarm on storage not yet taken over: a rebuilt
8047
- * object's constructor reads native storage, where Eutaxy's pending alarm is
8048
- * not. The wrapper only records; it returns what the native method returns.
8049
- */
8050
- function watchReads(storage) {
8051
- const proto = Object.getPrototypeOf(storage);
8052
- if (!proto || watched.has(proto) || typeof proto.getAlarm !== "function") return;
8053
- watched.add(proto);
8054
- const native = proto.getAlarm;
8055
- proto.getAlarm = function(...args) {
8056
- if (!takenOver.has(this)) readBeforeTakeover.add(this);
8057
- return native.apply(this, args);
8058
- };
8059
- }
8060
- /**
8061
- * Replace an object's alarm methods so no real alarm is ever scheduled. An
8062
- * alarm the object set before the takeover (in its constructor) is moved
8063
- * over: deleted from the runtime and set on the control, unless an alarm is
8064
- * still pending, which the constructor could not see in native storage
8065
- * (Eutaxy keeps it): then the pending one stays and the run is UNSUPPORTED.
8066
- */
8067
- async function takeOverAlarms(storage, alarm) {
8068
- if (takenOver.has(storage)) return;
8069
- watchReads(storage);
8070
- takenOver.add(storage);
8071
- 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");
8072
- const existing = await storage.getAlarm();
8073
- if (existing !== null) {
8074
- await storage.deleteAlarm();
8075
- if (alarm.get() === null) alarm.set(existing);
8076
- 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");
8077
- }
8078
- const s = storage;
8079
- let inSync = false;
8080
- const outsideSync = (op) => {
8081
- if (inSync) alarm.unsupported(`${op} inside transactionSync() is not modelled`);
8082
- };
8083
- Object.assign(s, {
8084
- setAlarm: async (time) => {
8085
- outsideSync("setAlarm");
8086
- alarm.set(timeOf(time));
8087
- },
8088
- getAlarm: async () => alarm.get(),
8089
- deleteAlarm: async () => {
8090
- outsideSync("deleteAlarm");
8091
- alarm.delete();
8092
- }
8093
- });
8094
- if (typeof s["transactionSync"] === "function") {
8095
- const transactionSync = s["transactionSync"].bind(storage);
8096
- s["transactionSync"] = (callback) => {
8097
- inSync = true;
8098
- try {
8099
- return transactionSync(callback);
8100
- } finally {
8101
- inSync = false;
8102
- }
8103
- };
8104
- }
8105
- const transaction = s["transaction"].bind(storage);
8106
- s["transaction"] = async (callback) => {
8107
- let pending;
8108
- let rolledBack = false;
8109
- const held = {
8110
- setAlarm: async (time) => {
8111
- pending = { time: timeOf(time) };
8112
- },
8113
- getAlarm: async () => pending ? pending.time : alarm.get(),
8114
- deleteAlarm: async () => {
8115
- pending = { time: null };
8116
- }
8117
- };
8118
- const result = await transaction((txn) => {
8119
- pending = void 0;
8120
- rolledBack = false;
8121
- return callback(new Proxy(txn, { get(target, prop) {
8122
- if (typeof prop === "string" && prop in held) return held[prop];
8123
- const value = target[prop];
8124
- if (prop === "rollback" && typeof value === "function") return (...args) => {
8125
- rolledBack = true;
8126
- return value.apply(target, args);
8127
- };
8128
- return typeof value === "function" ? value.bind(target) : value;
8129
- } }));
8130
- });
8131
- if (pending && !rolledBack) {
8132
- if (pending.time === null) alarm.delete();
8133
- else alarm.set(pending.time);
8134
- }
8135
- return result;
8136
- };
8137
- }
8138
- /**
8139
- * Fire an alarm event: skip it when the object's alarm has since moved or
8140
- * been deleted, run `alarm()` as one effect otherwise, and schedule a retry
8141
- * with backoff when the handler fails, crashes, or a fault says it did.
8142
- */
8143
- async function deliverAlarm(event, hooks, maxRedeliveries, d) {
8144
- const a = event.data;
8145
- const entry = d.book.entry(a.id);
8146
- if (entry.gen !== a.gen) return {
8147
- status: "completed",
8148
- followUps: []
8149
- };
8150
- if (a.retryCount === 0) {
8151
- if (entry.time !== a.time) return {
8152
- status: "completed",
8153
- followUps: []
8154
- };
8155
- if (entry.firings >= d.limit) {
8156
- entry.time = null;
8157
- d.bookkeep("alarm_not_fired", {
8158
- object: a.object,
8159
- firings: entry.firings
8160
- });
8161
- return {
8162
- status: "completed",
8163
- followUps: []
8164
- };
8165
- }
8166
- entry.firings++;
8167
- }
8168
- const invocation = invocationOf(event);
8169
- const inv = hooks.startInvocation(invocation);
8170
- const info = {
8171
- retryCount: a.retryCount,
8172
- isRetry: a.retryCount > 0
8173
- };
8174
- const { status } = await runInvocation(hooks, inv, () => hooks.effect({
8175
- invocation,
8176
- target: `DO:${d.binding}`,
8177
- op: "alarm",
8178
- args: {
8179
- object: a.object,
8180
- retryCount: a.retryCount
8181
- },
8182
- allowed: readFaults,
8183
- hostsEffects: true
8184
- }, async () => {
8185
- await d.runAlarm(a.id, a.object, info, a.gen);
8186
- return null;
8187
- }, () => null, {
8188
- onAbandon: () => d.abort(a.id),
8189
- mayPark: () => d.mayPark(a.id)
8190
- }));
8191
- if (status === "crashed") await d.evict(a.id);
8192
- if (status !== "completed") {
8193
- const next = redelivery(event, maxRetries, { maxRedeliveries });
8194
- if (next) {
8195
- const retryAt = Date.now() + firstRetryMs * 2 ** a.retryCount;
8196
- const data = {
8197
- ...a,
8198
- retryCount: a.retryCount + 1
8199
- };
8200
- if (entry.gen === a.gen) entry.time = retryAt;
8201
- hooks.enqueue({
8202
- ...next,
8203
- data,
8204
- at: retryAt
8205
- });
8206
- } else {
8207
- if (entry.gen === a.gen) entry.time = null;
8208
- d.bookkeep("alarm_gave_up", {
8209
- object: a.object,
8210
- retries: a.retryCount
8211
- });
8212
- }
8213
- }
8214
- return {
8215
- status,
8216
- followUps: []
8217
- };
8218
- }
8219
- // packages/cloudflare/src/durable-objects.ts
8220
- /**
8221
- * The Durable Object namespace proxy. The objects are the real ones workerd
8222
- * runs: storage, transactions and the input and output gates are the
8223
- * runtime's own. Eutaxy proxies the boundary a Worker crosses to reach them:
8224
- * every call on a stub is an effect point, so a call can fail before it
8225
- * reaches the object (`crash_before`, `error`), or reach it, commit, and
8226
- * lose its answer (`ambiguous`) or its caller (`crash_after`).
8227
- *
8228
- * Between runs every object is cleared, seeded from the scenario's setup
8229
- * and evicted, so it starts from storage alone; after a run its storage is
8230
- * snapshotted for state invariants. Both go through the Cloudflare Vitest
8231
- * plugin's test helpers. Alarms are taken over on each object's storage and
8232
- * fire in virtual time (see alarms.ts).
8233
- */
8234
- const typed = (helpers) => helpers;
8235
- function isDurableObjectNamespace(value) {
8236
- return typeof value === "object" && value !== null && typeof value.idFromName === "function" && typeof value.get === "function";
8237
- }
8238
- /** How deep each object state is inside blockConcurrencyWhile, while it is. */
8239
- const gateDepth = /* @__PURE__ */ new WeakMap();
8240
- /** Object-state prototypes whose blockConcurrencyWhile records that depth. */
8241
- const gateWatched = /* @__PURE__ */ new WeakSet();
8242
- /**
8243
- * Record when an object holds its input gate with blockConcurrencyWhile,
8244
- * on the state prototype so constructors are covered too; the wrapper only
8245
- * records and calls the native method.
8246
- */
8247
- function watchGate(state) {
8248
- const proto = Object.getPrototypeOf(state);
8249
- if (!proto || gateWatched.has(proto) || typeof proto.blockConcurrencyWhile !== "function") return;
8250
- gateWatched.add(proto);
8251
- const native = proto.blockConcurrencyWhile;
8252
- proto.blockConcurrencyWhile = function(callback) {
8253
- return native.call(this, async () => {
8254
- gateDepth.set(this, (gateDepth.get(this) ?? 0) + 1);
8255
- try {
8256
- return await callback();
8257
- } finally {
8258
- gateDepth.set(this, (gateDepth.get(this) ?? 1) - 1);
8259
- }
8260
- });
8261
- };
8262
- }
8263
- /** Whether the object is inside blockConcurrencyWhile now. */
8264
- function gateHeld(state) {
8265
- return state !== void 0 && (gateDepth.get(state) ?? 0) > 0;
8266
- }
8267
- /** What Eutaxy keeps about one namespace during a run; the platform clears it before each run. */
8268
- var BindingState = class {
8269
- /** Names learned this run (seeded ones come back with the setup), so traces never depend on earlier runs. */
8270
- names = /* @__PURE__ */ new Map();
8271
- /** Ids of the objects a call or an alarm reached this run. */
8272
- touched = /* @__PURE__ */ new Set();
8273
- /** The objects' alarms in virtual time. */
8274
- alarms = new AlarmBook();
8275
- /** Each reached object's live state, so an invocation that crashes inside it can reset it. */
8276
- states = /* @__PURE__ */ new Map();
8277
- /** Whether the object's own effects may wait for a turn: not while it holds its input gate. */
8278
- mayPark(id) {
8279
- return !gateHeld(this.states.get(id));
8280
- }
8281
- clear() {
8282
- this.names.clear();
8283
- this.touched.clear();
8284
- this.alarms.clear();
8285
- this.states.clear();
8286
- }
8287
- /**
8288
- * Reset an object the way a crash does, with `ctx.abort()`, which
8289
- * application code cannot catch: the runtime ends the requests inside it.
8290
- * Called where an injected crash happens inside the object's own work,
8291
- * which is the one place abort() works (from outside, workerd refuses).
8292
- */
8293
- abort(id) {
8294
- const state = this.states.get(id);
8295
- this.states.delete(id);
8296
- try {
8297
- state?.abort("Eutaxy: the invocation crashed inside this object");
8298
- } catch {}
8299
- }
8300
- };
8301
- /** The storage's own alarm deletion, even after Eutaxy replaced the method on it. */
8302
- async function deleteRealAlarm(storage) {
8303
- const proto = Object.getPrototypeOf(storage);
8304
- await (Object.hasOwn(storage, "deleteAlarm") ? proto.deleteAlarm : storage.deleteAlarm)?.call(storage);
8305
- }
8306
- /** An RPC argument as effect-log data; a Request becomes its method and URL. */
8307
- function argument(value) {
8308
- if (value instanceof Request) return {
8309
- method: value.method,
8310
- url: value.url
8311
- };
8312
- return toJson(value);
8313
- }
8314
- /**
8315
- * Whether a result is data the caller holds by value. Anything else (an RPC
8316
- * capability, an object with methods) would let later calls bypass the
8317
- * proxy, so it makes the run UNSUPPORTED.
8318
- */
8319
- function isPlainData(value, depth = 0) {
8320
- if (value === null || value === void 0) return true;
8321
- if (typeof value === "function") return false;
8322
- if (typeof value !== "object") return true;
8323
- if (depth > 8) return false;
8324
- if (value instanceof Response || value instanceof Date) return true;
8325
- if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) return true;
8326
- const proto = Object.getPrototypeOf(value);
8327
- if (Array.isArray(value)) return value.every((v) => isPlainData(v, depth + 1));
8328
- if (proto !== Object.prototype && proto !== null) return false;
8329
- return Object.values(value).every((v) => isPlainData(v, depth + 1));
8330
- }
8331
- /** An RPC result as effect-log data; a Response becomes its status. */
8332
- function summarize(result) {
8333
- if (result instanceof Response) return {
8334
- status: result.status,
8335
- ok: result.ok
8336
- };
8337
- return toJson(result);
8338
- }
8339
- function proxyNamespace(real, binding, ctx, state, helpers, isReset) {
8340
- const target = `DO:${binding}`;
8341
- const { names, touched, alarms: book } = state;
8342
- const nameOf = (id) => names.get(id.toString()) ?? id.toString();
8343
- function stubFor(stub, id, object) {
8344
- /** Make sure the call may reach the object, and take over its alarms first. */
8345
- async function reach(real) {
8346
- if (!helpers) ctx.hooks.unsupported(`Durable Object binding ${binding} needs the Cloudflare test helpers (pass durableObjects to createCloudflarePlatform)`);
8347
- 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`);
8348
- else {
8349
- touched.add(id);
8350
- await typed(helpers).runInDurableObject(real, (_instance, live) => {
8351
- watchGate(live);
8352
- state.states.set(id, live);
8353
- return takeOverAlarms(live.storage, alarmControl(book, binding, id, object, () => ctx.hooks));
8354
- });
8355
- }
8356
- }
8357
- /** A result passed back to the Worker; one that is not plain data cannot be followed. */
8358
- function plain(result) {
8359
- 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`);
8360
- return result;
8361
- }
8362
- /**
8363
- * The promise a call returns. On a real stub it is an RPC promise that
8364
- * pipelines property reads (`stub.getData().value`); this one is not, so
8365
- * a read on it makes the run UNSUPPORTED instead of yielding undefined.
8366
- */
8367
- function pipelineGuard(promise) {
8368
- return new Proxy(promise, { get(target, prop) {
8369
- if (typeof prop === "symbol" || prop === "then" || prop === "catch" || prop === "finally") {
8370
- const value = Reflect.get(target, prop, target);
8371
- return typeof value === "function" ? value.bind(target) : value;
8372
- }
8373
- ctx.hooks.unsupported(`Durable Object ${binding} ${object}: RPC promise pipelining (reading .${prop} on a call's promise) is not supported; await the call first`);
8374
- } });
8375
- }
8376
- /** One effect on the object: a method call, or awaiting an RPC property. */
8377
- function onObject(op, args, perform) {
8378
- return ctx.hooks.effect({
8379
- invocation: ctx.currentInvocation(),
8380
- target,
8381
- op,
8382
- args,
8383
- allowed: writeFaults,
8384
- hostsEffects: true
8385
- }, perform, summarize, {
8386
- onAbandon: () => state.abort(id),
8387
- mayPark: () => state.mayPark(id)
8388
- });
8389
- }
8390
- return new Proxy(stub, { get(real, prop, receiver) {
8391
- if (prop === "then") return void 0;
8392
- if (typeof prop !== "string" || prop === "id" || prop === "name") return Reflect.get(real, prop, receiver);
8393
- const call = (...args) => pipelineGuard(onObject(prop, {
8394
- object,
8395
- args: args.map(argument)
8396
- }, async () => {
8397
- await reach(real);
8398
- const method = real[prop];
8399
- if (typeof method !== "function") throw new TypeError(`${binding} stub has no ${prop}`);
8400
- return plain(await Reflect.apply(method, real, args));
8401
- }));
8402
- const read = () => onObject(prop, {
8403
- object,
8404
- property: true
8405
- }, async () => {
8406
- await reach(real);
8407
- return plain(await real[prop]);
8408
- });
8409
- const awaitable = (onFulfilled, onRejected) => read().then(onFulfilled, onRejected);
8410
- return new Proxy(call, { get(target, key) {
8411
- if (key === "then") return awaitable;
8412
- if (typeof key === "symbol") return Reflect.get(target, key);
8413
- ctx.hooks.unsupported(`Durable Object ${binding} ${object}: RPC promise pipelining (reading .${prop}.${key}) is not supported; await .${prop} first`);
8414
- } });
8415
- } });
8416
- }
8417
- function idFromName(name) {
8418
- const id = real.idFromName(name);
8419
- names.set(id.toString(), name);
8420
- return id;
8421
- }
8422
- return new Proxy(real, { get(target, prop, receiver) {
8423
- switch (prop) {
8424
- case "idFromName": return idFromName;
8425
- case "idFromString": return (hex) => target.idFromString(hex);
8426
- case "newUniqueId": return (options) => {
8427
- ctx.hooks.unsupported(`${binding}.newUniqueId() is random and differs on replay; use idFromName`);
8428
- return target.newUniqueId(options);
8429
- };
8430
- case "get": return (id, options) => stubFor(target.get(id, options), id.toString(), nameOf(id));
8431
- case "getByName": return (name) => {
8432
- const id = idFromName(name);
8433
- return stubFor(target.get(id), id.toString(), name);
8434
- };
8435
- case "jurisdiction": return (jurisdiction) => {
8436
- ctx.hooks.unsupported(`${binding}.jurisdiction() namespaces are not proxied or reset; use the namespace itself`);
8437
- return target.jurisdiction(jurisdiction);
8438
- };
8439
- default: {
8440
- const value = Reflect.get(target, prop, receiver);
8441
- return typeof value === "function" ? value.bind(target) : value;
8442
- }
8443
- }
8444
- } });
8445
- }
8446
- /** Drop an object's instance from outside it; one that is not running has nothing to drop. */
8447
- async function evictObject(real, helpers, id) {
8448
- if (!helpers) return;
8449
- await typed(helpers).evictDurableObject(real.get(real.idFromString(id))).catch(() => {});
8450
- }
8451
- /**
8452
- * Run an object's `alarm()` handler inside it, after taking over its alarms
8453
- * (the instance may be new since the alarm was set).
8454
- */
8455
- function alarmRunner(real, binding, ctx, helpers, state) {
8456
- return async (id, object, info, gen) => {
8457
- if (!helpers) {
8458
- ctx.hooks.unsupported(`Durable Object binding ${binding} needs the Cloudflare test helpers`);
8459
- return;
8460
- }
8461
- state.touched.add(id);
8462
- await typed(helpers).runInDurableObject(real.get(real.idFromString(id)), async (instance, live) => {
8463
- watchGate(live);
8464
- state.states.set(id, live);
8465
- await takeOverAlarms(live.storage, alarmControl(state.alarms, binding, id, object, () => ctx.hooks));
8466
- const entry = state.alarms.entry(id);
8467
- if (entry.gen !== gen) return;
8468
- entry.time = null;
8469
- const handler = instance.alarm;
8470
- if (typeof handler !== "function") {
8471
- ctx.hooks.unsupported(`Durable Object ${binding} ${object} set an alarm but has no alarm() handler`);
8472
- return;
8473
- }
8474
- await handler.call(instance, info);
8475
- });
8476
- };
8477
- }
8478
- /** The objects to reset: every id the namespace has created, plus the setup's named ones. */
8479
- async function objectIds(real, helpers, names, seeded) {
8480
- const ids = /* @__PURE__ */ new Map();
8481
- for (const id of await typed(helpers).listDurableObjectIds(real)) ids.set(id.toString(), id);
8482
- for (const name of seeded) {
8483
- const id = real.idFromName(name);
8484
- names.set(id.toString(), name);
8485
- ids.set(id.toString(), id);
8486
- }
8487
- return [...ids.values()].sort((a, b) => a.toString() < b.toString() ? -1 : 1);
8488
- }
8489
- /**
8490
- * Clear every object of the namespace, write the seeded entries, and evict
8491
- * them all, so each run's first call constructs the object from storage.
8492
- */
8493
- async function resetNamespace(real, helpers, names, objects) {
8494
- const { requested } = await withoutNetwork(() => clearAndSeed(real, helpers, names, objects));
8495
- 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");
8496
- }
8497
- async function clearAndSeed(real, helpers, names, objects) {
8498
- const ids = await objectIds(real, helpers, names, Object.keys(objects));
8499
- for (const id of ids) {
8500
- const stub = real.get(id);
8501
- const name = names.get(id.toString());
8502
- const entries = name !== void 0 && Object.hasOwn(objects, name) ? objects[name] : void 0;
8503
- await typed(helpers).runInDurableObject(stub, async (_instance, state) => {
8504
- watchGate(state);
8505
- await state.storage.deleteAll();
8506
- await deleteRealAlarm(state.storage);
8507
- if (entries && Object.keys(entries).length > 0) await state.storage.put(entries);
8508
- });
8509
- await typed(helpers).evictDurableObject(stub);
8510
- }
8511
- }
8512
- /**
8513
- * Each object's storage as rows `{ key, value }`, sorted by key, one table
8514
- * per object name. An object no call reached this run still holds exactly
8515
- * its seed (reset left it evicted), so its rows come from the seed and it is
8516
- * not constructed: its constructor would run outside the simulation. Such an
8517
- * object that is running anyway was reached some other way (through another
8518
- * object's own binding): `onIndirect` is told, and the seed is not its state.
8519
- * The tables are the seeded objects and those a call reached, never objects
8520
- * only earlier runs created, so a snapshot depends on this run alone.
8521
- */
8522
- async function snapshotNamespace(real, helpers, names, touched, objects, onIndirect, onUnsupported) {
8523
- const { value, requested } = await withoutNetwork(() => readTables(real, helpers, names, touched, objects, onIndirect, onUnsupported));
8524
- if (requested) onUnsupported("a Durable Object made a request while its storage was being snapshotted");
8525
- return value;
8526
- }
8527
- async function readTables(real, helpers, names, touched, objects, onIndirect, onUnsupported) {
8528
- const out = {};
8529
- for (const id of await objectIds(real, helpers, names, Object.keys(objects))) {
8530
- const name = names.get(id.toString()) ?? id.toString();
8531
- if (!touched.has(id.toString())) {
8532
- if (await typed(helpers).evictDurableObject(real.get(id)).then(() => true, () => false)) onIndirect(name);
8533
- if (!Object.hasOwn(objects, name)) continue;
8534
- }
8535
- const entries = touched.has(id.toString()) ? [...await typed(helpers).runInDurableObject(real.get(id), (_instance, state) => {
8536
- 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`);
8537
- return state.storage.list();
8538
- })] : Object.entries(Object.hasOwn(objects, name) ? objects[name] ?? {} : {});
8539
- Object.defineProperty(out, name, {
8540
- value: entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, value]) => ({
8541
- key,
8542
- value: toJson(value)
8543
- })),
8544
- enumerable: true,
8545
- writable: true,
8546
- configurable: true
8547
- });
8548
- }
8549
- return out;
8550
- }
8551
- // packages/cloudflare/src/r2.ts
8552
- /**
8553
- * The R2 binding proxy. Every `put`, `delete`, `get`, `head` and `list` is
8554
- * an effect point against the real Miniflare-backed bucket. A body is read
8555
- * inside its `get`'s effect and handed back in an object with the same
8556
- * fields and body methods: reading it later would be I/O the run cannot
8557
- * see. An object's random `version` and wall-clock `uploaded` are replaced
8558
- * by stand-ins (see `VersionBook`), so traces stay byte-identical.
8559
- */
8560
- /** Whether a binding is an R2 bucket (Miniflare's `R2Bucket`). */
8561
- function isR2(value) {
8562
- if (typeof value !== "object" || value === null) return false;
8563
- const v = value;
8564
- return [
8565
- "head",
8566
- "get",
8567
- "put",
8568
- "delete",
8569
- "list",
8570
- "createMultipartUpload"
8571
- ].every((m) => typeof v[m] === "function");
8572
- }
8573
- /**
8574
- * Stand-ins for the version and upload time of each object version the run
8575
- * sees, in the order it first sees them: versions count up, and the time is
8576
- * the virtual time it was first seen.
8577
- */
8578
- var VersionBook = class {
8579
- seen = /* @__PURE__ */ new Map();
8580
- clear() {
8581
- this.seen.clear();
8582
- }
8583
- standIn(realVersion, at) {
8584
- let s = this.seen.get(realVersion);
8585
- if (!s) {
8586
- s = {
8587
- version: (this.seen.size + 1).toString(16).padStart(32, "0"),
8588
- uploaded: new Date(at)
8589
- };
8590
- this.seen.set(realVersion, s);
8591
- }
8592
- return {
8593
- version: s.version,
8594
- uploaded: new Date(s.uploaded.getTime())
8595
- };
8596
- }
8597
- };
8598
- /** An object's metadata, with stand-ins for its version and upload time. */
8599
- function metadata(real, book, at) {
8600
- const { version, uploaded } = book.standIn(real.version, at);
8601
- return {
8602
- key: real.key,
8603
- version,
8604
- size: real.size,
8605
- etag: real.etag,
8606
- httpEtag: real.httpEtag,
8607
- uploaded,
8608
- httpMetadata: real.httpMetadata,
8609
- customMetadata: real.customMetadata,
8610
- range: real.range,
8611
- checksums: real.checksums,
8612
- storageClass: real.storageClass,
8613
- ssecKeyMd5: real.ssecKeyMd5,
8614
- writeHttpMetadata: (headers) => real.writeHttpMetadata(headers)
8615
- };
8616
- }
8617
- /**
8618
- * The bytes behind each body stream the proxy hands out. The stream itself
8619
- * has no known length, which the runtime's put requires, so a put given one
8620
- * (copying an object) is given its bytes instead.
8621
- */
8622
- const buffered = /* @__PURE__ */ new WeakMap();
8623
- /**
8624
- * An object with its body, already read: the stream and the body methods
8625
- * share one consumption, as a real body's do. A method fails once the
8626
- * stream is read, cancelled or locked by a reader; the stream ends empty
8627
- * once a method has read the body.
8628
- */
8629
- function withBody(meta, bytes) {
8630
- let used = false;
8631
- let stream;
8632
- const take = () => {
8633
- if (used || stream?.locked) throw new TypeError("Body has already been used");
8634
- used = true;
8635
- return bytes.slice();
8636
- };
8637
- return Object.defineProperties(meta, {
8638
- body: {
8639
- enumerable: true,
8640
- get: () => {
8641
- stream ??= new ReadableStream({
8642
- pull(controller) {
8643
- if (!used) controller.enqueue(bytes.slice());
8644
- used = true;
8645
- controller.close();
8646
- },
8647
- cancel() {
8648
- used = true;
8649
- }
8650
- }, { highWaterMark: 0 });
8651
- buffered.set(stream, take);
8652
- return stream;
8653
- }
8654
- },
8655
- bodyUsed: {
8656
- enumerable: true,
8657
- get: () => used
8658
- },
8659
- arrayBuffer: { value: async () => take().buffer },
8660
- bytes: { value: async () => take() },
8661
- text: { value: async () => new TextDecoder().decode(take()) },
8662
- json: { value: async () => JSON.parse(new TextDecoder().decode(take())) },
8663
- blob: { value: async () => new Blob([take()]) }
8664
- });
8665
- }
8666
- /** Conditions as the trace keeps them: a `Headers` object by its entries. */
8667
- function conditions(onlyIf) {
8668
- if (onlyIf === void 0) return {};
8669
- return { onlyIf: onlyIf instanceof Headers ? Object.fromEntries(onlyIf.entries()) : onlyIf };
8670
- }
8671
- /** What the trace keeps of a get's options: the conditions and range, never an encryption key. */
8672
- function getArgs(key, options) {
8673
- return toJson({
8674
- key,
8675
- ...conditions(options?.onlyIf),
8676
- ...options?.range === void 0 ? {} : { range: options.range }
8677
- });
8678
- }
8679
- /** What the trace keeps of a put's options: the conditions and metadata, not checksums or keys. */
8680
- function putArgs(options) {
8681
- if (!options) return {};
8682
- return toJson({
8683
- ...conditions(options.onlyIf),
8684
- ...options.customMetadata === void 0 ? {} : { customMetadata: options.customMetadata },
8685
- ...options.httpMetadata === void 0 ? {} : { httpMetadata: options.httpMetadata }
8686
- });
8687
- }
8688
- function proxyR2(real, binding, ctx, book) {
8689
- const target = `R2:${binding}`;
8690
- const point = (op, args, allowed) => ({
8691
- invocation: ctx.currentInvocation(),
8692
- target,
8693
- op,
8694
- args,
8695
- allowed
8696
- });
8697
- const notModelled = (what) => {
8698
- const reason = `R2 ${binding}: ${what} is not modelled`;
8699
- ctx.hooks.unsupported(reason);
8700
- throw new Error(`eutaxy: ${reason}`);
8701
- };
8702
- /** Date conditions compare the store's real upload time, not the stand-in the Worker saw. */
8703
- const checkConditions = (onlyIf) => {
8704
- 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`);
8705
- };
8706
- const described = (o) => o === null ? { found: false } : {
8707
- found: true,
8708
- key: o.key,
8709
- size: o.size,
8710
- etag: o.etag
8711
- };
8712
- return {
8713
- put: (key, value, options) => ctx.hooks.effect(point("put", {
8714
- key,
8715
- ...putArgs(options)
8716
- }, writeFaults), async () => {
8717
- checkConditions(options?.onlyIf);
8718
- const read = value instanceof ReadableStream ? buffered.get(value) : void 0;
8719
- const stored = await real.put(key, read ? read() : value, options);
8720
- return stored === null ? null : metadata(stored, book, Date.now());
8721
- }, (o) => o === null ? { stored: false } : {
8722
- stored: true,
8723
- size: o.size,
8724
- etag: o.etag
8725
- }),
8726
- delete: (keys) => ctx.hooks.effect(point("delete", { keys: typeof keys === "string" ? [keys] : [...keys] }, writeFaults), () => real.delete(keys), () => null),
8727
- get: (key, options) => ctx.hooks.effect(point("get", getArgs(key, options), readFaults), async () => {
8728
- checkConditions(options?.onlyIf);
8729
- const o = await real.get(key, options);
8730
- if (o === null) return null;
8731
- const meta = metadata(o, book, Date.now());
8732
- if (!("body" in o)) return meta;
8733
- return withBody(meta, new Uint8Array(await o.arrayBuffer()));
8734
- }, (o) => ({
8735
- ...described(o),
8736
- ...o !== null ? { body: "body" in o } : {}
8737
- })),
8738
- head: (key) => ctx.hooks.effect(point("head", { key }, readFaults), async () => {
8739
- const o = await real.head(key);
8740
- return o === null ? null : metadata(o, book, Date.now());
8741
- }, described),
8742
- list: (options) => ctx.hooks.effect(point("list", toJson(options ?? {}), readFaults), async () => {
8743
- const listed = await real.list(options);
8744
- const at = Date.now();
8745
- return {
8746
- ...listed,
8747
- objects: listed.objects.map((o) => metadata(o, book, at))
8748
- };
8749
- }, (l) => ({
8750
- keys: l.objects.map((o) => o.key),
8751
- truncated: l.truncated,
8752
- delimitedPrefixes: l.delimitedPrefixes
8753
- })),
8754
- createMultipartUpload: () => notModelled("createMultipartUpload()"),
8755
- resumeMultipartUpload: () => notModelled("resumeMultipartUpload()")
8756
- };
8757
- }
8758
- /** Every object of the bucket, through all pages of a listing. */
8759
- async function allObjects(real) {
8760
- const out = [];
8761
- let cursor;
8762
- for (;;) {
8763
- const page = await real.list({
8764
- include: ["customMetadata", "httpMetadata"],
8765
- ...cursor === void 0 ? {} : { cursor }
8766
- });
8767
- out.push(...page.objects);
8768
- if (!page.truncated) return out;
8769
- cursor = page.cursor;
8770
- }
8771
- }
8772
- /** Empty the bucket and put its seeds, before a run. */
8773
- async function resetR2(real, seeds) {
8774
- const keys = (await allObjects(real)).map((o) => o.key);
8775
- for (let i = 0; i < keys.length; i += 1e3) await real.delete(keys.slice(i, i + 1e3));
8776
- for (const [key, seed] of Object.entries(seeds)) if (typeof seed === "string") await real.put(key, seed);
8777
- else await real.put(key, seed.value, {
8778
- ...seed.customMetadata ? { customMetadata: { ...seed.customMetadata } } : {},
8779
- ...seed.httpMetadata ? { httpMetadata: { ...seed.httpMetadata } } : {}
8780
- });
8781
- }
8782
- /** Largest object whose text the snapshot keeps. */
8783
- const snapshotTextLimit = 4096;
8784
- /**
8785
- * The bucket's objects as rows `{ key, size, etag, customMetadata,
8786
- * httpMetadata, text? }` by key, `text` for an object of up to 4 KiB that is
8787
- * valid UTF-8. Versions and upload times are left out: they are the store's,
8788
- * not the Worker's.
8789
- */
8790
- async function snapshotR2(real) {
8791
- const rows = [];
8792
- const objects = (await allObjects(real)).sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
8793
- for (const o of objects) {
8794
- let text;
8795
- if (o.size <= snapshotTextLimit) {
8796
- const body = await real.get(o.key);
8797
- if (body && "body" in body) try {
8798
- text = new TextDecoder("utf-8", {
8799
- fatal: true,
8800
- ignoreBOM: false
8801
- }).decode(await body.arrayBuffer());
8802
- } catch {}
8803
- }
8804
- rows.push(toJson({
8805
- key: o.key,
8806
- size: o.size,
8807
- etag: o.etag,
8808
- customMetadata: o.customMetadata ?? {},
8809
- httpMetadata: o.httpMetadata ?? {},
8810
- ...text === void 0 ? {} : { text }
8811
- }));
8812
- }
8813
- return rows;
8814
- }
8815
- // packages/cloudflare/src/cron.ts
8816
- const fields = [
8817
- {
8818
- name: "minute",
8819
- min: 0,
8820
- max: 59
8821
- },
8822
- {
8823
- name: "hour",
8824
- min: 0,
8825
- max: 23
8826
- },
8827
- {
8828
- name: "day of month",
8829
- min: 1,
8830
- max: 31
8831
- },
8832
- {
8833
- name: "month",
8834
- min: 1,
8835
- max: 12,
8836
- names: [
8837
- "jan",
8838
- "feb",
8839
- "mar",
8840
- "apr",
8841
- "may",
8842
- "jun",
8843
- "jul",
8844
- "aug",
8845
- "sep",
8846
- "oct",
8847
- "nov",
8848
- "dec"
8849
- ],
8850
- firstName: 1
8851
- },
8852
- {
8853
- name: "weekday",
8854
- min: 1,
8855
- max: 7,
8856
- names: [
8857
- "sun",
8858
- "mon",
8859
- "tue",
8860
- "wed",
8861
- "thu",
8862
- "fri",
8863
- "sat"
8864
- ],
8865
- firstName: 1
8866
- }
8867
- ];
8868
- function value(token, field) {
8869
- const lower = token.toLowerCase();
8870
- if (field.names) {
8871
- const i = field.names.indexOf(lower);
8872
- if (i >= 0) return (field.firstName ?? 0) + i;
8873
- }
8874
- if (!/^\d+$/.test(token)) throw new Error(`${field.name}: ${JSON.stringify(token)} is not a value`);
8875
- const n = Number(token);
8876
- if (n < field.min || n > field.max) throw new Error(`${field.name}: ${n} is outside ${field.min}-${field.max}`);
8877
- return n;
8878
- }
8879
- function parseField(text, field) {
8880
- if (/[LW#]/i.test(text) && !field.names?.some((n) => text.toLowerCase().includes(n))) throw new Error(`${field.name}: L, W and # are not modelled`);
8881
- const out = /* @__PURE__ */ new Set();
8882
- for (const part of text.split(",")) {
8883
- const pieces = part.split("/");
8884
- if (pieces.length > 2 || part === "") throw new Error(`${field.name}: ${JSON.stringify(part)} is not a value, range or step`);
8885
- const [rangeText, stepText] = pieces;
8886
- let step = 1;
8887
- if (stepText !== void 0) {
8888
- if (!/^\d+$/.test(stepText) || Number(stepText) < 1) throw new Error(`${field.name}: step ${JSON.stringify(stepText)} is not a positive number`);
8889
- step = Number(stepText);
8890
- }
8891
- let from;
8892
- let to;
8893
- if (rangeText === "*") {
8894
- from = field.min;
8895
- to = field.max;
8896
- } else if (rangeText.includes("-")) {
8897
- const ends = rangeText.split("-");
8898
- if (ends.length !== 2) throw new Error(`${field.name}: ${JSON.stringify(rangeText)} is not a range`);
8899
- const [a, b] = ends;
8900
- from = value(a, field);
8901
- to = value(b, field);
8902
- if (from > to) throw new Error(`${field.name}: range ${rangeText} runs backwards`);
8903
- } else {
8904
- from = value(rangeText, field);
8905
- to = stepText === void 0 ? from : field.max;
8906
- }
8907
- for (let v = from; v <= to; v += step) out.add(v);
8908
- }
8909
- return out;
8910
- }
8911
- /** Parse an expression; throws with the field and the problem when it is not one Cloudflare accepts. */
8912
- function parseCron(expression) {
8913
- const parts = expression.trim().split(/\s+/);
8914
- if (parts.length !== 5) throw new Error(`a cron expression has five fields, got ${parts.length}: ${JSON.stringify(expression)}`);
8915
- const [minute, hour, dom, month, weekday] = parts;
8916
- return {
8917
- minutes: parseField(minute, fields[0]),
8918
- hours: parseField(hour, fields[1]),
8919
- daysOfMonth: parseField(dom, fields[2]),
8920
- months: parseField(month, fields[3]),
8921
- weekdays: parseField(weekday, fields[4]),
8922
- anyDayOfMonth: dom === "*",
8923
- anyWeekday: weekday === "*"
8924
- };
8925
- }
8926
- /** Whether the minute starting at `time` (ms since the epoch, UTC) matches. */
8927
- function cronMatches(schedule, time) {
8928
- const d = new Date(time);
8929
- if (!schedule.minutes.has(d.getUTCMinutes()) || !schedule.hours.has(d.getUTCHours())) return false;
8930
- if (!schedule.months.has(d.getUTCMonth() + 1)) return false;
8931
- const dayOk = schedule.daysOfMonth.has(d.getUTCDate());
8932
- const weekdayOk = schedule.weekdays.has(d.getUTCDay() + 1);
8933
- if (!schedule.anyDayOfMonth && !schedule.anyWeekday) return dayOk || weekdayOk;
8934
- return dayOk && weekdayOk;
8935
- }
8936
- const minuteMs = 6e4;
8937
- /**
8938
- * Between two matches of any expression Cloudflare accepts lie at most eight
8939
- * years (the 29th of February across a century's missing leap year); an
8940
- * expression with no match in that span never fires.
8941
- */
8942
- const longestGapMs = 4743360 * minuteMs;
8943
- /** The first `count` tick times at or after `from`, each the start of a matching minute. */
8944
- function cronTicks(expression, from, count) {
8945
- const schedule = parseCron(expression);
8946
- const out = [];
8947
- let t = Math.ceil(from / minuteMs) * minuteMs;
8948
- let horizon = t + longestGapMs;
8949
- while (out.length < count) {
8950
- if (t > horizon) throw new Error(`${JSON.stringify(expression)} never fires`);
8951
- if (cronMatches(schedule, t)) {
8952
- out.push(t);
8953
- horizon = t + longestGapMs;
8954
- }
8955
- t += minuteMs;
8956
- }
8957
- return out;
8958
- }
8959
- // packages/cloudflare/src/scenario.ts
8960
- /**
8961
- * Typed construction of scenario specs for Cloudflare Workers. Everything here
8962
- * produces the plain-data `ScenarioSpec` from core; this module only knows the
8963
- * Cloudflare shapes (queues, D1 bindings) and the effect conventions the
8964
- * proxies follow.
8965
- */
8966
- function http(requests, options = {}) {
8967
- return {
8968
- kind: "http",
8969
- requests: requests.map((r, i) => ({
8970
- id: r.id ?? `req-${i + 1}`,
8971
- method: (r.method ?? (r.body === void 0 ? "GET" : "POST")).toUpperCase(),
8972
- path: r.path,
8973
- headers: r.headers ?? {},
8974
- ...r.body === void 0 ? {} : { body: r.body }
8975
- })),
8976
- retries: options.retries ?? 3,
8977
- retryOn: options.retryOn ?? "non-2xx",
8978
- ...options.delaysMs === void 0 ? {} : { delaysMs: [...options.delaysMs] },
8979
- ...options.deadlineMs === void 0 ? {} : { deadlineMs: options.deadlineMs }
8980
- };
8981
- }
8982
- function rpc(calls, options = {}) {
8983
- return {
8984
- kind: "rpc",
8985
- ...options.entrypoint === void 0 ? {} : { entrypoint: options.entrypoint },
8986
- calls: calls.map((c, i) => ({
8987
- id: c.id ?? `call-${i + 1}`,
8988
- method: c.method,
8989
- args: [...c.args ?? []]
8990
- })),
8991
- retries: options.retries ?? 0,
8992
- ...options.delaysMs === void 0 ? {} : { delaysMs: [...options.delaysMs] },
8993
- ...options.deadlineMs === void 0 ? {} : { deadlineMs: options.deadlineMs }
8994
- };
8995
- }
8996
- /** The target of a call's effects: the method, under the entrypoint's name when the drive names one. */
8997
- function rpcTarget(drive, method) {
8998
- return `Rpc:${drive.entrypoint === void 0 ? method : `${drive.entrypoint}.${method}`}`;
8999
- }
9000
- function cron(expression, options = {}) {
9001
- const count = options.ticks ?? 1;
9002
- return {
9003
- kind: "cron",
9004
- cron: expression,
9005
- ticks: (Number.isInteger(count) && count >= 1 ? cronTicks(expression, virtualEpoch, count) : []).map((at, i) => ({
9006
- id: `tick-${i + 1}`,
9007
- at
9008
- })),
9009
- retries: options.retries ?? 0
9010
- };
9011
- }
9012
- /** The drive's events as they are first delivered: one per message, request or call, attempt 1. */
9013
- function driveEvents(drive) {
9014
- switch (drive.kind) {
9015
- case "queue": return drive.messages.map((m) => ({
9016
- id: m.id,
9017
- attempt: 1,
9018
- data: m.body
9019
- }));
9020
- case "http": return drive.requests.map((r) => ({
9021
- id: r.id,
9022
- attempt: 1,
9023
- data: r
9024
- }));
9025
- case "rpc": return drive.calls.map((c) => ({
9026
- id: c.id,
9027
- attempt: 1,
9028
- data: c
9029
- }));
9030
- case "cron": return drive.ticks.map((t) => ({
9031
- id: t.id,
9032
- attempt: 1,
9033
- data: {
9034
- cron: drive.cron,
9035
- scheduledTime: t.at
9036
- },
9037
- at: t.at
9038
- }));
9039
- }
9040
- }
9041
- /** The drive with only the named events kept, for shrinking. */
9042
- function restrictDrive(drive, keepIds) {
9043
- const keep = (id) => keepIds.includes(id);
9044
- switch (drive.kind) {
9045
- case "queue": return {
9046
- ...drive,
9047
- messages: drive.messages.filter((m) => keep(m.id))
9048
- };
9049
- case "http": return {
9050
- ...drive,
9051
- requests: drive.requests.filter((r) => keep(r.id))
9052
- };
9053
- case "rpc": return {
9054
- ...drive,
9055
- calls: drive.calls.filter((c) => keep(c.id))
9056
- };
9057
- case "cron": return {
9058
- ...drive,
9059
- ticks: drive.ticks.filter((t) => keep(t.id))
9060
- };
9061
- }
9062
- }
9063
- function durableObject(binding, objects = {}, options = {}) {
9064
- return {
9065
- kind: "durable_object",
9066
- binding,
9067
- objects,
9068
- ...options.alarmsPerObject === void 0 ? {} : { alarmsPerObject: options.alarmsPerObject }
9069
- };
9070
- }
9071
- function r2Bucket(binding, objects = {}) {
9072
- return {
9073
- kind: "r2",
9074
- binding,
9075
- objects
9076
- };
9077
- }
9078
- /**
9079
- * Selects an R2 bucket's operations that completed, a `put` by default; a
9080
- * put whose `onlyIf` failed stored nothing and is not selected, as a D1
9081
- * write that changed no row is not.
9082
- */
9083
- function r2Op(binding, op = "put") {
9084
- const target = `R2:${binding}`;
9085
- return op === "put" ? {
9086
- target,
9087
- op,
9088
- kind: "result",
9089
- where: { "result.stored": true }
9090
- } : {
9091
- target,
9092
- op,
9093
- kind: "result"
9094
- };
9095
- }
9096
- /** A bucket's objects at the end of the run as rows `{ key, size, etag, customMetadata, httpMetadata, text? }`. */
9097
- function r2Rows(binding, where) {
9098
- const target = `R2:${binding}`;
9099
- return where ? {
9100
- target,
9101
- table: "objects",
9102
- where
9103
- } : {
9104
- target,
9105
- table: "objects"
9106
- };
9107
- }
9108
- /**
9109
- * Every row the query returns is named by some row of `in` (its `column`
9110
- * equals the row's value at `path`), as with a foreign key.
9111
- */
9112
- function references(name, query, path, inQuery, column) {
9113
- return {
9114
- kind: "references",
9115
- name,
9116
- query,
9117
- path,
9118
- in: inQuery,
9119
- column
9120
- };
9121
- }
9122
- function workflow(binding, className, options = {}) {
9123
- return {
9124
- kind: "workflow",
9125
- binding,
9126
- className,
9127
- ...options.name === void 0 ? {} : { name: options.name }
9128
- };
9129
- }
9130
- function service(binding, options = {}) {
9131
- return {
9132
- kind: "service",
9133
- binding,
9134
- ...options.methods === void 0 ? {} : { methods: options.methods },
9135
- ...options.fetch === void 0 ? {} : { fetch: [...options.fetch] }
9136
- };
9137
- }
9138
- /** Selects the calls through a service binding that completed, one method's or all. */
9139
- function serviceCall(binding, method) {
9140
- return {
9141
- target: `Service:${binding}`,
9142
- ...method === void 0 ? {} : { op: method },
9143
- kind: "result"
9144
- };
9145
- }
9146
- /** Selects a Workflow's step attempts, optionally of one step; a failed attempt's result carries its error. */
9147
- function workflowStep(binding, step) {
9148
- return {
9149
- target: `Workflow:${binding}`,
9150
- op: "step_result",
9151
- kind: "result",
9152
- ...step === void 0 ? {} : { where: { "args.step": step } }
9153
- };
9154
- }
9155
- /** A Workflow's instances at the end of the run as rows `{ id, status, params, output?, error? }`. */
9156
- function workflowRows(binding, where) {
9157
- const target = `Workflow:${binding}`;
9158
- return where ? {
9159
- target,
9160
- table: "instances",
9161
- where
9162
- } : {
9163
- target,
9164
- table: "instances"
9165
- };
9166
- }
9167
- /**
9168
- * The storage of one object (by the name its id was made from) as rows
9169
- * `{ key, value }`, for state invariants.
9170
- */
9171
- function durableObjectRows(binding, object, where) {
9172
- const target = `DO:${binding}`;
9173
- return where ? {
9174
- target,
9175
- table: object,
9176
- where
9177
- } : {
9178
- target,
9179
- table: object
9180
- };
9181
- }
9182
- function queue(name, messages) {
9183
- return {
9184
- kind: "queue",
9185
- queue: name,
9186
- messages: messages.map((m, i) => ({
9187
- id: m.id ?? `msg-${i + 1}`,
9188
- body: m.body
9189
- }))
9190
- };
9191
- }
9192
- function d1Schema(binding, schemaFile) {
9193
- return {
9194
- kind: "d1",
9195
- binding,
9196
- schemaFile
9197
- };
9198
- }
9199
- /**
9200
- * Effect conventions for D1 (what the proxies record):
9201
- * call payload { args: { sql, params } }
9202
- * result payload { args: { sql, params }, result: { changes, lastRowId } }
9203
- * A committed write is a `result` whose `result.changes` is at least 1.
9204
- */
9205
- function d1Write(binding, op = "run") {
9206
- return {
9207
- target: `D1:${binding}`,
9208
- op,
9209
- kind: "result",
9210
- atLeast: { "result.changes": 1 }
9211
- };
9212
- }
9213
- /** Reads of a D1 binding: `first` (result payload `{ row }`), `all` or `raw`. */
9214
- function d1Read(binding, op = "first") {
9215
- return {
9216
- target: `D1:${binding}`,
9217
- op,
9218
- kind: "result"
9219
- };
9220
- }
9221
- /** Dot path to the Nth bound parameter of a D1 statement, in an effect payload. */
9222
- function d1Param(index) {
9223
- return `args.params.${index}`;
9224
- }
9225
- /**
9226
- * The shell follows the core function `decision` (see the `refines`
9227
- * invariant): every selected effect carries out the latest decision of its
9228
- * invocation, agrees with it on `follows`, and, with `state`, was not made
9229
- * stale by another invocation's write between the read it rests on and the
9230
- * effect. The core function's module must be listed in the scenario's
9231
- * `specs`, which is what records its calls.
9232
- */
9233
- function refines(name, decision, effect, options = {}) {
9234
- return {
9235
- kind: "refines",
9236
- name,
9237
- decision,
9238
- effect,
9239
- ...options
9240
- };
9241
- }
9242
- /**
9243
- * Every message's (or request's, or call's) `bodyKey` value must appear at
9244
- * least once as `key` in a selected effect: nothing the drive delivered may
9245
- * be lost. For an RPC drive `bodyKey` is a path into the call's arguments
9246
- * (`"0.orderId"`).
9247
- */
9248
- function atLeastOncePerMessage(name, drive, effect, key, bodyKey) {
9249
- if (drive.kind === "queue") return atLeastOncePerMessage$1(name, drive.messages, effect, key, bodyKey);
9250
- if (drive.kind === "cron") {
9251
- const ticks = drive.ticks.map((t) => ({
9252
- id: t.id,
9253
- body: {
9254
- cron: drive.cron,
9255
- scheduledTime: t.at
9256
- }
9257
- }));
9258
- return atLeastOncePerMessage$1(name, ticks, effect, key, bodyKey);
9259
- }
9260
- if (drive.kind === "rpc") {
9261
- const calls = drive.calls.map((c) => ({
9262
- id: c.id,
9263
- body: c.args
9264
- }));
9265
- return {
9266
- ...atLeastOncePerMessage$1(name, calls, effect, key, bodyKey),
9267
- perMessage: { bodyKey: bodyKey === "" ? "args" : `args.${bodyKey}` }
9268
- };
9269
- }
9270
- const requests = drive.requests.map((r) => ({
9271
- id: r.id,
9272
- body: r.body ?? null
9273
- }));
9274
- return {
9275
- ...atLeastOncePerMessage$1(name, requests, effect, key, bodyKey),
9276
- perMessage: { bodyKey: bodyKey === "" ? "body" : `body.${bodyKey}` }
9277
- };
9278
- }
9279
- /**
9280
- * Selects the responses the Worker returned for a path (`ok` narrows to 2xx
9281
- * or to everything else). One `result` per attempt: a crash before the
9282
- * response leaves none, a thrown error records status 500.
9283
- */
9284
- function httpResponse(path, options = {}) {
9285
- return {
9286
- target: `Http:${path}`,
9287
- op: "response",
9288
- kind: "result",
9289
- ...options.ok === void 0 ? {} : { where: { "result.ok": options.ok } }
9290
- };
9291
- }
9292
- /**
9293
- * Selects the answers an RPC method gave (`ok` narrows to values returned
9294
- * or to errors thrown). One `result` per attempt: a crash before the
9295
- * response leaves none.
9296
- */
9297
- function rpcResponse(method, options = {}) {
9298
- return {
9299
- target: rpcTarget(options, method),
9300
- op: "response",
9301
- kind: "result",
9302
- ...options.ok === void 0 ? {} : { where: { "result.ok": options.ok } }
9303
- };
9304
- }
9305
- /** Rows of a D1 table in the end-of-run snapshot, optionally filtered. */
9306
- function d1Rows(binding, table, where) {
9307
- return where ? {
9308
- target: `D1:${binding}`,
9309
- table,
9310
- where
9311
- } : {
9312
- target: `D1:${binding}`,
9313
- table
9314
- };
9315
- }
9316
- /** Every row the query selects satisfies all conditions. */
9317
- function everyRow(name, query, holds) {
9318
- return {
9319
- kind: "everyRow",
9320
- name,
9321
- query,
9322
- holds
9323
- };
9324
- }
9325
- /** No two rows the query selects share the value at `path` (a column, or a dot path into the row). */
9326
- function unique(name, query, path) {
9327
- return {
9328
- kind: "unique",
9329
- name,
9330
- query,
9331
- path
9332
- };
9333
- }
9334
- /** Every selected effect has a row whose column equals the effect's key. */
9335
- function implies(name, when, key, state, column) {
9336
- return {
9337
- kind: "implies",
9338
- name,
9339
- when,
9340
- key,
9341
- state,
9342
- column
9343
- };
9344
- }
9345
- /** Selects the acknowledgement that took effect for each message (explicit or implicit; not one ignored after a retry). */
9346
- function queueAck(queueName) {
9347
- return {
9348
- target: `Queue:${queueName}`,
9349
- op: "ack",
9350
- kind: "result",
9351
- where: { "result.effective": true }
9352
- };
9353
- }
9354
- /**
9355
- * Declare an external service: requests to `host` are answered from
9356
- * `responses` (every request gets 200 and an empty body when omitted), and
9357
- * `dedupeBy` names the header whose value makes repeated requests
9358
- * idempotent at that service.
9359
- */
9360
- function external(name, host, options = {}) {
9361
- return {
9362
- name,
9363
- host,
9364
- guarantees: options.dedupeBy ? { dedupeBy: options.dedupeBy } : {},
9365
- ...options.responses ? { responses: options.responses } : {}
9366
- };
9367
- }
9368
- /**
9369
- * Selects the requests to an external that took effect: a request replayed
9370
- * under a dedupe key the external had already seen is not counted.
9371
- */
9372
- function fetchCall(externalName, method) {
9373
- return {
9374
- target: `Fetch:${externalName}`,
9375
- ...method ? { op: method.toUpperCase() } : {},
9376
- kind: "result",
9377
- where: { "result.effective": true }
9378
- };
9379
- }
9380
- function validateHttpDrive(drive) {
9381
- const errors = [];
9382
- if (drive.requests.length === 0) errors.push("http drive needs at least one request");
9383
- const ids = /* @__PURE__ */ new Set();
9384
- drive.requests.forEach((r, i) => {
9385
- if (!r.path.startsWith("/")) errors.push(`requests[${i}].path must start with "/"`);
9386
- if (!r.method) errors.push(`requests[${i}].method must not be empty`);
9387
- if (ids.has(r.id)) errors.push(`duplicate request id ${JSON.stringify(r.id)}`);
9388
- ids.add(r.id);
9389
- if ((r.method === "GET" || r.method === "HEAD") && r.body !== void 0) errors.push(`requests[${i}] is a ${r.method} and cannot carry a body`);
9390
- });
9391
- errors.push(...validateCaller("http", drive));
9392
- return errors;
9393
- }
9394
- /** The caller's policy, as both drives a caller resends declare it. */
9395
- function validateCaller(kind, drive) {
9396
- const errors = [];
9397
- if (!(Number.isInteger(drive.retries) && drive.retries >= 0)) errors.push(`${kind} drive retries must be a non-negative integer`);
9398
- (drive.delaysMs ?? []).forEach((d, i) => {
9399
- if (!(Number.isInteger(d) && d >= 0)) errors.push(`${kind} drive delaysMs[${i}] must be a non-negative integer`);
9400
- });
9401
- if (drive.deadlineMs !== void 0 && !(Number.isInteger(drive.deadlineMs) && drive.deadlineMs > 0)) errors.push(`${kind} drive deadlineMs must be a positive integer`);
9402
- return errors;
9403
- }
9404
- function validateCronDrive(drive) {
9405
- const errors = [];
9406
- try {
9407
- parseCron(drive.cron);
9408
- } catch (err) {
9409
- errors.push(`cron drive: ${err.message}`);
9410
- }
9411
- if (drive.ticks.length === 0) errors.push("cron drive ticks must be a positive integer");
9412
- const ids = /* @__PURE__ */ new Set();
9413
- drive.ticks.forEach((t, i) => {
9414
- if (ids.has(t.id)) errors.push(`duplicate tick id ${JSON.stringify(t.id)}`);
9415
- ids.add(t.id);
9416
- const previous = drive.ticks[i - 1];
9417
- if (previous && !(t.at > previous.at)) errors.push(`ticks[${i}] does not come after ticks[${i - 1}]`);
9418
- });
9419
- if (!(Number.isInteger(drive.retries) && drive.retries >= 0)) errors.push("cron drive retries must be a non-negative integer");
9420
- return errors;
9421
- }
9422
- /** A method name the entrypoint can have: an identifier that is not the constructor. */
9423
- const methodName = /^[A-Za-z_$][\w$]*$/;
9424
- function validateRpcDrive(drive) {
9425
- const errors = [];
9426
- if (drive.entrypoint !== void 0 && !methodName.test(drive.entrypoint)) errors.push("rpc drive entrypoint must be an exported class name");
9427
- const ids = /* @__PURE__ */ new Set();
9428
- drive.calls.forEach((c, i) => {
9429
- if (!methodName.test(c.method) || c.method === "constructor") errors.push(`calls[${i}].method must be a method name`);
9430
- if (!Array.isArray(c.args)) errors.push(`calls[${i}].args must be an array`);
9431
- if (ids.has(c.id)) errors.push(`duplicate call id ${JSON.stringify(c.id)}`);
9432
- ids.add(c.id);
9433
- });
9434
- errors.push(...validateCaller("rpc", drive));
9435
- return errors;
9436
- }
9437
- /** Build and validate a scenario spec; throws with every problem listed. */
9438
- function defineScenario(input) {
9439
- const drive = input.drive.kind === "queue" ? queue(input.drive.queue, input.drive.messages) : input.drive;
9440
- const spec = {
9441
- version: 1,
9442
- name: input.name,
9443
- platform: "cloudflare",
9444
- worker: input.worker,
9445
- drive,
9446
- setup: input.setup ?? [],
9447
- externals: input.externals ?? [],
9448
- invariants: input.invariants,
9449
- bounds: {
9450
- ...defaultBounds,
9451
- ...input.bounds
9452
- },
9453
- ...input.specs ? { specs: input.specs } : {}
9454
- };
9455
- const errors = [
9456
- ...validateScenario(spec),
9457
- ...drive.kind === "http" ? validateHttpDrive(drive) : [],
9458
- ...drive.kind === "rpc" ? validateRpcDrive(drive) : [],
9459
- ...drive.kind === "cron" ? validateCronDrive(drive) : []
9460
- ];
9461
- if (errors.length > 0) throw new Error(`invalid scenario ${JSON.stringify(input.name)}:\n- ${errors.join("\n- ")}`);
9462
- return spec;
9463
- }
9464
- // packages/cloudflare/src/services.ts
9465
- /**
9466
- * Service bindings with the callee scripted. A Worker reaches a peer through
9467
- * `env.BINDING`, by RPC method or by `fetch()`; Cloudflare routes the call on
9468
- * the same thread and retries nothing (Workers, service bindings). The real
9469
- * binding is never called here: the scenario's `service()` setup scripts the
9470
- * replies, and each call is one effect with the faults of a Durable Object
9471
- * stub call, where `crash_before` and `error` mean the call never reached
9472
- * the callee, `ambiguous` that it acted and the answer was lost, and
9473
- * `crash_after` that the caller died after it.
9474
- */
9475
- /** Marks of the other kinds of binding, which a service binding's duck type must not carry. */
9476
- const otherKinds = [
9477
- "prepare",
9478
- "idFromName",
9479
- "head",
9480
- "createBatch"
9481
- ];
9482
- /**
9483
- * Whether an env value is a service binding (the runtime's `Fetcher`). In
9484
- * workerd it is an RPC stub whose every property read yields a callable, so
9485
- * duck typing alone would take it for any other kind: the runtime's class is
9486
- * checked first, and the duck type (fetch and connect, none of the other
9487
- * kinds' marks) serves test doubles.
9488
- */
9489
- function isServiceBinding(value) {
9490
- if (typeof value !== "object" || value === null) return false;
9491
- const fetcher = globalThis.Fetcher;
9492
- if (typeof fetcher === "function" && value instanceof fetcher) return true;
9493
- if ((Object.getPrototypeOf(value)?.constructor)?.name === "Fetcher") return true;
9494
- const v = value;
9495
- return typeof v["fetch"] === "function" && typeof v["connect"] === "function" && otherKinds.every((k) => typeof v[k] !== "function");
9496
- }
9497
- /** The built-in error classes RPC carries across as themselves (workerd keeps the type). */
9498
- const builtInErrors = {
9499
- Error,
9500
- EvalError,
9501
- RangeError,
9502
- ReferenceError,
9503
- SyntaxError,
9504
- TypeError,
9505
- URIError
9506
- };
9507
- /**
9508
- * The error the caller sees for a `throws` reply, `"<Name>: <message>"`: a
9509
- * built-in error class is that class, so `instanceof` holds as it does over
9510
- * RPC; any other name is an `Error` carrying the name.
9511
- */
9512
- function scriptedError(spec) {
9513
- const at = spec.indexOf(": ");
9514
- if (at < 0) return new Error(spec);
9515
- const name = spec.slice(0, at);
9516
- const message = spec.slice(at + 2);
9517
- const builtIn = builtInErrors[name];
9518
- if (builtIn) return new builtIn(message);
9519
- const error = new Error(message);
9520
- error.name = name;
9521
- return error;
9522
- }
9523
- /** The scripted stub a Worker sees under a service binding's name. */
9524
- function proxyService(binding, ctx, script) {
9525
- const target = `Service:${binding}`;
9526
- const point = (op, args) => ({
9527
- invocation: ctx.currentInvocation(),
9528
- target,
9529
- op,
9530
- args,
9531
- allowed: writeFaults
9532
- });
9533
- const unsupported = (what) => {
9534
- const reason = `service binding ${binding}: ${what}`;
9535
- ctx.hooks.unsupported(reason);
9536
- throw new Error(`eutaxy: ${reason}`);
9537
- };
9538
- /** The scripted reply to a method, by name; a method the script lacks cannot be answered. */
9539
- const replyTo = (method) => {
9540
- if (script.methods === void 0) return { returns: null };
9541
- if (!Object.hasOwn(script.methods, method)) return unsupported(`no scripted reply for method ${method}; add it to the service(${JSON.stringify(binding)}) setup's methods`);
9542
- return script.methods[method];
9543
- };
9544
- const answer = (method) => {
9545
- const reply = replyTo(method);
9546
- if ("throws" in reply) throw scriptedError(reply.throws);
9547
- return structuredClone(reply.returns);
9548
- };
9549
- const fetchThrough = async (input, init) => {
9550
- const request = new Request(input, init);
9551
- const url = new URL(request.url);
9552
- const method = request.method.toUpperCase();
9553
- const headers = {};
9554
- request.headers.forEach((value, name) => {
9555
- headers[name.toLowerCase()] = value;
9556
- });
9557
- const body = parseBody(await request.text());
9558
- const reply = await ctx.hooks.effect(point(method, {
9559
- url: request.url,
9560
- method,
9561
- headers,
9562
- body
9563
- }), async () => {
9564
- const found = findResponse({
9565
- name: binding,
9566
- host: url.host,
9567
- guarantees: {},
9568
- ...script.fetch === void 0 ? {} : { responses: script.fetch }
9569
- }, method, url.pathname);
9570
- if (found === void 0) return unsupported(`no scripted reply for fetch ${method} ${url.pathname}; add it to the service(${JSON.stringify(binding)}) setup's fetch`);
9571
- const reply = replyOf(found);
9572
- if (isRedirect(reply.status) && request.redirect !== "manual") return unsupported(`the scripted reply to ${method} ${url.pathname} is a ${reply.status} redirect, which the runtime would follow; script the final reply or fetch with redirect: "manual"`);
9573
- return reply;
9574
- }, (r) => ({ status: r.status }));
9575
- return toResponse(reply);
9576
- };
9577
- /**
9578
- * The promise a call returns. On the real stub it is an RPC promise that
9579
- * pipelines property reads (`stub.charge().id`); this one is not, so a read
9580
- * on it makes the run UNSUPPORTED instead of yielding undefined.
9581
- */
9582
- const pipelineGuard = (promise, method) => new Proxy(promise, { get(target, prop) {
9583
- if (typeof prop === "symbol" || prop === "then" || prop === "catch" || prop === "finally") {
9584
- const value = Reflect.get(target, prop, target);
9585
- return typeof value === "function" ? value.bind(target) : value;
9586
- }
9587
- ctx.hooks.unsupported(`service binding ${binding}: RPC promise pipelining (reading .${prop} on ${method}()'s promise) is not supported; await the call first`);
9588
- } });
9589
- /** One call: `stub.method(...)`, or `await stub.property` (an RPC getter). */
9590
- const call = (method) => {
9591
- const invoke = (...args) => pipelineGuard(ctx.hooks.effect(point(method, { args: args.map((a) => toJson(a)) }), async () => answer(method), (value) => ({ value: toJson(value) })), method);
9592
- const read = () => ctx.hooks.effect(point(method, { property: true }), async () => answer(method), (value) => ({ value: toJson(value) }));
9593
- const awaitable = (onFulfilled, onRejected) => read().then(onFulfilled, onRejected);
9594
- return new Proxy(invoke, { get(fn, key) {
9595
- if (key === "then") return awaitable;
9596
- if (typeof key === "symbol") return Reflect.get(fn, key);
9597
- ctx.hooks.unsupported(`service binding ${binding}: RPC promise pipelining (reading .${method}.${key}) is not supported; await .${method} first`);
9598
- } });
9599
- };
9600
- return new Proxy({}, { get(_stub, prop) {
9601
- if (prop === "then" || typeof prop === "symbol") return void 0;
9602
- if (prop === "fetch") return fetchThrough;
9603
- if (prop === "connect") return () => unsupported("connect() (a raw TCP socket) is not modelled");
9604
- return call(prop);
9605
- } });
9606
- }
9607
- // packages/cloudflare/src/entrypoint.ts
9608
- /**
9609
- * Constructing an entrypoint class (`WorkerEntrypoint`, `WorkflowEntrypoint`)
9610
- * outside the runtime, for the one `new` per call or instance run that the
9611
- * models make themselves.
9612
- */
9613
- /** Sets `ctx` and `env` as the runtime's base classes do, for the one `new` workerd would refuse. */
9614
- var StandInEntrypoint = class {
9615
- ctx;
9616
- env;
9617
- constructor(ctx, env) {
9618
- this.ctx = ctx;
9619
- this.env = env;
9620
- }
9621
- };
9622
- /**
9623
- * Construct a subclass of the entrypoint base class named `base`. workerd's
9624
- * base constructors accept only a native ExecutionContext, so for this one
9625
- * synchronous `new` the class that extends the base directly extends a
9626
- * stand-in instead; its own constructor and field initialisers run as
9627
- * written, and the base is put back before anything else can run.
9628
- */
9629
- function constructEntrypoint(cls, base, ctx, env) {
9630
- if (typeof cls !== "function") throw new TypeError("not a class");
9631
- let direct = cls;
9632
- for (;;) {
9633
- const parent = Object.getPrototypeOf(direct);
9634
- if (typeof parent !== "function" || parent === Function.prototype) throw new TypeError(`${cls.name} does not extend ${base}`);
9635
- if (parent.name === base) break;
9636
- direct = parent;
9637
- }
9638
- const original = Object.getPrototypeOf(direct);
9639
- Object.setPrototypeOf(direct, StandInEntrypoint);
9640
- try {
9641
- return Reflect.construct(cls, [ctx, env]);
9642
- } finally {
9643
- Object.setPrototypeOf(direct, original);
9644
- }
9645
- }
9646
- // packages/cloudflare/src/workflows.ts
9647
- /**
9648
- * Workflows, modelled: the binding's `create`/`get`, and each instance run
9649
- * as invocations of its class's `run(event, step)` against a model of the
9650
- * engine (persisted step results, retries in virtual time, restarts that
9651
- * re-run `run` from the start). The real local engine is never called: it
9652
- * runs on its own real-time clock and retry loop, which Eutaxy can neither
9653
- * fault nor schedule. See docs/design.md, "Workflows".
9654
- */
9655
- /** The `EventRef.source` of a Workflow instance's run. */
9656
- const workflowSource = "workflow";
9657
- /** Before a step's callback: the engine restarts before the step runs. */
9658
- const STEP_START = ["crash_before"];
9659
- /**
9660
- * After it: the engine restarts after the step ran but before its result
9661
- * was persisted (`crash_after`), or the attempt ran and counted as failed,
9662
- * as a timeout does (`ambiguous`).
9663
- */
9664
- const STEP_RESULT = ["crash_after", "ambiguous"];
9665
- /**
9666
- * Cloudflare's defaults for a step without a config (Workflows, Sleeping
9667
- * and retrying). A partial config is merged with them field by field, as
9668
- * the engine does. Miniflare's local engine waits 1 s by default; the
9669
- * model keeps the documented 10 s.
9670
- */
9671
- const defaultRetries = {
9672
- limit: 5,
9673
- delay: 1e4,
9674
- backoff: "exponential"
9675
- };
9676
- /** Keep a thrown value as the engine keeps it, with an Error's name, which the clone would lose. */
9677
- function failure(thrown) {
9678
- let kept;
9679
- try {
9680
- kept = structuredClone(thrown);
9681
- } catch {
9682
- kept = new Error(String(thrown));
9683
- }
9684
- return thrown instanceof Error ? {
9685
- ok: false,
9686
- error: kept,
9687
- errorName: thrown.name
9688
- } : {
9689
- ok: false,
9690
- error: kept
9691
- };
9692
- }
9693
- /** One binding's instances in the current run. */
9694
- var WorkflowRegistry = class {
9695
- instances = /* @__PURE__ */ new Map();
9696
- clear() {
9697
- this.instances.clear();
9698
- }
9699
- /** The instances as rows for the end-of-run snapshot, by id. */
9700
- rows() {
9701
- return [...this.instances.values()].sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0).map((i) => ({
9702
- id: i.id,
9703
- status: i.status,
9704
- params: toJson(i.params),
9705
- ...i.output === void 0 ? {} : { output: toJson(i.output) },
9706
- ...i.error === void 0 ? {} : { error: `${i.error.name}: ${i.error.message}` }
9707
- }));
9708
- }
9709
- };
9710
- /** A Workflow binding as the env shows it (Miniflare's `WorkflowImpl`). */
9711
- function isWorkflowBinding(value) {
9712
- if (typeof value !== "object" || value === null) return false;
9713
- const v = value;
9714
- return typeof v["create"] === "function" && typeof v["createBatch"] === "function" && typeof v["get"] === "function";
9715
- }
9716
- /** The binding's proxy: instances live in the registry and run as events, never in the real engine. */
9717
- function proxyWorkflow(binding, ctx, registry) {
9718
- const target = `Workflow:${binding}`;
9719
- const unsupported = (what) => {
9720
- const reason = `Workflow ${binding}: ${what} is not modelled`;
9721
- ctx.hooks.unsupported(reason);
9722
- throw new Error(`eutaxy: ${reason}`);
9723
- };
9724
- const handle = (id) => ({
9725
- id,
9726
- status: () => ctx.hooks.effect({
9727
- invocation: ctx.currentInvocation(),
9728
- target,
9729
- op: "status",
9730
- args: { id },
9731
- allowed: []
9732
- }, async () => {
9733
- const i = registry.instances.get(id);
9734
- if (!i) throw new Error("instance.not_found");
9735
- return {
9736
- status: i.status,
9737
- output: i.output === void 0 ? null : structuredClone(i.output),
9738
- ...i.error === void 0 ? {} : { error: { ...i.error } }
9739
- };
9740
- }, (s) => toJson(s)),
9741
- pause: () => unsupported("pause()"),
9742
- resume: () => unsupported("resume()"),
9743
- terminate: () => unsupported("terminate()"),
9744
- restart: () => unsupported("restart()"),
9745
- sendEvent: (args = {}) => ctx.hooks.effect({
9746
- invocation: ctx.currentInvocation(),
9747
- target,
9748
- op: "send_event",
9749
- args: {
9750
- id,
9751
- type: toJson(args.type),
9752
- payload: toJson(args.payload)
9753
- },
9754
- allowed: writeFaults
9755
- }, async () => {
9756
- const type = validEventType(args.type);
9757
- const i = registry.instances.get(id);
9758
- if (!i) throw new Error("instance.not_found");
9759
- if (i.status === "complete" || i.status === "errored") throw new Error(`(instance.not_running) Workflow instance with id "${id}" is ${i.status} and takes no events`);
9760
- const event = {
9761
- type,
9762
- payload: structuredClone(args.payload),
9763
- timestamp: /* @__PURE__ */ new Date()
9764
- };
9765
- const queue = i.events.get(type) ?? [];
9766
- queue.push(event);
9767
- i.events.set(type, queue);
9768
- if (i.status === "waiting" && i.waiting?.type === type && !i.waiting.woken) {
9769
- i.waiting.woken = true;
9770
- ctx.hooks.enqueue({
9771
- id: `workflow:${binding}:${id}:event-${i.waiting.gen}`,
9772
- attempt: 1,
9773
- source: workflowSource,
9774
- data: {
9775
- binding,
9776
- id,
9777
- wake: i.waiting.gen
9778
- }
9779
- });
9780
- }
9781
- return null;
9782
- }, () => null),
9783
- delete: () => unsupported("delete()"),
9784
- subscribe: () => unsupported("subscribe()")
9785
- });
9786
- return {
9787
- async create(options = {}) {
9788
- const id = options.id ?? crypto.randomUUID();
9789
- const params = structuredClone(options.params === void 0 ? {} : options.params);
9790
- return ctx.hooks.effect({
9791
- invocation: ctx.currentInvocation(),
9792
- target,
9793
- op: "create",
9794
- args: {
9795
- id,
9796
- params: toJson(params)
9797
- },
9798
- allowed: writeFaults
9799
- }, async () => {
9800
- if (!validInstanceId(id)) throw new Error("Workflow instance has invalid id");
9801
- if (registry.instances.has(id)) throw new Error(`(instance.already_exists) Workflow instance with id "${id}" already exists`);
9802
- registry.instances.set(id, {
9803
- id,
9804
- params,
9805
- createdAt: Date.now(),
9806
- status: "queued",
9807
- events: /* @__PURE__ */ new Map(),
9808
- waiting: void 0,
9809
- waitGen: 0,
9810
- persisted: /* @__PURE__ */ new Map(),
9811
- attempts: /* @__PURE__ */ new Map(),
9812
- configs: /* @__PURE__ */ new Map(),
9813
- deadlines: /* @__PURE__ */ new Map()
9814
- });
9815
- ctx.hooks.enqueue({
9816
- id: `workflow:${binding}:${id}`,
9817
- attempt: 1,
9818
- source: workflowSource,
9819
- data: {
9820
- binding,
9821
- id
9822
- }
9823
- });
9824
- return handle(id);
9825
- }, () => ({ id }));
9826
- },
9827
- async get(id) {
9828
- return ctx.hooks.effect({
9829
- invocation: ctx.currentInvocation(),
9830
- target,
9831
- op: "get",
9832
- args: { id },
9833
- allowed: []
9834
- }, async () => {
9835
- if (!registry.instances.has(id)) throw new Error("instance.not_found");
9836
- return handle(id);
9837
- }, () => ({ id }));
9838
- },
9839
- createBatch: () => unsupported("createBatch()"),
9840
- deleteBatch: () => unsupported("deleteBatch()")
9841
- };
9842
- }
9843
- /** The binding's rule for an instance id (Miniflare): up to 100 of these characters. */
9844
- function validInstanceId(id) {
9845
- return typeof id === "string" && id.length <= 100 && /^[a-zA-Z0-9_][a-zA-Z0-9-_]*$/.test(id);
9846
- }
9847
- /** An event type as Workflows accept it (Events and parameters): up to 100 of these characters, else `workflow.invalid_event_type`. */
9848
- function validEventType(type) {
9849
- if (typeof type === "string" && type.length <= 100 && /^[a-zA-Z0-9_][a-zA-Z0-9-_]*$/.test(type)) return type;
9850
- throw new Error(`(workflow.invalid_event_type) event type must be up to 100 letters, digits, - or _, got ${JSON.stringify(type)}`);
9851
- }
9852
- /** Thrown through `run()` to suspend an instance waiting for an event; never meant to be caught. */
9853
- var Suspension = class {
9854
- gen;
9855
- constructor(gen) {
9856
- this.gen = gen;
9857
- }
9858
- };
9859
- /**
9860
- * Whether a run event wakes the instance: not a wake at all, the restart of a
9861
- * run a wake began (its first delivery resumed the instance), or the wake of
9862
- * the wait still pending.
9863
- */
9864
- function wakes(instance, event) {
9865
- const wake = event.data.wake;
9866
- if (wake === void 0 || event.attempt > 1) return true;
9867
- return instance.status === "waiting" && instance.waiting?.gen === wake;
9868
- }
9869
- /** Construct a `WorkflowEntrypoint` subclass outside the runtime, for the one `new` per instance run. */
9870
- function constructWorkflow(cls, ctx, env) {
9871
- return constructEntrypoint(cls, "WorkflowEntrypoint", ctx, env);
9872
- }
9873
- /** The engine's conversion (itty-time): a year is 365.25 days, a month 30; an unknown unit counts 1. */
9874
- const units = {
9875
- year: 315576e5,
9876
- month: 2592e6,
9877
- week: 6048e5,
9878
- day: 864e5,
9879
- hour: 36e5,
9880
- minute: 6e4,
9881
- second: 1e3,
9882
- m: 1
9883
- };
9884
- /** The engine's reading of a duration, NaN where it reads none. */
9885
- function engineDuration(d) {
9886
- if (!Number.isNaN(Number(d)) && typeof d !== "object") return Number(d);
9887
- if (typeof d !== "string") return NaN;
9888
- const m = /^([^ ]+) +(\w\w*?)s?$/.exec(d);
9889
- if (!m) return NaN;
9890
- return Number(m[1]) * (units[m[2]] ?? 1);
9891
- }
9892
- /** A Workflows duration in milliseconds, read as the engine reads it. */
9893
- function durationMs(d) {
9894
- const ms = engineDuration(d);
9895
- if (Number.isNaN(ms) || ms < 0) throw new TypeError(`not a Workflows duration: ${String(d)}`);
9896
- return ms;
9897
- }
9898
- /** Miniflare's `isValidStepConfig`, exactly: its schema is strict, and a timeout `== 0` is refused. */
9899
- function validStepConfig(config) {
9900
- const only = (o, keys) => Object.keys(o).every((k) => keys.includes(k));
9901
- const durationOk = (v) => !Number.isNaN(engineDuration(v));
9902
- if (typeof config !== "object" || config === null || !only(config, [
9903
- "retries",
9904
- "timeout",
9905
- "sensitive"
9906
- ])) return false;
9907
- const c = config;
9908
- const r = c["retries"];
9909
- if (r !== void 0) {
9910
- if (typeof r !== "object" || r === null || !only(r, [
9911
- "delay",
9912
- "limit",
9913
- "backoff"
9914
- ])) return false;
9915
- const delay = r["delay"];
9916
- if (!(typeof delay === "function" || typeof delay === "string" || typeof delay === "number" && delay >= 0)) return false;
9917
- if (typeof r["limit"] !== "number" || r["limit"] < 0) return false;
9918
- if (r["backoff"] !== void 0 && ![
9919
- "constant",
9920
- "linear",
9921
- "exponential"
9922
- ].includes(r["backoff"])) return false;
9923
- if (typeof delay !== "function" && !durationOk(delay)) return false;
9924
- }
9925
- const t = c["timeout"];
9926
- if (t !== void 0) {
9927
- if (!(typeof t === "string" || typeof t === "number" && t >= 0)) return false;
9928
- if (t == 0 || !durationOk(t)) return false;
9929
- }
9930
- if (c["sensitive"] !== void 0 && c["sensitive"] !== "output") return false;
9931
- return true;
9932
- }
9933
- const utf8 = new TextEncoder();
9934
- /** About how many bytes a value takes stored, walking it as structured cloning does. */
9935
- function approximateBytes(value, seen = /* @__PURE__ */ new Set()) {
9936
- if (value === null || value === void 0) return 1;
9937
- switch (typeof value) {
9938
- case "string": return utf8.encode(value).length;
9939
- case "number":
9940
- case "bigint": return 8;
9941
- case "boolean": return 1;
9942
- case "object": break;
9943
- default: return 0;
9944
- }
9945
- const o = value;
9946
- if (seen.has(o)) return 0;
9947
- seen.add(o);
9948
- if (o instanceof ArrayBuffer || ArrayBuffer.isView(o)) return o.byteLength;
9949
- if (o instanceof Date) return 8;
9950
- let total = 0;
9951
- if (o instanceof Map) for (const [k, v] of o) total += approximateBytes(k, seen) + approximateBytes(v, seen);
9952
- else if (o instanceof Set) for (const v of o) total += approximateBytes(v, seen);
9953
- else for (const [k, v] of Object.entries(o)) total += utf8.encode(k).length + approximateBytes(v, seen);
9954
- return total;
9955
- }
9956
- function sleep(ms) {
9957
- return new Promise((resolve) => setTimeout(resolve, ms));
9958
- }
9959
- /**
9960
- * One engine attempt of an instance: construct its class and call `run`.
9961
- * Steps whose results were persisted return them without running; a crash
9962
- * restarts the instance (a new attempt, from the start of `run`).
9963
- */
9964
- async function deliverWorkflow(event, hooks, d) {
9965
- const invocation = invocationOf(event);
9966
- const inv = hooks.startInvocation(invocation);
9967
- const target = `Workflow:${d.binding}`;
9968
- const instance = d.instance;
9969
- if (!wakes(instance, event)) return {
9970
- status: "completed",
9971
- followUps: []
9972
- };
9973
- instance.status = "running";
9974
- instance.waiting = void 0;
9975
- const background = [];
9976
- const counts = /* @__PURE__ */ new Map();
9977
- const key = (kind, name) => {
9978
- const count = (counts.get(`${kind}:${name}`) ?? 0) + 1;
9979
- counts.set(`${kind}:${name}`, count);
9980
- return `${kind}:${name}#${count}`;
9981
- };
9982
- const replay = (o) => {
9983
- if (o.ok) return structuredClone(o.value);
9984
- const error = structuredClone(o.error);
9985
- if (o.errorName !== void 0 && error instanceof Error) error.name = o.errorName;
9986
- throw error;
9987
- };
9988
- const step = {
9989
- do: async (name, a, b, c) => {
9990
- const [config, fn, options] = typeof a === "function" ? [
9991
- {},
9992
- a,
9993
- b
9994
- ] : [
9995
- a ?? {},
9996
- b,
9997
- c
9998
- ];
9999
- if (suspending !== void 0) continuedAfterSuspension("step.do");
10000
- if (options?.rollback !== void 0) {
10001
- hooks.unsupported(`Workflow ${d.binding}: rollback handlers are not modelled`);
10002
- throw new Error("eutaxy: rollback handlers are not modelled");
10003
- }
10004
- const fatal = (message) => {
10005
- hooks.unsupported(`Workflow ${d.binding}: ${message}`);
10006
- const err = new Error(message);
10007
- err.name = "WorkflowFatalError";
10008
- throw err;
10009
- };
10010
- if (name.length > 256 || [...name].some((c) => c.charCodeAt(0) < 32)) fatal(`Step name "${name}" exceeds max length (256 chars) or invalid characters found`);
10011
- if (!validStepConfig(config)) fatal(`Step config for "${name}" is in a invalid format. See https://developers.cloudflare.com/workflows/build/sleeping-and-retrying/`);
10012
- const k = key("do", name);
10013
- const count = counts.get(`do:${name}`);
10014
- const done = instance.persisted.get(k);
10015
- if (done) return replay(done);
10016
- const live = {
10017
- ...defaultRetries,
10018
- ...config.retries
10019
- };
10020
- const first = instance.configs.get(k);
10021
- if (!first) instance.configs.set(k, {
10022
- retries: live,
10023
- timeout: config.timeout ?? "10 minutes",
10024
- ...config.sensitive === void 0 ? {} : { sensitive: config.sensitive }
10025
- });
10026
- const sensitive = first ? first.sensitive : config.sensitive;
10027
- const stored = first?.retries;
10028
- const retries = stored && typeof stored.delay === "function" ? {
10029
- ...stored,
10030
- delay: typeof live.delay === "function" ? live.delay : defaultRetries.delay
10031
- } : stored ?? live;
10032
- const limit = Math.min(retries.limit, d.maxRedeliveries);
10033
- const { delay, ...shown } = retries;
10034
- const resolved = {
10035
- retries: typeof delay === "function" ? shown : retries,
10036
- timeout: first ? first.timeout : config.timeout ?? "10 minutes",
10037
- ...sensitive === void 0 ? {} : { sensitive }
10038
- };
10039
- for (let attempt = (instance.attempts.get(k) ?? 0) + 1;; attempt++) {
10040
- const due = instance.deadlines.get(`retry:${k}`);
10041
- if (due !== void 0) {
10042
- await sleep(Math.max(0, due - Date.now()));
10043
- instance.deadlines.delete(`retry:${k}`);
10044
- }
10045
- const stepContext = {
10046
- step: {
10047
- name,
10048
- count
10049
- },
10050
- attempt,
10051
- config: {
10052
- ...resolved,
10053
- retries: { ...resolved.retries }
10054
- }
10055
- };
10056
- const args = {
10057
- instance: instance.id,
10058
- step: name,
10059
- count,
10060
- attempt
10061
- };
10062
- await hooks.effect({
10063
- invocation,
10064
- target,
10065
- op: "step",
10066
- args,
10067
- allowed: STEP_START
10068
- }, async () => null, () => null);
10069
- instance.attempts.set(k, attempt);
10070
- let failed = false;
10071
- let thrown;
10072
- let value;
10073
- let returned;
10074
- try {
10075
- returned = { value: await fn(stepContext) };
10076
- } catch (err) {
10077
- if (err instanceof CrashSignal || inv.isCrashed()) throw err;
10078
- failed = true;
10079
- thrown = err;
10080
- try {
10081
- hooks.effectSync({
10082
- invocation,
10083
- target,
10084
- op: "step_result",
10085
- args,
10086
- allowed: []
10087
- }, () => {
10088
- throw err;
10089
- }, () => null);
10090
- } catch {}
10091
- }
10092
- if (returned !== void 0) {
10093
- const notModelled = (reason) => {
10094
- hooks.unsupported(`Workflow ${d.binding}: step "${name}" ${reason}`);
10095
- throw new Error(`eutaxy: step "${name}" ${reason}`);
10096
- };
10097
- try {
10098
- value = structuredClone(returned.value);
10099
- } catch {
10100
- notModelled("returned a value that is not structured-cloneable (a ReadableStream is not modelled)");
10101
- }
10102
- if (approximateBytes(value) > 1048576) notModelled("returned more than about 1 MiB, which the engine refuses (\"output is too large\"); Eutaxy cannot measure the stored size exactly");
10103
- }
10104
- if (!failed) try {
10105
- await hooks.effect({
10106
- invocation,
10107
- target,
10108
- op: "step_result",
10109
- args,
10110
- allowed: STEP_RESULT
10111
- }, async () => value, (v) => ({ output: sensitive === "output" ? "[REDACTED]" : toJson(v) }));
10112
- instance.persisted.set(k, {
10113
- ok: true,
10114
- value
10115
- });
10116
- return structuredClone(value);
10117
- } catch (err) {
10118
- if (err instanceof CrashSignal || !(err instanceof InjectedEffectError)) throw err;
10119
- thrown = Object.assign(/* @__PURE__ */ new Error(`Execution timed out after ${durationMs(resolved.timeout)}ms`), { name: "WorkflowTimeoutError" });
10120
- }
10121
- if (thrown instanceof Error && (thrown.name === "NonRetryableError" || thrown.message.startsWith("NonRetryableError"))) throw thrown;
10122
- if (attempt > limit) {
10123
- instance.persisted.set(k, failure(thrown));
10124
- throw thrown;
10125
- }
10126
- let wait;
10127
- try {
10128
- const delayContext = {
10129
- step: {
10130
- name,
10131
- count
10132
- },
10133
- attempt,
10134
- config: {
10135
- ...resolved,
10136
- retries: { ...resolved.retries }
10137
- }
10138
- };
10139
- wait = await retryDelayMs$1(retries, attempt, delayContext, thrown);
10140
- } catch (err) {
10141
- hooks.unsupported(`Workflow ${d.binding}: step "${name}"'s retry delay function threw (${String(err)})`);
10142
- throw err;
10143
- }
10144
- instance.deadlines.set(`retry:${k}`, Date.now() + wait);
10145
- await sleep(wait);
10146
- instance.deadlines.delete(`retry:${k}`);
10147
- }
10148
- },
10149
- sleep: async (name, duration) => {
10150
- const ms = durationMs(duration);
10151
- await sleepStep(key("sleep", `${name}\u0000${ms}`), name, ms);
10152
- },
10153
- sleepUntil: async (name, timestamp) => {
10154
- const at = timestamp instanceof Date ? timestamp.getTime() : Number(timestamp);
10155
- const k = key("sleepUntil", `${name}\u0000${at}`);
10156
- if (instance.persisted.has(k)) {
10157
- if (at < Date.now()) hooks.unsupported(`Workflow ${d.binding}: step.sleepUntil "${name}" replayed after its time, where Miniflare's engine throws`);
10158
- return;
10159
- }
10160
- if (at < Date.now() && !instance.deadlines.has(k)) throw new Error("You can't sleep until a time in the past, time-traveler");
10161
- await sleepStep(k, name, Math.max(0, at - Date.now()), at);
10162
- },
10163
- waitForEvent: async (name, options = {}) => {
10164
- if (suspending !== void 0) continuedAfterSuspension("step.waitForEvent");
10165
- const type = validEventType(options.type);
10166
- const timeoutMs = durationMs(options.timeout ?? "24 hours");
10167
- if (!(timeoutMs >= 1e3 && timeoutMs <= 31536e6)) {
10168
- hooks.unsupported(`Workflow ${d.binding}: waitForEvent "${name}" timeout must be between 1 second and 365 days`);
10169
- const err = /* @__PURE__ */ new Error(`Invalid timeout for waitForEvent "${name}"`);
10170
- err.name = "WorkflowFatalError";
10171
- throw err;
10172
- }
10173
- const k = key("waitForEvent", name);
10174
- const done = instance.persisted.get(k);
10175
- if (done) return replay(done);
10176
- const args = {
10177
- instance: instance.id,
10178
- step: name,
10179
- type
10180
- };
10181
- const existing = instance.deadlines.get(k);
10182
- const queue = instance.events.get(type) ?? [];
10183
- const inTime = queue.findIndex((e) => existing === void 0 || e.timestamp.getTime() < existing);
10184
- const received = inTime < 0 ? void 0 : queue.splice(inTime, 1)[0];
10185
- if (received) {
10186
- hooks.effectSync({
10187
- invocation,
10188
- target,
10189
- op: "event",
10190
- args: {
10191
- ...args,
10192
- timestamp: received.timestamp.getTime()
10193
- },
10194
- allowed: []
10195
- }, () => received, (e) => ({ payload: toJson(e.payload) }));
10196
- instance.persisted.set(k, {
10197
- ok: true,
10198
- value: received
10199
- });
10200
- return structuredClone(received);
10201
- }
10202
- if (existing !== void 0 && Date.now() >= existing) {
10203
- const error = Object.assign(/* @__PURE__ */ new Error(`Execution timed out after ${timeoutMs}ms`), { name: "WorkflowTimeoutError" });
10204
- hooks.effectSync({
10205
- invocation,
10206
- target,
10207
- op: "wait_timeout",
10208
- args,
10209
- allowed: []
10210
- }, () => null, () => null);
10211
- instance.persisted.set(k, failure(error));
10212
- throw error;
10213
- }
10214
- const deadline = existing ?? Date.now() + timeoutMs;
10215
- if (existing === void 0) {
10216
- instance.deadlines.set(k, deadline);
10217
- hooks.effectSync({
10218
- invocation,
10219
- target,
10220
- op: "wait",
10221
- args: {
10222
- ...args,
10223
- timeoutMs
10224
- },
10225
- allowed: []
10226
- }, () => null, () => null);
10227
- }
10228
- const gen = ++instance.waitGen;
10229
- instance.waiting = {
10230
- type,
10231
- gen,
10232
- woken: false
10233
- };
10234
- suspending = {
10235
- gen,
10236
- deadline
10237
- };
10238
- throw new Suspension(gen);
10239
- }
10240
- };
10241
- /** Set once a wait suspended this run: anything the code does after it caught the suspension is not modelled. */
10242
- let suspending;
10243
- const continuedAfterSuspension = (what) => {
10244
- const reason = `Workflow ${d.binding}: ${what} after step.waitForEvent suspended the instance; the code caught the suspension (catch only the wait's WorkflowTimeoutError)`;
10245
- hooks.unsupported(reason);
10246
- throw new Error(`eutaxy: ${reason}`);
10247
- };
10248
- async function sleepStep(k, name, ms, until) {
10249
- if (suspending !== void 0) continuedAfterSuspension("step.sleep");
10250
- if (instance.persisted.has(k)) return;
10251
- const pending = instance.deadlines.get(k);
10252
- if (pending !== void 0) {
10253
- await sleep(Math.max(0, pending - Date.now()));
10254
- instance.persisted.set(k, {
10255
- ok: true,
10256
- value: null
10257
- });
10258
- return;
10259
- }
10260
- instance.deadlines.set(k, Date.now() + ms);
10261
- hooks.effectSync({
10262
- invocation,
10263
- target,
10264
- op: "sleep",
10265
- args: {
10266
- instance: instance.id,
10267
- step: name,
10268
- ms,
10269
- ...until === void 0 ? {} : { until }
10270
- },
10271
- allowed: []
10272
- }, () => null, () => null);
10273
- await sleep(ms);
10274
- instance.persisted.set(k, {
10275
- ok: true,
10276
- value: null
10277
- });
10278
- }
10279
- const ran = await runInvocation(hooks, inv, () => {
10280
- const flow = constructWorkflow(d.cls, executionContext(background), d.env);
10281
- const workflowEvent = {
10282
- payload: structuredClone(instance.params),
10283
- timestamp: new Date(instance.createdAt),
10284
- instanceId: instance.id
10285
- };
10286
- if (d.name !== void 0) workflowEvent["workflowName"] = d.name;
10287
- else Object.defineProperty(workflowEvent, "workflowName", {
10288
- enumerable: true,
10289
- get: () => {
10290
- hooks.unsupported(`Workflow ${d.binding}: event.workflowName needs the Workflow's name, workflow(binding, className, { name })`);
10291
- }
10292
- });
10293
- return flow.run(workflowEvent, step);
10294
- });
10295
- const serialised = (value) => {
10296
- try {
10297
- return {
10298
- status: "completed",
10299
- value: structuredClone(value)
10300
- };
10301
- } catch {
10302
- hooks.unsupported(`Workflow ${d.binding}: run() returned a value that is not structured-cloneable`);
10303
- return {
10304
- status: "errored",
10305
- error: /* @__PURE__ */ new Error("run() returned a value that is not structured-cloneable")
10306
- };
10307
- }
10308
- };
10309
- let result = ran.status === "completed" ? serialised(ran.value) : ran;
10310
- if (suspending !== void 0) {
10311
- if (!(ran.status === "errored" && ran.error instanceof Suspension) && ran.status !== "crashed") hooks.unsupported(`Workflow ${d.binding}: run() ${ran.status === "completed" ? "returned" : "threw"} after step.waitForEvent suspended the instance; the code caught the suspension (catch only the wait's WorkflowTimeoutError)`);
10312
- if (ran.status !== "crashed") result = {
10313
- status: "completed",
10314
- value: void 0
10315
- };
10316
- }
10317
- let status = result.status;
10318
- if (suspending !== void 0 && result.status === "completed") {
10319
- instance.status = "waiting";
10320
- const suspended = suspending;
10321
- if (await drainBackground(hooks, inv, invocation, target, background)) status = "crashed";
10322
- if (status === "crashed") {
10323
- instance.status = "running";
10324
- instance.waiting = void 0;
10325
- }
10326
- const followUps = status === "crashed" ? instance.status === "running" && event.attempt <= d.maxFaultsPerRun ? [{
10327
- ...event,
10328
- attempt: event.attempt + 1
10329
- }] : [] : [{
10330
- id: `workflow:${d.binding}:${instance.id}:timeout-${suspended.gen}`,
10331
- attempt: 1,
10332
- source: workflowSource,
10333
- data: {
10334
- binding: d.binding,
10335
- id: instance.id,
10336
- wake: suspended.gen
10337
- },
10338
- at: suspended.deadline
10339
- }];
10340
- return {
10341
- status,
10342
- followUps
10343
- };
10344
- }
10345
- if (result.status === "completed") {
10346
- instance.status = "complete";
10347
- instance.output = result.value;
10348
- hooks.effectSync({
10349
- invocation,
10350
- target,
10351
- op: "complete",
10352
- args: {
10353
- instance: instance.id,
10354
- output: toJson(instance.output)
10355
- },
10356
- allowed: []
10357
- }, () => null, () => null);
10358
- } else if (result.status === "errored") {
10359
- instance.status = "errored";
10360
- const e = result.error;
10361
- instance.error = e instanceof Error ? {
10362
- name: e.name,
10363
- message: e.message
10364
- } : {
10365
- name: "Error",
10366
- message: String(e)
10367
- };
10368
- hooks.effectSync({
10369
- invocation,
10370
- target,
10371
- op: "errored",
10372
- args: {
10373
- instance: instance.id,
10374
- error: `${instance.error.name}: ${instance.error.message}`
10375
- },
10376
- allowed: []
10377
- }, () => null, () => null);
10378
- }
10379
- if (await drainBackground(hooks, inv, invocation, target, background)) status = "crashed";
10380
- const followUps = status === "crashed" && instance.status === "running" && event.attempt <= d.maxFaultsPerRun ? [{
10381
- ...event,
10382
- attempt: event.attempt + 1
10383
- }] : [];
10384
- return {
10385
- status,
10386
- followUps
10387
- };
10388
- }
10389
- /** The delay before the next attempt (Workflows, Sleeping and retrying; a delay function is called). */
10390
- async function retryDelayMs$1(retries, attempt, ctx, error) {
10391
- const base = durationMs(typeof retries.delay === "function" ? await retries.delay({
10392
- ctx,
10393
- error
10394
- }) : retries.delay);
10395
- switch (retries.backoff) {
10396
- case "linear": return base * attempt;
10397
- case "exponential": return base * 2 ** (attempt - 1);
10398
- default: return base;
10399
- }
10400
- }
10401
- // packages/cloudflare/src/bindings.ts
10402
- /** A D1 database: Miniflare's SQLite, reset to the scenario's schema and read back whole. */
10403
- function d1Binding(schemas) {
10404
- const proxies = /* @__PURE__ */ new Map();
10405
- return {
10406
- kind: "d1",
10407
- target: "D1",
10408
- is: isD1,
10409
- proxy(name, real, ctx) {
10410
- let p = proxies.get(name);
10411
- if (!p) {
10412
- p = proxyD1(real, name, ctx);
10413
- proxies.set(name, p);
10414
- }
10415
- return p;
10416
- },
10417
- clear() {},
10418
- async reset(step, real) {
10419
- const schema = schemas[step.binding];
10420
- if (schema === void 0) throw new Error(`no schema provided for D1 binding ${step.binding}`);
10421
- if (!isD1(real)) throw new Error(`env.${step.binding} is not a D1 binding`);
10422
- await resetD1(real, schema);
10423
- },
10424
- async snapshot(_step, real) {
10425
- return isD1(real) ? snapshotD1(real) : null;
10426
- }
10427
- };
10428
- }
10429
- /** An R2 bucket: Miniflare's real one, emptied and seeded before each run. */
10430
- function r2Binding() {
10431
- /** The buckets the current scenario sets up. */
10432
- let setUp = /* @__PURE__ */ new Set();
10433
- const proxies = /* @__PURE__ */ new Map();
10434
- /** One book for every bucket: the stand-ins count up across them. */
10435
- const versions = new VersionBook();
10436
- return {
10437
- kind: "r2",
10438
- target: "R2",
10439
- is: isR2,
10440
- proxy(name, real, ctx) {
10441
- if (!setUp.has(name)) ctx.hooks.unsupported(`R2 binding ${name} needs an r2Bucket() setup step, which empties it before each run`);
10442
- let p = proxies.get(name);
10443
- if (!p) {
10444
- p = proxyR2(real, name, ctx, versions);
10445
- proxies.set(name, p);
10446
- }
10447
- return p;
10448
- },
10449
- clear() {
10450
- setUp = /* @__PURE__ */ new Set();
10451
- versions.clear();
10452
- },
10453
- async reset(step, real) {
10454
- if (!isR2(real)) throw new Error(`env.${step.binding} is not an R2 bucket`);
10455
- setUp.add(step.binding);
10456
- await resetR2(real, step.objects);
10457
- },
10458
- async snapshot(_step, real) {
10459
- return isR2(real) ? { objects: await snapshotR2(real) } : null;
10460
- }
10461
- };
10462
- }
10463
- /**
10464
- * A Durable Object namespace: the real objects workerd runs, cleared, seeded
10465
- * and evicted before each run, their storage snapshotted after it, and their
10466
- * alarms taken over and fired as events of the run.
10467
- */
10468
- function durableObjectBinding(deps) {
10469
- const { ctx, helpers } = deps;
10470
- const proxies = /* @__PURE__ */ new Map();
10471
- /** The bindings the current scenario's setup resets before each run. */
10472
- let setUp = /* @__PURE__ */ new Set();
10473
- /** Per binding, alarm firings allowed per object in the current run. */
10474
- let alarmLimits = /* @__PURE__ */ new Map();
10475
- /** Per binding, what the current run knows about its objects. */
10476
- const states = /* @__PURE__ */ new Map();
10477
- const stateFor = (binding) => {
10478
- let state = states.get(binding);
10479
- if (!state) {
10480
- state = new BindingState();
10481
- states.set(binding, state);
10482
- }
10483
- return state;
10484
- };
10485
- const namespace = (name, real = deps.real(name)) => {
10486
- if (!isDurableObjectNamespace(real)) throw new Error(`env.${name} is not a Durable Object namespace`);
10487
- return real;
10488
- };
10489
- const required = () => {
10490
- if (!helpers) throw new Error("Durable Object setup needs the Cloudflare test helpers: createCloudflarePlatform({ ..., durableObjects: await import(\"cloudflare:test\") })");
10491
- return helpers;
10492
- };
10493
- return {
10494
- kind: "durable_object",
10495
- target: "DO",
10496
- is: isDurableObjectNamespace,
10497
- proxy(name, real, ctx) {
10498
- let p = proxies.get(name);
10499
- if (!p) {
10500
- p = proxyNamespace(real, name, ctx, stateFor(name), helpers, () => setUp.has(name));
10501
- proxies.set(name, p);
10502
- }
10503
- return p;
10504
- },
10505
- clear() {
10506
- setUp = /* @__PURE__ */ new Set();
10507
- alarmLimits = /* @__PURE__ */ new Map();
10508
- for (const state of states.values()) state.clear();
10509
- },
10510
- async reset(step, real) {
10511
- setUp.add(step.binding);
10512
- alarmLimits.set(step.binding, step.alarmsPerObject ?? 3);
10513
- await resetNamespace(namespace(step.binding, real), required(), stateFor(step.binding).names, step.objects);
10514
- },
10515
- async snapshot(step, real, unsupported) {
10516
- const binding = step.binding;
10517
- return snapshotNamespace(namespace(binding, real), required(), stateFor(binding).names, stateFor(binding).touched, step.objects, (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);
10518
- },
10519
- source: alarmSource,
10520
- async deliver(event, hooks, spec) {
10521
- const binding = String(event.data.binding ?? "");
10522
- return deliverAlarm(event, hooks, spec.bounds.maxRedeliveries, {
10523
- binding,
10524
- book: stateFor(binding).alarms,
10525
- limit: alarmLimits.get(binding) ?? 3,
10526
- runAlarm: alarmRunner(namespace(binding), binding, ctx, helpers, stateFor(binding)),
10527
- abort: (id) => stateFor(binding).abort(id),
10528
- mayPark: (id) => stateFor(binding).mayPark(id),
10529
- evict: (id) => evictObject(namespace(binding), helpers, id),
10530
- bookkeep: (op, args) => hooks.effectSync({
10531
- invocation: hooks.bookkeeping(),
10532
- target: `DO:${binding}`,
10533
- op,
10534
- args,
10535
- allowed: []
10536
- }, () => null, () => null)
10537
- });
10538
- }
10539
- };
10540
- }
10541
- /**
10542
- * A Workflow binding: a model of the engine running the scenario's own
10543
- * class, never the real binding; instances live in a registry and run as
10544
- * events of the run.
10545
- */
10546
- function workflowBinding(deps) {
10547
- /** The bindings the current scenario sets up, with the class each runs. */
10548
- let classes = /* @__PURE__ */ new Map();
10549
- const registries = /* @__PURE__ */ new Map();
10550
- const registryFor = (binding) => {
10551
- let r = registries.get(binding);
10552
- if (!r) {
10553
- r = new WorkflowRegistry();
10554
- registries.set(binding, r);
10555
- }
10556
- return r;
10557
- };
10558
- const proxies = /* @__PURE__ */ new Map();
10559
- return {
10560
- kind: "workflow",
10561
- target: "Workflow",
10562
- is: isWorkflowBinding,
10563
- proxy(name, _real, ctx) {
10564
- if (!classes.has(name)) {
10565
- ctx.hooks.unsupported(`Workflow binding ${name} needs a workflow() setup step naming its class`);
10566
- return proxyWorkflow(name, ctx, new WorkflowRegistry());
10567
- }
10568
- let p = proxies.get(name);
10569
- if (!p) {
10570
- p = proxyWorkflow(name, ctx, registryFor(name));
10571
- proxies.set(name, p);
10572
- }
10573
- return p;
10574
- },
10575
- clear() {
10576
- classes = /* @__PURE__ */ new Map();
10577
- for (const registry of registries.values()) registry.clear();
10578
- },
10579
- async reset(step) {
10580
- classes.set(step.binding, step);
10581
- },
10582
- async snapshot(step) {
10583
- return { instances: registryFor(step.binding).rows() };
10584
- },
10585
- source: workflowSource,
10586
- async deliver(event, hooks, spec) {
10587
- const { binding, id } = event.data;
10588
- const setup = classes.get(binding);
10589
- if (!setup) return {
10590
- status: "errored",
10591
- followUps: []
10592
- };
10593
- const className = setup.className;
10594
- const cls = deps.exports?.[className];
10595
- const instance = registryFor(binding).instances.get(id);
10596
- if (typeof cls !== "function" || !instance) {
10597
- hooks.unsupported(`Workflow ${binding}: class ${className} is not among the Worker module's exports; pass them as createCloudflarePlatform({ ..., exports })`);
10598
- return {
10599
- status: "errored",
10600
- followUps: []
10601
- };
10602
- }
10603
- return deliverWorkflow(event, hooks, {
10604
- binding,
10605
- ...setup.name === void 0 ? {} : { name: setup.name },
10606
- instance,
10607
- cls,
10608
- env: deps.env(),
10609
- maxFaultsPerRun: spec.bounds.maxFaultsPerRun,
10610
- maxRedeliveries: spec.bounds.maxRedeliveries
10611
- });
10612
- }
10613
- };
10614
- }
10615
- /**
10616
- * A service binding: never the real binding, a stub answering from the
10617
- * scenario's `service` setup; each call one effect. Nothing to reset or
10618
- * snapshot, the callee is scripted.
10619
- */
10620
- function serviceBinding() {
10621
- /** The bindings the current scenario scripts. */
10622
- let scripts = /* @__PURE__ */ new Map();
10623
- /** Per binding, the stub for the current run's script. */
10624
- const proxies = /* @__PURE__ */ new Map();
10625
- return {
10626
- kind: "service",
10627
- target: "Service",
10628
- is: isServiceBinding,
10629
- proxy(name, _real, ctx) {
10630
- const script = scripts.get(name);
10631
- if (!script) {
10632
- ctx.hooks.unsupported(`service binding ${name} needs a service() setup step scripting the Worker it reaches`);
10633
- return proxyService(name, ctx, {
10634
- kind: "service",
10635
- binding: name,
10636
- methods: {}
10637
- });
10638
- }
10639
- let p = proxies.get(name);
10640
- if (!p) {
10641
- p = proxyService(name, ctx, script);
10642
- proxies.set(name, p);
10643
- }
10644
- return p;
10645
- },
10646
- clear() {
10647
- scripts = /* @__PURE__ */ new Map();
10648
- proxies.clear();
10649
- },
10650
- async reset(step) {
10651
- scripts.set(step.binding, step);
10652
- },
10653
- async snapshot() {
10654
- return null;
10655
- }
10656
- };
10657
- }
10658
- /**
10659
- * The setup steps these records own, each with its record, in setup order:
10660
- * what the platform resets and snapshots, and the differential runner
10661
- * compares. A step no record owns is left to the scenario's validation.
10662
- */
10663
- function ownedSetups(setup, bindings) {
10664
- const out = [];
10665
- for (const step of setup) {
10666
- const binding = bindings.find((b) => b.kind === step.kind);
10667
- if (binding) out.push([binding, step]);
10668
- }
10669
- return out;
10670
- }
10671
- // packages/cloudflare/src/caller.ts
10672
- /**
10673
- * The caller of an inbound request or RPC call. Cloudflare retries neither,
10674
- * so resends follow the policy the drive declares for the caller: how many
10675
- * times it resends, the virtual delay before each resend, and how long it
10676
- * waits for an answer. The decision is the caller's and is made once per
10677
- * attempt: at the response point, or at its deadline if the handler has
10678
- * not answered by then.
10679
- */
10680
- /** The response point: a crash before it is a response the caller never saw. */
10681
- const RESPOND = ["crash_before"];
10682
- /**
10683
- * With a caller deadline the answer can also arrive too late: `ambiguous`
10684
- * here means it was sent, the caller counted it as failed, and the handler
10685
- * carried on.
10686
- */
10687
- const RESPOND_WITH_DEADLINE = ["crash_before", "ambiguous"];
10688
- /** The virtual delay before resend number `resend` (1 for the first), per the policy. */
10689
- function retryDelayMs(policy, resend) {
10690
- const delays = policy.delaysMs ?? [];
10691
- return delays[Math.min(resend, delays.length) - 1] ?? 0;
10692
- }
10693
- /**
10694
- * Start waiting for the attempt's answer. With a deadline, a virtual timer
10695
- * makes the caller give up at it whatever the handler is doing, so a resend
10696
- * can start while the first attempt still runs. `gaveUp` is what the
10697
- * `gave_up` effect records when the retries are spent.
10698
- */
10699
- function startCaller(event, hooks, spec, policy, target, gaveUp) {
10700
- const started = Date.now();
10701
- const deadline = policy.deadlineMs;
10702
- const lateAt = deadline === void 0 ? void 0 : started + deadline;
10703
- /** The caller decides once: it accepts the answer, or gives up at `at` and resends or stops. */
10704
- let decided = false;
10705
- const giveUp = (at) => {
10706
- if (decided) return;
10707
- decided = true;
10708
- const next = redelivery(event, policy.retries, spec.bounds);
10709
- if (next) {
10710
- const resendAt = Math.max(at + retryDelayMs(policy, event.attempt), Date.now());
10711
- hooks.enqueue({
10712
- ...next,
10713
- ...resendAt > Date.now() ? { at: resendAt } : {}
10714
- });
10715
- } else hooks.effectSync({
10716
- invocation: hooks.bookkeeping(),
10717
- target,
10718
- op: "gave_up",
10719
- args: gaveUp,
10720
- allowed: []
10721
- }, () => null, () => null);
10722
- };
10723
- const deadlineTimer = lateAt === void 0 ? void 0 : setTimeout(() => giveUp(lateAt), deadline);
10724
- return {
10725
- responseFaults: deadline === void 0 ? RESPOND : RESPOND_WITH_DEADLINE,
10726
- isLate: () => lateAt !== void 0 && Date.now() > lateAt,
10727
- settle(accepted, late) {
10728
- if (deadlineTimer !== void 0) clearTimeout(deadlineTimer);
10729
- if (accepted) decided = true;
10730
- else giveUp(late && lateAt !== void 0 ? lateAt : Date.now());
10731
- }
10732
- };
10733
- }
10734
- // packages/cloudflare/src/http.ts
10735
- /** The URL inbound requests are addressed to; handlers read only the path. */
10736
- const requestOrigin = "https://worker.test";
10737
- /** Build the `Request` a drive entry describes. */
10738
- function requestFor(r) {
10739
- const headers = new Headers(r.headers);
10740
- let body = null;
10741
- if (r.body !== void 0) {
10742
- if (typeof r.body === "string") body = r.body;
10743
- else {
10744
- body = JSON.stringify(r.body);
10745
- if (!headers.has("content-type")) headers.set("content-type", "application/json");
10746
- }
10747
- }
10748
- return new Request(`${requestOrigin}${r.path}`, {
10749
- method: r.method,
10750
- headers,
10751
- body
10752
- });
10753
- }
10754
- /** A compact record of a response for the effect log: status, ok, and a bounded body. */
10755
- async function summarizeResponse(response) {
10756
- const text = await response.clone().text();
10757
- let body = text.length > 1e3 ? `${text.slice(0, 1e3)}…` : text;
10758
- if (text && (response.headers.get("content-type") ?? "").includes("json")) try {
10759
- body = JSON.parse(text);
10760
- } catch {}
10761
- return {
10762
- status: response.status,
10763
- ok: response.ok,
10764
- body
10765
- };
10766
- }
10767
- /** One attempt of an inbound request, under the caller's retry policy and deadline. */
10768
- async function deliverRequest(event, hooks, spec, drive, invocation, worker) {
10769
- const req = event.data;
10770
- const target = `Http:${req.path}`;
10771
- const inv = hooks.startInvocation(invocation);
10772
- const background = [];
10773
- const handler = worker.handler.fetch;
10774
- if (!handler) throw new Error("the Worker has no fetch() handler");
10775
- const args = {
10776
- requestId: event.id,
10777
- method: req.method,
10778
- path: req.path
10779
- };
10780
- const caller = startCaller(event, hooks, spec, drive, target, {
10781
- requestId: event.id,
10782
- attempts: event.attempt
10783
- });
10784
- const handled = await runInvocation(hooks, inv, () => handler.call(worker.handler, requestFor(req), worker.env, executionContext(background)));
10785
- const response = handled.status === "completed" ? handled.value : void 0;
10786
- let status = handled.status;
10787
- let summary = null;
10788
- let read = "errored";
10789
- if (status === "completed" && response) {
10790
- const body = await runInvocation(hooks, inv, () => summarizeResponse(response));
10791
- read = body.status === "completed" ? body.value : body.status;
10792
- if (read === "crashed" || read === "errored") status = read;
10793
- }
10794
- let late = caller.isLate();
10795
- const allowed = caller.responseFaults;
10796
- if (status === "completed" && typeof read === "object") {
10797
- const s = read;
10798
- try {
10799
- hooks.effectSync({
10800
- invocation,
10801
- target,
10802
- op: "response",
10803
- args,
10804
- allowed
10805
- }, () => s, (v) => v);
10806
- summary = s;
10807
- } catch (err) {
10808
- if (err instanceof CrashSignal) status = "crashed";
10809
- else if (err instanceof InjectedEffectError) {
10810
- summary = s;
10811
- late = true;
10812
- } else throw err;
10813
- }
10814
- } else if (status === "errored") {
10815
- const s = {
10816
- status: 500,
10817
- ok: false,
10818
- body: ""
10819
- };
10820
- hooks.effectSync({
10821
- invocation,
10822
- target,
10823
- op: "response",
10824
- args,
10825
- allowed: []
10826
- }, () => s, (v) => v);
10827
- summary = s;
10828
- }
10829
- const accepted = summary !== null && !late && (drive.retryOn === "5xx" ? summary.status < 500 : summary.ok);
10830
- caller.settle(accepted, late);
10831
- if (await drainBackground(hooks, inv, invocation, target, background)) status = "crashed";
10832
- return {
10833
- status,
10834
- followUps: []
10835
- };
10836
- }
10837
- // packages/cloudflare/src/queues.ts
10838
- /** Queue delivery: one invocation per delivery of a message, redelivered until acked or dead-lettered. */
10839
- /** Deep-copy JSON data so a handler that mutates its message cannot leak into other runs. */
10840
- function cloneJson(value) {
10841
- return JSON.parse(JSON.stringify(value));
10842
- }
10843
- /** One delivery of a queue message, with Queues' at-least-once semantics. */
10844
- async function deliverMessage(event, hooks, spec, drive, invocation, worker, maxRetries) {
10845
- const queueTarget = `Queue:${drive.queue}`;
10846
- const inv = hooks.startInvocation(invocation);
10847
- /** Cloudflare honours the first ack or retry decision per message; later ones are ignored. */
10848
- const state = { decision: null };
10849
- const background = [];
10850
- /** Records the call; the result says whether it took effect (the first decision wins). */
10851
- const decide = (op, args) => {
10852
- hooks.effectSync({
10853
- invocation,
10854
- target: queueTarget,
10855
- op,
10856
- args,
10857
- allowed: decisionFaults
10858
- }, () => {
10859
- if (state.decision !== null) return false;
10860
- state.decision = op;
10861
- return true;
10862
- }, (effective) => ({ effective }));
10863
- };
10864
- const message = {
10865
- id: event.id,
10866
- timestamp: /* @__PURE__ */ new Date(),
10867
- body: cloneJson(event.data),
10868
- attempts: event.attempt,
10869
- ack: () => decide("ack", {
10870
- messageId: event.id,
10871
- implicit: false,
10872
- body: event.data
10873
- }),
10874
- retry: () => decide("retry", {
10875
- messageId: event.id,
10876
- body: event.data
10877
- })
10878
- };
10879
- const batch = {
10880
- queue: drive.queue,
10881
- messages: [message],
10882
- metadata: { metrics: {
10883
- backlogCount: 0,
10884
- backlogBytes: 0
10885
- } },
10886
- ackAll: () => message.ack(),
10887
- retryAll: () => message.retry()
10888
- };
10889
- const execution = executionContext(background);
10890
- const handler = worker.handler.queue;
10891
- if (!handler) throw new Error("the Worker has no queue() handler");
10892
- let status = (await runInvocation(hooks, inv, () => handler.call(worker.handler, batch, worker.env, execution))).status;
10893
- if (status === "completed" && state.decision === null) try {
10894
- decide("ack", {
10895
- messageId: event.id,
10896
- implicit: true,
10897
- body: event.data
10898
- });
10899
- } catch (err) {
10900
- if (err instanceof CrashSignal) status = "crashed";
10901
- else throw err;
10902
- }
10903
- if (await drainBackground(hooks, inv, invocation, queueTarget, background)) status = "crashed";
10904
- const followUps = [];
10905
- if (state.decision !== "ack") {
10906
- const next = redelivery(event, maxRetries, spec.bounds);
10907
- if (next) followUps.push(next);
10908
- else hooks.effectSync({
10909
- invocation: hooks.bookkeeping(),
10910
- target: queueTarget,
10911
- op: "dead_letter",
10912
- args: {
10913
- messageId: event.id,
10914
- attempts: event.attempt
10915
- },
10916
- allowed: []
10917
- }, () => null, () => null);
10918
- }
10919
- return {
10920
- status,
10921
- followUps
10922
- };
10923
- }
10924
- // packages/cloudflare/src/rpc.ts
10925
- /**
10926
- * Inbound RPC delivery: one invocation per attempt of a `WorkerEntrypoint`
10927
- * method call the drive's caller makes. The entrypoint is constructed anew
10928
- * for each call, as the runtime does (Cloudflare, Workers RPC: a new
10929
- * instance of the class for every call), and its return value or the error
10930
- * it threw is the response the caller sees.
10931
- */
10932
- /**
10933
- * An error as the caller sees it over RPC: a new error object with the
10934
- * name and message (Cloudflare, RPC error handling), nothing of its class.
10935
- */
10936
- function describeError(error) {
10937
- if (error instanceof Error) return `${error.name}: ${error.message}`;
10938
- return typeof error === "string" ? error : JSON.stringify(toJson(error));
10939
- }
10940
- /** One attempt of a call, under the caller's retry policy and deadline. */
10941
- async function deliverCall(event, hooks, spec, drive, invocation, cls, env) {
10942
- const call = event.data;
10943
- const target = rpcTarget(drive, call.method);
10944
- const inv = hooks.startInvocation(invocation);
10945
- const background = [];
10946
- const args = {
10947
- callId: event.id,
10948
- method: call.method,
10949
- args: call.args
10950
- };
10951
- const caller = startCaller(event, hooks, spec, drive, target, {
10952
- callId: event.id,
10953
- attempts: event.attempt
10954
- });
10955
- const ran = await runInvocation(hooks, inv, () => callMethod(cls, call, executionContext(background), env));
10956
- let status = ran.status;
10957
- let late = caller.isLate();
10958
- let answer = null;
10959
- if (ran.status === "completed") {
10960
- 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`);
10961
- const s = {
10962
- ok: true,
10963
- value: toJson(ran.value)
10964
- };
10965
- try {
10966
- hooks.effectSync({
10967
- invocation,
10968
- target,
10969
- op: "response",
10970
- args,
10971
- allowed: caller.responseFaults
10972
- }, () => s, (v) => v);
10973
- answer = s;
10974
- } catch (err) {
10975
- if (err instanceof CrashSignal) status = "crashed";
10976
- else if (err instanceof InjectedEffectError) {
10977
- answer = s;
10978
- late = true;
10979
- } else throw err;
10980
- }
10981
- } else if (ran.status === "errored") {
10982
- const s = {
10983
- ok: false,
10984
- error: describeError(ran.error)
10985
- };
10986
- hooks.effectSync({
10987
- invocation,
10988
- target,
10989
- op: "response",
10990
- args,
10991
- allowed: []
10992
- }, () => s, (v) => v);
10993
- answer = s;
10994
- }
10995
- caller.settle(answer !== null && !late && answer.ok, late);
10996
- if (await drainBackground(hooks, inv, invocation, target, background)) status = "crashed";
10997
- return {
10998
- status,
10999
- followUps: []
11000
- };
11001
- }
11002
- /**
11003
- * The class an RPC drive calls: the named export, or the Worker's default
11004
- * export (the class passed as the handler, or `exports.default`). Not
11005
- * necessarily a class: the platform reports what it found instead.
11006
- */
11007
- function entrypointClass(handler, exports, entrypoint) {
11008
- if (entrypoint !== void 0) return exports?.[entrypoint];
11009
- return typeof handler === "function" ? handler : exports?.["default"];
11010
- }
11011
- /**
11012
- * The method RPC exposes under a name: one the class or a superclass defines
11013
- * on its prototype. An instance property, even a function, and Object's own
11014
- * methods are not callable (workerd: "The RPC receiver does not implement the
11015
- * method").
11016
- */
11017
- function rpcMethod(instance, name) {
11018
- for (let proto = Object.getPrototypeOf(instance); proto !== null && proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) {
11019
- const own = Object.getOwnPropertyDescriptor(proto, name);
11020
- if (!own) continue;
11021
- return typeof own.value === "function" && name !== "constructor" ? own.value : void 0;
11022
- }
11023
- }
11024
- /**
11025
- * Construct the entrypoint for one call and invoke the method, as the
11026
- * runtime does per call. The arguments are copied, as RPC copies them: a
11027
- * method that mutates one changes neither the scenario nor a later attempt.
11028
- */
11029
- function callMethod(cls, call, ctx, env) {
11030
- const instance = constructEntrypoint(cls, "WorkerEntrypoint", ctx, env);
11031
- const method = rpcMethod(instance, call.method);
11032
- if (!method) throw new TypeError(`The RPC receiver does not implement the method "${call.method}".`);
11033
- return method.apply(instance, structuredClone(call.args));
11034
- }
11035
- // packages/cloudflare/src/scheduled.ts
11036
- /**
11037
- * Cron Trigger delivery: one invocation of the Worker's `scheduled()` handler
11038
- * per tick attempt, with `scheduledTime` the tick's virtual time and `cron`
11039
- * the expression (Workers, Scheduled handler). Cloudflare documents
11040
- * `noRetry()` but no retry count, so the drive declares how many times a
11041
- * tick whose handler failed is re-run; `noRetry()` stops them.
11042
- */
11043
- /** One attempt of a tick: the handler runs, and a failure is re-run as the drive declares unless it said noRetry(). */
11044
- async function deliverTick(event, hooks, spec, drive, invocation, worker) {
11045
- const tick = event.data;
11046
- const target = `Cron:${drive.cron}`;
11047
- const inv = hooks.startInvocation(invocation);
11048
- const background = [];
11049
- /** Rejections of waitUntil work: the first one is the invocation's status (Cloudflare, Scheduled handler). */
11050
- const failures = [];
11051
- const handler = worker.handler.scheduled;
11052
- if (!handler) throw new Error("the Worker has no scheduled() handler");
11053
- let noRetry = false;
11054
- const controller = {
11055
- scheduledTime: tick.scheduledTime,
11056
- cron: tick.cron,
11057
- noRetry: () => {
11058
- hooks.effectSync({
11059
- invocation,
11060
- target,
11061
- op: "no_retry",
11062
- args: { tick: event.id },
11063
- allowed: decisionFaults
11064
- }, () => {
11065
- noRetry = true;
11066
- return null;
11067
- }, () => null);
11068
- }
11069
- };
11070
- let status = (await runInvocation(hooks, inv, () => handler.call(worker.handler, controller, worker.env, executionContext(background, failures)))).status;
11071
- if (await drainBackground(hooks, inv, invocation, target, background)) status = "crashed";
11072
- if (status === "completed" && failures.length > 0) status = "errored";
11073
- const followUps = [];
11074
- if (status !== "completed" && !noRetry) {
11075
- const next = redelivery(event, drive.retries, spec.bounds);
11076
- if (next) followUps.push(next);
11077
- else hooks.effectSync({
11078
- invocation: hooks.bookkeeping(),
11079
- target,
11080
- op: "gave_up",
11081
- args: {
11082
- tick: event.id,
11083
- attempts: event.attempt
11084
- },
11085
- allowed: []
11086
- }, () => null, () => null);
11087
- }
11088
- return {
11089
- status,
11090
- followUps
11091
- };
11092
- }
11093
- // packages/cloudflare/src/platform.ts
11094
- /**
11095
- * The Cloudflare platform: delivers queue messages to the Worker's `queue()`
11096
- * handler and inbound requests to its `fetch()` handler, with proxied
11097
- * bindings, and applies Queues' at-least-once semantics (explicit and
11098
- * implicit ack, retry, redelivery up to max_retries, dead-lettering) as
11099
- * documented by Cloudflare, and for requests the caller's retry policy
11100
- * declared in the drive.
11101
- */
11102
- function isBindingLike(value) {
11103
- if (typeof value === "function") return true;
11104
- if (typeof value !== "object" || value === null) return false;
11105
- const proto = Object.getPrototypeOf(value);
11106
- return [...Object.getOwnPropertyNames(value), ...Object.getOwnPropertyNames(proto ?? {})].some((k) => k !== "constructor" && typeof value[k] === "function");
11107
- }
11108
- const assumptions = [
11109
- "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",
11110
- "D1 statements run against Miniflare's SQLite; each run/first/all/raw/batch/exec is one effect",
11111
- "message.timestamp is the virtual clock's time at delivery",
11112
- "only D1, Durable Object, R2, Workflow and scripted service bindings are proxied; touching any other binding makes the run UNSUPPORTED",
11113
- "service bindings are scripted callees: the Worker behind a binding is never called; each RPC method call or fetch() through it is one effect answered from the scenario's service() setup, where crash_before and error mean the call never reached the callee, ambiguous that it acted and the answer was lost, and crash_after that the caller died after it (developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/); Cloudflare does not retry such a call",
11114
- "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",
11115
- "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/)",
11116
- "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)",
11117
- "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/)",
11118
- "state invariants read a snapshot of every D1 binding named in setup, taken after the last event",
11119
- "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",
11120
- "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/)",
11121
- "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",
11122
- "cron triggers: each tick of the drive's expression is one invocation of scheduled(), with scheduledTime the tick's virtual time (UTC, the expression's matches from the virtual epoch on, in Cloudflare's dialect where weekdays run 1 = Sunday to 7 = Saturday; L, W and # are not modelled) and cron the expression (developers.cloudflare.com/workers/runtime-apis/handlers/scheduled/, /workers/configuration/cron-triggers/); Cloudflare documents noRetry() but no retry count, so the drive declares how many times a tick whose handler failed is re-run, and none after noRetry()",
11123
- "inbound RPC: one invocation per call attempt, the entrypoint constructed anew for each with a fresh ExecutionContext (developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/rpc/); the return value is the response effect, and an exception reaches the caller as a new error with its name and message (developers.cloudflare.com/workers/runtime-apis/rpc/error-handling/); Cloudflare does not retry a call, so the drive's caller resends a call that threw or got no answer as the http drive's caller does; a result that is not plain data (a stub, a function, a stream) makes the run UNSUPPORTED"
11124
- ];
11125
- function createCloudflarePlatform(options) {
11126
- const env = options.env;
11127
- const maxRetries = options.maxRetries ?? 3;
11128
- let hooksRef = null;
11129
- const ctx = {
11130
- get hooks() {
11131
- if (!hooksRef) throw new Error("no run in progress");
11132
- return hooksRef;
11133
- },
11134
- currentInvocation: () => ctx.hooks.running()
11135
- };
11136
- /**
11137
- * The kinds of binding modelled, in the order an env value is tried against
11138
- * them: a service binding first, since in workerd it answers every duck
11139
- * type (its property reads are RPC stubs).
11140
- */
11141
- const bindings = [
11142
- serviceBinding(),
11143
- d1Binding(options.schemas),
11144
- durableObjectBinding({
11145
- ctx,
11146
- helpers: options.durableObjects,
11147
- real: (name) => env[name]
11148
- }),
11149
- r2Binding(),
11150
- workflowBinding({
11151
- exports: options.exports,
11152
- env: () => proxiedEnv
11153
- })
11154
- ];
11155
- const proxiedEnv = new Proxy(env, { get(target, prop, receiver) {
11156
- const value = Reflect.get(target, prop, receiver);
11157
- if (typeof prop !== "string") return value;
11158
- for (const binding of bindings) if (binding.is(value)) return binding.proxy(prop, value, ctx);
11159
- if (isBindingLike(value)) ctx.hooks.unsupported(`binding ${prop} is not proxied`);
11160
- return value;
11161
- } });
11162
- const worker = {
11163
- handler: typeof options.handler === "function" ? {} : options.handler,
11164
- env: proxiedEnv
11165
- };
11166
- return {
11167
- name: "cloudflare",
11168
- assumptions,
11169
- concurrent: true,
11170
- async reset(spec) {
11171
- for (const binding of bindings) binding.clear();
11172
- for (const [binding, setup] of ownedSetups(spec.setup, bindings)) await binding.reset(setup, env[setup.binding]);
11173
- },
11174
- restrictEvents(spec, keepIds) {
11175
- return {
11176
- ...spec,
11177
- drive: restrictDrive(spec.drive, keepIds)
11178
- };
11179
- },
11180
- async finish(spec, hooks) {
11181
- for (const [binding, setup] of ownedSetups(spec.setup, bindings)) {
11182
- const tables = await binding.snapshot(setup, env[setup.binding], (reason) => hooks.unsupported(reason));
11183
- if (tables) hooks.snapshot(hooks.bookkeeping(), `${binding.target}:${setup.binding}`, { tables });
11184
- }
11185
- },
11186
- initialEvents(spec) {
11187
- return driveEvents(spec.drive);
11188
- },
11189
- async deliver(event, hooks, spec) {
11190
- const drive = spec.drive;
11191
- const invocation = invocationOf(event);
11192
- hooksRef = hooks;
11193
- const owner = event.source === void 0 ? void 0 : bindings.find((b) => b.source === event.source);
11194
- if (owner?.deliver) return owner.deliver(event, hooks, spec);
11195
- switch (drive.kind) {
11196
- case "http": return deliverRequest(event, hooks, spec, drive, invocation, worker);
11197
- case "cron": return deliverTick(event, hooks, spec, drive, invocation, worker);
11198
- case "rpc": {
11199
- const cls = entrypointClass(options.handler, options.exports, drive.entrypoint);
11200
- if (typeof cls !== "function") {
11201
- hooks.unsupported(`Rpc: ${drive.entrypoint === void 0 ? "the Worker's default export" : `export ${drive.entrypoint}`} is not a WorkerEntrypoint class; pass the Worker module's exports as createCloudflarePlatform({ ..., exports })`);
11202
- return {
11203
- status: "errored",
11204
- followUps: []
11205
- };
11206
- }
11207
- return deliverCall(event, hooks, spec, drive, invocation, cls, proxiedEnv);
11208
- }
11209
- default: return deliverMessage(event, hooks, spec, drive, invocation, worker, maxRetries);
11210
- }
11211
- }
11212
- };
11213
- }
11214
- // packages/cloudflare/src/differential.ts
11215
- /**
11216
- * Differential check: the same fault-free scenario run once through Eutaxy's
11217
- * proxies and once against the raw bindings, with the queue model (or the
11218
- * HTTP caller's retry policy) applied on the raw side itself. Any difference in the per-attempt decisions or in
11219
- * the final D1 and R2 state is a bug in the proxies or the platform model, not in
11220
- * the Worker. The raw side shares Eutaxy's *reading* of Cloudflare's queue
11221
- * semantics (core's redelivery rule among it); what it does not share is any proxy code.
11222
- */
11223
- /**
11224
- * The raw side's only wrapper: counts D1 calls in flight (so the settle loop
11225
- * knows real I/O is pending) and advances the clock as the proxies do. It
11226
- * records nothing and injects nothing.
11227
- */
11228
- function countingD1(real, io, clock) {
11229
- const realOf = /* @__PURE__ */ new WeakMap();
11230
- const track = async (p) => {
11231
- io.n++;
11232
- try {
11233
- return await p;
11234
- } finally {
11235
- io.n--;
11236
- clock.advance(1);
11237
- }
11238
- };
11239
- const wrapStatement = (s) => {
11240
- const proxy = new Proxy(s, { get(t, prop, r) {
11241
- const v = Reflect.get(t, prop, r);
11242
- if (prop === "bind") return (...a) => wrapStatement(t.bind(...a));
11243
- if (prop === "run" || prop === "all" || prop === "first" || prop === "raw") return (...a) => track(v.apply(t, a));
11244
- return typeof v === "function" ? v.bind(t) : v;
11245
- } });
11246
- realOf.set(proxy, s);
11247
- return proxy;
11248
- };
11249
- return new Proxy(real, { get(t, prop, r) {
11250
- const v = Reflect.get(t, prop, r);
11251
- if (prop === "prepare") return (sql) => wrapStatement(t.prepare(sql));
11252
- if (prop === "batch") return (stmts) => track(t.batch(stmts.map((s) => realOf.get(s) ?? s)));
11253
- if (prop === "exec") return (sql) => track(t.exec(sql));
11254
- return typeof v === "function" ? v.bind(t) : v;
11255
- } });
11256
- }
11257
- /**
11258
- * The same for an R2 bucket: each call advances the clock as its proxied
11259
- * effect does, and reading a body it gave counts as I/O in flight but does
11260
- * not advance the clock (the proxy reads it inside the get). Reads through
11261
- * the body's own stream are not counted: wrapping it would lose the known
11262
- * length a copy's put needs, and Miniflare answers them within the settle
11263
- * loop's real tick (checked with an 8 MB body).
11264
- */
11265
- function countingR2(real, io, clock) {
11266
- const track = async (p, advance) => {
11267
- io.n++;
11268
- try {
11269
- return await p;
11270
- } finally {
11271
- io.n--;
11272
- if (advance) clock.advance(1);
11273
- }
11274
- };
11275
- const reads = [
11276
- "arrayBuffer",
11277
- "bytes",
11278
- "text",
11279
- "json",
11280
- "blob"
11281
- ];
11282
- const counted = (o) => {
11283
- if (o === null || typeof o !== "object" || !("body" in o)) return o;
11284
- return new Proxy(o, { get(t, prop) {
11285
- const v = Reflect.get(t, prop);
11286
- if (typeof prop === "string" && reads.includes(prop) && typeof v === "function") return (...a) => track(v.apply(t, a), false);
11287
- return typeof v === "function" ? v.bind(t) : v;
11288
- } });
11289
- };
11290
- return new Proxy(real, { get(t, prop, r) {
11291
- const v = Reflect.get(t, prop, r);
11292
- if (prop === "put" || prop === "delete" || prop === "get" || prop === "head" || prop === "list") return async (...a) => counted(await track(v.apply(t, a), true));
11293
- return typeof v === "function" ? v.bind(t) : v;
11294
- } });
11295
- }
11296
- /**
11297
- * The bindings whose state the two sides compare: those a store holds and
11298
- * the real binding resets and reads back (D1, R2). Durable Objects and
11299
- * Workflows have no raw side.
11300
- */
11301
- function storedBindings(options) {
11302
- return [d1Binding(options.schemas), r2Binding()];
11303
- }
11304
- async function snapshotAll(spec, options) {
11305
- const env = options.env;
11306
- const out = {};
11307
- for (const [binding, setup] of ownedSetups(spec.setup, storedBindings(options))) {
11308
- const tables = await binding.snapshot(setup, env[setup.binding], (reason) => {
11309
- throw new Error(`snapshot of ${setup.binding}: ${reason}`);
11310
- });
11311
- if (tables) out[setup.binding] = tables;
11312
- }
11313
- return out;
11314
- }
11315
- /** The Eutaxy side, keeping each delivery's status and the decision it made. */
11316
- async function eutaxySide(spec, options) {
11317
- const { attempts, unsupported } = await proxiedSide(spec, createCloudflarePlatform(options), (event, result, entries) => {
11318
- const invocation = invocationOf(event);
11319
- const mine = entries.filter((e) => e.invocation === invocation);
11320
- const decision = mine.some((e) => e.kind === "result" && e.op === "no_retry") ? "no_retry" : mine.find((e) => e.kind === "result" && (e.op === "ack" || e.op === "retry") && getPath(e.payload, "result.effective") === true)?.op;
11321
- const response = mine.find((e) => e.kind === "result" && e.op === "response");
11322
- const answer = () => {
11323
- if (!response) return {};
11324
- if (spec.drive.kind === "rpc") return { result: getPath(response.payload, "result") ?? null };
11325
- return { response: getPath(response.payload, "result.status") };
11326
- };
11327
- return {
11328
- event: event.id,
11329
- attempt: event.attempt,
11330
- status: result.status === "completed" ? "completed" : "errored",
11331
- decision: decision ?? null,
11332
- ...answer()
11333
- };
11334
- });
11335
- return {
11336
- attempts,
11337
- state: await snapshotAll(spec, options),
11338
- unsupported
11339
- };
11340
- }
11341
- /** Each binding's tables under `<binding>.<table>`, as the comparison names them. */
11342
- function flatten(state) {
11343
- const out = {};
11344
- for (const [binding, tables] of Object.entries(state)) for (const [table, rows] of Object.entries(tables)) out[`${binding}.${table}`] = rows;
11345
- return out;
11346
- }
11347
- /** The next event as the engine picks it: the earliest due, the first inserted among equals. */
11348
- function takeEarliest(pending) {
11349
- let best = 0;
11350
- for (let i = 1; i < pending.length; i++) if ((pending[i]?.at ?? 0) < (pending[best]?.at ?? 0)) best = i;
11351
- return pending.splice(best, 1)[0];
11352
- }
11353
- /** The raw side: the handler called directly with the real bindings and plain message or Request objects. */
11354
- async function rawSide(spec, options) {
11355
- const env = options.env;
11356
- const drive = spec.drive;
11357
- const maxRetries = options.maxRetries ?? 3;
11358
- for (const [binding, setup] of ownedSetups(spec.setup, storedBindings(options))) await binding.reset(setup, env[setup.binding]);
11359
- const attempts = [];
11360
- const pending = [...driveEvents(drive)];
11361
- const patched = patchGlobals(0);
11362
- const unsupported = [];
11363
- const restoreFetch = installScriptedFetch(spec.externals, null, (r) => unsupported.push(r), () => patched.clock.advance(1));
11364
- const io = { n: 0 };
11365
- const counting = /* @__PURE__ */ new Map();
11366
- const countedEnv = new Proxy(env, { get(target, prop, receiver) {
11367
- const value = Reflect.get(target, prop, receiver);
11368
- if (typeof prop !== "string" || !(isD1(value) || isR2(value))) return value;
11369
- let c = counting.get(prop);
11370
- if (!c) {
11371
- c = isD1(value) ? countingD1(value, io, patched.clock) : countingR2(value, io, patched.clock);
11372
- counting.set(prop, c);
11373
- }
11374
- return c;
11375
- } });
11376
- const settle = (p) => settleOn(p, {
11377
- clock: patched.clock,
11378
- inFlight: () => io.n,
11379
- crashed: () => false,
11380
- stuck: () => {
11381
- throw new DifferentialStuck();
11382
- }
11383
- });
11384
- try {
11385
- const handlers = typeof options.handler === "function" ? {} : options.handler;
11386
- if (drive.kind === "rpc") {
11387
- const cls = entrypointClass(options.handler, options.exports, drive.entrypoint);
11388
- if (typeof cls !== "function") throw new Error("the Worker has no WorkerEntrypoint class");
11389
- while (pending.length > 0) {
11390
- const event = takeEarliest(pending);
11391
- const call = event.data;
11392
- const background = [];
11393
- let status;
11394
- let result;
11395
- try {
11396
- const value = await settle(Promise.resolve().then(() => callMethod(cls, call, executionContext(background), countedEnv)));
11397
- result = {
11398
- ok: true,
11399
- value: toJson(value)
11400
- };
11401
- status = "completed";
11402
- } catch (err) {
11403
- if (err instanceof CrashSignal || err instanceof DifferentialStuck) throw err;
11404
- result = {
11405
- ok: false,
11406
- error: describeError(err)
11407
- };
11408
- status = "errored";
11409
- }
11410
- await settle(Promise.all(background));
11411
- attempts.push({
11412
- event: event.id,
11413
- attempt: event.attempt,
11414
- status,
11415
- decision: null,
11416
- result
11417
- });
11418
- const next = status === "completed" ? null : redelivery(event, drive.retries, spec.bounds);
11419
- if (next) pending.push(next);
11420
- }
11421
- } else if (drive.kind === "cron") {
11422
- const handler = handlers.scheduled;
11423
- if (!handler) throw new Error("the Worker has no scheduled() handler");
11424
- while (pending.length > 0) {
11425
- const event = takeEarliest(pending);
11426
- const tick = event.data;
11427
- if (event.at !== void 0 && event.at > patched.clock.now()) patched.clock.advance(event.at - patched.clock.now());
11428
- const background = [];
11429
- const failures = [];
11430
- let noRetry = false;
11431
- const controller = {
11432
- scheduledTime: tick.scheduledTime,
11433
- cron: tick.cron,
11434
- noRetry: () => {
11435
- noRetry = true;
11436
- }
11437
- };
11438
- let status;
11439
- try {
11440
- await settle(Promise.resolve().then(() => handler.call(handlers, controller, countedEnv, executionContext(background, failures))));
11441
- status = "completed";
11442
- } catch (err) {
11443
- if (err instanceof CrashSignal || err instanceof DifferentialStuck) throw err;
11444
- status = "errored";
11445
- }
11446
- await settle(Promise.all(background));
11447
- if (status === "completed" && failures.length > 0) status = "errored";
11448
- attempts.push({
11449
- event: event.id,
11450
- attempt: event.attempt,
11451
- status,
11452
- decision: noRetry ? "no_retry" : null
11453
- });
11454
- const next = status === "completed" || noRetry ? null : redelivery(event, drive.retries, spec.bounds);
11455
- if (next) pending.push(next);
11456
- }
11457
- } else if (drive.kind === "http") {
11458
- const handler = handlers.fetch;
11459
- if (!handler) throw new Error("the Worker has no fetch() handler");
11460
- while (pending.length > 0) {
11461
- const event = takeEarliest(pending);
11462
- const req = event.data;
11463
- const background = [];
11464
- let status;
11465
- let response = 500;
11466
- try {
11467
- const r = await settle(Promise.resolve().then(() => handler.call(handlers, requestFor(req), countedEnv, executionContext(background))));
11468
- await settle(r.clone().text());
11469
- response = r.status;
11470
- status = "completed";
11471
- } catch (err) {
11472
- if (err instanceof CrashSignal || err instanceof DifferentialStuck) throw err;
11473
- status = "errored";
11474
- }
11475
- await settle(Promise.all(background));
11476
- attempts.push({
11477
- event: event.id,
11478
- attempt: event.attempt,
11479
- status,
11480
- decision: null,
11481
- response
11482
- });
11483
- const next = (drive.retryOn === "5xx" ? response < 500 : response >= 200 && response < 300) ? null : redelivery(event, drive.retries, spec.bounds);
11484
- if (next) pending.push(next);
11485
- }
11486
- } else {
11487
- const handler = handlers.queue;
11488
- if (!handler) throw new Error("the Worker has no queue() handler");
11489
- while (pending.length > 0) {
11490
- const event = takeEarliest(pending);
11491
- let decision = null;
11492
- const background = [];
11493
- const message = {
11494
- id: event.id,
11495
- timestamp: /* @__PURE__ */ new Date(),
11496
- body: JSON.parse(JSON.stringify(event.data)),
11497
- attempts: event.attempt,
11498
- ack: () => {
11499
- decision ??= "ack";
11500
- },
11501
- retry: () => {
11502
- decision ??= "retry";
11503
- }
11504
- };
11505
- const batch = {
11506
- queue: drive.queue,
11507
- messages: [message],
11508
- metadata: { metrics: {
11509
- backlogCount: 0,
11510
- backlogBytes: 0
11511
- } },
11512
- ackAll: () => message.ack(),
11513
- retryAll: () => message.retry()
11514
- };
11515
- const ctx = executionContext(background);
11516
- let status;
11517
- try {
11518
- await settle(Promise.resolve().then(() => handler.call(handlers, batch, countedEnv, ctx)));
11519
- status = "completed";
11520
- } catch (err) {
11521
- if (err instanceof CrashSignal || err instanceof DifferentialStuck) throw err;
11522
- status = "errored";
11523
- }
11524
- if (status === "completed") decision ??= "ack";
11525
- await settle(Promise.all(background));
11526
- attempts.push({
11527
- event: event.id,
11528
- attempt: event.attempt,
11529
- status,
11530
- decision
11531
- });
11532
- const next = decision === "ack" ? null : redelivery(event, maxRetries, spec.bounds);
11533
- if (next) pending.push(next);
11534
- }
11535
- }
11536
- } finally {
11537
- restoreFetch();
11538
- patched.restore();
11539
- }
11540
- if (unsupported.length > 0) throw new DifferentialStuck(`raw side: ${unsupported.join("; ")}`);
11541
- return {
11542
- attempts,
11543
- state: await snapshotAll(spec, options)
11544
- };
11545
- }
11546
- /** Run both sides and compare. The Eutaxy side runs first; both start from the schema. */
11547
- async function runDifferential(spec, options) {
11548
- 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");
11549
- const { unsupported, ...eutaxy } = await eutaxySide(spec, options);
11550
- const raw = await rawSide(spec, options);
11551
- const differences = compareSides({
11552
- attempts: eutaxy.attempts,
11553
- state: flatten(eutaxy.state)
11554
- }, {
11555
- attempts: raw.attempts,
11556
- state: flatten(raw.state)
11557
- }, unsupported);
11558
- return {
11559
- equal: differences.length === 0,
11560
- eutaxy,
11561
- raw,
11562
- differences,
11563
- unsupported
11564
- };
11565
- }
11566
- // packages/cli/src/workerd.ts
11567
- /**
11568
- * The half of `eutaxy check` that runs inside workerd: the generated test
11569
- * passes its module globs here and stores what this returns in its task
11570
- * meta, which the CLI reads back. It imports nothing that needs Node, so
11571
- * the Cloudflare Vitest plugin can load it.
11572
- */
11573
- /** Each D1 binding's schema, read from the `.sql` files next to the scenario. */
11574
- function schemasFor(scenario, sqlFiles) {
11575
- const schemas = {};
11576
- for (const step of scenario.setup) {
11577
- if (step.kind !== "d1") continue;
11578
- const file = String(step["schemaFile"]);
11579
- const sql = sqlFiles[globKey(file)];
11580
- if (sql === void 0) throw new Error(`schema file ${file} not found next to the scenario`);
11581
- schemas[String(step["binding"])] = sql;
11582
- }
11583
- return schemas;
11584
- }
11585
- /**
11586
- * The modules the scenario's `specs` name, loaded with their specs and
11587
- * their spec files, and every reason the check cannot go ahead: a module
11588
- * that is not there, a spec that does not read, a function name observed
11589
- * in two modules (decisions are logged by name, so it would be ambiguous).
11590
- * The spec files are loaded here, before anything is observed, so the
11591
- * functions their specs hold are the modules' own.
11592
- */
11593
- async function selectSpecModules(scenario, modules, specEntries) {
11594
- const decisions = scenario.invariants.flatMap((i) => i.kind === "refines" ? [i.decision] : []);
11595
- const specErrors = [];
11596
- const selected = [];
11597
- for (const path of scenario.specs ?? []) {
11598
- const load = modules[globKey(path)];
11599
- if (!load) {
11600
- specErrors.push({
11601
- module: path,
11602
- line: 0,
11603
- message: "no such module next to the scenario"
11604
- });
11605
- continue;
11606
- }
11607
- const namespace = await load();
11608
- const key = specKey(path);
11609
- const entry = Object.hasOwn(specEntries, key) ? specEntries[key] : void 0;
11610
- const specs = entry?.specs ?? {
11611
- functions: [],
11612
- errors: []
11613
- };
11614
- for (const e of specs.errors) specErrors.push({
11615
- module: e.inModule ? path : `${path.replace(/\.ts$/, "")}.props.ts`,
11616
- line: e.line,
11617
- message: e.message
11618
- });
11619
- const props = entry ? await entry.load() : {};
11620
- const exported = decisions.filter((d) => typeof namespace[d] === "function");
11621
- const names = [.../* @__PURE__ */ new Set([...specs.functions.map((f) => f.name), ...exported])];
11622
- selected.push({
11623
- path,
11624
- key,
11625
- namespace,
11626
- specs,
11627
- props,
11628
- names
11629
- });
11630
- }
11631
- const observedIn = /* @__PURE__ */ new Map();
11632
- for (const m of selected) for (const n of m.names) {
11633
- const other = observedIn.get(n);
11634
- if (other === void 0) observedIn.set(n, m.path);
11635
- else specErrors.push({
11636
- module: m.path,
11637
- line: 0,
11638
- message: `${n} is observed in both ${other} and ${m.path}; decisions of one name must come from one module`
11639
- });
11640
- }
11641
- return {
11642
- selected,
11643
- specErrors
11644
- };
11645
- }
11646
- /** Run the scenario's check, with its specs observed, and return what the CLI reads back. */
11647
- async function checkInWorkerd(input) {
11648
- const { scenario } = input;
11649
- const schemas = schemasFor(scenario, input.sqlFiles);
11650
- const load = input.modules[globKey(scenario.worker.entry)];
11651
- if (!load) throw new Error(`worker entry ${scenario.worker.entry} not found next to the scenario`);
11652
- const worker = await load();
11653
- const platform = createCloudflarePlatform({
11654
- env: input.env,
11655
- handler: worker.default,
11656
- schemas,
11657
- durableObjects: input.durableObjects,
11658
- exports: worker
11659
- });
11660
- const { selected, specErrors } = await selectSpecModules(scenario, input.modules, input.specEntries);
11661
- const transportBase = {
11662
- worker: scenario.worker,
11663
- setup: scenario.setup,
11664
- drive: scenario.drive
11665
- };
11666
- if (specErrors.length > 0) return {
11667
- report: null,
11668
- specErrors,
11669
- ...transportBase
11670
- };
11671
- const observers = selected.map((m) => observeCore(m.namespace, m.names));
11672
- let verdict;
11673
- try {
11674
- verdict = await check(scenario, platform, {
11675
- seed: input.seed,
11676
- ...input.maxRuns === void 0 ? {} : { maxRuns: input.maxRuns },
11677
- ...input.budgetMs === void 0 ? {} : { budgetMs: input.budgetMs },
11678
- ...input.exhaustive ? { exhaustive: true } : {}
11679
- });
11680
- } finally {
11681
- for (const o of observers) o.restore();
11682
- }
11683
- const specs = selected.flatMap((m, i) => checkSpecModule(m.key, m.specs, m.props, m.namespace, observers[i], { tested: { seed: input.seed } }));
11684
- return {
11685
- report: JSON.parse(renderJson(verdict, specs)),
11686
- ...transportBase,
11687
- observed: selected.map((m) => ({
11688
- module: m.path,
11689
- functions: m.names
11690
- }))
11691
- };
11692
- }
11693
- export { serviceCall as A, r2Op as C, rpc as D, refines as E, snapshotD1 as F, check as I, expectHolds as L, workflow as M, workflowRows as N, rpcResponse as O, workflowStep as P, main as R, r2Bucket as S, references as T, http as _, cron as a, queue as b, d1Rows as c, defineScenario as d, durableObject as f, fetchCall as g, external as h, atLeastOncePerMessage as i, unique as j, service as k, d1Schema as l, everyRow as m, runDifferential as n, d1Param as o, durableObjectRows as p, createCloudflarePlatform as r, d1Read as s, checkInWorkerd as t, d1Write as u, httpResponse as v, r2Rows as w, queueAck as x, implies as y, cloudflareRegressionTest as z };
7700
+ export { main as t };
11694
7701
 
11695
- //# sourceMappingURL=src-DIG0_CjU.mjs.map
7702
+ //# sourceMappingURL=cli-D3SPblWw.mjs.map