eutaxy 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +2 -2
  2. package/dist/aws.d.mts +7 -5
  3. package/dist/aws.d.mts.map +1 -1
  4. package/dist/aws.mjs +41 -135
  5. package/dist/aws.mjs.map +1 -1
  6. package/dist/bin.mjs +2 -2
  7. package/dist/checked-CGpA2-F0.d.mts +285 -0
  8. package/dist/checked-CGpA2-F0.d.mts.map +1 -0
  9. package/dist/cli-IJrKkeYS.mjs +2 -0
  10. package/dist/cli.d.mts.map +1 -1
  11. package/dist/cli.mjs +2 -2
  12. package/dist/cloudflare.d.mts +232 -51
  13. package/dist/cloudflare.d.mts.map +1 -1
  14. package/dist/cloudflare.mjs +3 -1083
  15. package/dist/delivery-invariants-BraYqcYN.d.mts +5 -0
  16. package/dist/delivery-invariants-BraYqcYN.d.mts.map +1 -0
  17. package/dist/delivery-invariants-Cuxdna28.mjs +39 -0
  18. package/dist/delivery-invariants-Cuxdna28.mjs.map +1 -0
  19. package/dist/index.d.mts +66 -5
  20. package/dist/index.d.mts.map +1 -1
  21. package/dist/index.mjs +81 -5
  22. package/dist/index.mjs.map +1 -0
  23. package/dist/{platform-TwATAkL3.d.mts → platform-DfMwknw1.d.mts} +179 -42
  24. package/dist/platform-DfMwknw1.d.mts.map +1 -0
  25. package/dist/src-Bqc9Eyb1.mjs +2655 -0
  26. package/dist/src-Bqc9Eyb1.mjs.map +1 -0
  27. package/dist/src-DKb-fkdb.mjs +3399 -0
  28. package/dist/src-DKb-fkdb.mjs.map +1 -0
  29. package/dist/src-Dxl9ZlKn.mjs +1752 -0
  30. package/dist/src-Dxl9ZlKn.mjs.map +1 -0
  31. package/package.json +1 -1
  32. package/dist/cli-Dr-Ziogu.mjs +0 -2
  33. package/dist/cloudflare.mjs.map +0 -1
  34. package/dist/explore-YVHTRjjS.d.mts +0 -63
  35. package/dist/explore-YVHTRjjS.d.mts.map +0 -1
  36. package/dist/platform-TwATAkL3.d.mts.map +0 -1
  37. package/dist/src-BBXd0WEp.mjs +0 -117
  38. package/dist/src-BBXd0WEp.mjs.map +0 -1
  39. package/dist/src-BGdIBGkN.mjs +0 -311
  40. package/dist/src-BGdIBGkN.mjs.map +0 -1
  41. package/dist/src-Brt0dfNL.mjs +0 -1286
  42. package/dist/src-Brt0dfNL.mjs.map +0 -1
  43. package/dist/src-s6uYyC0B.mjs +0 -89
  44. package/dist/src-s6uYyC0B.mjs.map +0 -1
  45. package/dist/verdict-evEM5Gxx.mjs +0 -12
  46. package/dist/verdict-evEM5Gxx.mjs.map +0 -1
@@ -1,1083 +1,3 @@
1
- import { i as canonicalJson } from "./src-s6uYyC0B.mjs";
2
- import { a as Run, d as validateScenario, i as CrashSignal, l as settleOn, m as getPath, o as installScriptedFetch, s as patchGlobals, t as explore, u as defaultBounds } from "./src-Brt0dfNL.mjs";
3
- import { t as describeVerdict } from "./verdict-evEM5Gxx.mjs";
4
- import { n as cloudflareRegressionTest } from "./src-BGdIBGkN.mjs";
5
- // packages/cloudflare/src/check.ts
6
- /** Explore a scenario on a platform and return its verdict. */
7
- function check(spec, platform, options = { seed: spec.name }) {
8
- return explore(spec, platform, options);
9
- }
10
- /** For use from a test: passes only when the scenario is BOUNDED. */
11
- async function expectHolds(spec, platform, options) {
12
- const verdict = await check(spec, platform, options);
13
- if (verdict.kind !== "BOUNDED") throw new Error(describeVerdict(verdict));
14
- }
15
- // packages/cloudflare/src/json.ts
16
- /** Reduce any runtime value to JSON data for the effect log; never throws. */
17
- function toJson(value, depth = 0) {
18
- if (value === null || value === void 0) return null;
19
- switch (typeof value) {
20
- case "boolean":
21
- case "string": return value;
22
- case "number": return Number.isFinite(value) ? value : String(value);
23
- case "bigint": return value.toString();
24
- case "object": {
25
- if (depth > 8) return "<nested>";
26
- if (Array.isArray(value)) return value.map((v) => toJson(v, depth + 1));
27
- if (value instanceof ArrayBuffer) return `<bytes ${value.byteLength}>`;
28
- if (ArrayBuffer.isView(value)) return `<bytes ${value.byteLength}>`;
29
- if (value instanceof Date) return value.toISOString();
30
- const out = {};
31
- for (const k of Object.keys(value).sort()) out[k] = toJson(value[k], depth + 1);
32
- return out;
33
- }
34
- default: return `<${typeof value}>`;
35
- }
36
- }
37
- // packages/cloudflare/src/d1.ts
38
- /**
39
- * The D1 binding proxy. Every statement execution is an effect point: the
40
- * engine decides the fault, the real Miniflare-backed D1 performs the query,
41
- * and the log records call, result and fault in the documented shape.
42
- */
43
- const WRITE = [
44
- "crash_before",
45
- "crash_after",
46
- "ambiguous",
47
- "error"
48
- ];
49
- const READ = [
50
- "crash_before",
51
- "crash_after",
52
- "error"
53
- ];
54
- function point(ctx, target, op, args, allowed) {
55
- return {
56
- invocation: ctx.currentInvocation(),
57
- target,
58
- op,
59
- args,
60
- allowed
61
- };
62
- }
63
- function metaOf(result) {
64
- return {
65
- changes: result.meta.changes ?? 0,
66
- lastRowId: result.meta.last_row_id ?? null
67
- };
68
- }
69
- var StatementProxy = class StatementProxy {
70
- real;
71
- target;
72
- ctx;
73
- sql;
74
- params;
75
- constructor(real, target, ctx, sql, params) {
76
- this.real = real;
77
- this.target = target;
78
- this.ctx = ctx;
79
- this.sql = sql;
80
- this.params = params;
81
- }
82
- /** The real statement, for `batch()`. */
83
- get statement() {
84
- return this.real;
85
- }
86
- args() {
87
- return {
88
- sql: this.sql,
89
- params: toJson(this.params)
90
- };
91
- }
92
- bind(...values) {
93
- return new StatementProxy(this.real.bind(...values), this.target, this.ctx, this.sql, values);
94
- }
95
- run() {
96
- return this.ctx.hooks.effect(point(this.ctx, this.target, "run", this.args(), WRITE), () => this.real.run(), (r) => metaOf(r));
97
- }
98
- all() {
99
- return this.ctx.hooks.effect(point(this.ctx, this.target, "all", this.args(), READ), () => this.real.all(), (r) => ({
100
- rows: r.results.length,
101
- changes: r.meta.changes ?? 0
102
- }));
103
- }
104
- first(colName) {
105
- return this.ctx.hooks.effect(point(this.ctx, this.target, "first", {
106
- ...this.args(),
107
- column: colName ?? null
108
- }, READ), () => colName === void 0 ? this.real.first() : this.real.first(colName), (r) => ({ row: toJson(r) }));
109
- }
110
- raw(options) {
111
- return this.ctx.hooks.effect(point(this.ctx, this.target, "raw", this.args(), READ), () => options ? this.real.raw(options) : this.real.raw(), (r) => ({ rows: r.length }));
112
- }
113
- };
114
- /** Wrap a D1 binding. Methods not modelled fall through to the real binding and mark the run unsupported. */
115
- function proxyD1(real, binding, ctx) {
116
- const target = `D1:${binding}`;
117
- const modelled = {
118
- prepare(sql) {
119
- return new StatementProxy(real.prepare(sql), target, ctx, sql, []);
120
- },
121
- batch(statements) {
122
- const unwrapped = statements.map((s) => s instanceof StatementProxy ? s.statement : s);
123
- const args = { statements: statements.map((s) => s instanceof StatementProxy ? {
124
- sql: s.sql,
125
- params: toJson(s.params)
126
- } : "<unproxied statement>") };
127
- return ctx.hooks.effect(point(ctx, target, "batch", args, WRITE), () => real.batch(unwrapped), (rs) => ({
128
- changes: rs.reduce((n, r) => n + (r.meta.changes ?? 0), 0),
129
- statements: rs.length
130
- }));
131
- },
132
- exec(sql) {
133
- return ctx.hooks.effect(point(ctx, target, "exec", { sql }, WRITE), () => real.exec(sql), (r) => ({
134
- count: r.count,
135
- duration: 0
136
- }));
137
- }
138
- };
139
- return new Proxy(real, { get(obj, prop, receiver) {
140
- if (prop in modelled) return modelled[prop];
141
- const value = Reflect.get(obj, prop, receiver);
142
- if (typeof value === "function") {
143
- ctx.hooks.unsupported(`D1 ${binding}.${String(prop)} is not modelled`);
144
- return value.bind(obj);
145
- }
146
- return value;
147
- } });
148
- }
149
- /**
150
- * Statements in a schema file. Splits on semicolons outside string literals,
151
- * quoted identifiers and comments, and keeps CREATE TRIGGER bodies (and CASE
152
- * expressions) whole by tracking BEGIN/CASE ... END nesting.
153
- */
154
- function splitSql(sql) {
155
- const out = [];
156
- let cur = "";
157
- let depth = 0;
158
- let i = 0;
159
- const isWordChar = (c) => c !== void 0 && /[A-Za-z0-9_]/.test(c);
160
- while (i < sql.length) {
161
- const c = sql[i];
162
- const next = sql[i + 1];
163
- if (c === "-" && next === "-") {
164
- while (i < sql.length && sql[i] !== "\n") i++;
165
- continue;
166
- }
167
- if (c === "/" && next === "*") {
168
- const end = sql.indexOf("*/", i + 2);
169
- i = end === -1 ? sql.length : end + 2;
170
- continue;
171
- }
172
- if (c === "'" || c === "\"" || c === "`" || c === "[") {
173
- const close = c === "[" ? "]" : c;
174
- let j = i + 1;
175
- for (;;) {
176
- const k = sql.indexOf(close, j);
177
- if (k === -1) {
178
- j = sql.length;
179
- break;
180
- }
181
- if (close !== "]" && sql[k + 1] === close) {
182
- j = k + 2;
183
- continue;
184
- }
185
- j = k + 1;
186
- break;
187
- }
188
- cur += sql.slice(i, j);
189
- i = j;
190
- continue;
191
- }
192
- if (isWordChar(c) && !isWordChar(sql[i - 1])) {
193
- let j = i;
194
- while (isWordChar(sql[j])) j++;
195
- const word = sql.slice(i, j);
196
- const upper = word.toUpperCase();
197
- if (upper === "BEGIN" || upper === "CASE") depth++;
198
- else if (upper === "END" && depth > 0) depth--;
199
- cur += word;
200
- i = j;
201
- continue;
202
- }
203
- if (c === ";" && depth === 0) {
204
- const statement = cur.trim();
205
- if (statement.length > 0) out.push(statement);
206
- cur = "";
207
- i++;
208
- continue;
209
- }
210
- cur += c;
211
- i++;
212
- }
213
- const last = cur.trim();
214
- if (last.length > 0) out.push(last);
215
- return out;
216
- }
217
- /** Drop every user table and re-apply the schema, using the real binding (not an effect). */
218
- async function resetD1(real, schema) {
219
- 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();
220
- for (const { name } of tables.results) await real.prepare(`DROP TABLE IF EXISTS "${name.replace(/"/g, "\"\"")}"`).run();
221
- for (const statement of splitSql(schema)) await real.prepare(statement).run();
222
- }
223
- /** Every user table's rows, sorted canonically, read through the real binding (not an effect). */
224
- async function snapshotD1(real) {
225
- 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();
226
- const out = {};
227
- for (const { name } of tables.results) out[name] = (await real.prepare(`SELECT * FROM "${name.replace(/"/g, "\"\"")}"`).all()).results.map((r) => toJson(r)).map((j) => [canonicalJson(j), j]).sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0).map(([, j]) => j);
228
- return out;
229
- }
230
- // packages/cloudflare/src/platform.ts
231
- const ACK = ["crash_before", "crash_after"];
232
- const CUT_OFF = ["cut_off"];
233
- /** The response point: a crash before it is a response the caller never saw. */
234
- const RESPOND = ["crash_before"];
235
- /** The URL inbound requests are addressed to; handlers read only the path. */
236
- const requestOrigin = "https://worker.test";
237
- /** Build the `Request` a drive entry describes. */
238
- function requestFor(r) {
239
- const headers = new Headers(r.headers);
240
- let body = null;
241
- if (r.body !== void 0) {
242
- if (typeof r.body === "string") body = r.body;
243
- else {
244
- body = JSON.stringify(r.body);
245
- if (!headers.has("content-type")) headers.set("content-type", "application/json");
246
- }
247
- }
248
- return new Request(`${requestOrigin}${r.path}`, {
249
- method: r.method,
250
- headers,
251
- body
252
- });
253
- }
254
- /** A compact record of a response for the effect log: status, ok, and a bounded body. */
255
- async function summarizeResponse(response) {
256
- const text = await response.clone().text();
257
- let body = text.length > 1e3 ? `${text.slice(0, 1e3)}…` : text;
258
- if (text && (response.headers.get("content-type") ?? "").includes("json")) try {
259
- body = JSON.parse(text);
260
- } catch {}
261
- return {
262
- status: response.status,
263
- ok: response.ok,
264
- body
265
- };
266
- }
267
- function isD1$1(value) {
268
- return typeof value === "object" && value !== null && typeof value.prepare === "function" && typeof value.batch === "function";
269
- }
270
- function isBindingLike(value) {
271
- if (typeof value === "function") return true;
272
- if (typeof value !== "object" || value === null) return false;
273
- const proto = Object.getPrototypeOf(value);
274
- return [...Object.getOwnPropertyNames(value), ...Object.getOwnPropertyNames(proto ?? {})].some((k) => k !== "constructor" && typeof value[k] === "function");
275
- }
276
- /** Deep-copy JSON data so a handler that mutates its message cannot leak into other runs. */
277
- function cloneJson(value) {
278
- return JSON.parse(JSON.stringify(value));
279
- }
280
- const assumptions = [
281
- "platform model: Cloudflare Queues at-least-once delivery; the first ack or retry decision per message wins; unacked messages are redelivered up to max_retries then dead-lettered",
282
- "D1 statements run against Miniflare's SQLite; each run/first/all/raw/batch/exec is one effect",
283
- "message.timestamp is the virtual clock's time at delivery",
284
- "only D1 bindings are proxied; touching any other binding makes the run UNSUPPORTED",
285
- "state invariants read a snapshot of every D1 binding named in setup, taken after the last event",
286
- "work passed to ctx.waitUntil runs after the handler returns and never affects acknowledgement or the response; a cut_off fault at that point loses work not yet started, and an effect in flight commits without its continuation",
287
- "inbound requests: one invocation per attempt; an uncaught exception is a 500 response; the drive's caller resends a request it got no acceptable response for (crash before the response, or a status its retryOn policy rejects) up to its retries"
288
- ];
289
- function createCloudflarePlatform(options) {
290
- const env = options.env;
291
- const maxRetries = options.maxRetries ?? 3;
292
- let currentInvocation = "";
293
- let hooksRef = null;
294
- const ctx = {
295
- get hooks() {
296
- if (!hooksRef) throw new Error("no run in progress");
297
- return hooksRef;
298
- },
299
- currentInvocation: () => currentInvocation
300
- };
301
- const d1Proxies = /* @__PURE__ */ new Map();
302
- const proxiedEnv = new Proxy(env, { get(target, prop, receiver) {
303
- const value = Reflect.get(target, prop, receiver);
304
- if (typeof prop !== "string") return value;
305
- if (isD1$1(value)) {
306
- let p = d1Proxies.get(prop);
307
- if (!p) {
308
- p = proxyD1(value, prop, ctx);
309
- d1Proxies.set(prop, p);
310
- }
311
- return p;
312
- }
313
- if (isBindingLike(value)) ctx.hooks.unsupported(`binding ${prop} is not proxied`);
314
- return value;
315
- } });
316
- /** Platform-level actions (dead-lettering) are recorded under an invocation no fault can crash. */
317
- const platformInvocations = /* @__PURE__ */ new WeakMap();
318
- function platformInvocation(hooks) {
319
- let id = platformInvocations.get(hooks);
320
- if (id === void 0) {
321
- id = "platform";
322
- hooks.startInvocation(id);
323
- platformInvocations.set(hooks, id);
324
- }
325
- return id;
326
- }
327
- return {
328
- name: "cloudflare",
329
- assumptions,
330
- async reset(spec) {
331
- for (const step of spec.setup) {
332
- if (step.kind !== "d1") continue;
333
- const binding = String(step["binding"]);
334
- const schema = options.schemas[binding];
335
- if (schema === void 0) throw new Error(`no schema provided for D1 binding ${binding}`);
336
- const real = env[binding];
337
- if (!isD1$1(real)) throw new Error(`env.${binding} is not a D1 binding`);
338
- await resetD1(real, schema);
339
- }
340
- },
341
- restrictEvents(spec, keepIds) {
342
- const drive = spec.drive;
343
- if (drive.kind === "http") return {
344
- ...spec,
345
- drive: {
346
- ...drive,
347
- requests: drive.requests.filter((r) => keepIds.includes(r.id))
348
- }
349
- };
350
- return {
351
- ...spec,
352
- drive: {
353
- ...drive,
354
- messages: drive.messages.filter((m) => keepIds.includes(m.id))
355
- }
356
- };
357
- },
358
- async finish(spec, hooks) {
359
- for (const step of spec.setup) {
360
- if (step.kind !== "d1") continue;
361
- const binding = String(step["binding"]);
362
- const real = env[binding];
363
- if (!isD1$1(real)) continue;
364
- const tables = await snapshotD1(real);
365
- hooks.snapshot(platformInvocation(hooks), `D1:${binding}`, { tables });
366
- }
367
- },
368
- initialEvents(spec) {
369
- const drive = spec.drive;
370
- if (drive.kind === "http") return drive.requests.map((r) => ({
371
- id: r.id,
372
- attempt: 1,
373
- data: r
374
- }));
375
- return drive.messages.map((m) => ({
376
- id: m.id,
377
- attempt: 1,
378
- data: m.body
379
- }));
380
- },
381
- async deliver(event, hooks, spec) {
382
- const drive = spec.drive;
383
- const invocation = `${event.id}#${event.attempt}`;
384
- hooksRef = hooks;
385
- currentInvocation = invocation;
386
- try {
387
- return drive.kind === "http" ? await deliverRequest(event, hooks, spec, drive, invocation) : await deliverMessage(event, hooks, spec, drive, invocation);
388
- } finally {
389
- currentInvocation = "";
390
- }
391
- }
392
- };
393
- /** The `ExecutionContext` handed to a handler; `waitUntil` work is collected to run after it returns. */
394
- function executionContext(background) {
395
- return {
396
- waitUntil: (promise) => {
397
- background.push(promise.then(() => void 0, () => void 0));
398
- },
399
- passThroughOnException: () => {},
400
- props: {}
401
- };
402
- }
403
- /**
404
- * Background work extends the invocation but never changes the acknowledgement or the response.
405
- * A cut-off here is the isolate dying after them: work not yet started is lost.
406
- */
407
- async function drainBackground(hooks, inv, invocation, target, background) {
408
- if (background.length === 0 || inv.isCrashed()) return false;
409
- try {
410
- hooks.effectSync({
411
- invocation,
412
- target,
413
- op: "background",
414
- args: { pending: background.length },
415
- allowed: CUT_OFF
416
- }, () => null, () => null);
417
- await Promise.race([hooks.settle(Promise.all(background), invocation), inv.crashed]);
418
- return false;
419
- } catch (err) {
420
- if (!(err instanceof CrashSignal)) throw err;
421
- return true;
422
- }
423
- }
424
- async function deliverRequest(event, hooks, spec, drive, invocation) {
425
- const req = event.data;
426
- const target = `Http:${req.path}`;
427
- const inv = hooks.startInvocation(invocation);
428
- const background = [];
429
- const handler = options.handler.fetch;
430
- if (!handler) throw new Error("the Worker has no fetch() handler");
431
- const args = {
432
- requestId: event.id,
433
- method: req.method,
434
- path: req.path
435
- };
436
- let response;
437
- const outcome = Promise.resolve().then(() => handler.call(options.handler, requestFor(req), proxiedEnv, executionContext(background))).then((r) => {
438
- response = r;
439
- return "completed";
440
- }, (err) => err instanceof CrashSignal ? "crashed" : "errored");
441
- let status = await Promise.race([hooks.settle(outcome, invocation), inv.crashed.then(() => "crashed")]);
442
- let summary = null;
443
- let read = "errored";
444
- if (status === "completed" && response) {
445
- read = await Promise.race([hooks.settle(summarizeResponse(response), invocation).then((s) => s, (err) => err instanceof CrashSignal ? "crashed" : "errored"), inv.crashed.then(() => "crashed")]);
446
- if (read === "crashed" || read === "errored") status = read;
447
- }
448
- if (status === "completed" && typeof read === "object") {
449
- const s = read;
450
- try {
451
- hooks.effectSync({
452
- invocation,
453
- target,
454
- op: "response",
455
- args,
456
- allowed: RESPOND
457
- }, () => s, (v) => v);
458
- summary = s;
459
- } catch (err) {
460
- if (err instanceof CrashSignal) status = "crashed";
461
- else throw err;
462
- }
463
- } else if (status === "errored") {
464
- const s = {
465
- status: 500,
466
- ok: false,
467
- body: ""
468
- };
469
- hooks.effectSync({
470
- invocation,
471
- target,
472
- op: "response",
473
- args,
474
- allowed: []
475
- }, () => s, (v) => v);
476
- summary = s;
477
- }
478
- if (await drainBackground(hooks, inv, invocation, target, background)) status = "crashed";
479
- const accepted = summary !== null && (drive.retryOn === "5xx" ? summary.status < 500 : summary.ok);
480
- const followUps = [];
481
- if (!accepted) {
482
- const redeliveries = event.attempt - 1;
483
- if (redeliveries < drive.retries && redeliveries < spec.bounds.maxRedeliveries) followUps.push({
484
- ...event,
485
- attempt: event.attempt + 1
486
- });
487
- else hooks.effectSync({
488
- invocation: platformInvocation(hooks),
489
- target,
490
- op: "gave_up",
491
- args: {
492
- requestId: event.id,
493
- attempts: event.attempt
494
- },
495
- allowed: []
496
- }, () => null, () => null);
497
- }
498
- return {
499
- status,
500
- followUps
501
- };
502
- }
503
- async function deliverMessage(event, hooks, spec, drive, invocation) {
504
- {
505
- const queueTarget = `Queue:${drive.queue}`;
506
- const inv = hooks.startInvocation(invocation);
507
- /** Cloudflare honours the first ack or retry decision per message; later ones are ignored. */
508
- const state = { decision: null };
509
- const background = [];
510
- /** Records the call; the result says whether it took effect (the first decision wins). */
511
- const decide = (op, args) => {
512
- hooks.effectSync({
513
- invocation,
514
- target: queueTarget,
515
- op,
516
- args,
517
- allowed: ACK
518
- }, () => {
519
- if (state.decision !== null) return false;
520
- state.decision = op;
521
- return true;
522
- }, (effective) => ({ effective }));
523
- };
524
- const message = {
525
- id: event.id,
526
- timestamp: /* @__PURE__ */ new Date(),
527
- body: cloneJson(event.data),
528
- attempts: event.attempt,
529
- ack: () => decide("ack", {
530
- messageId: event.id,
531
- implicit: false,
532
- body: event.data
533
- }),
534
- retry: () => decide("retry", {
535
- messageId: event.id,
536
- body: event.data
537
- })
538
- };
539
- const batch = {
540
- queue: drive.queue,
541
- messages: [message],
542
- metadata: { metrics: {
543
- backlogCount: 0,
544
- backlogBytes: 0
545
- } },
546
- ackAll: () => message.ack(),
547
- retryAll: () => message.retry()
548
- };
549
- const execution = executionContext(background);
550
- const handler = options.handler.queue;
551
- if (!handler) throw new Error("the Worker has no queue() handler");
552
- const outcome = Promise.resolve().then(() => handler.call(options.handler, batch, proxiedEnv, execution)).then(() => "completed", (err) => err instanceof CrashSignal ? "crashed" : "errored");
553
- let status = await Promise.race([hooks.settle(outcome, invocation), inv.crashed.then(() => "crashed")]);
554
- if (status === "completed" && state.decision === null) try {
555
- decide("ack", {
556
- messageId: event.id,
557
- implicit: true,
558
- body: event.data
559
- });
560
- } catch (err) {
561
- if (err instanceof CrashSignal) status = "crashed";
562
- else throw err;
563
- }
564
- if (await drainBackground(hooks, inv, invocation, queueTarget, background)) status = "crashed";
565
- const followUps = [];
566
- if (state.decision !== "ack") {
567
- const redeliveries = event.attempt - 1;
568
- if (event.attempt <= maxRetries && redeliveries < spec.bounds.maxRedeliveries) followUps.push({
569
- ...event,
570
- attempt: event.attempt + 1
571
- });
572
- else hooks.effectSync({
573
- invocation: platformInvocation(hooks),
574
- target: queueTarget,
575
- op: "dead_letter",
576
- args: {
577
- messageId: event.id,
578
- attempts: event.attempt
579
- },
580
- allowed: []
581
- }, () => null, () => null);
582
- }
583
- return {
584
- status,
585
- followUps
586
- };
587
- }
588
- }
589
- }
590
- // packages/cloudflare/src/differential.ts
591
- /**
592
- * Differential check: the same fault-free scenario run once through Eutaxy's
593
- * proxies and once against the raw bindings, with the queue model (or the
594
- * HTTP caller's retry policy) applied by hand on the raw side. Any difference in the per-attempt decisions or in
595
- * the final D1 state is a bug in the proxies or the platform model, not in
596
- * the Worker. The raw side shares Eutaxy's *reading* of Cloudflare's queue
597
- * semantics; what it does not share is any proxy code.
598
- */
599
- /** The raw side cannot abandon an invocation the way the engine does; a stuck handler ends the comparison. */
600
- var StuckError = class extends Error {
601
- name = "StuckError";
602
- constructor(message = "the handler is waiting on something outside the run (no timer due, no effect in flight)") {
603
- super(message);
604
- }
605
- };
606
- /**
607
- * The raw side's only wrapper: counts D1 calls in flight (so the settle loop
608
- * knows real I/O is pending) and advances the clock as the proxies do. It
609
- * records nothing and injects nothing.
610
- */
611
- function countingD1(real, io, clock) {
612
- const realOf = /* @__PURE__ */ new WeakMap();
613
- const track = async (p) => {
614
- io.n++;
615
- try {
616
- return await p;
617
- } finally {
618
- io.n--;
619
- clock.advance(1);
620
- }
621
- };
622
- const wrapStatement = (s) => {
623
- const proxy = new Proxy(s, { get(t, prop, r) {
624
- const v = Reflect.get(t, prop, r);
625
- if (prop === "bind") return (...a) => wrapStatement(t.bind(...a));
626
- if (prop === "run" || prop === "all" || prop === "first" || prop === "raw") return (...a) => track(v.apply(t, a));
627
- return typeof v === "function" ? v.bind(t) : v;
628
- } });
629
- realOf.set(proxy, s);
630
- return proxy;
631
- };
632
- return new Proxy(real, { get(t, prop, r) {
633
- const v = Reflect.get(t, prop, r);
634
- if (prop === "prepare") return (sql) => wrapStatement(t.prepare(sql));
635
- if (prop === "batch") return (stmts) => track(t.batch(stmts.map((s) => realOf.get(s) ?? s)));
636
- if (prop === "exec") return (sql) => track(t.exec(sql));
637
- return typeof v === "function" ? v.bind(t) : v;
638
- } });
639
- }
640
- function isD1(value) {
641
- return typeof value === "object" && value !== null && typeof value.prepare === "function";
642
- }
643
- async function snapshotAll(spec, options) {
644
- const env = options.env;
645
- const out = {};
646
- for (const step of spec.setup) {
647
- if (step.kind !== "d1") continue;
648
- const binding = String(step["binding"]);
649
- const real = env[binding];
650
- if (isD1(real)) out[binding] = await snapshotD1(real);
651
- }
652
- return out;
653
- }
654
- /** The Eutaxy side: one run with no faults, driven like `runOnce` but keeping each delivery's status. */
655
- async function eutaxySide(spec, options) {
656
- const platform = createCloudflarePlatform(options);
657
- const run = new Run({
658
- mode: "replay",
659
- schedule: {
660
- seed: 0,
661
- faults: []
662
- },
663
- bounds: spec.bounds,
664
- faultProbability: 0
665
- });
666
- const attempts = [];
667
- await platform.reset(spec);
668
- run.install(spec.externals);
669
- try {
670
- const pending = [...platform.initialEvents(spec)];
671
- while (pending.length > 0) {
672
- const event = pending.shift();
673
- const invocation = `${event.id}#${event.attempt}`;
674
- const before = run.log.entries.length;
675
- const result = await platform.deliver(event, run, spec);
676
- const mine = run.log.entries.slice(before).filter((e) => e.invocation === invocation);
677
- const decision = mine.find((e) => e.kind === "result" && (e.op === "ack" || e.op === "retry") && getPath(e.payload, "result.effective") === true)?.op;
678
- const response = mine.find((e) => e.kind === "result" && e.op === "response");
679
- attempts.push({
680
- event: event.id,
681
- attempt: event.attempt,
682
- status: result.status === "completed" ? "completed" : "errored",
683
- decision: decision ?? null,
684
- ...response ? { response: getPath(response.payload, "result.status") } : {}
685
- });
686
- pending.push(...result.followUps);
687
- }
688
- } finally {
689
- run.uninstall();
690
- }
691
- await platform.finish?.(spec, run);
692
- return {
693
- attempts,
694
- state: await snapshotAll(spec, options),
695
- unsupported: run.unsupportedReasons
696
- };
697
- }
698
- /** The raw side: the handler called directly with the real bindings and plain message or Request objects. */
699
- async function rawSide(spec, options) {
700
- const env = options.env;
701
- const drive = spec.drive;
702
- const maxRetries = options.maxRetries ?? 3;
703
- for (const step of spec.setup) {
704
- if (step.kind !== "d1") continue;
705
- const binding = String(step["binding"]);
706
- const schema = options.schemas[binding];
707
- const real = env[binding];
708
- if (schema !== void 0 && isD1(real)) await resetD1(real, schema);
709
- }
710
- const attempts = [];
711
- const pending = drive.kind === "http" ? drive.requests.map((r) => ({
712
- id: r.id,
713
- attempt: 1,
714
- data: r
715
- })) : drive.messages.map((m) => ({
716
- id: m.id,
717
- attempt: 1,
718
- data: m.body
719
- }));
720
- const patched = patchGlobals(0);
721
- const unsupported = [];
722
- const restoreFetch = installScriptedFetch(spec.externals, null, (r) => unsupported.push(r), () => patched.clock.advance(1));
723
- const io = { n: 0 };
724
- const counting = /* @__PURE__ */ new Map();
725
- const countedEnv = new Proxy(env, { get(target, prop, receiver) {
726
- const value = Reflect.get(target, prop, receiver);
727
- if (typeof prop !== "string" || !isD1(value)) return value;
728
- let c = counting.get(prop);
729
- if (!c) {
730
- c = countingD1(value, io, patched.clock);
731
- counting.set(prop, c);
732
- }
733
- return c;
734
- } });
735
- const settle = (p) => settleOn(p, {
736
- clock: patched.clock,
737
- inFlight: () => io.n,
738
- crashed: () => false,
739
- stuck: () => {
740
- throw new StuckError();
741
- }
742
- });
743
- const ctxFor = (background) => ({
744
- waitUntil: (p) => {
745
- background.push(p.then(() => void 0, () => void 0));
746
- },
747
- passThroughOnException: () => {},
748
- props: {}
749
- });
750
- try {
751
- if (drive.kind === "http") {
752
- const handler = options.handler.fetch;
753
- if (!handler) throw new Error("the Worker has no fetch() handler");
754
- while (pending.length > 0) {
755
- const event = pending.shift();
756
- const req = event.data;
757
- const background = [];
758
- let status;
759
- let response = 500;
760
- try {
761
- const r = await settle(Promise.resolve().then(() => handler.call(options.handler, requestFor(req), countedEnv, ctxFor(background))));
762
- await settle(r.clone().text());
763
- response = r.status;
764
- status = "completed";
765
- } catch (err) {
766
- if (err instanceof CrashSignal || err instanceof StuckError) throw err;
767
- status = "errored";
768
- }
769
- await settle(Promise.all(background));
770
- attempts.push({
771
- event: event.id,
772
- attempt: event.attempt,
773
- status,
774
- decision: null,
775
- response
776
- });
777
- if (!(drive.retryOn === "5xx" ? response < 500 : response >= 200 && response < 300) && event.attempt - 1 < drive.retries && event.attempt - 1 < spec.bounds.maxRedeliveries) pending.push({
778
- ...event,
779
- attempt: event.attempt + 1
780
- });
781
- }
782
- } else {
783
- const handler = options.handler.queue;
784
- if (!handler) throw new Error("the Worker has no queue() handler");
785
- while (pending.length > 0) {
786
- const event = pending.shift();
787
- let decision = null;
788
- const background = [];
789
- const message = {
790
- id: event.id,
791
- timestamp: /* @__PURE__ */ new Date(),
792
- body: JSON.parse(JSON.stringify(event.data)),
793
- attempts: event.attempt,
794
- ack: () => {
795
- decision ??= "ack";
796
- },
797
- retry: () => {
798
- decision ??= "retry";
799
- }
800
- };
801
- const batch = {
802
- queue: drive.queue,
803
- messages: [message],
804
- metadata: { metrics: {
805
- backlogCount: 0,
806
- backlogBytes: 0
807
- } },
808
- ackAll: () => message.ack(),
809
- retryAll: () => message.retry()
810
- };
811
- const ctx = ctxFor(background);
812
- let status;
813
- try {
814
- await settle(Promise.resolve().then(() => handler.call(options.handler, batch, countedEnv, ctx)));
815
- status = "completed";
816
- } catch (err) {
817
- if (err instanceof CrashSignal || err instanceof StuckError) throw err;
818
- status = "errored";
819
- }
820
- if (status === "completed") decision ??= "ack";
821
- await settle(Promise.all(background));
822
- attempts.push({
823
- event: event.id,
824
- attempt: event.attempt,
825
- status,
826
- decision
827
- });
828
- if (decision !== "ack" && event.attempt <= maxRetries && event.attempt - 1 < spec.bounds.maxRedeliveries) pending.push({
829
- ...event,
830
- attempt: event.attempt + 1
831
- });
832
- }
833
- }
834
- } finally {
835
- restoreFetch();
836
- patched.restore();
837
- }
838
- if (unsupported.length > 0) throw new StuckError(`raw side: ${unsupported.join("; ")}`);
839
- return {
840
- attempts,
841
- state: await snapshotAll(spec, options)
842
- };
843
- }
844
- /** Run both sides and compare. The Eutaxy side runs first; both start from the schema. */
845
- async function runDifferential(spec, options) {
846
- const { unsupported, ...eutaxy } = await eutaxySide(spec, options);
847
- const raw = await rawSide(spec, options);
848
- const differences = [];
849
- if (unsupported.length > 0) differences.push(`the proxied run touched unsupported APIs: ${unsupported.join("; ")}`);
850
- const a = canonicalJson(eutaxy.attempts);
851
- const b = canonicalJson(raw.attempts);
852
- if (a !== b) differences.push(`attempts differ:\n eutaxy ${a}\n raw ${b}`);
853
- const bindings = /* @__PURE__ */ new Set([...Object.keys(eutaxy.state), ...Object.keys(raw.state)]);
854
- for (const binding of [...bindings].sort()) {
855
- const tables = /* @__PURE__ */ new Set([...Object.keys(eutaxy.state[binding] ?? {}), ...Object.keys(raw.state[binding] ?? {})]);
856
- for (const table of [...tables].sort()) {
857
- const x = canonicalJson(eutaxy.state[binding]?.[table] ?? []);
858
- const y = canonicalJson(raw.state[binding]?.[table] ?? []);
859
- if (x !== y) differences.push(`${binding}.${table} differs:\n eutaxy ${x}\n raw ${y}`);
860
- }
861
- }
862
- return {
863
- equal: differences.length === 0,
864
- eutaxy,
865
- raw,
866
- differences,
867
- unsupported
868
- };
869
- }
870
- // packages/cloudflare/src/scenario.ts
871
- /**
872
- * Typed construction of scenario specs for Cloudflare Workers. Everything here
873
- * produces the plain-data `ScenarioSpec` from core; this module only knows the
874
- * Cloudflare shapes (queues, D1 bindings) and the effect conventions the
875
- * proxies follow.
876
- */
877
- function http(requests, options = {}) {
878
- return {
879
- kind: "http",
880
- requests: requests.map((r, i) => ({
881
- id: r.id ?? `req-${i + 1}`,
882
- method: (r.method ?? (r.body === void 0 ? "GET" : "POST")).toUpperCase(),
883
- path: r.path,
884
- headers: r.headers ?? {},
885
- ...r.body === void 0 ? {} : { body: r.body }
886
- })),
887
- retries: options.retries ?? 3,
888
- retryOn: options.retryOn ?? "non-2xx"
889
- };
890
- }
891
- function queue(name, messages) {
892
- return {
893
- kind: "queue",
894
- queue: name,
895
- messages: messages.map((m, i) => ({
896
- id: m.id ?? `msg-${i + 1}`,
897
- body: m.body
898
- }))
899
- };
900
- }
901
- function d1Schema(binding, schemaFile) {
902
- return {
903
- kind: "d1",
904
- binding,
905
- schemaFile
906
- };
907
- }
908
- /**
909
- * Effect conventions for D1 (what the proxies record):
910
- * call payload { args: { sql, params } }
911
- * result payload { args: { sql, params }, result: { changes, lastRowId } }
912
- * A committed write is a `result` whose `result.changes` is at least 1.
913
- */
914
- function d1Write(binding, op = "run") {
915
- return {
916
- target: `D1:${binding}`,
917
- op,
918
- kind: "result",
919
- atLeast: { "result.changes": 1 }
920
- };
921
- }
922
- /** Dot path to the Nth bound parameter of a D1 statement, in an effect payload. */
923
- function d1Param(index) {
924
- return `args.params.${index}`;
925
- }
926
- function atMostOncePerKey(name, effect, key) {
927
- return {
928
- kind: "atMostOncePerKey",
929
- name,
930
- effect,
931
- key
932
- };
933
- }
934
- function atLeastOnce(name, effect, key, expected) {
935
- return {
936
- kind: "atLeastOnce",
937
- name,
938
- effect,
939
- key,
940
- expected
941
- };
942
- }
943
- /**
944
- * Every message's (or request's) `bodyKey` value must appear at least once
945
- * as `key` in a selected effect: nothing the drive delivered may be lost.
946
- */
947
- function atLeastOncePerMessage(name, drive, effect, key, bodyKey) {
948
- const expected = [];
949
- const items = drive.kind === "queue" ? drive.messages.map((m) => ({
950
- id: m.id,
951
- body: m.body
952
- })) : drive.requests.map((r) => ({
953
- id: r.id,
954
- body: r.body ?? null
955
- }));
956
- for (const m of items) {
957
- const v = getPath(m.body, bodyKey);
958
- if (v === void 0) throw new Error(`${drive.kind} event ${m.id} has no ${JSON.stringify(bodyKey)} in its body`);
959
- expected.push(v);
960
- }
961
- const perMessage = { bodyKey: drive.kind === "queue" ? bodyKey : bodyKey === "" ? "body" : `body.${bodyKey}` };
962
- return {
963
- ...atLeastOnce(name, effect, key, expected),
964
- perMessage
965
- };
966
- }
967
- /**
968
- * Selects the responses the Worker returned for a path (`ok` narrows to 2xx
969
- * or to everything else). One `result` per attempt: a crash before the
970
- * response leaves none, a thrown error records status 500.
971
- */
972
- function httpResponse(path, options = {}) {
973
- return {
974
- target: `Http:${path}`,
975
- op: "response",
976
- kind: "result",
977
- ...options.ok === void 0 ? {} : { where: { "result.ok": options.ok } }
978
- };
979
- }
980
- /** Rows of a D1 table in the end-of-run snapshot, optionally filtered. */
981
- function d1Rows(binding, table, where) {
982
- return where ? {
983
- target: `D1:${binding}`,
984
- table,
985
- where
986
- } : {
987
- target: `D1:${binding}`,
988
- table
989
- };
990
- }
991
- /** Every row the query selects satisfies all conditions. */
992
- function everyRow(name, query, holds) {
993
- return {
994
- kind: "everyRow",
995
- name,
996
- query,
997
- holds
998
- };
999
- }
1000
- /** Every selected effect has a row whose column equals the effect's key. */
1001
- function implies(name, when, key, state, column) {
1002
- return {
1003
- kind: "implies",
1004
- name,
1005
- when,
1006
- key,
1007
- state,
1008
- column
1009
- };
1010
- }
1011
- /** Selects the acknowledgement that took effect for each message (explicit or implicit; not one ignored after a retry). */
1012
- function queueAck(queueName) {
1013
- return {
1014
- target: `Queue:${queueName}`,
1015
- op: "ack",
1016
- kind: "result",
1017
- where: { "result.effective": true }
1018
- };
1019
- }
1020
- /**
1021
- * Declare an external service: requests to `host` are answered from
1022
- * `responses` (every request gets 200 and an empty body when omitted), and
1023
- * `dedupeBy` names the header whose value makes repeated requests
1024
- * idempotent at that service.
1025
- */
1026
- function external(name, host, options = {}) {
1027
- return {
1028
- name,
1029
- host,
1030
- guarantees: options.dedupeBy ? { dedupeBy: options.dedupeBy } : {},
1031
- ...options.responses ? { responses: options.responses } : {}
1032
- };
1033
- }
1034
- /**
1035
- * Selects the requests to an external that took effect: a request replayed
1036
- * under a dedupe key the external had already seen is not counted.
1037
- */
1038
- function fetchCall(externalName, method) {
1039
- return {
1040
- target: `Fetch:${externalName}`,
1041
- ...method ? { op: method.toUpperCase() } : {},
1042
- kind: "result",
1043
- where: { "result.effective": true }
1044
- };
1045
- }
1046
- function validateHttpDrive(drive) {
1047
- const errors = [];
1048
- if (drive.requests.length === 0) errors.push("http drive needs at least one request");
1049
- const ids = /* @__PURE__ */ new Set();
1050
- drive.requests.forEach((r, i) => {
1051
- if (!r.path.startsWith("/")) errors.push(`requests[${i}].path must start with "/"`);
1052
- if (!r.method) errors.push(`requests[${i}].method must not be empty`);
1053
- if (ids.has(r.id)) errors.push(`duplicate request id ${JSON.stringify(r.id)}`);
1054
- ids.add(r.id);
1055
- if ((r.method === "GET" || r.method === "HEAD") && r.body !== void 0) errors.push(`requests[${i}] is a ${r.method} and cannot carry a body`);
1056
- });
1057
- if (!(Number.isInteger(drive.retries) && drive.retries >= 0)) errors.push("http drive retries must be a non-negative integer");
1058
- return errors;
1059
- }
1060
- /** Build and validate a scenario spec; throws with every problem listed. */
1061
- function defineScenario(input) {
1062
- const drive = input.drive.kind === "http" ? input.drive : "messages" in input.drive && input.drive.messages.every((m) => "id" in m && typeof m.id === "string") ? input.drive : queue(input.drive.queue, input.drive.messages);
1063
- const spec = {
1064
- version: 1,
1065
- name: input.name,
1066
- platform: "cloudflare",
1067
- worker: input.worker,
1068
- drive,
1069
- setup: input.setup ?? [],
1070
- externals: input.externals ?? [],
1071
- invariants: input.invariants,
1072
- bounds: {
1073
- ...defaultBounds,
1074
- ...input.bounds
1075
- }
1076
- };
1077
- const errors = [...validateScenario(spec), ...drive.kind === "http" ? validateHttpDrive(drive) : []];
1078
- if (errors.length > 0) throw new Error(`invalid scenario ${JSON.stringify(input.name)}:\n- ${errors.join("\n- ")}`);
1079
- return spec;
1080
- }
1081
- export { atLeastOnce, atLeastOncePerMessage, atMostOncePerKey, check, cloudflareRegressionTest, createCloudflarePlatform, d1Param, d1Rows, d1Schema, d1Write, defineScenario, everyRow, expectHolds, external, fetchCall, http, httpResponse, implies, queue, queueAck, runDifferential, snapshotD1 };
1082
-
1083
- //# sourceMappingURL=cloudflare.mjs.map
1
+ import { r as atMostOncePerKey, t as atLeastOnce } from "./delivery-invariants-Cuxdna28.mjs";
2
+ import { A as snapshotD1, C as r2Rows, D as workflow, E as unique, M as expectHolds, O as workflowRows, P as cloudflareRegressionTest, S as r2Op, T as refines, _ as httpResponse, a as d1Param, b as queueAck, c as d1Schema, d as durableObject, f as durableObjectRows, g as http, h as fetchCall, i as atLeastOncePerMessage, j as check, k as workflowStep, l as d1Write, m as external, n as runDifferential, o as d1Read, p as everyRow, r as createCloudflarePlatform, s as d1Rows, t as checkInWorkerd, u as defineScenario, v as implies, w as references, x as r2Bucket, y as queue } from "./src-DKb-fkdb.mjs";
3
+ export { atLeastOnce, atLeastOncePerMessage, atMostOncePerKey, check, checkInWorkerd, cloudflareRegressionTest, createCloudflarePlatform, d1Param, d1Read, d1Rows, d1Schema, d1Write, defineScenario, durableObject, durableObjectRows, everyRow, expectHolds, external, fetchCall, http, httpResponse, implies, queue, queueAck, r2Bucket, r2Op, r2Rows, references, refines, runDifferential, snapshotD1, unique, workflow, workflowRows, workflowStep };