eutaxy 0.5.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.
- package/README.md +1 -1
- package/dist/aws.d.mts +7 -5
- package/dist/aws.d.mts.map +1 -1
- package/dist/aws.mjs +41 -135
- package/dist/aws.mjs.map +1 -1
- package/dist/bin.mjs +2 -2
- package/dist/checked-CGpA2-F0.d.mts +285 -0
- package/dist/checked-CGpA2-F0.d.mts.map +1 -0
- package/dist/cli-IJrKkeYS.mjs +2 -0
- package/dist/cli.d.mts.map +1 -1
- package/dist/cli.mjs +2 -2
- package/dist/cloudflare.d.mts +158 -54
- package/dist/cloudflare.d.mts.map +1 -1
- package/dist/cloudflare.mjs +3 -1815
- package/dist/delivery-invariants-BraYqcYN.d.mts +5 -0
- package/dist/delivery-invariants-BraYqcYN.d.mts.map +1 -0
- package/dist/delivery-invariants-Cuxdna28.mjs +39 -0
- package/dist/delivery-invariants-Cuxdna28.mjs.map +1 -0
- package/dist/index.d.mts +22 -189
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +17 -197
- package/dist/index.mjs.map +1 -1
- package/dist/{platform-eVgCMbX0.d.mts → platform-DfMwknw1.d.mts} +94 -73
- package/dist/platform-DfMwknw1.d.mts.map +1 -0
- package/dist/{src-C19_yfMM.mjs → src-Bqc9Eyb1.mjs} +961 -543
- package/dist/src-Bqc9Eyb1.mjs.map +1 -0
- package/dist/src-DKb-fkdb.mjs +3399 -0
- package/dist/src-DKb-fkdb.mjs.map +1 -0
- package/dist/{src-CgfGiH25.mjs → src-Dxl9ZlKn.mjs} +223 -17
- package/dist/src-Dxl9ZlKn.mjs.map +1 -0
- package/package.json +1 -1
- package/dist/cli-NqY61bpo.mjs +0 -2
- package/dist/cloudflare.mjs.map +0 -1
- package/dist/explore-BHYvAZKN.d.mts +0 -84
- package/dist/explore-BHYvAZKN.d.mts.map +0 -1
- package/dist/platform-eVgCMbX0.d.mts.map +0 -1
- package/dist/src-BD3jkjgG.mjs +0 -477
- package/dist/src-BD3jkjgG.mjs.map +0 -1
- package/dist/src-C19_yfMM.mjs.map +0 -1
- package/dist/src-CgfGiH25.mjs.map +0 -1
- package/dist/src-s6uYyC0B.mjs +0 -89
- package/dist/src-s6uYyC0B.mjs.map +0 -1
- package/dist/verdict-evEM5Gxx.mjs +0 -12
- package/dist/verdict-evEM5Gxx.mjs.map +0 -1
package/dist/cloudflare.mjs
CHANGED
|
@@ -1,1815 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { _ as
|
|
3
|
-
|
|
4
|
-
import { n as cloudflareRegressionTest } from "./src-BD3jkjgG.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/alarms.ts
|
|
231
|
-
/** `EventRef.source` of an alarm event. */
|
|
232
|
-
const alarmSource = "durable_object_alarm";
|
|
233
|
-
/** Crash before: the handler never ran. Crash after: it ran and committed, but counts as failed. */
|
|
234
|
-
const ALARM = [
|
|
235
|
-
"crash_before",
|
|
236
|
-
"crash_after",
|
|
237
|
-
"error"
|
|
238
|
-
];
|
|
239
|
-
/** Cloudflare retries a failed alarm handler up to six times, after 2 s, 4 s, 8 s, ... */
|
|
240
|
-
const maxRetries = 6;
|
|
241
|
-
const firstRetryMs = 2e3;
|
|
242
|
-
/** The alarms of one namespace's objects; the platform clears it before each run. */
|
|
243
|
-
var AlarmBook = class {
|
|
244
|
-
entries = /* @__PURE__ */ new Map();
|
|
245
|
-
clear() {
|
|
246
|
-
this.entries.clear();
|
|
247
|
-
}
|
|
248
|
-
entry(id) {
|
|
249
|
-
let e = this.entries.get(id);
|
|
250
|
-
if (!e) {
|
|
251
|
-
e = {
|
|
252
|
-
time: null,
|
|
253
|
-
seq: 0,
|
|
254
|
-
gen: 0,
|
|
255
|
-
firings: 0
|
|
256
|
-
};
|
|
257
|
-
this.entries.set(id, e);
|
|
258
|
-
}
|
|
259
|
-
return e;
|
|
260
|
-
}
|
|
261
|
-
};
|
|
262
|
-
/** One alarm control per object: setting schedules an event at the alarm's virtual time. */
|
|
263
|
-
function alarmControl(book, binding, id, object, hooks) {
|
|
264
|
-
const entry = book.entry(id);
|
|
265
|
-
return {
|
|
266
|
-
get: () => entry.time,
|
|
267
|
-
set: (time) => {
|
|
268
|
-
entry.time = time;
|
|
269
|
-
entry.seq++;
|
|
270
|
-
entry.gen = entry.seq;
|
|
271
|
-
const data = {
|
|
272
|
-
binding,
|
|
273
|
-
gen: entry.gen,
|
|
274
|
-
id,
|
|
275
|
-
object,
|
|
276
|
-
time,
|
|
277
|
-
retryCount: 0
|
|
278
|
-
};
|
|
279
|
-
const now = Date.now();
|
|
280
|
-
hooks().enqueue({
|
|
281
|
-
id: `alarm:${binding}:${object}:${entry.seq}`,
|
|
282
|
-
attempt: 1,
|
|
283
|
-
source: alarmSource,
|
|
284
|
-
data,
|
|
285
|
-
...time > now ? { at: time } : {}
|
|
286
|
-
});
|
|
287
|
-
},
|
|
288
|
-
delete: () => {
|
|
289
|
-
entry.time = null;
|
|
290
|
-
entry.seq++;
|
|
291
|
-
entry.gen = entry.seq;
|
|
292
|
-
},
|
|
293
|
-
unsupported: (reason) => hooks().unsupported(`Durable Object ${binding} ${object}: ${reason}`)
|
|
294
|
-
};
|
|
295
|
-
}
|
|
296
|
-
/** Storage objects whose alarm methods Eutaxy has taken over (one per live instance). */
|
|
297
|
-
const takenOver = /* @__PURE__ */ new WeakSet();
|
|
298
|
-
const timeOf = (time) => typeof time === "number" ? time : time.getTime();
|
|
299
|
-
/** Storage objects whose alarm was read before Eutaxy took them over (in a constructor). */
|
|
300
|
-
const readBeforeTakeover = /* @__PURE__ */ new WeakSet();
|
|
301
|
-
/** Storage prototypes whose getAlarm records such reads. */
|
|
302
|
-
const watched = /* @__PURE__ */ new WeakSet();
|
|
303
|
-
/**
|
|
304
|
-
* Record reads of the native alarm on storage not yet taken over: a rebuilt
|
|
305
|
-
* object's constructor reads native storage, where Eutaxy's pending alarm is
|
|
306
|
-
* not. The wrapper only records; it returns what the native method returns.
|
|
307
|
-
*/
|
|
308
|
-
function watchReads(storage) {
|
|
309
|
-
const proto = Object.getPrototypeOf(storage);
|
|
310
|
-
if (!proto || watched.has(proto) || typeof proto.getAlarm !== "function") return;
|
|
311
|
-
watched.add(proto);
|
|
312
|
-
const native = proto.getAlarm;
|
|
313
|
-
proto.getAlarm = function(...args) {
|
|
314
|
-
if (!takenOver.has(this)) readBeforeTakeover.add(this);
|
|
315
|
-
return native.apply(this, args);
|
|
316
|
-
};
|
|
317
|
-
}
|
|
318
|
-
/**
|
|
319
|
-
* Replace an object's alarm methods so no real alarm is ever scheduled. An
|
|
320
|
-
* alarm the object set before the takeover (in its constructor) is moved
|
|
321
|
-
* over: deleted from the runtime and set on the control, unless an alarm is
|
|
322
|
-
* still pending, which the constructor could not see in native storage
|
|
323
|
-
* (Eutaxy keeps it): then the pending one stays and the run is UNSUPPORTED.
|
|
324
|
-
*/
|
|
325
|
-
async function takeOverAlarms(storage, alarm) {
|
|
326
|
-
if (takenOver.has(storage)) return;
|
|
327
|
-
watchReads(storage);
|
|
328
|
-
takenOver.add(storage);
|
|
329
|
-
if (readBeforeTakeover.has(storage) && alarm.get() !== null) alarm.unsupported("its constructor read the alarm while one was pending; natively it would have seen that alarm, so constructors that read the alarm are not modelled");
|
|
330
|
-
const existing = await storage.getAlarm();
|
|
331
|
-
if (existing !== null) {
|
|
332
|
-
await storage.deleteAlarm();
|
|
333
|
-
if (alarm.get() === null) alarm.set(existing);
|
|
334
|
-
else alarm.unsupported("its constructor set an alarm while one was pending; natively it would have seen that alarm, so constructors that read the alarm are not modelled");
|
|
335
|
-
}
|
|
336
|
-
const s = storage;
|
|
337
|
-
let inSync = false;
|
|
338
|
-
const outsideSync = (op) => {
|
|
339
|
-
if (inSync) alarm.unsupported(`${op} inside transactionSync() is not modelled`);
|
|
340
|
-
};
|
|
341
|
-
Object.assign(s, {
|
|
342
|
-
setAlarm: async (time) => {
|
|
343
|
-
outsideSync("setAlarm");
|
|
344
|
-
alarm.set(timeOf(time));
|
|
345
|
-
},
|
|
346
|
-
getAlarm: async () => alarm.get(),
|
|
347
|
-
deleteAlarm: async () => {
|
|
348
|
-
outsideSync("deleteAlarm");
|
|
349
|
-
alarm.delete();
|
|
350
|
-
}
|
|
351
|
-
});
|
|
352
|
-
if (typeof s["transactionSync"] === "function") {
|
|
353
|
-
const transactionSync = s["transactionSync"].bind(storage);
|
|
354
|
-
s["transactionSync"] = (callback) => {
|
|
355
|
-
inSync = true;
|
|
356
|
-
try {
|
|
357
|
-
return transactionSync(callback);
|
|
358
|
-
} finally {
|
|
359
|
-
inSync = false;
|
|
360
|
-
}
|
|
361
|
-
};
|
|
362
|
-
}
|
|
363
|
-
const transaction = s["transaction"].bind(storage);
|
|
364
|
-
s["transaction"] = async (callback) => {
|
|
365
|
-
let pending;
|
|
366
|
-
let rolledBack = false;
|
|
367
|
-
const held = {
|
|
368
|
-
setAlarm: async (time) => {
|
|
369
|
-
pending = { time: timeOf(time) };
|
|
370
|
-
},
|
|
371
|
-
getAlarm: async () => pending ? pending.time : alarm.get(),
|
|
372
|
-
deleteAlarm: async () => {
|
|
373
|
-
pending = { time: null };
|
|
374
|
-
}
|
|
375
|
-
};
|
|
376
|
-
const result = await transaction((txn) => {
|
|
377
|
-
pending = void 0;
|
|
378
|
-
rolledBack = false;
|
|
379
|
-
return callback(new Proxy(txn, { get(target, prop) {
|
|
380
|
-
if (typeof prop === "string" && prop in held) return held[prop];
|
|
381
|
-
const value = target[prop];
|
|
382
|
-
if (prop === "rollback" && typeof value === "function") return (...args) => {
|
|
383
|
-
rolledBack = true;
|
|
384
|
-
return value.apply(target, args);
|
|
385
|
-
};
|
|
386
|
-
return typeof value === "function" ? value.bind(target) : value;
|
|
387
|
-
} }));
|
|
388
|
-
});
|
|
389
|
-
if (pending && !rolledBack) {
|
|
390
|
-
if (pending.time === null) alarm.delete();
|
|
391
|
-
else alarm.set(pending.time);
|
|
392
|
-
}
|
|
393
|
-
return result;
|
|
394
|
-
};
|
|
395
|
-
}
|
|
396
|
-
/**
|
|
397
|
-
* Fire an alarm event: skip it when the object's alarm has since moved or
|
|
398
|
-
* been deleted, run `alarm()` as one effect otherwise, and schedule a retry
|
|
399
|
-
* with backoff when the handler fails, crashes, or a fault says it did.
|
|
400
|
-
*/
|
|
401
|
-
async function deliverAlarm(event, hooks, maxRedeliveries, d) {
|
|
402
|
-
const a = event.data;
|
|
403
|
-
const entry = d.book.entry(a.id);
|
|
404
|
-
if (entry.gen !== a.gen) return {
|
|
405
|
-
status: "completed",
|
|
406
|
-
followUps: []
|
|
407
|
-
};
|
|
408
|
-
if (a.retryCount === 0) {
|
|
409
|
-
if (entry.time !== a.time) return {
|
|
410
|
-
status: "completed",
|
|
411
|
-
followUps: []
|
|
412
|
-
};
|
|
413
|
-
if (entry.firings >= d.limit) {
|
|
414
|
-
entry.time = null;
|
|
415
|
-
d.bookkeep("alarm_not_fired", {
|
|
416
|
-
object: a.object,
|
|
417
|
-
firings: entry.firings
|
|
418
|
-
});
|
|
419
|
-
return {
|
|
420
|
-
status: "completed",
|
|
421
|
-
followUps: []
|
|
422
|
-
};
|
|
423
|
-
}
|
|
424
|
-
entry.firings++;
|
|
425
|
-
}
|
|
426
|
-
const invocation = `${event.id}#${event.attempt}`;
|
|
427
|
-
const inv = hooks.startInvocation(invocation);
|
|
428
|
-
const info = {
|
|
429
|
-
retryCount: a.retryCount,
|
|
430
|
-
isRetry: a.retryCount > 0
|
|
431
|
-
};
|
|
432
|
-
const outcome = hooks.effect({
|
|
433
|
-
invocation,
|
|
434
|
-
target: `DO:${d.binding}`,
|
|
435
|
-
op: "alarm",
|
|
436
|
-
args: {
|
|
437
|
-
object: a.object,
|
|
438
|
-
retryCount: a.retryCount
|
|
439
|
-
},
|
|
440
|
-
allowed: ALARM,
|
|
441
|
-
hostsEffects: true
|
|
442
|
-
}, async () => {
|
|
443
|
-
await d.runAlarm(a.id, a.object, info, a.gen);
|
|
444
|
-
return null;
|
|
445
|
-
}, () => null, {
|
|
446
|
-
onAbandon: () => d.abort(a.id),
|
|
447
|
-
mayPark: () => d.mayPark(a.id)
|
|
448
|
-
}).then(() => "completed", (err) => err instanceof CrashSignal ? "crashed" : "errored");
|
|
449
|
-
const status = await Promise.race([hooks.settle(outcome, invocation), inv.crashed.then(() => "crashed")]);
|
|
450
|
-
if (status === "crashed") await d.evict(a.id);
|
|
451
|
-
if (status !== "completed") {
|
|
452
|
-
if (a.retryCount < maxRetries && a.retryCount < maxRedeliveries) {
|
|
453
|
-
const retryAt = Date.now() + firstRetryMs * 2 ** a.retryCount;
|
|
454
|
-
const data = {
|
|
455
|
-
...a,
|
|
456
|
-
retryCount: a.retryCount + 1
|
|
457
|
-
};
|
|
458
|
-
if (entry.gen === a.gen) entry.time = retryAt;
|
|
459
|
-
hooks.enqueue({
|
|
460
|
-
...event,
|
|
461
|
-
attempt: event.attempt + 1,
|
|
462
|
-
data,
|
|
463
|
-
at: retryAt
|
|
464
|
-
});
|
|
465
|
-
} else {
|
|
466
|
-
if (entry.gen === a.gen) entry.time = null;
|
|
467
|
-
d.bookkeep("alarm_gave_up", {
|
|
468
|
-
object: a.object,
|
|
469
|
-
retries: a.retryCount
|
|
470
|
-
});
|
|
471
|
-
}
|
|
472
|
-
}
|
|
473
|
-
return {
|
|
474
|
-
status,
|
|
475
|
-
followUps: []
|
|
476
|
-
};
|
|
477
|
-
}
|
|
478
|
-
// packages/cloudflare/src/durable-objects.ts
|
|
479
|
-
const CALL = [
|
|
480
|
-
"crash_before",
|
|
481
|
-
"crash_after",
|
|
482
|
-
"ambiguous",
|
|
483
|
-
"error"
|
|
484
|
-
];
|
|
485
|
-
const typed = (helpers) => helpers;
|
|
486
|
-
function isDurableObjectNamespace(value) {
|
|
487
|
-
return typeof value === "object" && value !== null && typeof value.idFromName === "function" && typeof value.get === "function";
|
|
488
|
-
}
|
|
489
|
-
/** How deep each object state is inside blockConcurrencyWhile, while it is. */
|
|
490
|
-
const gateDepth = /* @__PURE__ */ new WeakMap();
|
|
491
|
-
/** Object-state prototypes whose blockConcurrencyWhile records that depth. */
|
|
492
|
-
const gateWatched = /* @__PURE__ */ new WeakSet();
|
|
493
|
-
/**
|
|
494
|
-
* Record when an object holds its input gate with blockConcurrencyWhile,
|
|
495
|
-
* on the state prototype so constructors are covered too; the wrapper only
|
|
496
|
-
* records and calls the native method.
|
|
497
|
-
*/
|
|
498
|
-
function watchGate(state) {
|
|
499
|
-
const proto = Object.getPrototypeOf(state);
|
|
500
|
-
if (!proto || gateWatched.has(proto) || typeof proto.blockConcurrencyWhile !== "function") return;
|
|
501
|
-
gateWatched.add(proto);
|
|
502
|
-
const native = proto.blockConcurrencyWhile;
|
|
503
|
-
proto.blockConcurrencyWhile = function(callback) {
|
|
504
|
-
return native.call(this, async () => {
|
|
505
|
-
gateDepth.set(this, (gateDepth.get(this) ?? 0) + 1);
|
|
506
|
-
try {
|
|
507
|
-
return await callback();
|
|
508
|
-
} finally {
|
|
509
|
-
gateDepth.set(this, (gateDepth.get(this) ?? 1) - 1);
|
|
510
|
-
}
|
|
511
|
-
});
|
|
512
|
-
};
|
|
513
|
-
}
|
|
514
|
-
/** Whether the object is inside blockConcurrencyWhile now. */
|
|
515
|
-
function gateHeld(state) {
|
|
516
|
-
return state !== void 0 && (gateDepth.get(state) ?? 0) > 0;
|
|
517
|
-
}
|
|
518
|
-
/** What Eutaxy keeps about one namespace during a run; the platform clears it before each run. */
|
|
519
|
-
var BindingState = class {
|
|
520
|
-
/** Names learned this run (seeded ones come back with the setup), so traces never depend on earlier runs. */
|
|
521
|
-
names = /* @__PURE__ */ new Map();
|
|
522
|
-
/** Ids of the objects a call or an alarm reached this run. */
|
|
523
|
-
touched = /* @__PURE__ */ new Set();
|
|
524
|
-
/** The objects' alarms in virtual time. */
|
|
525
|
-
alarms = new AlarmBook();
|
|
526
|
-
/** Each reached object's live state, so an invocation that crashes inside it can reset it. */
|
|
527
|
-
states = /* @__PURE__ */ new Map();
|
|
528
|
-
/** Whether the object's own effects may wait for a turn: not while it holds its input gate. */
|
|
529
|
-
mayPark(id) {
|
|
530
|
-
return !gateHeld(this.states.get(id));
|
|
531
|
-
}
|
|
532
|
-
clear() {
|
|
533
|
-
this.names.clear();
|
|
534
|
-
this.touched.clear();
|
|
535
|
-
this.alarms.clear();
|
|
536
|
-
this.states.clear();
|
|
537
|
-
}
|
|
538
|
-
/**
|
|
539
|
-
* Reset an object the way a crash does, with `ctx.abort()`, which
|
|
540
|
-
* application code cannot catch: the runtime ends the requests inside it.
|
|
541
|
-
* Called where an injected crash happens inside the object's own work,
|
|
542
|
-
* which is the one place abort() works (from outside, workerd refuses).
|
|
543
|
-
*/
|
|
544
|
-
abort(id) {
|
|
545
|
-
const state = this.states.get(id);
|
|
546
|
-
this.states.delete(id);
|
|
547
|
-
try {
|
|
548
|
-
state?.abort("Eutaxy: the invocation crashed inside this object");
|
|
549
|
-
} catch {}
|
|
550
|
-
}
|
|
551
|
-
};
|
|
552
|
-
/** The storage's own alarm deletion, even after Eutaxy replaced the method on it. */
|
|
553
|
-
async function deleteRealAlarm(storage) {
|
|
554
|
-
const proto = Object.getPrototypeOf(storage);
|
|
555
|
-
await (Object.hasOwn(storage, "deleteAlarm") ? proto.deleteAlarm : storage.deleteAlarm)?.call(storage);
|
|
556
|
-
}
|
|
557
|
-
/** An RPC argument as effect-log data; a Request becomes its method and URL. */
|
|
558
|
-
function argument(value) {
|
|
559
|
-
if (value instanceof Request) return {
|
|
560
|
-
method: value.method,
|
|
561
|
-
url: value.url
|
|
562
|
-
};
|
|
563
|
-
return toJson(value);
|
|
564
|
-
}
|
|
565
|
-
/**
|
|
566
|
-
* Whether a result is data the caller holds by value. Anything else (an RPC
|
|
567
|
-
* capability, an object with methods) would let later calls bypass the
|
|
568
|
-
* proxy, so it makes the run UNSUPPORTED.
|
|
569
|
-
*/
|
|
570
|
-
function isPlainData(value, depth = 0) {
|
|
571
|
-
if (value === null || value === void 0) return true;
|
|
572
|
-
if (typeof value === "function") return false;
|
|
573
|
-
if (typeof value !== "object") return true;
|
|
574
|
-
if (depth > 8) return false;
|
|
575
|
-
if (value instanceof Response || value instanceof Date) return true;
|
|
576
|
-
if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) return true;
|
|
577
|
-
const proto = Object.getPrototypeOf(value);
|
|
578
|
-
if (Array.isArray(value)) return value.every((v) => isPlainData(v, depth + 1));
|
|
579
|
-
if (proto !== Object.prototype && proto !== null) return false;
|
|
580
|
-
return Object.values(value).every((v) => isPlainData(v, depth + 1));
|
|
581
|
-
}
|
|
582
|
-
/** An RPC result as effect-log data; a Response becomes its status. */
|
|
583
|
-
function summarize(result) {
|
|
584
|
-
if (result instanceof Response) return {
|
|
585
|
-
status: result.status,
|
|
586
|
-
ok: result.ok
|
|
587
|
-
};
|
|
588
|
-
return toJson(result);
|
|
589
|
-
}
|
|
590
|
-
function proxyNamespace(real, binding, ctx, state, helpers, isReset) {
|
|
591
|
-
const target = `DO:${binding}`;
|
|
592
|
-
const { names, touched, alarms: book } = state;
|
|
593
|
-
const nameOf = (id) => names.get(id.toString()) ?? id.toString();
|
|
594
|
-
function stubFor(stub, id, object) {
|
|
595
|
-
/** Make sure the call may reach the object, and take over its alarms first. */
|
|
596
|
-
async function reach(real) {
|
|
597
|
-
if (!helpers) ctx.hooks.unsupported(`Durable Object binding ${binding} needs the Cloudflare test helpers (pass durableObjects to createCloudflarePlatform)`);
|
|
598
|
-
else if (!isReset()) ctx.hooks.unsupported(`Durable Object binding ${binding} has no durableObject setup, so its objects are not reset between runs; add durableObject(${JSON.stringify(binding)}) to the scenario's setup`);
|
|
599
|
-
else {
|
|
600
|
-
touched.add(id);
|
|
601
|
-
await typed(helpers).runInDurableObject(real, (_instance, live) => {
|
|
602
|
-
watchGate(live);
|
|
603
|
-
state.states.set(id, live);
|
|
604
|
-
return takeOverAlarms(live.storage, alarmControl(book, binding, id, object, () => ctx.hooks));
|
|
605
|
-
});
|
|
606
|
-
}
|
|
607
|
-
}
|
|
608
|
-
/** A result passed back to the Worker; one that is not plain data cannot be followed. */
|
|
609
|
-
function plain(result) {
|
|
610
|
-
if (!isPlainData(result)) ctx.hooks.unsupported(`Durable Object ${binding} ${object} returned something that is not plain data (an RPC capability or an object with methods); calls on it would bypass Eutaxy`);
|
|
611
|
-
return result;
|
|
612
|
-
}
|
|
613
|
-
/**
|
|
614
|
-
* The promise a call returns. On a real stub it is an RPC promise that
|
|
615
|
-
* pipelines property reads (`stub.getData().value`); this one is not, so
|
|
616
|
-
* a read on it makes the run UNSUPPORTED instead of yielding undefined.
|
|
617
|
-
*/
|
|
618
|
-
function pipelineGuard(promise) {
|
|
619
|
-
return new Proxy(promise, { get(target, prop) {
|
|
620
|
-
if (typeof prop === "symbol" || prop === "then" || prop === "catch" || prop === "finally") {
|
|
621
|
-
const value = Reflect.get(target, prop, target);
|
|
622
|
-
return typeof value === "function" ? value.bind(target) : value;
|
|
623
|
-
}
|
|
624
|
-
ctx.hooks.unsupported(`Durable Object ${binding} ${object}: RPC promise pipelining (reading .${prop} on a call's promise) is not supported; await the call first`);
|
|
625
|
-
} });
|
|
626
|
-
}
|
|
627
|
-
/** One effect on the object: a method call, or awaiting an RPC property. */
|
|
628
|
-
function onObject(op, args, perform) {
|
|
629
|
-
return ctx.hooks.effect({
|
|
630
|
-
invocation: ctx.currentInvocation(),
|
|
631
|
-
target,
|
|
632
|
-
op,
|
|
633
|
-
args,
|
|
634
|
-
allowed: CALL,
|
|
635
|
-
hostsEffects: true
|
|
636
|
-
}, perform, summarize, {
|
|
637
|
-
onAbandon: () => state.abort(id),
|
|
638
|
-
mayPark: () => state.mayPark(id)
|
|
639
|
-
});
|
|
640
|
-
}
|
|
641
|
-
return new Proxy(stub, { get(real, prop, receiver) {
|
|
642
|
-
if (prop === "then") return void 0;
|
|
643
|
-
if (typeof prop !== "string" || prop === "id" || prop === "name") return Reflect.get(real, prop, receiver);
|
|
644
|
-
const call = (...args) => pipelineGuard(onObject(prop, {
|
|
645
|
-
object,
|
|
646
|
-
args: args.map(argument)
|
|
647
|
-
}, async () => {
|
|
648
|
-
await reach(real);
|
|
649
|
-
const method = real[prop];
|
|
650
|
-
if (typeof method !== "function") throw new TypeError(`${binding} stub has no ${prop}`);
|
|
651
|
-
return plain(await Reflect.apply(method, real, args));
|
|
652
|
-
}));
|
|
653
|
-
const read = () => onObject(prop, {
|
|
654
|
-
object,
|
|
655
|
-
property: true
|
|
656
|
-
}, async () => {
|
|
657
|
-
await reach(real);
|
|
658
|
-
return plain(await real[prop]);
|
|
659
|
-
});
|
|
660
|
-
const awaitable = (onFulfilled, onRejected) => read().then(onFulfilled, onRejected);
|
|
661
|
-
return new Proxy(call, { get(target, key) {
|
|
662
|
-
if (key === "then") return awaitable;
|
|
663
|
-
if (typeof key === "symbol") return Reflect.get(target, key);
|
|
664
|
-
ctx.hooks.unsupported(`Durable Object ${binding} ${object}: RPC promise pipelining (reading .${prop}.${key}) is not supported; await .${prop} first`);
|
|
665
|
-
} });
|
|
666
|
-
} });
|
|
667
|
-
}
|
|
668
|
-
function idFromName(name) {
|
|
669
|
-
const id = real.idFromName(name);
|
|
670
|
-
names.set(id.toString(), name);
|
|
671
|
-
return id;
|
|
672
|
-
}
|
|
673
|
-
return new Proxy(real, { get(target, prop, receiver) {
|
|
674
|
-
switch (prop) {
|
|
675
|
-
case "idFromName": return idFromName;
|
|
676
|
-
case "idFromString": return (hex) => target.idFromString(hex);
|
|
677
|
-
case "newUniqueId": return (options) => {
|
|
678
|
-
ctx.hooks.unsupported(`${binding}.newUniqueId() is random and differs on replay; use idFromName`);
|
|
679
|
-
return target.newUniqueId(options);
|
|
680
|
-
};
|
|
681
|
-
case "get": return (id, options) => stubFor(target.get(id, options), id.toString(), nameOf(id));
|
|
682
|
-
case "getByName": return (name) => {
|
|
683
|
-
const id = idFromName(name);
|
|
684
|
-
return stubFor(target.get(id), id.toString(), name);
|
|
685
|
-
};
|
|
686
|
-
case "jurisdiction": return (jurisdiction) => {
|
|
687
|
-
ctx.hooks.unsupported(`${binding}.jurisdiction() namespaces are not proxied or reset; use the namespace itself`);
|
|
688
|
-
return target.jurisdiction(jurisdiction);
|
|
689
|
-
};
|
|
690
|
-
default: {
|
|
691
|
-
const value = Reflect.get(target, prop, receiver);
|
|
692
|
-
return typeof value === "function" ? value.bind(target) : value;
|
|
693
|
-
}
|
|
694
|
-
}
|
|
695
|
-
} });
|
|
696
|
-
}
|
|
697
|
-
/**
|
|
698
|
-
* Run an object's `alarm()` handler inside it, after taking over its alarms
|
|
699
|
-
* (the instance may be new since the alarm was set).
|
|
700
|
-
*/
|
|
701
|
-
/** Drop an object's instance from outside it; one that is not running has nothing to drop. */
|
|
702
|
-
async function evictObject(real, helpers, id) {
|
|
703
|
-
if (!helpers) return;
|
|
704
|
-
await typed(helpers).evictDurableObject(real.get(real.idFromString(id))).catch(() => {});
|
|
705
|
-
}
|
|
706
|
-
function alarmRunner(real, binding, ctx, helpers, state) {
|
|
707
|
-
return async (id, object, info, gen) => {
|
|
708
|
-
if (!helpers) {
|
|
709
|
-
ctx.hooks.unsupported(`Durable Object binding ${binding} needs the Cloudflare test helpers`);
|
|
710
|
-
return;
|
|
711
|
-
}
|
|
712
|
-
state.touched.add(id);
|
|
713
|
-
await typed(helpers).runInDurableObject(real.get(real.idFromString(id)), async (instance, live) => {
|
|
714
|
-
watchGate(live);
|
|
715
|
-
state.states.set(id, live);
|
|
716
|
-
await takeOverAlarms(live.storage, alarmControl(state.alarms, binding, id, object, () => ctx.hooks));
|
|
717
|
-
const entry = state.alarms.entry(id);
|
|
718
|
-
if (entry.gen !== gen) return;
|
|
719
|
-
entry.time = null;
|
|
720
|
-
const handler = instance.alarm;
|
|
721
|
-
if (typeof handler !== "function") {
|
|
722
|
-
ctx.hooks.unsupported(`Durable Object ${binding} ${object} set an alarm but has no alarm() handler`);
|
|
723
|
-
return;
|
|
724
|
-
}
|
|
725
|
-
await handler.call(instance, info);
|
|
726
|
-
});
|
|
727
|
-
};
|
|
728
|
-
}
|
|
729
|
-
/** The objects to reset: every id the namespace has created, plus the setup's named ones. */
|
|
730
|
-
async function objectIds(real, helpers, names, seeded) {
|
|
731
|
-
const ids = /* @__PURE__ */ new Map();
|
|
732
|
-
for (const id of await typed(helpers).listDurableObjectIds(real)) ids.set(id.toString(), id);
|
|
733
|
-
for (const name of seeded) {
|
|
734
|
-
const id = real.idFromName(name);
|
|
735
|
-
names.set(id.toString(), name);
|
|
736
|
-
ids.set(id.toString(), id);
|
|
737
|
-
}
|
|
738
|
-
return [...ids.values()].sort((a, b) => a.toString() < b.toString() ? -1 : 1);
|
|
739
|
-
}
|
|
740
|
-
/**
|
|
741
|
-
* Clear every object of the namespace, write the seeded entries, and evict
|
|
742
|
-
* them all, so each run's first call constructs the object from storage.
|
|
743
|
-
*/
|
|
744
|
-
async function resetNamespace(real, helpers, names, objects) {
|
|
745
|
-
const { requested } = await withoutNetwork(() => clearAndSeed(real, helpers, names, objects));
|
|
746
|
-
if (requested) throw new Error("a Durable Object constructor made a request during reset; constructors run outside the simulation there, so objects whose constructor does I/O are not supported");
|
|
747
|
-
}
|
|
748
|
-
async function clearAndSeed(real, helpers, names, objects) {
|
|
749
|
-
const ids = await objectIds(real, helpers, names, Object.keys(objects));
|
|
750
|
-
for (const id of ids) {
|
|
751
|
-
const stub = real.get(id);
|
|
752
|
-
const name = names.get(id.toString());
|
|
753
|
-
const entries = name !== void 0 && Object.hasOwn(objects, name) ? objects[name] : void 0;
|
|
754
|
-
await typed(helpers).runInDurableObject(stub, async (_instance, state) => {
|
|
755
|
-
watchGate(state);
|
|
756
|
-
await state.storage.deleteAll();
|
|
757
|
-
await deleteRealAlarm(state.storage);
|
|
758
|
-
if (entries && Object.keys(entries).length > 0) await state.storage.put(entries);
|
|
759
|
-
});
|
|
760
|
-
await typed(helpers).evictDurableObject(stub);
|
|
761
|
-
}
|
|
762
|
-
}
|
|
763
|
-
/**
|
|
764
|
-
* Each object's storage as rows `{ key, value }`, sorted by key, one table
|
|
765
|
-
* per object name. An object no call reached this run still holds exactly
|
|
766
|
-
* its seed (reset left it evicted), so its rows come from the seed and it is
|
|
767
|
-
* not constructed: its constructor would run outside the simulation. Such an
|
|
768
|
-
* object that is running anyway was reached some other way (through another
|
|
769
|
-
* object's own binding): `onIndirect` is told, and the seed is not its state.
|
|
770
|
-
* The tables are the seeded objects and those a call reached, never objects
|
|
771
|
-
* only earlier runs created, so a snapshot depends on this run alone.
|
|
772
|
-
*/
|
|
773
|
-
async function snapshotNamespace(real, helpers, names, touched, objects, onIndirect, onUnsupported) {
|
|
774
|
-
const { value, requested } = await withoutNetwork(() => readTables(real, helpers, names, touched, objects, onIndirect, onUnsupported));
|
|
775
|
-
if (requested) onUnsupported("a Durable Object made a request while its storage was being snapshotted");
|
|
776
|
-
return value;
|
|
777
|
-
}
|
|
778
|
-
async function readTables(real, helpers, names, touched, objects, onIndirect, onUnsupported) {
|
|
779
|
-
const out = {};
|
|
780
|
-
for (const id of await objectIds(real, helpers, names, Object.keys(objects))) {
|
|
781
|
-
const name = names.get(id.toString()) ?? id.toString();
|
|
782
|
-
if (!touched.has(id.toString())) {
|
|
783
|
-
if (await typed(helpers).evictDurableObject(real.get(id)).then(() => true, () => false)) onIndirect(name);
|
|
784
|
-
if (!Object.hasOwn(objects, name)) continue;
|
|
785
|
-
}
|
|
786
|
-
const entries = touched.has(id.toString()) ? [...await typed(helpers).runInDurableObject(real.get(id), (_instance, state) => {
|
|
787
|
-
if (!takenOver.has(state.storage)) onUnsupported(`Durable Object ${name} was reset during the run and reconstructed for the snapshot; its constructor ran outside the simulation`);
|
|
788
|
-
return state.storage.list();
|
|
789
|
-
})] : Object.entries(Object.hasOwn(objects, name) ? objects[name] ?? {} : {});
|
|
790
|
-
Object.defineProperty(out, name, {
|
|
791
|
-
value: entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, value]) => ({
|
|
792
|
-
key,
|
|
793
|
-
value: toJson(value)
|
|
794
|
-
})),
|
|
795
|
-
enumerable: true,
|
|
796
|
-
writable: true,
|
|
797
|
-
configurable: true
|
|
798
|
-
});
|
|
799
|
-
}
|
|
800
|
-
return out;
|
|
801
|
-
}
|
|
802
|
-
// packages/cloudflare/src/scenario.ts
|
|
803
|
-
/**
|
|
804
|
-
* Typed construction of scenario specs for Cloudflare Workers. Everything here
|
|
805
|
-
* produces the plain-data `ScenarioSpec` from core; this module only knows the
|
|
806
|
-
* Cloudflare shapes (queues, D1 bindings) and the effect conventions the
|
|
807
|
-
* proxies follow.
|
|
808
|
-
*/
|
|
809
|
-
function http(requests, options = {}) {
|
|
810
|
-
return {
|
|
811
|
-
kind: "http",
|
|
812
|
-
requests: requests.map((r, i) => ({
|
|
813
|
-
id: r.id ?? `req-${i + 1}`,
|
|
814
|
-
method: (r.method ?? (r.body === void 0 ? "GET" : "POST")).toUpperCase(),
|
|
815
|
-
path: r.path,
|
|
816
|
-
headers: r.headers ?? {},
|
|
817
|
-
...r.body === void 0 ? {} : { body: r.body }
|
|
818
|
-
})),
|
|
819
|
-
retries: options.retries ?? 3,
|
|
820
|
-
retryOn: options.retryOn ?? "non-2xx",
|
|
821
|
-
...options.delaysMs === void 0 ? {} : { delaysMs: [...options.delaysMs] },
|
|
822
|
-
...options.deadlineMs === void 0 ? {} : { deadlineMs: options.deadlineMs }
|
|
823
|
-
};
|
|
824
|
-
}
|
|
825
|
-
/** The virtual delay before resend number `resend` (1 for the first), per the drive's caller. */
|
|
826
|
-
function retryDelayMs(drive, resend) {
|
|
827
|
-
const delays = drive.delaysMs ?? [];
|
|
828
|
-
return delays[Math.min(resend, delays.length) - 1] ?? 0;
|
|
829
|
-
}
|
|
830
|
-
function durableObject(binding, objects = {}, options = {}) {
|
|
831
|
-
return {
|
|
832
|
-
kind: "durable_object",
|
|
833
|
-
binding,
|
|
834
|
-
objects,
|
|
835
|
-
...options.alarmsPerObject === void 0 ? {} : { alarmsPerObject: options.alarmsPerObject }
|
|
836
|
-
};
|
|
837
|
-
}
|
|
838
|
-
/**
|
|
839
|
-
* The storage of one object (by the name its id was made from) as rows
|
|
840
|
-
* `{ key, value }`, for state invariants.
|
|
841
|
-
*/
|
|
842
|
-
function durableObjectRows(binding, object, where) {
|
|
843
|
-
const target = `DO:${binding}`;
|
|
844
|
-
return where ? {
|
|
845
|
-
target,
|
|
846
|
-
table: object,
|
|
847
|
-
where
|
|
848
|
-
} : {
|
|
849
|
-
target,
|
|
850
|
-
table: object
|
|
851
|
-
};
|
|
852
|
-
}
|
|
853
|
-
function queue(name, messages) {
|
|
854
|
-
return {
|
|
855
|
-
kind: "queue",
|
|
856
|
-
queue: name,
|
|
857
|
-
messages: messages.map((m, i) => ({
|
|
858
|
-
id: m.id ?? `msg-${i + 1}`,
|
|
859
|
-
body: m.body
|
|
860
|
-
}))
|
|
861
|
-
};
|
|
862
|
-
}
|
|
863
|
-
function d1Schema(binding, schemaFile) {
|
|
864
|
-
return {
|
|
865
|
-
kind: "d1",
|
|
866
|
-
binding,
|
|
867
|
-
schemaFile
|
|
868
|
-
};
|
|
869
|
-
}
|
|
870
|
-
/**
|
|
871
|
-
* Effect conventions for D1 (what the proxies record):
|
|
872
|
-
* call payload { args: { sql, params } }
|
|
873
|
-
* result payload { args: { sql, params }, result: { changes, lastRowId } }
|
|
874
|
-
* A committed write is a `result` whose `result.changes` is at least 1.
|
|
875
|
-
*/
|
|
876
|
-
function d1Write(binding, op = "run") {
|
|
877
|
-
return {
|
|
878
|
-
target: `D1:${binding}`,
|
|
879
|
-
op,
|
|
880
|
-
kind: "result",
|
|
881
|
-
atLeast: { "result.changes": 1 }
|
|
882
|
-
};
|
|
883
|
-
}
|
|
884
|
-
/** Reads of a D1 binding: `first` (result payload `{ row }`), `all` or `raw`. */
|
|
885
|
-
function d1Read(binding, op = "first") {
|
|
886
|
-
return {
|
|
887
|
-
target: `D1:${binding}`,
|
|
888
|
-
op,
|
|
889
|
-
kind: "result"
|
|
890
|
-
};
|
|
891
|
-
}
|
|
892
|
-
/** Dot path to the Nth bound parameter of a D1 statement, in an effect payload. */
|
|
893
|
-
function d1Param(index) {
|
|
894
|
-
return `args.params.${index}`;
|
|
895
|
-
}
|
|
896
|
-
/**
|
|
897
|
-
* The shell follows the core function `decision` (see the `refines`
|
|
898
|
-
* invariant): every selected effect carries out the latest decision of its
|
|
899
|
-
* invocation, agrees with it on `follows`, and, with `state`, was not made
|
|
900
|
-
* stale by another invocation's write between the read it rests on and the
|
|
901
|
-
* effect. The core function's module must be listed in the scenario's
|
|
902
|
-
* `specs`, which is what records its calls.
|
|
903
|
-
*/
|
|
904
|
-
function refines(name, decision, effect, options = {}) {
|
|
905
|
-
return {
|
|
906
|
-
kind: "refines",
|
|
907
|
-
name,
|
|
908
|
-
decision,
|
|
909
|
-
effect,
|
|
910
|
-
...options
|
|
911
|
-
};
|
|
912
|
-
}
|
|
913
|
-
function atMostOncePerKey(name, effect, key) {
|
|
914
|
-
return {
|
|
915
|
-
kind: "atMostOncePerKey",
|
|
916
|
-
name,
|
|
917
|
-
effect,
|
|
918
|
-
key
|
|
919
|
-
};
|
|
920
|
-
}
|
|
921
|
-
function atLeastOnce(name, effect, key, expected) {
|
|
922
|
-
return {
|
|
923
|
-
kind: "atLeastOnce",
|
|
924
|
-
name,
|
|
925
|
-
effect,
|
|
926
|
-
key,
|
|
927
|
-
expected
|
|
928
|
-
};
|
|
929
|
-
}
|
|
930
|
-
/**
|
|
931
|
-
* Every message's (or request's) `bodyKey` value must appear at least once
|
|
932
|
-
* as `key` in a selected effect: nothing the drive delivered may be lost.
|
|
933
|
-
*/
|
|
934
|
-
function atLeastOncePerMessage(name, drive, effect, key, bodyKey) {
|
|
935
|
-
const expected = [];
|
|
936
|
-
const items = drive.kind === "queue" ? drive.messages.map((m) => ({
|
|
937
|
-
id: m.id,
|
|
938
|
-
body: m.body
|
|
939
|
-
})) : drive.requests.map((r) => ({
|
|
940
|
-
id: r.id,
|
|
941
|
-
body: r.body ?? null
|
|
942
|
-
}));
|
|
943
|
-
for (const m of items) {
|
|
944
|
-
const v = getPath(m.body, bodyKey);
|
|
945
|
-
if (v === void 0) throw new Error(`${drive.kind} event ${m.id} has no ${JSON.stringify(bodyKey)} in its body`);
|
|
946
|
-
expected.push(v);
|
|
947
|
-
}
|
|
948
|
-
const perMessage = { bodyKey: drive.kind === "queue" ? bodyKey : bodyKey === "" ? "body" : `body.${bodyKey}` };
|
|
949
|
-
return {
|
|
950
|
-
...atLeastOnce(name, effect, key, expected),
|
|
951
|
-
perMessage
|
|
952
|
-
};
|
|
953
|
-
}
|
|
954
|
-
/**
|
|
955
|
-
* Selects the responses the Worker returned for a path (`ok` narrows to 2xx
|
|
956
|
-
* or to everything else). One `result` per attempt: a crash before the
|
|
957
|
-
* response leaves none, a thrown error records status 500.
|
|
958
|
-
*/
|
|
959
|
-
function httpResponse(path, options = {}) {
|
|
960
|
-
return {
|
|
961
|
-
target: `Http:${path}`,
|
|
962
|
-
op: "response",
|
|
963
|
-
kind: "result",
|
|
964
|
-
...options.ok === void 0 ? {} : { where: { "result.ok": options.ok } }
|
|
965
|
-
};
|
|
966
|
-
}
|
|
967
|
-
/** Rows of a D1 table in the end-of-run snapshot, optionally filtered. */
|
|
968
|
-
function d1Rows(binding, table, where) {
|
|
969
|
-
return where ? {
|
|
970
|
-
target: `D1:${binding}`,
|
|
971
|
-
table,
|
|
972
|
-
where
|
|
973
|
-
} : {
|
|
974
|
-
target: `D1:${binding}`,
|
|
975
|
-
table
|
|
976
|
-
};
|
|
977
|
-
}
|
|
978
|
-
/** Every row the query selects satisfies all conditions. */
|
|
979
|
-
function everyRow(name, query, holds) {
|
|
980
|
-
return {
|
|
981
|
-
kind: "everyRow",
|
|
982
|
-
name,
|
|
983
|
-
query,
|
|
984
|
-
holds
|
|
985
|
-
};
|
|
986
|
-
}
|
|
987
|
-
/** No two rows the query selects share the value at `path` (a column, or a dot path into the row). */
|
|
988
|
-
function unique(name, query, path) {
|
|
989
|
-
return {
|
|
990
|
-
kind: "unique",
|
|
991
|
-
name,
|
|
992
|
-
query,
|
|
993
|
-
path
|
|
994
|
-
};
|
|
995
|
-
}
|
|
996
|
-
/** Every selected effect has a row whose column equals the effect's key. */
|
|
997
|
-
function implies(name, when, key, state, column) {
|
|
998
|
-
return {
|
|
999
|
-
kind: "implies",
|
|
1000
|
-
name,
|
|
1001
|
-
when,
|
|
1002
|
-
key,
|
|
1003
|
-
state,
|
|
1004
|
-
column
|
|
1005
|
-
};
|
|
1006
|
-
}
|
|
1007
|
-
/** Selects the acknowledgement that took effect for each message (explicit or implicit; not one ignored after a retry). */
|
|
1008
|
-
function queueAck(queueName) {
|
|
1009
|
-
return {
|
|
1010
|
-
target: `Queue:${queueName}`,
|
|
1011
|
-
op: "ack",
|
|
1012
|
-
kind: "result",
|
|
1013
|
-
where: { "result.effective": true }
|
|
1014
|
-
};
|
|
1015
|
-
}
|
|
1016
|
-
/**
|
|
1017
|
-
* Declare an external service: requests to `host` are answered from
|
|
1018
|
-
* `responses` (every request gets 200 and an empty body when omitted), and
|
|
1019
|
-
* `dedupeBy` names the header whose value makes repeated requests
|
|
1020
|
-
* idempotent at that service.
|
|
1021
|
-
*/
|
|
1022
|
-
function external(name, host, options = {}) {
|
|
1023
|
-
return {
|
|
1024
|
-
name,
|
|
1025
|
-
host,
|
|
1026
|
-
guarantees: options.dedupeBy ? { dedupeBy: options.dedupeBy } : {},
|
|
1027
|
-
...options.responses ? { responses: options.responses } : {}
|
|
1028
|
-
};
|
|
1029
|
-
}
|
|
1030
|
-
/**
|
|
1031
|
-
* Selects the requests to an external that took effect: a request replayed
|
|
1032
|
-
* under a dedupe key the external had already seen is not counted.
|
|
1033
|
-
*/
|
|
1034
|
-
function fetchCall(externalName, method) {
|
|
1035
|
-
return {
|
|
1036
|
-
target: `Fetch:${externalName}`,
|
|
1037
|
-
...method ? { op: method.toUpperCase() } : {},
|
|
1038
|
-
kind: "result",
|
|
1039
|
-
where: { "result.effective": true }
|
|
1040
|
-
};
|
|
1041
|
-
}
|
|
1042
|
-
function validateHttpDrive(drive) {
|
|
1043
|
-
const errors = [];
|
|
1044
|
-
if (drive.requests.length === 0) errors.push("http drive needs at least one request");
|
|
1045
|
-
const ids = /* @__PURE__ */ new Set();
|
|
1046
|
-
drive.requests.forEach((r, i) => {
|
|
1047
|
-
if (!r.path.startsWith("/")) errors.push(`requests[${i}].path must start with "/"`);
|
|
1048
|
-
if (!r.method) errors.push(`requests[${i}].method must not be empty`);
|
|
1049
|
-
if (ids.has(r.id)) errors.push(`duplicate request id ${JSON.stringify(r.id)}`);
|
|
1050
|
-
ids.add(r.id);
|
|
1051
|
-
if ((r.method === "GET" || r.method === "HEAD") && r.body !== void 0) errors.push(`requests[${i}] is a ${r.method} and cannot carry a body`);
|
|
1052
|
-
});
|
|
1053
|
-
if (!(Number.isInteger(drive.retries) && drive.retries >= 0)) errors.push("http drive retries must be a non-negative integer");
|
|
1054
|
-
(drive.delaysMs ?? []).forEach((d, i) => {
|
|
1055
|
-
if (!(Number.isInteger(d) && d >= 0)) errors.push(`http drive delaysMs[${i}] must be a non-negative integer`);
|
|
1056
|
-
});
|
|
1057
|
-
if (drive.deadlineMs !== void 0 && !(Number.isInteger(drive.deadlineMs) && drive.deadlineMs > 0)) errors.push("http drive deadlineMs must be a positive integer");
|
|
1058
|
-
return errors;
|
|
1059
|
-
}
|
|
1060
|
-
/** Build and validate a scenario spec; throws with every problem listed. */
|
|
1061
|
-
function defineScenario(input) {
|
|
1062
|
-
const drive = input.drive.kind === "http" ? input.drive : "messages" in input.drive && input.drive.messages.every((m) => "id" in m && typeof m.id === "string") ? input.drive : queue(input.drive.queue, input.drive.messages);
|
|
1063
|
-
const spec = {
|
|
1064
|
-
version: 1,
|
|
1065
|
-
name: input.name,
|
|
1066
|
-
platform: "cloudflare",
|
|
1067
|
-
worker: input.worker,
|
|
1068
|
-
drive,
|
|
1069
|
-
setup: input.setup ?? [],
|
|
1070
|
-
externals: input.externals ?? [],
|
|
1071
|
-
invariants: input.invariants,
|
|
1072
|
-
bounds: {
|
|
1073
|
-
...defaultBounds,
|
|
1074
|
-
...input.bounds
|
|
1075
|
-
},
|
|
1076
|
-
...input.specs ? { specs: input.specs } : {}
|
|
1077
|
-
};
|
|
1078
|
-
const errors = [...validateScenario(spec), ...drive.kind === "http" ? validateHttpDrive(drive) : []];
|
|
1079
|
-
if (errors.length > 0) throw new Error(`invalid scenario ${JSON.stringify(input.name)}:\n- ${errors.join("\n- ")}`);
|
|
1080
|
-
return spec;
|
|
1081
|
-
}
|
|
1082
|
-
// packages/cloudflare/src/platform.ts
|
|
1083
|
-
const ACK = ["crash_before", "crash_after"];
|
|
1084
|
-
const CUT_OFF = ["cut_off"];
|
|
1085
|
-
/** The response point: a crash before it is a response the caller never saw. */
|
|
1086
|
-
const RESPOND = ["crash_before"];
|
|
1087
|
-
/**
|
|
1088
|
-
* With a caller deadline the answer can also arrive too late: `ambiguous`
|
|
1089
|
-
* here means it was sent, the caller counted it as failed, and the handler
|
|
1090
|
-
* carried on.
|
|
1091
|
-
*/
|
|
1092
|
-
const RESPOND_WITH_DEADLINE = ["crash_before", "ambiguous"];
|
|
1093
|
-
/** The URL inbound requests are addressed to; handlers read only the path. */
|
|
1094
|
-
const requestOrigin = "https://worker.test";
|
|
1095
|
-
/** Build the `Request` a drive entry describes. */
|
|
1096
|
-
function requestFor(r) {
|
|
1097
|
-
const headers = new Headers(r.headers);
|
|
1098
|
-
let body = null;
|
|
1099
|
-
if (r.body !== void 0) {
|
|
1100
|
-
if (typeof r.body === "string") body = r.body;
|
|
1101
|
-
else {
|
|
1102
|
-
body = JSON.stringify(r.body);
|
|
1103
|
-
if (!headers.has("content-type")) headers.set("content-type", "application/json");
|
|
1104
|
-
}
|
|
1105
|
-
}
|
|
1106
|
-
return new Request(`${requestOrigin}${r.path}`, {
|
|
1107
|
-
method: r.method,
|
|
1108
|
-
headers,
|
|
1109
|
-
body
|
|
1110
|
-
});
|
|
1111
|
-
}
|
|
1112
|
-
/** A compact record of a response for the effect log: status, ok, and a bounded body. */
|
|
1113
|
-
async function summarizeResponse(response) {
|
|
1114
|
-
const text = await response.clone().text();
|
|
1115
|
-
let body = text.length > 1e3 ? `${text.slice(0, 1e3)}…` : text;
|
|
1116
|
-
if (text && (response.headers.get("content-type") ?? "").includes("json")) try {
|
|
1117
|
-
body = JSON.parse(text);
|
|
1118
|
-
} catch {}
|
|
1119
|
-
return {
|
|
1120
|
-
status: response.status,
|
|
1121
|
-
ok: response.ok,
|
|
1122
|
-
body
|
|
1123
|
-
};
|
|
1124
|
-
}
|
|
1125
|
-
function isD1$1(value) {
|
|
1126
|
-
return typeof value === "object" && value !== null && typeof value.prepare === "function" && typeof value.batch === "function";
|
|
1127
|
-
}
|
|
1128
|
-
function isBindingLike(value) {
|
|
1129
|
-
if (typeof value === "function") return true;
|
|
1130
|
-
if (typeof value !== "object" || value === null) return false;
|
|
1131
|
-
const proto = Object.getPrototypeOf(value);
|
|
1132
|
-
return [...Object.getOwnPropertyNames(value), ...Object.getOwnPropertyNames(proto ?? {})].some((k) => k !== "constructor" && typeof value[k] === "function");
|
|
1133
|
-
}
|
|
1134
|
-
/** Deep-copy JSON data so a handler that mutates its message cannot leak into other runs. */
|
|
1135
|
-
function cloneJson(value) {
|
|
1136
|
-
return JSON.parse(JSON.stringify(value));
|
|
1137
|
-
}
|
|
1138
|
-
const assumptions = [
|
|
1139
|
-
"platform model: Cloudflare Queues at-least-once delivery; the first ack or retry decision per message wins; unacked messages are redelivered up to max_retries then dead-lettered",
|
|
1140
|
-
"D1 statements run against Miniflare's SQLite; each run/first/all/raw/batch/exec is one effect",
|
|
1141
|
-
"message.timestamp is the virtual clock's time at delivery",
|
|
1142
|
-
"only D1 and Durable Object bindings are proxied; touching any other binding makes the run UNSUPPORTED",
|
|
1143
|
-
"Durable Objects are the real objects workerd runs (storage, transactions, input and output gates are the runtime's own); each stub call is one effect: crash_before or error means it never reached the object, ambiguous means the object committed and the caller lost the answer, crash_after means the caller died after it; in a concurrent run an object's own outbound I/O during a call is a turn, so another event may enter the object meanwhile (its input gate is open then), except while it holds the gate with blockConcurrencyWhile, when its effects run at once; storage operations are not turns (the input gate holds other events during them); the object's own binding calls are not recorded; objects are cleared, seeded and evicted before each run and their storage is snapshotted after it (developers.cloudflare.com/durable-objects/api/storage-api/)",
|
|
1144
|
-
"Durable Object alarms are taken over so none is scheduled on the real clock and fire in virtual time: one alarm per object, a later setAlarm replaces it, setAlarm in a transaction applies on commit, the alarm survives eviction, alarm() is one effect (crash_before: it never ran; crash_after: it ran and counts as failed; error: it threw), and a failed alarm is retried after 2 s, 4 s, 8 s ... up to six retries and maxRedeliveries, with retryCount and isRetry (developers.cloudflare.com/durable-objects/api/base/#alarm); each object's alarm fires at most alarmsPerObject times per run (default 3)",
|
|
1145
|
-
"state invariants read a snapshot of every D1 binding named in setup, taken after the last event",
|
|
1146
|
-
"work passed to ctx.waitUntil runs after the handler returns and never affects acknowledgement or the response; a cut_off fault at that point loses work not yet started, and an effect in flight commits without its continuation",
|
|
1147
|
-
"concurrent invocations (maxConcurrentInvocations above 1) share one isolate's module state and bindings, and another may run while one awaits I/O (developers.cloudflare.com/workers/reference/how-workers-works/); queue consumers run concurrently up to max_concurrency (developers.cloudflare.com/queues/configuration/consumer-concurrency/)",
|
|
1148
|
-
"inbound requests: one invocation per attempt; an uncaught exception is a 500 response; the drive's caller resends a request it got no acceptable response for (crash before the response, an answer after its deadlineMs, or a status its retryOn policy rejects) up to its retries, each resend after its delaysMs entry of virtual time; the handler's own time is virtual, so a late answer is the ambiguous fault at the response point or an answer later than deadlineMs in virtual time"
|
|
1149
|
-
];
|
|
1150
|
-
function createCloudflarePlatform(options) {
|
|
1151
|
-
const env = options.env;
|
|
1152
|
-
const maxRetries = options.maxRetries ?? 3;
|
|
1153
|
-
let hooksRef = null;
|
|
1154
|
-
const ctx = {
|
|
1155
|
-
get hooks() {
|
|
1156
|
-
if (!hooksRef) throw new Error("no run in progress");
|
|
1157
|
-
return hooksRef;
|
|
1158
|
-
},
|
|
1159
|
-
currentInvocation: () => ctx.hooks.running()
|
|
1160
|
-
};
|
|
1161
|
-
const d1Proxies = /* @__PURE__ */ new Map();
|
|
1162
|
-
const doProxies = /* @__PURE__ */ new Map();
|
|
1163
|
-
/** The Durable Object bindings the current scenario's setup resets before each run. */
|
|
1164
|
-
let resetBindings = /* @__PURE__ */ new Set();
|
|
1165
|
-
/** Per binding, what the current run knows about its objects. */
|
|
1166
|
-
const bindingStates = /* @__PURE__ */ new Map();
|
|
1167
|
-
const stateFor = (binding) => {
|
|
1168
|
-
let state = bindingStates.get(binding);
|
|
1169
|
-
if (!state) {
|
|
1170
|
-
state = new BindingState();
|
|
1171
|
-
bindingStates.set(binding, state);
|
|
1172
|
-
}
|
|
1173
|
-
return state;
|
|
1174
|
-
};
|
|
1175
|
-
/** Per binding, alarm firings allowed per object in the current run. */
|
|
1176
|
-
let alarmLimits = /* @__PURE__ */ new Map();
|
|
1177
|
-
const namespace = (binding) => {
|
|
1178
|
-
const real = env[binding];
|
|
1179
|
-
if (!isDurableObjectNamespace(real)) throw new Error(`env.${binding} is not a Durable Object namespace`);
|
|
1180
|
-
return real;
|
|
1181
|
-
};
|
|
1182
|
-
const helpers = () => {
|
|
1183
|
-
if (!options.durableObjects) throw new Error("Durable Object setup needs the Cloudflare test helpers: createCloudflarePlatform({ ..., durableObjects: await import(\"cloudflare:test\") })");
|
|
1184
|
-
return options.durableObjects;
|
|
1185
|
-
};
|
|
1186
|
-
const proxiedEnv = new Proxy(env, { get(target, prop, receiver) {
|
|
1187
|
-
const value = Reflect.get(target, prop, receiver);
|
|
1188
|
-
if (typeof prop !== "string") return value;
|
|
1189
|
-
if (isD1$1(value)) {
|
|
1190
|
-
let p = d1Proxies.get(prop);
|
|
1191
|
-
if (!p) {
|
|
1192
|
-
p = proxyD1(value, prop, ctx);
|
|
1193
|
-
d1Proxies.set(prop, p);
|
|
1194
|
-
}
|
|
1195
|
-
return p;
|
|
1196
|
-
}
|
|
1197
|
-
if (isDurableObjectNamespace(value)) {
|
|
1198
|
-
let p = doProxies.get(prop);
|
|
1199
|
-
if (!p) {
|
|
1200
|
-
p = proxyNamespace(value, prop, ctx, stateFor(prop), options.durableObjects, () => resetBindings.has(prop));
|
|
1201
|
-
doProxies.set(prop, p);
|
|
1202
|
-
}
|
|
1203
|
-
return p;
|
|
1204
|
-
}
|
|
1205
|
-
if (isBindingLike(value)) ctx.hooks.unsupported(`binding ${prop} is not proxied`);
|
|
1206
|
-
return value;
|
|
1207
|
-
} });
|
|
1208
|
-
/** Platform-level actions (dead-lettering) are recorded under an invocation no fault can crash. */
|
|
1209
|
-
const platformInvocations = /* @__PURE__ */ new WeakMap();
|
|
1210
|
-
function platformInvocation(hooks) {
|
|
1211
|
-
let id = platformInvocations.get(hooks);
|
|
1212
|
-
if (id === void 0) {
|
|
1213
|
-
id = "platform";
|
|
1214
|
-
hooks.startInvocation(id, { bookkeeping: true });
|
|
1215
|
-
platformInvocations.set(hooks, id);
|
|
1216
|
-
}
|
|
1217
|
-
return id;
|
|
1218
|
-
}
|
|
1219
|
-
return {
|
|
1220
|
-
name: "cloudflare",
|
|
1221
|
-
assumptions,
|
|
1222
|
-
concurrent: true,
|
|
1223
|
-
async reset(spec) {
|
|
1224
|
-
resetBindings = new Set(spec.setup.filter((s) => s.kind === "durable_object").map((s) => String(s["binding"])));
|
|
1225
|
-
for (const state of bindingStates.values()) state.clear();
|
|
1226
|
-
alarmLimits = new Map(spec.setup.filter((s) => s.kind === "durable_object").map((s) => [String(s["binding"]), s.alarmsPerObject ?? 3]));
|
|
1227
|
-
for (const step of spec.setup) {
|
|
1228
|
-
if (step.kind === "durable_object") {
|
|
1229
|
-
const setup = step;
|
|
1230
|
-
await resetNamespace(namespace(setup.binding), helpers(), stateFor(setup.binding).names, setup.objects);
|
|
1231
|
-
continue;
|
|
1232
|
-
}
|
|
1233
|
-
if (step.kind !== "d1") continue;
|
|
1234
|
-
const binding = String(step["binding"]);
|
|
1235
|
-
const schema = options.schemas[binding];
|
|
1236
|
-
if (schema === void 0) throw new Error(`no schema provided for D1 binding ${binding}`);
|
|
1237
|
-
const real = env[binding];
|
|
1238
|
-
if (!isD1$1(real)) throw new Error(`env.${binding} is not a D1 binding`);
|
|
1239
|
-
await resetD1(real, schema);
|
|
1240
|
-
}
|
|
1241
|
-
},
|
|
1242
|
-
restrictEvents(spec, keepIds) {
|
|
1243
|
-
const drive = spec.drive;
|
|
1244
|
-
if (drive.kind === "http") return {
|
|
1245
|
-
...spec,
|
|
1246
|
-
drive: {
|
|
1247
|
-
...drive,
|
|
1248
|
-
requests: drive.requests.filter((r) => keepIds.includes(r.id))
|
|
1249
|
-
}
|
|
1250
|
-
};
|
|
1251
|
-
return {
|
|
1252
|
-
...spec,
|
|
1253
|
-
drive: {
|
|
1254
|
-
...drive,
|
|
1255
|
-
messages: drive.messages.filter((m) => keepIds.includes(m.id))
|
|
1256
|
-
}
|
|
1257
|
-
};
|
|
1258
|
-
},
|
|
1259
|
-
async finish(spec, hooks) {
|
|
1260
|
-
for (const step of spec.setup) {
|
|
1261
|
-
if (step.kind === "durable_object") {
|
|
1262
|
-
const setup = step;
|
|
1263
|
-
const binding = setup.binding;
|
|
1264
|
-
const tables = await snapshotNamespace(namespace(binding), helpers(), stateFor(binding).names, stateFor(binding).touched, setup.objects, (object) => hooks.unsupported(`Durable Object ${binding} ${object} was reached without a call Eutaxy saw (through another object's binding); calls between objects are not proxied yet`), (reason) => hooks.unsupported(reason));
|
|
1265
|
-
hooks.snapshot(platformInvocation(hooks), `DO:${binding}`, { tables });
|
|
1266
|
-
continue;
|
|
1267
|
-
}
|
|
1268
|
-
if (step.kind !== "d1") continue;
|
|
1269
|
-
const binding = String(step["binding"]);
|
|
1270
|
-
const real = env[binding];
|
|
1271
|
-
if (!isD1$1(real)) continue;
|
|
1272
|
-
const tables = await snapshotD1(real);
|
|
1273
|
-
hooks.snapshot(platformInvocation(hooks), `D1:${binding}`, { tables });
|
|
1274
|
-
}
|
|
1275
|
-
},
|
|
1276
|
-
initialEvents(spec) {
|
|
1277
|
-
const drive = spec.drive;
|
|
1278
|
-
if (drive.kind === "http") return drive.requests.map((r) => ({
|
|
1279
|
-
id: r.id,
|
|
1280
|
-
attempt: 1,
|
|
1281
|
-
data: r
|
|
1282
|
-
}));
|
|
1283
|
-
return drive.messages.map((m) => ({
|
|
1284
|
-
id: m.id,
|
|
1285
|
-
attempt: 1,
|
|
1286
|
-
data: m.body
|
|
1287
|
-
}));
|
|
1288
|
-
},
|
|
1289
|
-
async deliver(event, hooks, spec) {
|
|
1290
|
-
const drive = spec.drive;
|
|
1291
|
-
const invocation = `${event.id}#${event.attempt}`;
|
|
1292
|
-
hooksRef = hooks;
|
|
1293
|
-
if (event.source === "durable_object_alarm") {
|
|
1294
|
-
const binding = String(event.data.binding ?? "");
|
|
1295
|
-
return deliverAlarm(event, hooks, spec.bounds.maxRedeliveries, {
|
|
1296
|
-
binding,
|
|
1297
|
-
book: stateFor(binding).alarms,
|
|
1298
|
-
limit: alarmLimits.get(binding) ?? 3,
|
|
1299
|
-
runAlarm: alarmRunner(namespace(binding), binding, ctx, options.durableObjects, stateFor(binding)),
|
|
1300
|
-
abort: (id) => stateFor(binding).abort(id),
|
|
1301
|
-
mayPark: (id) => stateFor(binding).mayPark(id),
|
|
1302
|
-
evict: (id) => evictObject(namespace(binding), options.durableObjects, id),
|
|
1303
|
-
bookkeep: (op, args) => hooks.effectSync({
|
|
1304
|
-
invocation: platformInvocation(hooks),
|
|
1305
|
-
target: `DO:${binding}`,
|
|
1306
|
-
op,
|
|
1307
|
-
args,
|
|
1308
|
-
allowed: []
|
|
1309
|
-
}, () => null, () => null)
|
|
1310
|
-
});
|
|
1311
|
-
}
|
|
1312
|
-
return drive.kind === "http" ? await deliverRequest(event, hooks, spec, drive, invocation) : await deliverMessage(event, hooks, spec, drive, invocation);
|
|
1313
|
-
}
|
|
1314
|
-
};
|
|
1315
|
-
/** The `ExecutionContext` handed to a handler; `waitUntil` work is collected to run after it returns. */
|
|
1316
|
-
function executionContext(background) {
|
|
1317
|
-
return {
|
|
1318
|
-
waitUntil: (promise) => {
|
|
1319
|
-
background.push(promise.then(() => void 0, () => void 0));
|
|
1320
|
-
},
|
|
1321
|
-
passThroughOnException: () => {},
|
|
1322
|
-
props: {}
|
|
1323
|
-
};
|
|
1324
|
-
}
|
|
1325
|
-
/**
|
|
1326
|
-
* Background work extends the invocation but never changes the acknowledgement or the response.
|
|
1327
|
-
* A cut-off here is the isolate dying after them: work not yet started is lost.
|
|
1328
|
-
*/
|
|
1329
|
-
async function drainBackground(hooks, inv, invocation, target, background) {
|
|
1330
|
-
if (background.length === 0 || inv.isCrashed()) return false;
|
|
1331
|
-
try {
|
|
1332
|
-
hooks.effectSync({
|
|
1333
|
-
invocation,
|
|
1334
|
-
target,
|
|
1335
|
-
op: "background",
|
|
1336
|
-
args: { pending: background.length },
|
|
1337
|
-
allowed: CUT_OFF
|
|
1338
|
-
}, () => null, () => null);
|
|
1339
|
-
await Promise.race([hooks.settle(Promise.all(background), invocation), inv.crashed]);
|
|
1340
|
-
return false;
|
|
1341
|
-
} catch (err) {
|
|
1342
|
-
if (!(err instanceof CrashSignal)) throw err;
|
|
1343
|
-
return true;
|
|
1344
|
-
}
|
|
1345
|
-
}
|
|
1346
|
-
async function deliverRequest(event, hooks, spec, drive, invocation) {
|
|
1347
|
-
const req = event.data;
|
|
1348
|
-
const target = `Http:${req.path}`;
|
|
1349
|
-
const inv = hooks.startInvocation(invocation);
|
|
1350
|
-
const started = Date.now();
|
|
1351
|
-
const background = [];
|
|
1352
|
-
const handler = options.handler.fetch;
|
|
1353
|
-
if (!handler) throw new Error("the Worker has no fetch() handler");
|
|
1354
|
-
const args = {
|
|
1355
|
-
requestId: event.id,
|
|
1356
|
-
method: req.method,
|
|
1357
|
-
path: req.path
|
|
1358
|
-
};
|
|
1359
|
-
const deadline = drive.deadlineMs;
|
|
1360
|
-
const lateAt = deadline === void 0 ? void 0 : started + deadline;
|
|
1361
|
-
/** The caller decides once: it accepts the answer, or gives up at `at` and resends or stops. */
|
|
1362
|
-
let decided = false;
|
|
1363
|
-
const giveUp = (at) => {
|
|
1364
|
-
if (decided) return;
|
|
1365
|
-
decided = true;
|
|
1366
|
-
const redeliveries = event.attempt - 1;
|
|
1367
|
-
if (redeliveries < drive.retries && redeliveries < spec.bounds.maxRedeliveries) {
|
|
1368
|
-
const resendAt = Math.max(at + retryDelayMs(drive, event.attempt), Date.now());
|
|
1369
|
-
hooks.enqueue({
|
|
1370
|
-
...event,
|
|
1371
|
-
attempt: event.attempt + 1,
|
|
1372
|
-
...resendAt > Date.now() ? { at: resendAt } : {}
|
|
1373
|
-
});
|
|
1374
|
-
} else hooks.effectSync({
|
|
1375
|
-
invocation: platformInvocation(hooks),
|
|
1376
|
-
target,
|
|
1377
|
-
op: "gave_up",
|
|
1378
|
-
args: {
|
|
1379
|
-
requestId: event.id,
|
|
1380
|
-
attempts: event.attempt
|
|
1381
|
-
},
|
|
1382
|
-
allowed: []
|
|
1383
|
-
}, () => null, () => null);
|
|
1384
|
-
};
|
|
1385
|
-
const deadlineTimer = deadline === void 0 || lateAt === void 0 ? void 0 : setTimeout(() => giveUp(lateAt), deadline);
|
|
1386
|
-
let response;
|
|
1387
|
-
const outcome = Promise.resolve().then(() => handler.call(options.handler, requestFor(req), proxiedEnv, executionContext(background))).then((r) => {
|
|
1388
|
-
response = r;
|
|
1389
|
-
return "completed";
|
|
1390
|
-
}, (err) => err instanceof CrashSignal ? "crashed" : "errored");
|
|
1391
|
-
let status = await Promise.race([hooks.settle(outcome, invocation), inv.crashed.then(() => "crashed")]);
|
|
1392
|
-
let summary = null;
|
|
1393
|
-
let read = "errored";
|
|
1394
|
-
if (status === "completed" && response) {
|
|
1395
|
-
read = await Promise.race([hooks.settle(summarizeResponse(response), invocation).then((s) => s, (err) => err instanceof CrashSignal ? "crashed" : "errored"), inv.crashed.then(() => "crashed")]);
|
|
1396
|
-
if (read === "crashed" || read === "errored") status = read;
|
|
1397
|
-
}
|
|
1398
|
-
let late = lateAt !== void 0 && Date.now() > lateAt;
|
|
1399
|
-
const allowed = deadline === void 0 ? RESPOND : RESPOND_WITH_DEADLINE;
|
|
1400
|
-
if (status === "completed" && typeof read === "object") {
|
|
1401
|
-
const s = read;
|
|
1402
|
-
try {
|
|
1403
|
-
hooks.effectSync({
|
|
1404
|
-
invocation,
|
|
1405
|
-
target,
|
|
1406
|
-
op: "response",
|
|
1407
|
-
args,
|
|
1408
|
-
allowed
|
|
1409
|
-
}, () => s, (v) => v);
|
|
1410
|
-
summary = s;
|
|
1411
|
-
} catch (err) {
|
|
1412
|
-
if (err instanceof CrashSignal) status = "crashed";
|
|
1413
|
-
else if (err instanceof InjectedEffectError) {
|
|
1414
|
-
summary = s;
|
|
1415
|
-
late = true;
|
|
1416
|
-
} else throw err;
|
|
1417
|
-
}
|
|
1418
|
-
} else if (status === "errored") {
|
|
1419
|
-
const s = {
|
|
1420
|
-
status: 500,
|
|
1421
|
-
ok: false,
|
|
1422
|
-
body: ""
|
|
1423
|
-
};
|
|
1424
|
-
hooks.effectSync({
|
|
1425
|
-
invocation,
|
|
1426
|
-
target,
|
|
1427
|
-
op: "response",
|
|
1428
|
-
args,
|
|
1429
|
-
allowed: []
|
|
1430
|
-
}, () => s, (v) => v);
|
|
1431
|
-
summary = s;
|
|
1432
|
-
}
|
|
1433
|
-
if (deadlineTimer !== void 0) clearTimeout(deadlineTimer);
|
|
1434
|
-
if (summary !== null && !late && (drive.retryOn === "5xx" ? summary.status < 500 : summary.ok)) decided = true;
|
|
1435
|
-
else giveUp(late && lateAt !== void 0 ? lateAt : Date.now());
|
|
1436
|
-
if (await drainBackground(hooks, inv, invocation, target, background)) status = "crashed";
|
|
1437
|
-
return {
|
|
1438
|
-
status,
|
|
1439
|
-
followUps: []
|
|
1440
|
-
};
|
|
1441
|
-
}
|
|
1442
|
-
async function deliverMessage(event, hooks, spec, drive, invocation) {
|
|
1443
|
-
{
|
|
1444
|
-
const queueTarget = `Queue:${drive.queue}`;
|
|
1445
|
-
const inv = hooks.startInvocation(invocation);
|
|
1446
|
-
/** Cloudflare honours the first ack or retry decision per message; later ones are ignored. */
|
|
1447
|
-
const state = { decision: null };
|
|
1448
|
-
const background = [];
|
|
1449
|
-
/** Records the call; the result says whether it took effect (the first decision wins). */
|
|
1450
|
-
const decide = (op, args) => {
|
|
1451
|
-
hooks.effectSync({
|
|
1452
|
-
invocation,
|
|
1453
|
-
target: queueTarget,
|
|
1454
|
-
op,
|
|
1455
|
-
args,
|
|
1456
|
-
allowed: ACK
|
|
1457
|
-
}, () => {
|
|
1458
|
-
if (state.decision !== null) return false;
|
|
1459
|
-
state.decision = op;
|
|
1460
|
-
return true;
|
|
1461
|
-
}, (effective) => ({ effective }));
|
|
1462
|
-
};
|
|
1463
|
-
const message = {
|
|
1464
|
-
id: event.id,
|
|
1465
|
-
timestamp: /* @__PURE__ */ new Date(),
|
|
1466
|
-
body: cloneJson(event.data),
|
|
1467
|
-
attempts: event.attempt,
|
|
1468
|
-
ack: () => decide("ack", {
|
|
1469
|
-
messageId: event.id,
|
|
1470
|
-
implicit: false,
|
|
1471
|
-
body: event.data
|
|
1472
|
-
}),
|
|
1473
|
-
retry: () => decide("retry", {
|
|
1474
|
-
messageId: event.id,
|
|
1475
|
-
body: event.data
|
|
1476
|
-
})
|
|
1477
|
-
};
|
|
1478
|
-
const batch = {
|
|
1479
|
-
queue: drive.queue,
|
|
1480
|
-
messages: [message],
|
|
1481
|
-
metadata: { metrics: {
|
|
1482
|
-
backlogCount: 0,
|
|
1483
|
-
backlogBytes: 0
|
|
1484
|
-
} },
|
|
1485
|
-
ackAll: () => message.ack(),
|
|
1486
|
-
retryAll: () => message.retry()
|
|
1487
|
-
};
|
|
1488
|
-
const execution = executionContext(background);
|
|
1489
|
-
const handler = options.handler.queue;
|
|
1490
|
-
if (!handler) throw new Error("the Worker has no queue() handler");
|
|
1491
|
-
const outcome = Promise.resolve().then(() => handler.call(options.handler, batch, proxiedEnv, execution)).then(() => "completed", (err) => err instanceof CrashSignal ? "crashed" : "errored");
|
|
1492
|
-
let status = await Promise.race([hooks.settle(outcome, invocation), inv.crashed.then(() => "crashed")]);
|
|
1493
|
-
if (status === "completed" && state.decision === null) try {
|
|
1494
|
-
decide("ack", {
|
|
1495
|
-
messageId: event.id,
|
|
1496
|
-
implicit: true,
|
|
1497
|
-
body: event.data
|
|
1498
|
-
});
|
|
1499
|
-
} catch (err) {
|
|
1500
|
-
if (err instanceof CrashSignal) status = "crashed";
|
|
1501
|
-
else throw err;
|
|
1502
|
-
}
|
|
1503
|
-
if (await drainBackground(hooks, inv, invocation, queueTarget, background)) status = "crashed";
|
|
1504
|
-
const followUps = [];
|
|
1505
|
-
if (state.decision !== "ack") {
|
|
1506
|
-
const redeliveries = event.attempt - 1;
|
|
1507
|
-
if (event.attempt <= maxRetries && redeliveries < spec.bounds.maxRedeliveries) followUps.push({
|
|
1508
|
-
...event,
|
|
1509
|
-
attempt: event.attempt + 1
|
|
1510
|
-
});
|
|
1511
|
-
else hooks.effectSync({
|
|
1512
|
-
invocation: platformInvocation(hooks),
|
|
1513
|
-
target: queueTarget,
|
|
1514
|
-
op: "dead_letter",
|
|
1515
|
-
args: {
|
|
1516
|
-
messageId: event.id,
|
|
1517
|
-
attempts: event.attempt
|
|
1518
|
-
},
|
|
1519
|
-
allowed: []
|
|
1520
|
-
}, () => null, () => null);
|
|
1521
|
-
}
|
|
1522
|
-
return {
|
|
1523
|
-
status,
|
|
1524
|
-
followUps
|
|
1525
|
-
};
|
|
1526
|
-
}
|
|
1527
|
-
}
|
|
1528
|
-
}
|
|
1529
|
-
// packages/cloudflare/src/differential.ts
|
|
1530
|
-
/**
|
|
1531
|
-
* Differential check: the same fault-free scenario run once through Eutaxy's
|
|
1532
|
-
* proxies and once against the raw bindings, with the queue model (or the
|
|
1533
|
-
* HTTP caller's retry policy) applied by hand on the raw side. Any difference in the per-attempt decisions or in
|
|
1534
|
-
* the final D1 state is a bug in the proxies or the platform model, not in
|
|
1535
|
-
* the Worker. The raw side shares Eutaxy's *reading* of Cloudflare's queue
|
|
1536
|
-
* semantics; what it does not share is any proxy code.
|
|
1537
|
-
*/
|
|
1538
|
-
/** The raw side cannot abandon an invocation the way the engine does; a stuck handler ends the comparison. */
|
|
1539
|
-
var StuckError = class extends Error {
|
|
1540
|
-
name = "StuckError";
|
|
1541
|
-
constructor(message = "the handler is waiting on something outside the run (no timer due, no effect in flight)") {
|
|
1542
|
-
super(message);
|
|
1543
|
-
}
|
|
1544
|
-
};
|
|
1545
|
-
/**
|
|
1546
|
-
* The raw side's only wrapper: counts D1 calls in flight (so the settle loop
|
|
1547
|
-
* knows real I/O is pending) and advances the clock as the proxies do. It
|
|
1548
|
-
* records nothing and injects nothing.
|
|
1549
|
-
*/
|
|
1550
|
-
function countingD1(real, io, clock) {
|
|
1551
|
-
const realOf = /* @__PURE__ */ new WeakMap();
|
|
1552
|
-
const track = async (p) => {
|
|
1553
|
-
io.n++;
|
|
1554
|
-
try {
|
|
1555
|
-
return await p;
|
|
1556
|
-
} finally {
|
|
1557
|
-
io.n--;
|
|
1558
|
-
clock.advance(1);
|
|
1559
|
-
}
|
|
1560
|
-
};
|
|
1561
|
-
const wrapStatement = (s) => {
|
|
1562
|
-
const proxy = new Proxy(s, { get(t, prop, r) {
|
|
1563
|
-
const v = Reflect.get(t, prop, r);
|
|
1564
|
-
if (prop === "bind") return (...a) => wrapStatement(t.bind(...a));
|
|
1565
|
-
if (prop === "run" || prop === "all" || prop === "first" || prop === "raw") return (...a) => track(v.apply(t, a));
|
|
1566
|
-
return typeof v === "function" ? v.bind(t) : v;
|
|
1567
|
-
} });
|
|
1568
|
-
realOf.set(proxy, s);
|
|
1569
|
-
return proxy;
|
|
1570
|
-
};
|
|
1571
|
-
return new Proxy(real, { get(t, prop, r) {
|
|
1572
|
-
const v = Reflect.get(t, prop, r);
|
|
1573
|
-
if (prop === "prepare") return (sql) => wrapStatement(t.prepare(sql));
|
|
1574
|
-
if (prop === "batch") return (stmts) => track(t.batch(stmts.map((s) => realOf.get(s) ?? s)));
|
|
1575
|
-
if (prop === "exec") return (sql) => track(t.exec(sql));
|
|
1576
|
-
return typeof v === "function" ? v.bind(t) : v;
|
|
1577
|
-
} });
|
|
1578
|
-
}
|
|
1579
|
-
function isD1(value) {
|
|
1580
|
-
return typeof value === "object" && value !== null && typeof value.prepare === "function";
|
|
1581
|
-
}
|
|
1582
|
-
async function snapshotAll(spec, options) {
|
|
1583
|
-
const env = options.env;
|
|
1584
|
-
const out = {};
|
|
1585
|
-
for (const step of spec.setup) {
|
|
1586
|
-
if (step.kind !== "d1") continue;
|
|
1587
|
-
const binding = String(step["binding"]);
|
|
1588
|
-
const real = env[binding];
|
|
1589
|
-
if (isD1(real)) out[binding] = await snapshotD1(real);
|
|
1590
|
-
}
|
|
1591
|
-
return out;
|
|
1592
|
-
}
|
|
1593
|
-
/** The Eutaxy side: one run with no faults, driven like `runOnce` but keeping each delivery's status. */
|
|
1594
|
-
async function eutaxySide(spec, options) {
|
|
1595
|
-
const platform = createCloudflarePlatform(options);
|
|
1596
|
-
const run = new Run({
|
|
1597
|
-
mode: "replay",
|
|
1598
|
-
schedule: {
|
|
1599
|
-
seed: 0,
|
|
1600
|
-
faults: []
|
|
1601
|
-
},
|
|
1602
|
-
bounds: {
|
|
1603
|
-
...spec.bounds,
|
|
1604
|
-
maxConcurrentInvocations: 1
|
|
1605
|
-
},
|
|
1606
|
-
faultProbability: 0
|
|
1607
|
-
});
|
|
1608
|
-
const attempts = [];
|
|
1609
|
-
await platform.reset(spec);
|
|
1610
|
-
run.install(spec.externals);
|
|
1611
|
-
try {
|
|
1612
|
-
const pending = [...platform.initialEvents(spec)];
|
|
1613
|
-
while (pending.length > 0) {
|
|
1614
|
-
const event = pending.shift();
|
|
1615
|
-
const invocation = `${event.id}#${event.attempt}`;
|
|
1616
|
-
const before = run.log.entries.length;
|
|
1617
|
-
const result = await platform.deliver(event, run, spec);
|
|
1618
|
-
const mine = run.log.entries.slice(before).filter((e) => e.invocation === invocation);
|
|
1619
|
-
const decision = mine.find((e) => e.kind === "result" && (e.op === "ack" || e.op === "retry") && getPath(e.payload, "result.effective") === true)?.op;
|
|
1620
|
-
const response = mine.find((e) => e.kind === "result" && e.op === "response");
|
|
1621
|
-
attempts.push({
|
|
1622
|
-
event: event.id,
|
|
1623
|
-
attempt: event.attempt,
|
|
1624
|
-
status: result.status === "completed" ? "completed" : "errored",
|
|
1625
|
-
decision: decision ?? null,
|
|
1626
|
-
...response ? { response: getPath(response.payload, "result.status") } : {}
|
|
1627
|
-
});
|
|
1628
|
-
pending.push(...run.takeQueued(), ...result.followUps);
|
|
1629
|
-
}
|
|
1630
|
-
} finally {
|
|
1631
|
-
run.uninstall();
|
|
1632
|
-
}
|
|
1633
|
-
await platform.finish?.(spec, run);
|
|
1634
|
-
return {
|
|
1635
|
-
attempts,
|
|
1636
|
-
state: await snapshotAll(spec, options),
|
|
1637
|
-
unsupported: run.unsupportedReasons
|
|
1638
|
-
};
|
|
1639
|
-
}
|
|
1640
|
-
/** The raw side: the handler called directly with the real bindings and plain message or Request objects. */
|
|
1641
|
-
async function rawSide(spec, options) {
|
|
1642
|
-
const env = options.env;
|
|
1643
|
-
const drive = spec.drive;
|
|
1644
|
-
const maxRetries = options.maxRetries ?? 3;
|
|
1645
|
-
for (const step of spec.setup) {
|
|
1646
|
-
if (step.kind !== "d1") continue;
|
|
1647
|
-
const binding = String(step["binding"]);
|
|
1648
|
-
const schema = options.schemas[binding];
|
|
1649
|
-
const real = env[binding];
|
|
1650
|
-
if (schema !== void 0 && isD1(real)) await resetD1(real, schema);
|
|
1651
|
-
}
|
|
1652
|
-
const attempts = [];
|
|
1653
|
-
const pending = drive.kind === "http" ? drive.requests.map((r) => ({
|
|
1654
|
-
id: r.id,
|
|
1655
|
-
attempt: 1,
|
|
1656
|
-
data: r
|
|
1657
|
-
})) : drive.messages.map((m) => ({
|
|
1658
|
-
id: m.id,
|
|
1659
|
-
attempt: 1,
|
|
1660
|
-
data: m.body
|
|
1661
|
-
}));
|
|
1662
|
-
const patched = patchGlobals(0);
|
|
1663
|
-
const unsupported = [];
|
|
1664
|
-
const restoreFetch = installScriptedFetch(spec.externals, null, (r) => unsupported.push(r), () => patched.clock.advance(1));
|
|
1665
|
-
const io = { n: 0 };
|
|
1666
|
-
const counting = /* @__PURE__ */ new Map();
|
|
1667
|
-
const countedEnv = new Proxy(env, { get(target, prop, receiver) {
|
|
1668
|
-
const value = Reflect.get(target, prop, receiver);
|
|
1669
|
-
if (typeof prop !== "string" || !isD1(value)) return value;
|
|
1670
|
-
let c = counting.get(prop);
|
|
1671
|
-
if (!c) {
|
|
1672
|
-
c = countingD1(value, io, patched.clock);
|
|
1673
|
-
counting.set(prop, c);
|
|
1674
|
-
}
|
|
1675
|
-
return c;
|
|
1676
|
-
} });
|
|
1677
|
-
const settle = (p) => settleOn(p, {
|
|
1678
|
-
clock: patched.clock,
|
|
1679
|
-
inFlight: () => io.n,
|
|
1680
|
-
crashed: () => false,
|
|
1681
|
-
stuck: () => {
|
|
1682
|
-
throw new StuckError();
|
|
1683
|
-
}
|
|
1684
|
-
});
|
|
1685
|
-
const ctxFor = (background) => ({
|
|
1686
|
-
waitUntil: (p) => {
|
|
1687
|
-
background.push(p.then(() => void 0, () => void 0));
|
|
1688
|
-
},
|
|
1689
|
-
passThroughOnException: () => {},
|
|
1690
|
-
props: {}
|
|
1691
|
-
});
|
|
1692
|
-
try {
|
|
1693
|
-
if (drive.kind === "http") {
|
|
1694
|
-
const handler = options.handler.fetch;
|
|
1695
|
-
if (!handler) throw new Error("the Worker has no fetch() handler");
|
|
1696
|
-
while (pending.length > 0) {
|
|
1697
|
-
const event = pending.shift();
|
|
1698
|
-
const req = event.data;
|
|
1699
|
-
const background = [];
|
|
1700
|
-
let status;
|
|
1701
|
-
let response = 500;
|
|
1702
|
-
try {
|
|
1703
|
-
const r = await settle(Promise.resolve().then(() => handler.call(options.handler, requestFor(req), countedEnv, ctxFor(background))));
|
|
1704
|
-
await settle(r.clone().text());
|
|
1705
|
-
response = r.status;
|
|
1706
|
-
status = "completed";
|
|
1707
|
-
} catch (err) {
|
|
1708
|
-
if (err instanceof CrashSignal || err instanceof StuckError) throw err;
|
|
1709
|
-
status = "errored";
|
|
1710
|
-
}
|
|
1711
|
-
await settle(Promise.all(background));
|
|
1712
|
-
attempts.push({
|
|
1713
|
-
event: event.id,
|
|
1714
|
-
attempt: event.attempt,
|
|
1715
|
-
status,
|
|
1716
|
-
decision: null,
|
|
1717
|
-
response
|
|
1718
|
-
});
|
|
1719
|
-
if (!(drive.retryOn === "5xx" ? response < 500 : response >= 200 && response < 300) && event.attempt - 1 < drive.retries && event.attempt - 1 < spec.bounds.maxRedeliveries) pending.push({
|
|
1720
|
-
...event,
|
|
1721
|
-
attempt: event.attempt + 1
|
|
1722
|
-
});
|
|
1723
|
-
}
|
|
1724
|
-
} else {
|
|
1725
|
-
const handler = options.handler.queue;
|
|
1726
|
-
if (!handler) throw new Error("the Worker has no queue() handler");
|
|
1727
|
-
while (pending.length > 0) {
|
|
1728
|
-
const event = pending.shift();
|
|
1729
|
-
let decision = null;
|
|
1730
|
-
const background = [];
|
|
1731
|
-
const message = {
|
|
1732
|
-
id: event.id,
|
|
1733
|
-
timestamp: /* @__PURE__ */ new Date(),
|
|
1734
|
-
body: JSON.parse(JSON.stringify(event.data)),
|
|
1735
|
-
attempts: event.attempt,
|
|
1736
|
-
ack: () => {
|
|
1737
|
-
decision ??= "ack";
|
|
1738
|
-
},
|
|
1739
|
-
retry: () => {
|
|
1740
|
-
decision ??= "retry";
|
|
1741
|
-
}
|
|
1742
|
-
};
|
|
1743
|
-
const batch = {
|
|
1744
|
-
queue: drive.queue,
|
|
1745
|
-
messages: [message],
|
|
1746
|
-
metadata: { metrics: {
|
|
1747
|
-
backlogCount: 0,
|
|
1748
|
-
backlogBytes: 0
|
|
1749
|
-
} },
|
|
1750
|
-
ackAll: () => message.ack(),
|
|
1751
|
-
retryAll: () => message.retry()
|
|
1752
|
-
};
|
|
1753
|
-
const ctx = ctxFor(background);
|
|
1754
|
-
let status;
|
|
1755
|
-
try {
|
|
1756
|
-
await settle(Promise.resolve().then(() => handler.call(options.handler, batch, countedEnv, ctx)));
|
|
1757
|
-
status = "completed";
|
|
1758
|
-
} catch (err) {
|
|
1759
|
-
if (err instanceof CrashSignal || err instanceof StuckError) throw err;
|
|
1760
|
-
status = "errored";
|
|
1761
|
-
}
|
|
1762
|
-
if (status === "completed") decision ??= "ack";
|
|
1763
|
-
await settle(Promise.all(background));
|
|
1764
|
-
attempts.push({
|
|
1765
|
-
event: event.id,
|
|
1766
|
-
attempt: event.attempt,
|
|
1767
|
-
status,
|
|
1768
|
-
decision
|
|
1769
|
-
});
|
|
1770
|
-
if (decision !== "ack" && event.attempt <= maxRetries && event.attempt - 1 < spec.bounds.maxRedeliveries) pending.push({
|
|
1771
|
-
...event,
|
|
1772
|
-
attempt: event.attempt + 1
|
|
1773
|
-
});
|
|
1774
|
-
}
|
|
1775
|
-
}
|
|
1776
|
-
} finally {
|
|
1777
|
-
restoreFetch();
|
|
1778
|
-
patched.restore();
|
|
1779
|
-
}
|
|
1780
|
-
if (unsupported.length > 0) throw new StuckError(`raw side: ${unsupported.join("; ")}`);
|
|
1781
|
-
return {
|
|
1782
|
-
attempts,
|
|
1783
|
-
state: await snapshotAll(spec, options)
|
|
1784
|
-
};
|
|
1785
|
-
}
|
|
1786
|
-
/** Run both sides and compare. The Eutaxy side runs first; both start from the schema. */
|
|
1787
|
-
async function runDifferential(spec, options) {
|
|
1788
|
-
if (spec.drive.kind === "http" && ("delaysMs" in spec.drive || "deadlineMs" in spec.drive)) throw new Error("runDifferential does not model the caller's delaysMs or deadlineMs yet");
|
|
1789
|
-
const { unsupported, ...eutaxy } = await eutaxySide(spec, options);
|
|
1790
|
-
const raw = await rawSide(spec, options);
|
|
1791
|
-
const differences = [];
|
|
1792
|
-
if (unsupported.length > 0) differences.push(`the proxied run touched unsupported APIs: ${unsupported.join("; ")}`);
|
|
1793
|
-
const a = canonicalJson(eutaxy.attempts);
|
|
1794
|
-
const b = canonicalJson(raw.attempts);
|
|
1795
|
-
if (a !== b) differences.push(`attempts differ:\n eutaxy ${a}\n raw ${b}`);
|
|
1796
|
-
const bindings = /* @__PURE__ */ new Set([...Object.keys(eutaxy.state), ...Object.keys(raw.state)]);
|
|
1797
|
-
for (const binding of [...bindings].sort()) {
|
|
1798
|
-
const tables = /* @__PURE__ */ new Set([...Object.keys(eutaxy.state[binding] ?? {}), ...Object.keys(raw.state[binding] ?? {})]);
|
|
1799
|
-
for (const table of [...tables].sort()) {
|
|
1800
|
-
const x = canonicalJson(eutaxy.state[binding]?.[table] ?? []);
|
|
1801
|
-
const y = canonicalJson(raw.state[binding]?.[table] ?? []);
|
|
1802
|
-
if (x !== y) differences.push(`${binding}.${table} differs:\n eutaxy ${x}\n raw ${y}`);
|
|
1803
|
-
}
|
|
1804
|
-
}
|
|
1805
|
-
return {
|
|
1806
|
-
equal: differences.length === 0,
|
|
1807
|
-
eutaxy,
|
|
1808
|
-
raw,
|
|
1809
|
-
differences,
|
|
1810
|
-
unsupported
|
|
1811
|
-
};
|
|
1812
|
-
}
|
|
1813
|
-
export { atLeastOnce, atLeastOncePerMessage, atMostOncePerKey, check, cloudflareRegressionTest, createCloudflarePlatform, d1Param, d1Read, d1Rows, d1Schema, d1Write, defineScenario, durableObject, durableObjectRows, everyRow, expectHolds, external, fetchCall, http, httpResponse, implies, queue, queueAck, refines, runDifferential, snapshotD1, unique };
|
|
1814
|
-
|
|
1815
|
-
//# 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 };
|