eutaxy 0.13.0 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -6
- package/dist/aws.d.mts +28 -2
- package/dist/aws.d.mts.map +1 -1
- package/dist/aws.mjs +13 -2
- package/dist/aws.mjs.map +1 -1
- package/dist/bin.mjs +1 -1
- package/dist/{cli-D3SPblWw.mjs → cli-CzGCMudc.mjs} +1269 -117
- package/dist/cli-CzGCMudc.mjs.map +1 -0
- package/dist/cli.d.mts.map +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/cloudflare.d.mts +180 -15
- package/dist/cloudflare.d.mts.map +1 -1
- package/dist/cloudflare.mjs +3 -3
- package/dist/{combinators-Bsd9HKtw.d.mts → combinators-BecOKcmi.d.mts} +7 -1
- package/dist/combinators-BecOKcmi.d.mts.map +1 -0
- package/dist/{combinators-CVjxodAJ.mjs → combinators-CLfsPfhT.mjs} +6 -1
- package/dist/combinators-CLfsPfhT.mjs.map +1 -0
- package/dist/{delivery-invariants-Br29H7Rg.mjs → delivery-invariants-BCtvzAfW.mjs} +7 -2
- package/dist/delivery-invariants-BCtvzAfW.mjs.map +1 -0
- package/dist/delivery-invariants-DzMy3iPs.d.mts +10 -0
- package/dist/delivery-invariants-DzMy3iPs.d.mts.map +1 -0
- package/dist/{explore-B7aR_5Hy.d.mts → explore-B52m-wmk.d.mts} +13 -2
- package/dist/explore-B52m-wmk.d.mts.map +1 -0
- package/dist/index.d.mts +25 -3
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/dist/{platform-CCz48WF9.d.mts → platform-Ba1Kvdza.d.mts} +18 -1
- package/dist/platform-Ba1Kvdza.d.mts.map +1 -0
- package/dist/provers-DS44OeEm.mjs.map +1 -1
- package/dist/spec.d.mts +1 -1
- package/dist/spec.mjs +1 -1
- package/dist/{src-5pKRvj02.mjs → src-nwQA9Xwr.mjs} +9 -3
- package/dist/src-nwQA9Xwr.mjs.map +1 -0
- package/dist/{src-DGh7w877.mjs → src-ud5wEfnx.mjs} +111 -16
- package/dist/src-ud5wEfnx.mjs.map +1 -0
- package/dist/{workerd-BMJ-GKx8.mjs → workerd-Be43_PZo.mjs} +2050 -1503
- package/dist/workerd-Be43_PZo.mjs.map +1 -0
- package/package.json +1 -1
- package/dist/cli-D3SPblWw.mjs.map +0 -1
- package/dist/combinators-Bsd9HKtw.d.mts.map +0 -1
- package/dist/combinators-CVjxodAJ.mjs.map +0 -1
- package/dist/delivery-invariants-Br29H7Rg.mjs.map +0 -1
- package/dist/delivery-invariants-DZOBkCMR.d.mts +0 -5
- package/dist/delivery-invariants-DZOBkCMR.d.mts.map +0 -1
- package/dist/explore-B7aR_5Hy.d.mts.map +0 -1
- package/dist/platform-CCz48WF9.d.mts.map +0 -1
- package/dist/src-5pKRvj02.mjs.map +0 -1
- package/dist/src-DGh7w877.mjs.map +0 -1
- package/dist/workerd-BMJ-GKx8.mjs.map +0 -1
|
@@ -1,26 +1,74 @@
|
|
|
1
|
-
import { A as
|
|
2
|
-
import { a as redelivery, i as invocationOf, n as atLeastOncePerMessage$1 } from "./delivery-invariants-
|
|
3
|
-
import { c as checkSpecModule, s as emitRegressionTest, t as renderJson, y as describeVerdict } from "./src-
|
|
1
|
+
import { A as readFaults, E as validateScenario, I as getPath, L as canonicalJson, S as virtualEpoch, T as defaultBounds, _ as toResponse, a as explore, b as realTick, c as hostInvocation, d as InjectedEffectError, f as findResponse, g as replyOf, h as parseBody, i as proxiedSide, j as writeFaults, k as decisionFaults, l as runInvocation, m as isRedirect, n as DifferentialStuck, p as installScriptedFetch, r as compareSides, t as observeCore, u as CrashSignal, v as withoutNetwork, w as toJson, x as settleOn, y as patchGlobals } from "./src-ud5wEfnx.mjs";
|
|
2
|
+
import { a as redelivery, i as invocationOf, n as atLeastOncePerMessage$1 } from "./delivery-invariants-BCtvzAfW.mjs";
|
|
3
|
+
import { c as checkSpecModule, s as emitRegressionTest, t as renderJson, y as describeVerdict } from "./src-nwQA9Xwr.mjs";
|
|
4
4
|
// packages/cli/src/regression.ts
|
|
5
|
+
/**
|
|
6
|
+
* Identifiers for binding names: a qualified name (`orders/DB`) becomes
|
|
7
|
+
* `orders_DB`, and a name whose identifier another already took gets a
|
|
8
|
+
* count (`orders_DB_2`), so two imports never share a name.
|
|
9
|
+
*/
|
|
10
|
+
function identifiers(names) {
|
|
11
|
+
const taken = /* @__PURE__ */ new Set();
|
|
12
|
+
const out = /* @__PURE__ */ new Map();
|
|
13
|
+
for (const name of names) {
|
|
14
|
+
const base = name.replace(/[^A-Za-z0-9_$]/g, "_");
|
|
15
|
+
let id = base;
|
|
16
|
+
for (let n = 2; taken.has(id); n++) id = `${base}_${n}`;
|
|
17
|
+
taken.add(id);
|
|
18
|
+
out.set(name, id);
|
|
19
|
+
}
|
|
20
|
+
return out;
|
|
21
|
+
}
|
|
22
|
+
/** A binding name as an object key: bare where it is an identifier, quoted otherwise. */
|
|
23
|
+
const key = (binding) => /^[A-Za-z_$][\w$]*$/.test(binding) ? binding : JSON.stringify(binding);
|
|
5
24
|
/** A Vitest regression test for a Cloudflare scenario, to run under the Cloudflare Vitest plugin. */
|
|
6
25
|
function cloudflareRegressionTest(verdict, options) {
|
|
7
26
|
const bindings = Object.keys(options.schemaPaths).sort();
|
|
27
|
+
const callees = Object.keys(options.callees ?? {}).sort();
|
|
28
|
+
/**
|
|
29
|
+
* Each binding's files, in setup order, each with an identifier of its own: the binding's name for the
|
|
30
|
+
* first, a count after it for the later ones, made unique across all files as `identifiers` does.
|
|
31
|
+
*/
|
|
32
|
+
const taken = /* @__PURE__ */ new Set();
|
|
33
|
+
const files = bindings.flatMap((b) => {
|
|
34
|
+
const paths = options.schemaPaths[b] ?? [];
|
|
35
|
+
return (typeof paths === "string" ? [paths] : paths).map((path, i) => {
|
|
36
|
+
const base = (i === 0 ? b : `${b}_${i + 1}`).replace(/[^A-Za-z0-9_$]/g, "_");
|
|
37
|
+
let id = base;
|
|
38
|
+
for (let n = 2; taken.has(id); n++) id = `${base}_${n}`;
|
|
39
|
+
taken.add(id);
|
|
40
|
+
return {
|
|
41
|
+
binding: b,
|
|
42
|
+
path,
|
|
43
|
+
id
|
|
44
|
+
};
|
|
45
|
+
});
|
|
46
|
+
});
|
|
47
|
+
const calleeIds = identifiers(callees);
|
|
8
48
|
const withExports = options.exports === true || options.workflows === true;
|
|
9
49
|
const imports = [
|
|
50
|
+
...callees.length === 0 || (options.calleeBindings ?? []).length === 0 ? [] : [`// Needs the callees' bindings in this test's isolate under their qualified names: ${(options.calleeBindings ?? []).join(", ")}.`, "// Declare them in the wrangler config, or run this test under the config eutaxy check --keep leaves in .eutaxy/."],
|
|
10
51
|
"import { createCloudflarePlatform } from \"eutaxy/cloudflare\";",
|
|
11
52
|
"import { env } from \"cloudflare:workers\";",
|
|
12
53
|
...options.durableObjects ? ["import * as cloudflareTest from \"cloudflare:test\";"] : [],
|
|
13
54
|
`import scenario from ${JSON.stringify(options.scenarioPath)};`,
|
|
14
|
-
...
|
|
55
|
+
...files.map((f) => `import schema_${f.id} from ${JSON.stringify(`${f.path}?raw`)};`),
|
|
56
|
+
...callees.map((b) => `import * as callee_${calleeIds.get(b)} from ${JSON.stringify(options.callees?.[b]?.path)};`),
|
|
15
57
|
withExports ? `import * as worker from ${JSON.stringify(options.workerPath)};` : `import handler from ${JSON.stringify(options.workerPath)};`,
|
|
16
58
|
...(options.specModules ?? []).map((m, i) => `import * as core_${i} from ${JSON.stringify(m.path)};`)
|
|
17
59
|
];
|
|
18
|
-
const
|
|
60
|
+
const schemaOf = (b) => {
|
|
61
|
+
const own = files.filter((f) => f.binding === b).map((f) => `schema_${f.id}`);
|
|
62
|
+
return own.length === 1 ? own[0] : `[${own.join(", ")}].join("\\n;\\n")`;
|
|
63
|
+
};
|
|
64
|
+
const schemas = `{ ${bindings.map((b) => `${key(b)}: ${schemaOf(b)}`).join(", ")} }`;
|
|
65
|
+
const calleeOption = callees.length === 0 ? "" : `, callees: { ${callees.map((b) => `${key(b)}: { name: ${JSON.stringify(options.callees?.[b]?.name)}, exports: callee_${calleeIds.get(b)}${options.callees?.[b]?.entrypoint === void 0 ? "" : `, entrypoint: ${JSON.stringify(options.callees?.[b]?.entrypoint)}`}${options.callees?.[b]?.props === void 0 ? "" : `, props: ${JSON.stringify(options.callees?.[b]?.props)}`} }`).join(", ")} }`;
|
|
19
66
|
const retries = options.maxRetries === void 0 ? "" : `, maxRetries: ${options.maxRetries}`;
|
|
67
|
+
const aliases = options.aliases === void 0 || Object.keys(options.aliases).length === 0 ? "" : `, aliases: ${JSON.stringify(options.aliases)}`;
|
|
20
68
|
const objects = options.durableObjects ? ", durableObjects: cloudflareTest" : "";
|
|
21
69
|
return emitRegressionTest(verdict, {
|
|
22
70
|
imports,
|
|
23
|
-
platform: `createCloudflarePlatform({ env, ${withExports ? "handler: worker.default" : "handler"}, schemas: ${schemas}${retries}${objects}${withExports ? ", exports: worker" : ""} })`,
|
|
71
|
+
platform: `createCloudflarePlatform({ env, ${withExports ? "handler: worker.default" : "handler"}, schemas: ${schemas}${retries}${objects}${withExports ? ", exports: worker" : ""}${calleeOption}${aliases} })`,
|
|
24
72
|
scenario: options.budgetMs === void 0 ? "scenario" : `{ ...scenario, bounds: { ...scenario.bounds, budgetMs: ${options.budgetMs} } }`,
|
|
25
73
|
...options.expect ? { expect: options.expect } : {},
|
|
26
74
|
...options.engineModule ? { engineModule: options.engineModule } : {},
|
|
@@ -30,211 +78,16 @@ function cloudflareRegressionTest(verdict, options) {
|
|
|
30
78
|
})) } : {}
|
|
31
79
|
});
|
|
32
80
|
}
|
|
33
|
-
// packages/cloudflare/src/check.ts
|
|
34
|
-
/** Explore a scenario on a platform and return its verdict. */
|
|
35
|
-
function check(spec, platform, options = { seed: spec.name }) {
|
|
36
|
-
return explore(spec, platform, options);
|
|
37
|
-
}
|
|
38
|
-
/** For use from a test: passes only when the scenario is BOUNDED. */
|
|
39
|
-
async function expectHolds(spec, platform, options) {
|
|
40
|
-
const verdict = await check(spec, platform, options);
|
|
41
|
-
if (verdict.kind !== "BOUNDED") throw new Error(describeVerdict(verdict));
|
|
42
|
-
}
|
|
43
|
-
// packages/cloudflare/src/d1.ts
|
|
44
|
-
/**
|
|
45
|
-
* The D1 binding proxy. Every statement execution is an effect point: the
|
|
46
|
-
* engine decides the fault, the real Miniflare-backed D1 performs the query,
|
|
47
|
-
* and the log records call, result and fault in the documented shape.
|
|
48
|
-
*/
|
|
49
|
-
/** Whether a binding is a D1 database (what the proxies and the differential wrap). */
|
|
50
|
-
function isD1(value) {
|
|
51
|
-
return typeof value === "object" && value !== null && typeof value.prepare === "function" && typeof value.batch === "function";
|
|
52
|
-
}
|
|
53
|
-
function point(ctx, target, op, args, allowed) {
|
|
54
|
-
return {
|
|
55
|
-
invocation: ctx.currentInvocation(),
|
|
56
|
-
target,
|
|
57
|
-
op,
|
|
58
|
-
args,
|
|
59
|
-
allowed
|
|
60
|
-
};
|
|
61
|
-
}
|
|
62
|
-
function metaOf(result) {
|
|
63
|
-
return {
|
|
64
|
-
changes: result.meta.changes ?? 0,
|
|
65
|
-
lastRowId: result.meta.last_row_id ?? null
|
|
66
|
-
};
|
|
67
|
-
}
|
|
68
|
-
var StatementProxy = class StatementProxy {
|
|
69
|
-
real;
|
|
70
|
-
target;
|
|
71
|
-
ctx;
|
|
72
|
-
sql;
|
|
73
|
-
params;
|
|
74
|
-
constructor(real, target, ctx, sql, params) {
|
|
75
|
-
this.real = real;
|
|
76
|
-
this.target = target;
|
|
77
|
-
this.ctx = ctx;
|
|
78
|
-
this.sql = sql;
|
|
79
|
-
this.params = params;
|
|
80
|
-
}
|
|
81
|
-
/** The real statement, for `batch()`. */
|
|
82
|
-
get statement() {
|
|
83
|
-
return this.real;
|
|
84
|
-
}
|
|
85
|
-
args() {
|
|
86
|
-
return {
|
|
87
|
-
sql: this.sql,
|
|
88
|
-
params: toJson(this.params)
|
|
89
|
-
};
|
|
90
|
-
}
|
|
91
|
-
bind(...values) {
|
|
92
|
-
return new StatementProxy(this.real.bind(...values), this.target, this.ctx, this.sql, values);
|
|
93
|
-
}
|
|
94
|
-
run() {
|
|
95
|
-
return this.ctx.hooks.effect(point(this.ctx, this.target, "run", this.args(), writeFaults), () => this.real.run(), (r) => metaOf(r));
|
|
96
|
-
}
|
|
97
|
-
all() {
|
|
98
|
-
return this.ctx.hooks.effect(point(this.ctx, this.target, "all", this.args(), readFaults), () => this.real.all(), (r) => ({
|
|
99
|
-
rows: r.results.length,
|
|
100
|
-
changes: r.meta.changes ?? 0
|
|
101
|
-
}));
|
|
102
|
-
}
|
|
103
|
-
first(colName) {
|
|
104
|
-
return this.ctx.hooks.effect(point(this.ctx, this.target, "first", {
|
|
105
|
-
...this.args(),
|
|
106
|
-
column: colName ?? null
|
|
107
|
-
}, readFaults), () => colName === void 0 ? this.real.first() : this.real.first(colName), (r) => ({ row: toJson(r) }));
|
|
108
|
-
}
|
|
109
|
-
raw(options) {
|
|
110
|
-
return this.ctx.hooks.effect(point(this.ctx, this.target, "raw", this.args(), readFaults), () => options ? this.real.raw(options) : this.real.raw(), (r) => ({ rows: r.length }));
|
|
111
|
-
}
|
|
112
|
-
};
|
|
113
|
-
/** Wrap a D1 binding. Methods not modelled fall through to the real binding and mark the run unsupported. */
|
|
114
|
-
function proxyD1(real, binding, ctx) {
|
|
115
|
-
const target = `D1:${binding}`;
|
|
116
|
-
const modelled = {
|
|
117
|
-
prepare(sql) {
|
|
118
|
-
return new StatementProxy(real.prepare(sql), target, ctx, sql, []);
|
|
119
|
-
},
|
|
120
|
-
batch(statements) {
|
|
121
|
-
const unwrapped = statements.map((s) => s instanceof StatementProxy ? s.statement : s);
|
|
122
|
-
const args = { statements: statements.map((s) => s instanceof StatementProxy ? {
|
|
123
|
-
sql: s.sql,
|
|
124
|
-
params: toJson(s.params)
|
|
125
|
-
} : "<unproxied statement>") };
|
|
126
|
-
return ctx.hooks.effect(point(ctx, target, "batch", args, writeFaults), () => real.batch(unwrapped), (rs) => ({
|
|
127
|
-
changes: rs.reduce((n, r) => n + (r.meta.changes ?? 0), 0),
|
|
128
|
-
statements: rs.length
|
|
129
|
-
}));
|
|
130
|
-
},
|
|
131
|
-
exec(sql) {
|
|
132
|
-
return ctx.hooks.effect(point(ctx, target, "exec", { sql }, writeFaults), () => real.exec(sql), (r) => ({
|
|
133
|
-
count: r.count,
|
|
134
|
-
duration: 0
|
|
135
|
-
}));
|
|
136
|
-
}
|
|
137
|
-
};
|
|
138
|
-
return new Proxy(real, { get(obj, prop, receiver) {
|
|
139
|
-
if (prop in modelled) return modelled[prop];
|
|
140
|
-
const value = Reflect.get(obj, prop, receiver);
|
|
141
|
-
if (typeof value === "function") {
|
|
142
|
-
ctx.hooks.unsupported(`D1 ${binding}.${String(prop)} is not modelled`);
|
|
143
|
-
return value.bind(obj);
|
|
144
|
-
}
|
|
145
|
-
return value;
|
|
146
|
-
} });
|
|
147
|
-
}
|
|
148
|
-
/**
|
|
149
|
-
* Statements in a schema file. Splits on semicolons outside string literals,
|
|
150
|
-
* quoted identifiers and comments, and keeps CREATE TRIGGER bodies (and CASE
|
|
151
|
-
* expressions) whole by tracking BEGIN/CASE ... END nesting.
|
|
152
|
-
*/
|
|
153
|
-
function splitSql(sql) {
|
|
154
|
-
const out = [];
|
|
155
|
-
let cur = "";
|
|
156
|
-
let depth = 0;
|
|
157
|
-
let i = 0;
|
|
158
|
-
const isWordChar = (c) => c !== void 0 && /[A-Za-z0-9_]/.test(c);
|
|
159
|
-
while (i < sql.length) {
|
|
160
|
-
const c = sql[i];
|
|
161
|
-
const next = sql[i + 1];
|
|
162
|
-
if (c === "-" && next === "-") {
|
|
163
|
-
while (i < sql.length && sql[i] !== "\n") i++;
|
|
164
|
-
continue;
|
|
165
|
-
}
|
|
166
|
-
if (c === "/" && next === "*") {
|
|
167
|
-
const end = sql.indexOf("*/", i + 2);
|
|
168
|
-
i = end === -1 ? sql.length : end + 2;
|
|
169
|
-
continue;
|
|
170
|
-
}
|
|
171
|
-
if (c === "'" || c === "\"" || c === "`" || c === "[") {
|
|
172
|
-
const close = c === "[" ? "]" : c;
|
|
173
|
-
let j = i + 1;
|
|
174
|
-
for (;;) {
|
|
175
|
-
const k = sql.indexOf(close, j);
|
|
176
|
-
if (k === -1) {
|
|
177
|
-
j = sql.length;
|
|
178
|
-
break;
|
|
179
|
-
}
|
|
180
|
-
if (close !== "]" && sql[k + 1] === close) {
|
|
181
|
-
j = k + 2;
|
|
182
|
-
continue;
|
|
183
|
-
}
|
|
184
|
-
j = k + 1;
|
|
185
|
-
break;
|
|
186
|
-
}
|
|
187
|
-
cur += sql.slice(i, j);
|
|
188
|
-
i = j;
|
|
189
|
-
continue;
|
|
190
|
-
}
|
|
191
|
-
if (isWordChar(c) && !isWordChar(sql[i - 1])) {
|
|
192
|
-
let j = i;
|
|
193
|
-
while (isWordChar(sql[j])) j++;
|
|
194
|
-
const word = sql.slice(i, j);
|
|
195
|
-
const upper = word.toUpperCase();
|
|
196
|
-
if (upper === "BEGIN" || upper === "CASE") depth++;
|
|
197
|
-
else if (upper === "END" && depth > 0) depth--;
|
|
198
|
-
cur += word;
|
|
199
|
-
i = j;
|
|
200
|
-
continue;
|
|
201
|
-
}
|
|
202
|
-
if (c === ";" && depth === 0) {
|
|
203
|
-
const statement = cur.trim();
|
|
204
|
-
if (statement.length > 0) out.push(statement);
|
|
205
|
-
cur = "";
|
|
206
|
-
i++;
|
|
207
|
-
continue;
|
|
208
|
-
}
|
|
209
|
-
cur += c;
|
|
210
|
-
i++;
|
|
211
|
-
}
|
|
212
|
-
const last = cur.trim();
|
|
213
|
-
if (last.length > 0) out.push(last);
|
|
214
|
-
return out;
|
|
215
|
-
}
|
|
216
|
-
/** Drop every user table and re-apply the schema, using the real binding (not an effect). */
|
|
217
|
-
async function resetD1(real, schema) {
|
|
218
|
-
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();
|
|
219
|
-
for (const { name } of tables.results) await real.prepare(`DROP TABLE IF EXISTS "${name.replace(/"/g, "\"\"")}"`).run();
|
|
220
|
-
for (const statement of splitSql(schema)) await real.prepare(statement).run();
|
|
221
|
-
}
|
|
222
|
-
/** Every user table's rows, sorted canonically, read through the real binding (not an effect). */
|
|
223
|
-
async function snapshotD1(real) {
|
|
224
|
-
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();
|
|
225
|
-
const out = {};
|
|
226
|
-
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);
|
|
227
|
-
return out;
|
|
228
|
-
}
|
|
229
81
|
// packages/cloudflare/src/background.ts
|
|
230
82
|
const CUT_OFF = ["cut_off"];
|
|
231
83
|
/**
|
|
232
84
|
* The `ExecutionContext` handed to a handler; `waitUntil` work is collected to
|
|
233
|
-
* run after it returns
|
|
85
|
+
* run after it returns, and `props` is what the caller's binding carries
|
|
86
|
+
* (developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/rpc/, props). A rejection is kept in `failures` when given: a
|
|
234
87
|
* scheduled invocation's status is that of its first failed `waitUntil`
|
|
235
88
|
* (Cloudflare, Scheduled handler); a queue or HTTP delivery's is not.
|
|
236
89
|
*/
|
|
237
|
-
function executionContext(background, failures) {
|
|
90
|
+
function executionContext(background, failures, props = {}) {
|
|
238
91
|
return {
|
|
239
92
|
waitUntil: (promise) => {
|
|
240
93
|
background.push(promise.then(() => void 0, (error) => {
|
|
@@ -242,7 +95,7 @@ function executionContext(background, failures) {
|
|
|
242
95
|
}));
|
|
243
96
|
},
|
|
244
97
|
passThroughOnException: () => {},
|
|
245
|
-
props:
|
|
98
|
+
props: structuredClone(props)
|
|
246
99
|
};
|
|
247
100
|
}
|
|
248
101
|
/**
|
|
@@ -260,7 +113,7 @@ async function drainBackground(hooks, inv, invocation, target, background) {
|
|
|
260
113
|
allowed: CUT_OFF
|
|
261
114
|
}, () => null, () => null);
|
|
262
115
|
await Promise.race([hooks.settle(Promise.all(background), invocation), inv.crashed]);
|
|
263
|
-
return
|
|
116
|
+
return inv.isCrashed();
|
|
264
117
|
} catch (err) {
|
|
265
118
|
if (!(err instanceof CrashSignal)) throw err;
|
|
266
119
|
return true;
|
|
@@ -953,1232 +806,1983 @@ async function readTables(real, helpers, names, touched, objects, sql, seededSql
|
|
|
953
806
|
}
|
|
954
807
|
return out;
|
|
955
808
|
}
|
|
956
|
-
// packages/cloudflare/src/
|
|
809
|
+
// packages/cloudflare/src/entrypoint.ts
|
|
957
810
|
/**
|
|
958
|
-
*
|
|
959
|
-
*
|
|
960
|
-
*
|
|
961
|
-
* fields and body methods: reading it later would be I/O the run cannot
|
|
962
|
-
* see. An object's random `version` and wall-clock `uploaded` are replaced
|
|
963
|
-
* by stand-ins (see `VersionBook`), so traces stay byte-identical.
|
|
811
|
+
* Constructing an entrypoint class (`WorkerEntrypoint`, `WorkflowEntrypoint`)
|
|
812
|
+
* outside the runtime, for the one `new` per call or instance run that the
|
|
813
|
+
* models make themselves.
|
|
964
814
|
*/
|
|
965
|
-
/**
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
"list",
|
|
975
|
-
"createMultipartUpload"
|
|
976
|
-
].every((m) => typeof v[m] === "function");
|
|
977
|
-
}
|
|
815
|
+
/** Sets `ctx` and `env` as the runtime's base classes do, for the one `new` workerd would refuse. */
|
|
816
|
+
var StandInEntrypoint = class {
|
|
817
|
+
ctx;
|
|
818
|
+
env;
|
|
819
|
+
constructor(ctx, env) {
|
|
820
|
+
this.ctx = ctx;
|
|
821
|
+
this.env = env;
|
|
822
|
+
}
|
|
823
|
+
};
|
|
978
824
|
/**
|
|
979
|
-
*
|
|
980
|
-
*
|
|
981
|
-
* the
|
|
825
|
+
* Construct a subclass of the entrypoint base class named `base`. workerd's
|
|
826
|
+
* base constructors accept only a native ExecutionContext, so for this one
|
|
827
|
+
* synchronous `new` the class that extends the base directly extends a
|
|
828
|
+
* stand-in instead; its own constructor and field initialisers run as
|
|
829
|
+
* written, and the base is put back before anything else can run.
|
|
982
830
|
*/
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
831
|
+
function constructEntrypoint(cls, base, ctx, env) {
|
|
832
|
+
if (typeof cls !== "function") throw new TypeError("not a class");
|
|
833
|
+
let direct = cls;
|
|
834
|
+
for (;;) {
|
|
835
|
+
const parent = Object.getPrototypeOf(direct);
|
|
836
|
+
if (typeof parent !== "function" || parent === Function.prototype) throw new TypeError(`${cls.name} does not extend ${base}`);
|
|
837
|
+
if (parent.name === base) break;
|
|
838
|
+
direct = parent;
|
|
839
|
+
}
|
|
840
|
+
const original = Object.getPrototypeOf(direct);
|
|
841
|
+
Object.setPrototypeOf(direct, StandInEntrypoint);
|
|
842
|
+
try {
|
|
843
|
+
return Reflect.construct(cls, [ctx, env]);
|
|
844
|
+
} finally {
|
|
845
|
+
Object.setPrototypeOf(direct, original);
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
/**
|
|
849
|
+
* The handler object a `WorkerEntrypoint` class stands for when it is the Worker's default export: each
|
|
850
|
+
* of `fetch`, `queue` and `scheduled` the class defines constructs it anew with the invocation's env and
|
|
851
|
+
* ctx, as workerd does per event, and calls the method with the event alone (its env and ctx are on the
|
|
852
|
+
* instance) (developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/rpc/).
|
|
853
|
+
*/
|
|
854
|
+
function entrypointHandler(cls) {
|
|
855
|
+
const proto = typeof cls === "function" ? cls.prototype : void 0;
|
|
856
|
+
const out = {};
|
|
857
|
+
for (const name of [
|
|
858
|
+
"fetch",
|
|
859
|
+
"queue",
|
|
860
|
+
"scheduled"
|
|
861
|
+
]) if (typeof proto?.[name] === "function") out[name] = (event, env, ctx) => {
|
|
862
|
+
const instance = constructEntrypoint(cls, "WorkerEntrypoint", ctx, env);
|
|
863
|
+
return instance[name].call(instance, event);
|
|
864
|
+
};
|
|
865
|
+
return out;
|
|
866
|
+
}
|
|
867
|
+
// packages/cloudflare/src/caller.ts
|
|
868
|
+
/**
|
|
869
|
+
* The caller of an inbound request or RPC call. Cloudflare retries neither,
|
|
870
|
+
* so resends follow the policy the drive declares for the caller: how many
|
|
871
|
+
* times it resends, the virtual delay before each resend, and how long it
|
|
872
|
+
* waits for an answer. The decision is the caller's and is made once per
|
|
873
|
+
* attempt: at the response point, or at its deadline if the handler has
|
|
874
|
+
* not answered by then.
|
|
875
|
+
*/
|
|
876
|
+
/** The response point: a crash before it is a response the caller never saw. */
|
|
877
|
+
const RESPOND = ["crash_before"];
|
|
878
|
+
/**
|
|
879
|
+
* With a caller deadline the answer can also arrive too late: `ambiguous`
|
|
880
|
+
* here means it was sent, the caller counted it as failed, and the handler
|
|
881
|
+
* carried on.
|
|
882
|
+
*/
|
|
883
|
+
const RESPOND_WITH_DEADLINE = ["crash_before", "ambiguous"];
|
|
884
|
+
/** The virtual delay before resend number `resend` (1 for the first), per the policy. */
|
|
885
|
+
function retryDelayMs$1(policy, resend) {
|
|
886
|
+
const delays = policy.delaysMs ?? [];
|
|
887
|
+
return delays[Math.min(resend, delays.length) - 1] ?? 0;
|
|
888
|
+
}
|
|
889
|
+
/**
|
|
890
|
+
* Start waiting for the attempt's answer. With a deadline, a virtual timer
|
|
891
|
+
* makes the caller give up at it whatever the handler is doing, so a resend
|
|
892
|
+
* can start while the first attempt still runs. `gaveUp` is what the
|
|
893
|
+
* `gave_up` effect records when the retries are spent.
|
|
894
|
+
*/
|
|
895
|
+
function startCaller(event, hooks, spec, policy, target, gaveUp) {
|
|
896
|
+
const started = Date.now();
|
|
897
|
+
const deadline = policy.deadlineMs;
|
|
898
|
+
const lateAt = deadline === void 0 ? void 0 : started + deadline;
|
|
899
|
+
/** The caller decides once: it accepts the answer, or gives up at `at` and resends or stops. */
|
|
900
|
+
let decided = false;
|
|
901
|
+
const giveUp = (at) => {
|
|
902
|
+
if (decided) return;
|
|
903
|
+
decided = true;
|
|
904
|
+
const next = redelivery(event, policy.retries, spec.bounds);
|
|
905
|
+
if (next) {
|
|
906
|
+
const resendAt = Math.max(at + retryDelayMs$1(policy, event.attempt), Date.now());
|
|
907
|
+
hooks.enqueue({
|
|
908
|
+
...next,
|
|
909
|
+
...resendAt > Date.now() ? { at: resendAt } : {}
|
|
910
|
+
});
|
|
911
|
+
} else hooks.effectSync({
|
|
912
|
+
invocation: hooks.bookkeeping(),
|
|
913
|
+
target,
|
|
914
|
+
op: "gave_up",
|
|
915
|
+
args: gaveUp,
|
|
916
|
+
allowed: []
|
|
917
|
+
}, () => null, () => null);
|
|
918
|
+
};
|
|
919
|
+
const deadlineTimer = lateAt === void 0 ? void 0 : setTimeout(() => giveUp(lateAt), deadline);
|
|
920
|
+
return {
|
|
921
|
+
responseFaults: deadline === void 0 ? RESPOND : RESPOND_WITH_DEADLINE,
|
|
922
|
+
isLate: () => lateAt !== void 0 && Date.now() > lateAt,
|
|
923
|
+
settle(accepted, late) {
|
|
924
|
+
if (deadlineTimer !== void 0) clearTimeout(deadlineTimer);
|
|
925
|
+
if (accepted) decided = true;
|
|
926
|
+
else giveUp(late && lateAt !== void 0 ? lateAt : Date.now());
|
|
927
|
+
}
|
|
928
|
+
};
|
|
929
|
+
}
|
|
930
|
+
// packages/cloudflare/src/cron.ts
|
|
931
|
+
const fields = [
|
|
932
|
+
{
|
|
933
|
+
name: "minute",
|
|
934
|
+
min: 0,
|
|
935
|
+
max: 59
|
|
936
|
+
},
|
|
937
|
+
{
|
|
938
|
+
name: "hour",
|
|
939
|
+
min: 0,
|
|
940
|
+
max: 23
|
|
941
|
+
},
|
|
942
|
+
{
|
|
943
|
+
name: "day of month",
|
|
944
|
+
min: 1,
|
|
945
|
+
max: 31
|
|
946
|
+
},
|
|
947
|
+
{
|
|
948
|
+
name: "month",
|
|
949
|
+
min: 1,
|
|
950
|
+
max: 12,
|
|
951
|
+
names: [
|
|
952
|
+
"jan",
|
|
953
|
+
"feb",
|
|
954
|
+
"mar",
|
|
955
|
+
"apr",
|
|
956
|
+
"may",
|
|
957
|
+
"jun",
|
|
958
|
+
"jul",
|
|
959
|
+
"aug",
|
|
960
|
+
"sep",
|
|
961
|
+
"oct",
|
|
962
|
+
"nov",
|
|
963
|
+
"dec"
|
|
964
|
+
],
|
|
965
|
+
firstName: 1
|
|
966
|
+
},
|
|
967
|
+
{
|
|
968
|
+
name: "weekday",
|
|
969
|
+
min: 1,
|
|
970
|
+
max: 7,
|
|
971
|
+
names: [
|
|
972
|
+
"sun",
|
|
973
|
+
"mon",
|
|
974
|
+
"tue",
|
|
975
|
+
"wed",
|
|
976
|
+
"thu",
|
|
977
|
+
"fri",
|
|
978
|
+
"sat"
|
|
979
|
+
],
|
|
980
|
+
firstName: 1
|
|
981
|
+
}
|
|
982
|
+
];
|
|
983
|
+
function value(token, field) {
|
|
984
|
+
const lower = token.toLowerCase();
|
|
985
|
+
if (field.names) {
|
|
986
|
+
const i = field.names.indexOf(lower);
|
|
987
|
+
if (i >= 0) return (field.firstName ?? 0) + i;
|
|
988
|
+
}
|
|
989
|
+
if (!/^\d+$/.test(token)) throw new Error(`${field.name}: ${JSON.stringify(token)} is not a value`);
|
|
990
|
+
const n = Number(token);
|
|
991
|
+
if (n < field.min || n > field.max) throw new Error(`${field.name}: ${n} is outside ${field.min}-${field.max}`);
|
|
992
|
+
return n;
|
|
993
|
+
}
|
|
994
|
+
function parseField(text, field) {
|
|
995
|
+
if (/[LW#]/i.test(text) && !field.names?.some((n) => text.toLowerCase().includes(n))) throw new Error(`${field.name}: L, W and # are not modelled`);
|
|
996
|
+
const out = /* @__PURE__ */ new Set();
|
|
997
|
+
for (const part of text.split(",")) {
|
|
998
|
+
const pieces = part.split("/");
|
|
999
|
+
if (pieces.length > 2 || part === "") throw new Error(`${field.name}: ${JSON.stringify(part)} is not a value, range or step`);
|
|
1000
|
+
const [rangeText, stepText] = pieces;
|
|
1001
|
+
let step = 1;
|
|
1002
|
+
if (stepText !== void 0) {
|
|
1003
|
+
if (!/^\d+$/.test(stepText) || Number(stepText) < 1) throw new Error(`${field.name}: step ${JSON.stringify(stepText)} is not a positive number`);
|
|
1004
|
+
step = Number(stepText);
|
|
1005
|
+
}
|
|
1006
|
+
let from;
|
|
1007
|
+
let to;
|
|
1008
|
+
if (rangeText === "*") {
|
|
1009
|
+
from = field.min;
|
|
1010
|
+
to = field.max;
|
|
1011
|
+
} else if (rangeText.includes("-")) {
|
|
1012
|
+
const ends = rangeText.split("-");
|
|
1013
|
+
if (ends.length !== 2) throw new Error(`${field.name}: ${JSON.stringify(rangeText)} is not a range`);
|
|
1014
|
+
const [a, b] = ends;
|
|
1015
|
+
from = value(a, field);
|
|
1016
|
+
to = value(b, field);
|
|
1017
|
+
if (from > to) throw new Error(`${field.name}: range ${rangeText} runs backwards`);
|
|
1018
|
+
} else {
|
|
1019
|
+
from = value(rangeText, field);
|
|
1020
|
+
to = stepText === void 0 ? from : field.max;
|
|
1021
|
+
}
|
|
1022
|
+
for (let v = from; v <= to; v += step) out.add(v);
|
|
1023
|
+
}
|
|
1024
|
+
return out;
|
|
1025
|
+
}
|
|
1026
|
+
/** Parse an expression; throws with the field and the problem when it is not one Cloudflare accepts. */
|
|
1027
|
+
function parseCron(expression) {
|
|
1028
|
+
const parts = expression.trim().split(/\s+/);
|
|
1029
|
+
if (parts.length !== 5) throw new Error(`a cron expression has five fields, got ${parts.length}: ${JSON.stringify(expression)}`);
|
|
1030
|
+
const [minute, hour, dom, month, weekday] = parts;
|
|
1031
|
+
return {
|
|
1032
|
+
minutes: parseField(minute, fields[0]),
|
|
1033
|
+
hours: parseField(hour, fields[1]),
|
|
1034
|
+
daysOfMonth: parseField(dom, fields[2]),
|
|
1035
|
+
months: parseField(month, fields[3]),
|
|
1036
|
+
weekdays: parseField(weekday, fields[4]),
|
|
1037
|
+
anyDayOfMonth: dom === "*",
|
|
1038
|
+
anyWeekday: weekday === "*"
|
|
1039
|
+
};
|
|
1040
|
+
}
|
|
1041
|
+
/** Whether the minute starting at `time` (ms since the epoch, UTC) matches. */
|
|
1042
|
+
function cronMatches(schedule, time) {
|
|
1043
|
+
const d = new Date(time);
|
|
1044
|
+
if (!schedule.minutes.has(d.getUTCMinutes()) || !schedule.hours.has(d.getUTCHours())) return false;
|
|
1045
|
+
if (!schedule.months.has(d.getUTCMonth() + 1)) return false;
|
|
1046
|
+
const dayOk = schedule.daysOfMonth.has(d.getUTCDate());
|
|
1047
|
+
const weekdayOk = schedule.weekdays.has(d.getUTCDay() + 1);
|
|
1048
|
+
if (!schedule.anyDayOfMonth && !schedule.anyWeekday) return dayOk || weekdayOk;
|
|
1049
|
+
return dayOk && weekdayOk;
|
|
1050
|
+
}
|
|
1051
|
+
const minuteMs = 6e4;
|
|
1052
|
+
/**
|
|
1053
|
+
* Between two matches of any expression Cloudflare accepts lie at most eight
|
|
1054
|
+
* years (the 29th of February across a century's missing leap year); an
|
|
1055
|
+
* expression with no match in that span never fires.
|
|
1056
|
+
*/
|
|
1057
|
+
const longestGapMs = 4743360 * minuteMs;
|
|
1058
|
+
/** The first `count` tick times at or after `from`, each the start of a matching minute. */
|
|
1059
|
+
function cronTicks(expression, from, count) {
|
|
1060
|
+
const schedule = parseCron(expression);
|
|
1061
|
+
const out = [];
|
|
1062
|
+
let t = Math.ceil(from / minuteMs) * minuteMs;
|
|
1063
|
+
let horizon = t + longestGapMs;
|
|
1064
|
+
while (out.length < count) {
|
|
1065
|
+
if (t > horizon) throw new Error(`${JSON.stringify(expression)} never fires`);
|
|
1066
|
+
if (cronMatches(schedule, t)) {
|
|
1067
|
+
out.push(t);
|
|
1068
|
+
horizon = t + longestGapMs;
|
|
1069
|
+
}
|
|
1070
|
+
t += minuteMs;
|
|
1071
|
+
}
|
|
1072
|
+
return out;
|
|
1073
|
+
}
|
|
1074
|
+
// packages/cloudflare/src/scenario.ts
|
|
1075
|
+
/**
|
|
1076
|
+
* Typed construction of scenario specs for Cloudflare Workers. Everything here
|
|
1077
|
+
* produces the plain-data `ScenarioSpec` from core; this module only knows the
|
|
1078
|
+
* Cloudflare shapes (queues, D1 bindings) and the effect conventions the
|
|
1079
|
+
* proxies follow.
|
|
1080
|
+
*/
|
|
1081
|
+
/**
|
|
1082
|
+
* Drive the Worker's `fetch()` handler with these requests, each resent as `options` say. A request's
|
|
1083
|
+
* method defaults to POST with a body and GET without; its id to `req-<n>`, by position.
|
|
1084
|
+
*/
|
|
1085
|
+
function http(requests, options = {}) {
|
|
1086
|
+
return {
|
|
1087
|
+
kind: "http",
|
|
1088
|
+
requests: requests.map((r, i) => ({
|
|
1089
|
+
id: r.id ?? `req-${i + 1}`,
|
|
1090
|
+
method: (r.method ?? (r.body === void 0 ? "GET" : "POST")).toUpperCase(),
|
|
1091
|
+
path: r.path,
|
|
1092
|
+
headers: r.headers ?? {},
|
|
1093
|
+
...r.body === void 0 ? {} : { body: r.body }
|
|
1094
|
+
})),
|
|
1095
|
+
retries: options.retries ?? 3,
|
|
1096
|
+
retryOn: options.retryOn ?? "non-2xx",
|
|
1097
|
+
...options.delaysMs === void 0 ? {} : { delaysMs: [...options.delaysMs] },
|
|
1098
|
+
...options.deadlineMs === void 0 ? {} : { deadlineMs: options.deadlineMs }
|
|
1099
|
+
};
|
|
1100
|
+
}
|
|
1101
|
+
/**
|
|
1102
|
+
* Drive the Worker over these WebSocket connections: each opened through its `fetch()` and handed to a
|
|
1103
|
+
* Durable Object, its messages delivered in order to the object's `webSocketMessage` handler.
|
|
1104
|
+
*/
|
|
1105
|
+
function websocket(connections) {
|
|
1106
|
+
return {
|
|
1107
|
+
kind: "websocket",
|
|
1108
|
+
connections: connections.map((c, i) => {
|
|
1109
|
+
const id = c.id ?? `conn-${i + 1}`;
|
|
1110
|
+
return {
|
|
1111
|
+
id,
|
|
1112
|
+
path: c.path,
|
|
1113
|
+
headers: c.headers ?? {},
|
|
1114
|
+
messages: (c.messages ?? []).map((m, j) => ({
|
|
1115
|
+
id: m.id ?? `${id}:${j + 1}`,
|
|
1116
|
+
data: m.data
|
|
1117
|
+
}))
|
|
994
1118
|
};
|
|
995
|
-
|
|
1119
|
+
})
|
|
1120
|
+
};
|
|
1121
|
+
}
|
|
1122
|
+
/** Drive a `WorkerEntrypoint` of the Worker with these method calls; a call's id defaults to `call-<n>`. */
|
|
1123
|
+
function rpc(calls, options = {}) {
|
|
1124
|
+
return {
|
|
1125
|
+
kind: "rpc",
|
|
1126
|
+
...options.entrypoint === void 0 ? {} : { entrypoint: options.entrypoint },
|
|
1127
|
+
calls: calls.map((c, i) => ({
|
|
1128
|
+
id: c.id ?? `call-${i + 1}`,
|
|
1129
|
+
method: c.method,
|
|
1130
|
+
args: [...c.args ?? []]
|
|
1131
|
+
})),
|
|
1132
|
+
retries: options.retries ?? 0,
|
|
1133
|
+
...options.delaysMs === void 0 ? {} : { delaysMs: [...options.delaysMs] },
|
|
1134
|
+
...options.deadlineMs === void 0 ? {} : { deadlineMs: options.deadlineMs }
|
|
1135
|
+
};
|
|
1136
|
+
}
|
|
1137
|
+
/** The target of a call's effects: the method, under the entrypoint's name when the drive names one. */
|
|
1138
|
+
function rpcTarget(drive, method) {
|
|
1139
|
+
return `Rpc:${drive.entrypoint === void 0 ? method : `${drive.entrypoint}.${method}`}`;
|
|
1140
|
+
}
|
|
1141
|
+
/**
|
|
1142
|
+
* Drive the Worker's `scheduled()` handler with the ticks of a Cron Trigger expression, in Cloudflare's
|
|
1143
|
+
* dialect: one tick by default, re-run 0 times by default.
|
|
1144
|
+
*/
|
|
1145
|
+
function cron(expression, options = {}) {
|
|
1146
|
+
const count = options.ticks ?? 1;
|
|
1147
|
+
return {
|
|
1148
|
+
kind: "cron",
|
|
1149
|
+
cron: expression,
|
|
1150
|
+
ticks: (Number.isInteger(count) && count >= 1 ? cronTicks(expression, virtualEpoch, count) : []).map((at, i) => ({
|
|
1151
|
+
id: `tick-${i + 1}`,
|
|
1152
|
+
at
|
|
1153
|
+
})),
|
|
1154
|
+
retries: options.retries ?? 0
|
|
1155
|
+
};
|
|
1156
|
+
}
|
|
1157
|
+
/** The drive's events as they are first delivered: one per message, request or call, attempt 1. */
|
|
1158
|
+
function driveEvents(drive) {
|
|
1159
|
+
switch (drive.kind) {
|
|
1160
|
+
case "queue": return drive.messages.map((m) => ({
|
|
1161
|
+
id: m.id,
|
|
1162
|
+
attempt: 1,
|
|
1163
|
+
data: m.body
|
|
1164
|
+
}));
|
|
1165
|
+
case "http": return drive.requests.map((r) => ({
|
|
1166
|
+
id: r.id,
|
|
1167
|
+
attempt: 1,
|
|
1168
|
+
data: r
|
|
1169
|
+
}));
|
|
1170
|
+
case "rpc": return drive.calls.map((c) => ({
|
|
1171
|
+
id: c.id,
|
|
1172
|
+
attempt: 1,
|
|
1173
|
+
data: c
|
|
1174
|
+
}));
|
|
1175
|
+
case "cron": return drive.ticks.map((t) => ({
|
|
1176
|
+
id: t.id,
|
|
1177
|
+
attempt: 1,
|
|
1178
|
+
data: {
|
|
1179
|
+
cron: drive.cron,
|
|
1180
|
+
scheduledTime: t.at
|
|
1181
|
+
},
|
|
1182
|
+
at: t.at
|
|
1183
|
+
}));
|
|
1184
|
+
case "websocket": {
|
|
1185
|
+
const opens = drive.connections.map((c) => ({
|
|
1186
|
+
id: c.id,
|
|
1187
|
+
attempt: 1,
|
|
1188
|
+
data: {
|
|
1189
|
+
kind: "open",
|
|
1190
|
+
connection: c.id,
|
|
1191
|
+
path: c.path,
|
|
1192
|
+
headers: c.headers
|
|
1193
|
+
}
|
|
1194
|
+
}));
|
|
1195
|
+
const rounds = Math.max(0, ...drive.connections.map((c) => c.messages.length));
|
|
1196
|
+
const messages = [];
|
|
1197
|
+
for (let i = 0; i < rounds; i++) for (const c of drive.connections) {
|
|
1198
|
+
const m = c.messages[i];
|
|
1199
|
+
if (m) messages.push({
|
|
1200
|
+
id: m.id,
|
|
1201
|
+
attempt: 1,
|
|
1202
|
+
data: {
|
|
1203
|
+
kind: "message",
|
|
1204
|
+
connection: c.id,
|
|
1205
|
+
message: m.id,
|
|
1206
|
+
index: i,
|
|
1207
|
+
data: m.data
|
|
1208
|
+
}
|
|
1209
|
+
});
|
|
1210
|
+
}
|
|
1211
|
+
return [...opens, ...messages];
|
|
996
1212
|
}
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
/** The drive with only the named events kept, for shrinking. */
|
|
1216
|
+
function restrictDrive(drive, keepIds) {
|
|
1217
|
+
const keep = (id) => keepIds.includes(id);
|
|
1218
|
+
switch (drive.kind) {
|
|
1219
|
+
case "queue": return {
|
|
1220
|
+
...drive,
|
|
1221
|
+
messages: drive.messages.filter((m) => keep(m.id))
|
|
1222
|
+
};
|
|
1223
|
+
case "http": return {
|
|
1224
|
+
...drive,
|
|
1225
|
+
requests: drive.requests.filter((r) => keep(r.id))
|
|
1226
|
+
};
|
|
1227
|
+
case "rpc": return {
|
|
1228
|
+
...drive,
|
|
1229
|
+
calls: drive.calls.filter((c) => keep(c.id))
|
|
1230
|
+
};
|
|
1231
|
+
case "cron": return {
|
|
1232
|
+
...drive,
|
|
1233
|
+
ticks: drive.ticks.filter((t) => keep(t.id))
|
|
1234
|
+
};
|
|
1235
|
+
case "websocket": return {
|
|
1236
|
+
...drive,
|
|
1237
|
+
connections: drive.connections.filter((c) => keep(c.id)).map((c) => ({
|
|
1238
|
+
...c,
|
|
1239
|
+
messages: c.messages.filter((m) => keep(m.id))
|
|
1240
|
+
}))
|
|
1000
1241
|
};
|
|
1001
1242
|
}
|
|
1002
|
-
}
|
|
1003
|
-
/**
|
|
1004
|
-
|
|
1005
|
-
|
|
1243
|
+
}
|
|
1244
|
+
/**
|
|
1245
|
+
* A Durable Object namespace the scenario uses: cleared before each run, the named objects seeded with
|
|
1246
|
+
* key-value entries (and with `sql`, a SQLite-backed object's tables and rows), and its storage snapshotted
|
|
1247
|
+
* after the run. `alarmsPerObject` caps an object's alarm firings per run (default 3).
|
|
1248
|
+
*/
|
|
1249
|
+
function durableObject(binding, objects = {}, options = {}) {
|
|
1250
|
+
return {
|
|
1251
|
+
kind: "durable_object",
|
|
1252
|
+
binding,
|
|
1253
|
+
objects,
|
|
1254
|
+
...options.alarmsPerObject === void 0 ? {} : { alarmsPerObject: options.alarmsPerObject },
|
|
1255
|
+
...options.sql === void 0 ? {} : { sql: options.sql }
|
|
1256
|
+
};
|
|
1257
|
+
}
|
|
1258
|
+
/** An R2 bucket the scenario uses: emptied before each run, then seeded with these objects by key. */
|
|
1259
|
+
function r2Bucket(binding, objects = {}) {
|
|
1260
|
+
return {
|
|
1261
|
+
kind: "r2",
|
|
1262
|
+
binding,
|
|
1263
|
+
objects
|
|
1264
|
+
};
|
|
1265
|
+
}
|
|
1266
|
+
/**
|
|
1267
|
+
* Selects an R2 bucket's operations that completed, a `put` by default; a
|
|
1268
|
+
* put whose `onlyIf` failed stored nothing and is not selected, as a D1
|
|
1269
|
+
* write that changed no row is not.
|
|
1270
|
+
*/
|
|
1271
|
+
function r2Op(binding, op = "put") {
|
|
1272
|
+
const target = `R2:${binding}`;
|
|
1273
|
+
return op === "put" ? {
|
|
1274
|
+
target,
|
|
1275
|
+
op,
|
|
1276
|
+
kind: "result",
|
|
1277
|
+
where: { "result.stored": true }
|
|
1278
|
+
} : {
|
|
1279
|
+
target,
|
|
1280
|
+
op,
|
|
1281
|
+
kind: "result"
|
|
1282
|
+
};
|
|
1283
|
+
}
|
|
1284
|
+
/** A bucket's objects at the end of the run as rows `{ key, size, etag, customMetadata, httpMetadata, text? }`. */
|
|
1285
|
+
function r2Rows(binding, where) {
|
|
1286
|
+
const target = `R2:${binding}`;
|
|
1287
|
+
return where ? {
|
|
1288
|
+
target,
|
|
1289
|
+
table: "objects",
|
|
1290
|
+
where
|
|
1291
|
+
} : {
|
|
1292
|
+
target,
|
|
1293
|
+
table: "objects"
|
|
1294
|
+
};
|
|
1295
|
+
}
|
|
1296
|
+
/**
|
|
1297
|
+
* Every row the query returns is named by some row of `in` (its `column`
|
|
1298
|
+
* equals the row's value at `path`), as with a foreign key.
|
|
1299
|
+
*/
|
|
1300
|
+
function references(name, query, path, inQuery, column) {
|
|
1006
1301
|
return {
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
httpMetadata: real.httpMetadata,
|
|
1014
|
-
customMetadata: real.customMetadata,
|
|
1015
|
-
range: real.range,
|
|
1016
|
-
checksums: real.checksums,
|
|
1017
|
-
storageClass: real.storageClass,
|
|
1018
|
-
ssecKeyMd5: real.ssecKeyMd5,
|
|
1019
|
-
writeHttpMetadata: (headers) => real.writeHttpMetadata(headers)
|
|
1302
|
+
kind: "references",
|
|
1303
|
+
name,
|
|
1304
|
+
query,
|
|
1305
|
+
path,
|
|
1306
|
+
in: inQuery,
|
|
1307
|
+
column
|
|
1020
1308
|
};
|
|
1021
1309
|
}
|
|
1022
1310
|
/**
|
|
1023
|
-
*
|
|
1024
|
-
*
|
|
1025
|
-
* (copying an object) is given its bytes instead.
|
|
1311
|
+
* A Workflow binding and the class its instances run, an export of the Worker module; `name` is the
|
|
1312
|
+
* Workflow's name in the wrangler config, which instances read as `event.workflowName`.
|
|
1026
1313
|
*/
|
|
1027
|
-
|
|
1314
|
+
function workflow(binding, className, options = {}) {
|
|
1315
|
+
return {
|
|
1316
|
+
kind: "workflow",
|
|
1317
|
+
binding,
|
|
1318
|
+
className,
|
|
1319
|
+
...options.name === void 0 ? {} : { name: options.name }
|
|
1320
|
+
};
|
|
1321
|
+
}
|
|
1028
1322
|
/**
|
|
1029
|
-
*
|
|
1030
|
-
*
|
|
1031
|
-
* stream is read, cancelled or locked by a reader; the stream ends empty
|
|
1032
|
-
* once a method has read the body.
|
|
1323
|
+
* Script the Worker behind a service binding: its RPC methods answer from `methods` and its `fetch()` from
|
|
1324
|
+
* `fetch`, and the real binding is never called. See `ServiceSetup`.
|
|
1033
1325
|
*/
|
|
1034
|
-
function
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
return bytes.slice();
|
|
1326
|
+
function service(binding, options = {}) {
|
|
1327
|
+
return {
|
|
1328
|
+
kind: "service",
|
|
1329
|
+
binding,
|
|
1330
|
+
...options.methods === void 0 ? {} : { methods: options.methods },
|
|
1331
|
+
...options.fetch === void 0 ? {} : { fetch: [...options.fetch] }
|
|
1041
1332
|
};
|
|
1042
|
-
return Object.defineProperties(meta, {
|
|
1043
|
-
body: {
|
|
1044
|
-
enumerable: true,
|
|
1045
|
-
get: () => {
|
|
1046
|
-
stream ??= new ReadableStream({
|
|
1047
|
-
pull(controller) {
|
|
1048
|
-
if (!used) controller.enqueue(bytes.slice());
|
|
1049
|
-
used = true;
|
|
1050
|
-
controller.close();
|
|
1051
|
-
},
|
|
1052
|
-
cancel() {
|
|
1053
|
-
used = true;
|
|
1054
|
-
}
|
|
1055
|
-
}, { highWaterMark: 0 });
|
|
1056
|
-
buffered.set(stream, take);
|
|
1057
|
-
return stream;
|
|
1058
|
-
}
|
|
1059
|
-
},
|
|
1060
|
-
bodyUsed: {
|
|
1061
|
-
enumerable: true,
|
|
1062
|
-
get: () => used
|
|
1063
|
-
},
|
|
1064
|
-
arrayBuffer: { value: async () => take().buffer },
|
|
1065
|
-
bytes: { value: async () => take() },
|
|
1066
|
-
text: { value: async () => new TextDecoder().decode(take()) },
|
|
1067
|
-
json: { value: async () => JSON.parse(new TextDecoder().decode(take())) },
|
|
1068
|
-
blob: { value: async () => new Blob([take()]) }
|
|
1069
|
-
});
|
|
1070
1333
|
}
|
|
1071
|
-
/**
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1334
|
+
/**
|
|
1335
|
+
* Run the Worker behind a service binding for real, named by its module and its wrangler config, relative
|
|
1336
|
+
* to the scenario; `entrypoint` names the export the binding reaches. See `CalleeSetup`.
|
|
1337
|
+
*/
|
|
1338
|
+
function callee(binding, worker) {
|
|
1339
|
+
return {
|
|
1340
|
+
kind: "callee",
|
|
1341
|
+
binding,
|
|
1342
|
+
entry: worker.entry,
|
|
1343
|
+
config: worker.config,
|
|
1344
|
+
...worker.entrypoint === void 0 ? {} : { entrypoint: worker.entrypoint }
|
|
1345
|
+
};
|
|
1075
1346
|
}
|
|
1076
|
-
/**
|
|
1077
|
-
function
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1347
|
+
/** A callee and a script for one binding would contradict each other; a callee needs both files named. */
|
|
1348
|
+
function validateCalleeSetups(setup) {
|
|
1349
|
+
const errors = [];
|
|
1350
|
+
const scripted = new Set(setup.filter((s) => s.kind === "service").map((s) => String(s["binding"])));
|
|
1351
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1352
|
+
for (const step of setup) {
|
|
1353
|
+
if (step.kind !== "callee") continue;
|
|
1354
|
+
const binding = String(step["binding"]);
|
|
1355
|
+
if (!step["binding"]) errors.push("callee() needs a binding name");
|
|
1356
|
+
if (!step["entry"]) errors.push(`callee(${JSON.stringify(binding)}) needs the callee's entry`);
|
|
1357
|
+
if (!step["config"]) errors.push(`callee(${JSON.stringify(binding)}) needs the callee's wrangler config`);
|
|
1358
|
+
if (scripted.has(binding)) errors.push(`service binding ${JSON.stringify(binding)} has both a service() script and a callee(); keep one`);
|
|
1359
|
+
if (seen.has(binding)) errors.push(`service binding ${JSON.stringify(binding)} has two callee() steps`);
|
|
1360
|
+
seen.add(binding);
|
|
1361
|
+
}
|
|
1362
|
+
return errors;
|
|
1083
1363
|
}
|
|
1084
|
-
/**
|
|
1085
|
-
function
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
...
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
});
|
|
1364
|
+
/** Selects the calls through a service binding that completed (scripted or a callee's), one method's or all. */
|
|
1365
|
+
function serviceCall(binding, method) {
|
|
1366
|
+
return {
|
|
1367
|
+
target: `Service:${binding}`,
|
|
1368
|
+
...method === void 0 ? {} : { op: method },
|
|
1369
|
+
kind: "result"
|
|
1370
|
+
};
|
|
1092
1371
|
}
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1372
|
+
/** Selects a Workflow's step attempts, optionally of one step; a failed attempt's result carries its error. */
|
|
1373
|
+
function workflowStep(binding, step) {
|
|
1374
|
+
return {
|
|
1375
|
+
target: `Workflow:${binding}`,
|
|
1376
|
+
op: "step_result",
|
|
1377
|
+
kind: "result",
|
|
1378
|
+
...step === void 0 ? {} : { where: { "args.step": step } }
|
|
1379
|
+
};
|
|
1380
|
+
}
|
|
1381
|
+
/** A Workflow's instances at the end of the run as rows `{ id, status, params, output?, error? }`. */
|
|
1382
|
+
function workflowRows(binding, where) {
|
|
1383
|
+
const target = `Workflow:${binding}`;
|
|
1384
|
+
return where ? {
|
|
1097
1385
|
target,
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
const reason = `R2 ${binding}: ${what} is not modelled`;
|
|
1104
|
-
ctx.hooks.unsupported(reason);
|
|
1105
|
-
throw new Error(`eutaxy: ${reason}`);
|
|
1386
|
+
table: "instances",
|
|
1387
|
+
where
|
|
1388
|
+
} : {
|
|
1389
|
+
target,
|
|
1390
|
+
table: "instances"
|
|
1106
1391
|
};
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1392
|
+
}
|
|
1393
|
+
/**
|
|
1394
|
+
* The storage of one object (by the name its id was made from) as rows
|
|
1395
|
+
* `{ key, value }`, for state invariants.
|
|
1396
|
+
*/
|
|
1397
|
+
function durableObjectRows(binding, object, where) {
|
|
1398
|
+
const target = `DO:${binding}`;
|
|
1399
|
+
return where ? {
|
|
1400
|
+
target,
|
|
1401
|
+
table: object,
|
|
1402
|
+
where
|
|
1403
|
+
} : {
|
|
1404
|
+
target,
|
|
1405
|
+
table: object
|
|
1110
1406
|
};
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1407
|
+
}
|
|
1408
|
+
/**
|
|
1409
|
+
* One SQL table of a SQLite-backed object (by the name its id was made
|
|
1410
|
+
* from) at the end of the run, its rows as the table holds them, for state
|
|
1411
|
+
* invariants. The snapshot names it `<object>/<table>`.
|
|
1412
|
+
*/
|
|
1413
|
+
function durableObjectTable(binding, object, table, where) {
|
|
1414
|
+
const target = `DO:${binding}`;
|
|
1415
|
+
const name = `${object}/${table}`;
|
|
1416
|
+
return where ? {
|
|
1417
|
+
target,
|
|
1418
|
+
table: name,
|
|
1419
|
+
where
|
|
1420
|
+
} : {
|
|
1421
|
+
target,
|
|
1422
|
+
table: name
|
|
1116
1423
|
};
|
|
1424
|
+
}
|
|
1425
|
+
/** Drive the Worker's `queue()` handler with these messages from the named queue; an id defaults to `msg-<n>`. */
|
|
1426
|
+
function queue(name, messages) {
|
|
1117
1427
|
return {
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
const at = Date.now();
|
|
1150
|
-
return {
|
|
1151
|
-
...listed,
|
|
1152
|
-
objects: listed.objects.map((o) => metadata(o, book, at))
|
|
1153
|
-
};
|
|
1154
|
-
}, (l) => ({
|
|
1155
|
-
keys: l.objects.map((o) => o.key),
|
|
1156
|
-
truncated: l.truncated,
|
|
1157
|
-
delimitedPrefixes: l.delimitedPrefixes
|
|
1158
|
-
})),
|
|
1159
|
-
createMultipartUpload: () => notModelled("createMultipartUpload()"),
|
|
1160
|
-
resumeMultipartUpload: () => notModelled("resumeMultipartUpload()")
|
|
1428
|
+
kind: "queue",
|
|
1429
|
+
queue: name,
|
|
1430
|
+
messages: messages.map((m, i) => ({
|
|
1431
|
+
id: m.id ?? `msg-${i + 1}`,
|
|
1432
|
+
body: m.body
|
|
1433
|
+
}))
|
|
1434
|
+
};
|
|
1435
|
+
}
|
|
1436
|
+
/**
|
|
1437
|
+
* A D1 binding the scenario uses: its tables dropped before each run and the schema file applied, relative
|
|
1438
|
+
* to the scenario. Several steps on one binding apply their files in order, a migration per file.
|
|
1439
|
+
*/
|
|
1440
|
+
function d1Schema(binding, schemaFile) {
|
|
1441
|
+
return {
|
|
1442
|
+
kind: "d1",
|
|
1443
|
+
binding,
|
|
1444
|
+
schemaFile
|
|
1445
|
+
};
|
|
1446
|
+
}
|
|
1447
|
+
/**
|
|
1448
|
+
* Effect conventions for D1 (what the proxies record):
|
|
1449
|
+
* call payload { args: { sql, params } }
|
|
1450
|
+
* result payload { args: { sql, params }, result: { changes, lastRowId } }
|
|
1451
|
+
* A committed write is a `result` whose `result.changes` is at least 1.
|
|
1452
|
+
*/
|
|
1453
|
+
function d1Write(binding, op = "run") {
|
|
1454
|
+
return {
|
|
1455
|
+
target: `D1:${binding}`,
|
|
1456
|
+
op,
|
|
1457
|
+
kind: "result",
|
|
1458
|
+
atLeast: { "result.changes": 1 }
|
|
1161
1459
|
};
|
|
1162
1460
|
}
|
|
1163
|
-
/**
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
...cursor === void 0 ? {} : { cursor }
|
|
1171
|
-
});
|
|
1172
|
-
out.push(...page.objects);
|
|
1173
|
-
if (!page.truncated) return out;
|
|
1174
|
-
cursor = page.cursor;
|
|
1175
|
-
}
|
|
1461
|
+
/** Reads of a D1 binding: `first` (result payload `{ row }`), `all` or `raw`. */
|
|
1462
|
+
function d1Read(binding, op = "first") {
|
|
1463
|
+
return {
|
|
1464
|
+
target: `D1:${binding}`,
|
|
1465
|
+
op,
|
|
1466
|
+
kind: "result"
|
|
1467
|
+
};
|
|
1176
1468
|
}
|
|
1177
|
-
/**
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
for (let i = 0; i < keys.length; i += 1e3) await real.delete(keys.slice(i, i + 1e3));
|
|
1181
|
-
for (const [key, seed] of Object.entries(seeds)) if (typeof seed === "string") await real.put(key, seed);
|
|
1182
|
-
else await real.put(key, seed.value, {
|
|
1183
|
-
...seed.customMetadata ? { customMetadata: { ...seed.customMetadata } } : {},
|
|
1184
|
-
...seed.httpMetadata ? { httpMetadata: { ...seed.httpMetadata } } : {}
|
|
1185
|
-
});
|
|
1469
|
+
/** Dot path to the Nth bound parameter of a D1 statement, in an effect payload. */
|
|
1470
|
+
function d1Param(index) {
|
|
1471
|
+
return `args.params.${index}`;
|
|
1186
1472
|
}
|
|
1187
|
-
/** Largest object whose text the snapshot keeps. */
|
|
1188
|
-
const snapshotTextLimit = 4096;
|
|
1189
1473
|
/**
|
|
1190
|
-
* The
|
|
1191
|
-
*
|
|
1192
|
-
*
|
|
1193
|
-
*
|
|
1474
|
+
* The shell follows the core function `decision` (see the `refines`
|
|
1475
|
+
* invariant): every selected effect carries out the latest decision of its
|
|
1476
|
+
* invocation, agrees with it on `follows`, and, with `state`, was not made
|
|
1477
|
+
* stale by another invocation's write between the read it rests on and the
|
|
1478
|
+
* effect. The core function's module must be listed in the scenario's
|
|
1479
|
+
* `specs`, which is what records its calls.
|
|
1194
1480
|
*/
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
text = new TextDecoder("utf-8", {
|
|
1204
|
-
fatal: true,
|
|
1205
|
-
ignoreBOM: false
|
|
1206
|
-
}).decode(await body.arrayBuffer());
|
|
1207
|
-
} catch {}
|
|
1208
|
-
}
|
|
1209
|
-
rows.push(toJson({
|
|
1210
|
-
key: o.key,
|
|
1211
|
-
size: o.size,
|
|
1212
|
-
etag: o.etag,
|
|
1213
|
-
customMetadata: o.customMetadata ?? {},
|
|
1214
|
-
httpMetadata: o.httpMetadata ?? {},
|
|
1215
|
-
...text === void 0 ? {} : { text }
|
|
1216
|
-
}));
|
|
1217
|
-
}
|
|
1218
|
-
return rows;
|
|
1481
|
+
function refines(name, decision, effect, options = {}) {
|
|
1482
|
+
return {
|
|
1483
|
+
kind: "refines",
|
|
1484
|
+
name,
|
|
1485
|
+
decision,
|
|
1486
|
+
effect,
|
|
1487
|
+
...options
|
|
1488
|
+
};
|
|
1219
1489
|
}
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
{
|
|
1238
|
-
name: "month",
|
|
1239
|
-
min: 1,
|
|
1240
|
-
max: 12,
|
|
1241
|
-
names: [
|
|
1242
|
-
"jan",
|
|
1243
|
-
"feb",
|
|
1244
|
-
"mar",
|
|
1245
|
-
"apr",
|
|
1246
|
-
"may",
|
|
1247
|
-
"jun",
|
|
1248
|
-
"jul",
|
|
1249
|
-
"aug",
|
|
1250
|
-
"sep",
|
|
1251
|
-
"oct",
|
|
1252
|
-
"nov",
|
|
1253
|
-
"dec"
|
|
1254
|
-
],
|
|
1255
|
-
firstName: 1
|
|
1256
|
-
},
|
|
1257
|
-
{
|
|
1258
|
-
name: "weekday",
|
|
1259
|
-
min: 1,
|
|
1260
|
-
max: 7,
|
|
1261
|
-
names: [
|
|
1262
|
-
"sun",
|
|
1263
|
-
"mon",
|
|
1264
|
-
"tue",
|
|
1265
|
-
"wed",
|
|
1266
|
-
"thu",
|
|
1267
|
-
"fri",
|
|
1268
|
-
"sat"
|
|
1269
|
-
],
|
|
1270
|
-
firstName: 1
|
|
1490
|
+
/**
|
|
1491
|
+
* Every message's (or request's, or call's) `bodyKey` value must appear at
|
|
1492
|
+
* least once as `key` in a selected effect: nothing the drive delivered may
|
|
1493
|
+
* be lost. For an RPC drive `bodyKey` is a path into the call's arguments
|
|
1494
|
+
* (`"0.orderId"`).
|
|
1495
|
+
*/
|
|
1496
|
+
function atLeastOncePerMessage(name, drive, effect, key, bodyKey) {
|
|
1497
|
+
if (drive.kind === "queue") return atLeastOncePerMessage$1(name, drive.messages, effect, key, bodyKey);
|
|
1498
|
+
if (drive.kind === "cron") {
|
|
1499
|
+
const ticks = drive.ticks.map((t) => ({
|
|
1500
|
+
id: t.id,
|
|
1501
|
+
body: {
|
|
1502
|
+
cron: drive.cron,
|
|
1503
|
+
scheduledTime: t.at
|
|
1504
|
+
}
|
|
1505
|
+
}));
|
|
1506
|
+
return atLeastOncePerMessage$1(name, ticks, effect, key, bodyKey);
|
|
1271
1507
|
}
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1508
|
+
if (drive.kind === "rpc") {
|
|
1509
|
+
const calls = drive.calls.map((c) => ({
|
|
1510
|
+
id: c.id,
|
|
1511
|
+
body: c.args
|
|
1512
|
+
}));
|
|
1513
|
+
return {
|
|
1514
|
+
...atLeastOncePerMessage$1(name, calls, effect, key, bodyKey),
|
|
1515
|
+
perMessage: { bodyKey: bodyKey === "" ? "args" : `args.${bodyKey}` }
|
|
1516
|
+
};
|
|
1278
1517
|
}
|
|
1279
|
-
if (
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
if (pieces.length > 2 || part === "") throw new Error(`${field.name}: ${JSON.stringify(part)} is not a value, range or step`);
|
|
1290
|
-
const [rangeText, stepText] = pieces;
|
|
1291
|
-
let step = 1;
|
|
1292
|
-
if (stepText !== void 0) {
|
|
1293
|
-
if (!/^\d+$/.test(stepText) || Number(stepText) < 1) throw new Error(`${field.name}: step ${JSON.stringify(stepText)} is not a positive number`);
|
|
1294
|
-
step = Number(stepText);
|
|
1295
|
-
}
|
|
1296
|
-
let from;
|
|
1297
|
-
let to;
|
|
1298
|
-
if (rangeText === "*") {
|
|
1299
|
-
from = field.min;
|
|
1300
|
-
to = field.max;
|
|
1301
|
-
} else if (rangeText.includes("-")) {
|
|
1302
|
-
const ends = rangeText.split("-");
|
|
1303
|
-
if (ends.length !== 2) throw new Error(`${field.name}: ${JSON.stringify(rangeText)} is not a range`);
|
|
1304
|
-
const [a, b] = ends;
|
|
1305
|
-
from = value(a, field);
|
|
1306
|
-
to = value(b, field);
|
|
1307
|
-
if (from > to) throw new Error(`${field.name}: range ${rangeText} runs backwards`);
|
|
1308
|
-
} else {
|
|
1309
|
-
from = value(rangeText, field);
|
|
1310
|
-
to = stepText === void 0 ? from : field.max;
|
|
1311
|
-
}
|
|
1312
|
-
for (let v = from; v <= to; v += step) out.add(v);
|
|
1518
|
+
if (drive.kind === "websocket") {
|
|
1519
|
+
if (bodyKey !== "") throw new Error(`atLeastOncePerMessage ${JSON.stringify(name)}: a websocket drive keys each connection by its path; bodyKey must be ""`);
|
|
1520
|
+
const conns = drive.connections.map((c) => ({
|
|
1521
|
+
id: c.id,
|
|
1522
|
+
body: c.path
|
|
1523
|
+
}));
|
|
1524
|
+
return {
|
|
1525
|
+
...atLeastOncePerMessage$1(name, conns, effect, key, ""),
|
|
1526
|
+
perMessage: { bodyKey: "path" }
|
|
1527
|
+
};
|
|
1313
1528
|
}
|
|
1314
|
-
|
|
1529
|
+
const requests = drive.requests.map((r) => ({
|
|
1530
|
+
id: r.id,
|
|
1531
|
+
body: r.body ?? null
|
|
1532
|
+
}));
|
|
1533
|
+
return {
|
|
1534
|
+
...atLeastOncePerMessage$1(name, requests, effect, key, bodyKey),
|
|
1535
|
+
perMessage: { bodyKey: bodyKey === "" ? "body" : `body.${bodyKey}` }
|
|
1536
|
+
};
|
|
1315
1537
|
}
|
|
1316
|
-
/**
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1538
|
+
/**
|
|
1539
|
+
* Selects the frames the Worker sent on a connection (`WebSocket:<connection>`,
|
|
1540
|
+
* op `message`), each recorded at the end of the run, in arrival order, with
|
|
1541
|
+
* its data (JSON where it parses, text otherwise).
|
|
1542
|
+
*/
|
|
1543
|
+
function webSocketReceived(connection) {
|
|
1321
1544
|
return {
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
months: parseField(month, fields[3]),
|
|
1326
|
-
weekdays: parseField(weekday, fields[4]),
|
|
1327
|
-
anyDayOfMonth: dom === "*",
|
|
1328
|
-
anyWeekday: weekday === "*"
|
|
1545
|
+
target: `WebSocket:${connection}`,
|
|
1546
|
+
op: "message",
|
|
1547
|
+
kind: "result"
|
|
1329
1548
|
};
|
|
1330
1549
|
}
|
|
1331
|
-
/**
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1550
|
+
/**
|
|
1551
|
+
* Selects the responses the Worker returned for a path (`ok` narrows to 2xx
|
|
1552
|
+
* or to everything else). One `result` per attempt: a crash before the
|
|
1553
|
+
* response leaves none, a thrown error records status 500.
|
|
1554
|
+
*/
|
|
1555
|
+
function httpResponse(path, options = {}) {
|
|
1556
|
+
return {
|
|
1557
|
+
target: `Http:${path}`,
|
|
1558
|
+
op: "response",
|
|
1559
|
+
kind: "result",
|
|
1560
|
+
...options.ok === void 0 ? {} : { where: { "result.ok": options.ok } }
|
|
1561
|
+
};
|
|
1340
1562
|
}
|
|
1341
|
-
const minuteMs = 6e4;
|
|
1342
1563
|
/**
|
|
1343
|
-
*
|
|
1344
|
-
*
|
|
1345
|
-
*
|
|
1564
|
+
* Selects the answers an RPC method gave (`ok` narrows to values returned
|
|
1565
|
+
* or to errors thrown). One `result` per attempt: a crash before the
|
|
1566
|
+
* response leaves none.
|
|
1346
1567
|
*/
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
while (out.length < count) {
|
|
1355
|
-
if (t > horizon) throw new Error(`${JSON.stringify(expression)} never fires`);
|
|
1356
|
-
if (cronMatches(schedule, t)) {
|
|
1357
|
-
out.push(t);
|
|
1358
|
-
horizon = t + longestGapMs;
|
|
1359
|
-
}
|
|
1360
|
-
t += minuteMs;
|
|
1361
|
-
}
|
|
1362
|
-
return out;
|
|
1568
|
+
function rpcResponse(method, options = {}) {
|
|
1569
|
+
return {
|
|
1570
|
+
target: rpcTarget(options, method),
|
|
1571
|
+
op: "response",
|
|
1572
|
+
kind: "result",
|
|
1573
|
+
...options.ok === void 0 ? {} : { where: { "result.ok": options.ok } }
|
|
1574
|
+
};
|
|
1363
1575
|
}
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1576
|
+
/** Rows of a D1 table in the end-of-run snapshot, optionally filtered. */
|
|
1577
|
+
function d1Rows(binding, table, where) {
|
|
1578
|
+
return where ? {
|
|
1579
|
+
target: `D1:${binding}`,
|
|
1580
|
+
table,
|
|
1581
|
+
where
|
|
1582
|
+
} : {
|
|
1583
|
+
target: `D1:${binding}`,
|
|
1584
|
+
table
|
|
1585
|
+
};
|
|
1586
|
+
}
|
|
1587
|
+
/** Every row the query selects satisfies all conditions. */
|
|
1588
|
+
function everyRow(name, query, holds) {
|
|
1372
1589
|
return {
|
|
1373
|
-
kind: "
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
path: r.path,
|
|
1378
|
-
headers: r.headers ?? {},
|
|
1379
|
-
...r.body === void 0 ? {} : { body: r.body }
|
|
1380
|
-
})),
|
|
1381
|
-
retries: options.retries ?? 3,
|
|
1382
|
-
retryOn: options.retryOn ?? "non-2xx",
|
|
1383
|
-
...options.delaysMs === void 0 ? {} : { delaysMs: [...options.delaysMs] },
|
|
1384
|
-
...options.deadlineMs === void 0 ? {} : { deadlineMs: options.deadlineMs }
|
|
1590
|
+
kind: "everyRow",
|
|
1591
|
+
name,
|
|
1592
|
+
query,
|
|
1593
|
+
holds
|
|
1385
1594
|
};
|
|
1386
1595
|
}
|
|
1387
|
-
|
|
1596
|
+
/** No two rows the query selects share the value at `path` (a column, or a dot path into the row). */
|
|
1597
|
+
function unique(name, query, path) {
|
|
1388
1598
|
return {
|
|
1389
|
-
kind: "
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
id,
|
|
1394
|
-
path: c.path,
|
|
1395
|
-
headers: c.headers ?? {},
|
|
1396
|
-
messages: (c.messages ?? []).map((m, j) => ({
|
|
1397
|
-
id: m.id ?? `${id}:${j + 1}`,
|
|
1398
|
-
data: m.data
|
|
1399
|
-
}))
|
|
1400
|
-
};
|
|
1401
|
-
})
|
|
1599
|
+
kind: "unique",
|
|
1600
|
+
name,
|
|
1601
|
+
query,
|
|
1602
|
+
path
|
|
1402
1603
|
};
|
|
1403
1604
|
}
|
|
1404
|
-
|
|
1605
|
+
/** Every selected effect has a row whose column equals the effect's key. */
|
|
1606
|
+
function implies(name, when, key, state, column) {
|
|
1405
1607
|
return {
|
|
1406
|
-
kind: "
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
})),
|
|
1413
|
-
retries: options.retries ?? 0,
|
|
1414
|
-
...options.delaysMs === void 0 ? {} : { delaysMs: [...options.delaysMs] },
|
|
1415
|
-
...options.deadlineMs === void 0 ? {} : { deadlineMs: options.deadlineMs }
|
|
1608
|
+
kind: "implies",
|
|
1609
|
+
name,
|
|
1610
|
+
when,
|
|
1611
|
+
key,
|
|
1612
|
+
state,
|
|
1613
|
+
column
|
|
1416
1614
|
};
|
|
1417
1615
|
}
|
|
1418
|
-
/**
|
|
1419
|
-
function
|
|
1420
|
-
return
|
|
1616
|
+
/** Selects the acknowledgement that took effect for each message (explicit or implicit; not one ignored after a retry). */
|
|
1617
|
+
function queueAck(queueName) {
|
|
1618
|
+
return {
|
|
1619
|
+
target: `Queue:${queueName}`,
|
|
1620
|
+
op: "ack",
|
|
1621
|
+
kind: "result",
|
|
1622
|
+
where: { "result.effective": true }
|
|
1623
|
+
};
|
|
1421
1624
|
}
|
|
1422
|
-
|
|
1423
|
-
|
|
1625
|
+
/**
|
|
1626
|
+
* Declare an external service: requests to `host` are answered from
|
|
1627
|
+
* `responses` (every request gets 200 and an empty body when omitted), and
|
|
1628
|
+
* `dedupeBy` names the header whose value makes repeated requests
|
|
1629
|
+
* idempotent at that service.
|
|
1630
|
+
*/
|
|
1631
|
+
function external(name, host, options = {}) {
|
|
1424
1632
|
return {
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
at
|
|
1430
|
-
})),
|
|
1431
|
-
retries: options.retries ?? 0
|
|
1633
|
+
name,
|
|
1634
|
+
host,
|
|
1635
|
+
guarantees: options.dedupeBy ? { dedupeBy: options.dedupeBy } : {},
|
|
1636
|
+
...options.responses ? { responses: options.responses } : {}
|
|
1432
1637
|
};
|
|
1433
1638
|
}
|
|
1434
|
-
/**
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
}
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
})
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
scheduledTime: t.at
|
|
1458
|
-
},
|
|
1459
|
-
at: t.at
|
|
1460
|
-
}));
|
|
1461
|
-
case "websocket": {
|
|
1462
|
-
const opens = drive.connections.map((c) => ({
|
|
1463
|
-
id: c.id,
|
|
1464
|
-
attempt: 1,
|
|
1465
|
-
data: {
|
|
1466
|
-
kind: "open",
|
|
1467
|
-
connection: c.id,
|
|
1468
|
-
path: c.path,
|
|
1469
|
-
headers: c.headers
|
|
1470
|
-
}
|
|
1471
|
-
}));
|
|
1472
|
-
const rounds = Math.max(0, ...drive.connections.map((c) => c.messages.length));
|
|
1473
|
-
const messages = [];
|
|
1474
|
-
for (let i = 0; i < rounds; i++) for (const c of drive.connections) {
|
|
1475
|
-
const m = c.messages[i];
|
|
1476
|
-
if (m) messages.push({
|
|
1477
|
-
id: m.id,
|
|
1478
|
-
attempt: 1,
|
|
1479
|
-
data: {
|
|
1480
|
-
kind: "message",
|
|
1481
|
-
connection: c.id,
|
|
1482
|
-
message: m.id,
|
|
1483
|
-
index: i,
|
|
1484
|
-
data: m.data
|
|
1485
|
-
}
|
|
1486
|
-
});
|
|
1487
|
-
}
|
|
1488
|
-
return [...opens, ...messages];
|
|
1639
|
+
/**
|
|
1640
|
+
* Selects the requests to an external that took effect: a request replayed
|
|
1641
|
+
* under a dedupe key the external had already seen is not counted.
|
|
1642
|
+
*/
|
|
1643
|
+
function fetchCall(externalName, method) {
|
|
1644
|
+
return {
|
|
1645
|
+
target: `Fetch:${externalName}`,
|
|
1646
|
+
...method ? { op: method.toUpperCase() } : {},
|
|
1647
|
+
kind: "result",
|
|
1648
|
+
where: { "result.effective": true }
|
|
1649
|
+
};
|
|
1650
|
+
}
|
|
1651
|
+
function validateWebSocketDrive(drive) {
|
|
1652
|
+
const errors = [];
|
|
1653
|
+
if (drive.connections.length === 0) errors.push("websocket drive needs at least one connection");
|
|
1654
|
+
const ids = /* @__PURE__ */ new Set();
|
|
1655
|
+
drive.connections.forEach((c, i) => {
|
|
1656
|
+
if (!c.path.startsWith("/")) errors.push(`connections[${i}].path must start with "/"`);
|
|
1657
|
+
if (ids.has(c.id)) errors.push(`duplicate connection id ${JSON.stringify(c.id)}`);
|
|
1658
|
+
ids.add(c.id);
|
|
1659
|
+
for (const m of c.messages) {
|
|
1660
|
+
if (ids.has(m.id)) errors.push(`duplicate message id ${JSON.stringify(m.id)}`);
|
|
1661
|
+
ids.add(m.id);
|
|
1489
1662
|
}
|
|
1490
|
-
}
|
|
1663
|
+
});
|
|
1664
|
+
return errors;
|
|
1491
1665
|
}
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
};
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
...drive,
|
|
1506
|
-
calls: drive.calls.filter((c) => keep(c.id))
|
|
1507
|
-
};
|
|
1508
|
-
case "cron": return {
|
|
1509
|
-
...drive,
|
|
1510
|
-
ticks: drive.ticks.filter((t) => keep(t.id))
|
|
1511
|
-
};
|
|
1512
|
-
case "websocket": return {
|
|
1513
|
-
...drive,
|
|
1514
|
-
connections: drive.connections.filter((c) => keep(c.id)).map((c) => ({
|
|
1515
|
-
...c,
|
|
1516
|
-
messages: c.messages.filter((m) => keep(m.id))
|
|
1517
|
-
}))
|
|
1518
|
-
};
|
|
1519
|
-
}
|
|
1666
|
+
function validateHttpDrive(drive) {
|
|
1667
|
+
const errors = [];
|
|
1668
|
+
if (drive.requests.length === 0) errors.push("http drive needs at least one request");
|
|
1669
|
+
const ids = /* @__PURE__ */ new Set();
|
|
1670
|
+
drive.requests.forEach((r, i) => {
|
|
1671
|
+
if (!r.path.startsWith("/")) errors.push(`requests[${i}].path must start with "/"`);
|
|
1672
|
+
if (!r.method) errors.push(`requests[${i}].method must not be empty`);
|
|
1673
|
+
if (ids.has(r.id)) errors.push(`duplicate request id ${JSON.stringify(r.id)}`);
|
|
1674
|
+
ids.add(r.id);
|
|
1675
|
+
if ((r.method === "GET" || r.method === "HEAD") && r.body !== void 0) errors.push(`requests[${i}] is a ${r.method} and cannot carry a body`);
|
|
1676
|
+
});
|
|
1677
|
+
errors.push(...validateCaller("http", drive));
|
|
1678
|
+
return errors;
|
|
1520
1679
|
}
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
};
|
|
1680
|
+
/** The caller's policy, as both drives a caller resends declare it. */
|
|
1681
|
+
function validateCaller(kind, drive) {
|
|
1682
|
+
const errors = [];
|
|
1683
|
+
if (!(Number.isInteger(drive.retries) && drive.retries >= 0)) errors.push(`${kind} drive retries must be a non-negative integer`);
|
|
1684
|
+
(drive.delaysMs ?? []).forEach((d, i) => {
|
|
1685
|
+
if (!(Number.isInteger(d) && d >= 0)) errors.push(`${kind} drive delaysMs[${i}] must be a non-negative integer`);
|
|
1686
|
+
});
|
|
1687
|
+
if (drive.deadlineMs !== void 0 && !(Number.isInteger(drive.deadlineMs) && drive.deadlineMs > 0)) errors.push(`${kind} drive deadlineMs must be a positive integer`);
|
|
1688
|
+
return errors;
|
|
1529
1689
|
}
|
|
1530
|
-
function
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1690
|
+
function validateCronDrive(drive) {
|
|
1691
|
+
const errors = [];
|
|
1692
|
+
try {
|
|
1693
|
+
parseCron(drive.cron);
|
|
1694
|
+
} catch (err) {
|
|
1695
|
+
errors.push(`cron drive: ${err.message}`);
|
|
1696
|
+
}
|
|
1697
|
+
if (drive.ticks.length === 0) errors.push("cron drive ticks must be a positive integer");
|
|
1698
|
+
const ids = /* @__PURE__ */ new Set();
|
|
1699
|
+
drive.ticks.forEach((t, i) => {
|
|
1700
|
+
if (ids.has(t.id)) errors.push(`duplicate tick id ${JSON.stringify(t.id)}`);
|
|
1701
|
+
ids.add(t.id);
|
|
1702
|
+
const previous = drive.ticks[i - 1];
|
|
1703
|
+
if (previous && !(t.at > previous.at)) errors.push(`ticks[${i}] does not come after ticks[${i - 1}]`);
|
|
1704
|
+
});
|
|
1705
|
+
if (!(Number.isInteger(drive.retries) && drive.retries >= 0)) errors.push("cron drive retries must be a non-negative integer");
|
|
1706
|
+
return errors;
|
|
1707
|
+
}
|
|
1708
|
+
/** A method name the entrypoint can have: an identifier that is not the constructor. */
|
|
1709
|
+
const methodName = /^[A-Za-z_$][\w$]*$/;
|
|
1710
|
+
function validateRpcDrive(drive) {
|
|
1711
|
+
const errors = [];
|
|
1712
|
+
if (drive.entrypoint !== void 0 && !methodName.test(drive.entrypoint)) errors.push("rpc drive entrypoint must be an exported class name");
|
|
1713
|
+
const ids = /* @__PURE__ */ new Set();
|
|
1714
|
+
drive.calls.forEach((c, i) => {
|
|
1715
|
+
if (!methodName.test(c.method) || c.method === "constructor") errors.push(`calls[${i}].method must be a method name`);
|
|
1716
|
+
if (!Array.isArray(c.args)) errors.push(`calls[${i}].args must be an array`);
|
|
1717
|
+
if (ids.has(c.id)) errors.push(`duplicate call id ${JSON.stringify(c.id)}`);
|
|
1718
|
+
ids.add(c.id);
|
|
1719
|
+
});
|
|
1720
|
+
errors.push(...validateCaller("rpc", drive));
|
|
1721
|
+
return errors;
|
|
1536
1722
|
}
|
|
1537
1723
|
/**
|
|
1538
|
-
*
|
|
1539
|
-
*
|
|
1540
|
-
*
|
|
1724
|
+
* Durable Object setups: an object's or a SQL table's name may not hold
|
|
1725
|
+
* "/", since the snapshot names a table `<object>/<table>` and a selector
|
|
1726
|
+
* must read back to one place.
|
|
1541
1727
|
*/
|
|
1542
|
-
function
|
|
1543
|
-
const
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1728
|
+
function validateDurableObjectSetups(setup) {
|
|
1729
|
+
const errors = [];
|
|
1730
|
+
for (const step of setup) {
|
|
1731
|
+
if (step["kind"] !== "durable_object") continue;
|
|
1732
|
+
const s = step;
|
|
1733
|
+
for (const name of [...Object.keys(s.objects), ...Object.keys(s.sql ?? {})]) if (name.includes("/")) errors.push(`durableObject ${s.binding}: object name ${JSON.stringify(name)} holds "/", which the snapshot uses between an object and its table`);
|
|
1734
|
+
for (const [name, seed] of Object.entries(s.sql ?? {})) {
|
|
1735
|
+
if (typeof seed.schema !== "string" || seed.schema.trim() === "") errors.push(`durableObject ${s.binding}: object ${JSON.stringify(name)} has a sql seed without a schema`);
|
|
1736
|
+
for (const [table, rows] of Object.entries(seed.rows ?? {})) {
|
|
1737
|
+
if (table.includes("/")) errors.push(`durableObject ${s.binding}: table name ${JSON.stringify(table)} of ${JSON.stringify(name)} holds "/"`);
|
|
1738
|
+
if (!Array.isArray(rows) || rows.some((r) => typeof r !== "object" || r === null || Array.isArray(r))) errors.push(`durableObject ${s.binding}: rows of ${JSON.stringify(name)}.${table} must be an array of objects`);
|
|
1739
|
+
}
|
|
1740
|
+
}
|
|
1741
|
+
}
|
|
1742
|
+
return errors;
|
|
1554
1743
|
}
|
|
1555
|
-
/**
|
|
1556
|
-
function
|
|
1557
|
-
const
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1744
|
+
/** Build and validate a scenario spec; throws with every problem listed. */
|
|
1745
|
+
function defineScenario(input) {
|
|
1746
|
+
const drive = input.drive.kind === "queue" ? queue(input.drive.queue, input.drive.messages) : input.drive;
|
|
1747
|
+
const spec = {
|
|
1748
|
+
version: 1,
|
|
1749
|
+
name: input.name,
|
|
1750
|
+
platform: "cloudflare",
|
|
1751
|
+
worker: input.worker,
|
|
1752
|
+
drive,
|
|
1753
|
+
setup: input.setup ?? [],
|
|
1754
|
+
externals: input.externals ?? [],
|
|
1755
|
+
invariants: input.invariants,
|
|
1756
|
+
bounds: {
|
|
1757
|
+
...defaultBounds,
|
|
1758
|
+
...input.bounds
|
|
1759
|
+
},
|
|
1760
|
+
...input.specs ? { specs: input.specs } : {}
|
|
1565
1761
|
};
|
|
1762
|
+
const errors = [
|
|
1763
|
+
...validateScenario(spec),
|
|
1764
|
+
...validateDurableObjectSetups(spec.setup),
|
|
1765
|
+
...validateCalleeSetups(spec.setup),
|
|
1766
|
+
...drive.kind === "http" ? validateHttpDrive(drive) : [],
|
|
1767
|
+
...drive.kind === "rpc" ? validateRpcDrive(drive) : [],
|
|
1768
|
+
...drive.kind === "cron" ? validateCronDrive(drive) : [],
|
|
1769
|
+
...drive.kind === "websocket" ? validateWebSocketDrive(drive) : []
|
|
1770
|
+
];
|
|
1771
|
+
if (errors.length > 0) throw new Error(`invalid scenario ${JSON.stringify(input.name)}:\n- ${errors.join("\n- ")}`);
|
|
1772
|
+
return spec;
|
|
1566
1773
|
}
|
|
1774
|
+
// packages/cloudflare/src/rpc.ts
|
|
1567
1775
|
/**
|
|
1568
|
-
*
|
|
1569
|
-
*
|
|
1776
|
+
* Inbound RPC delivery: one invocation per attempt of a `WorkerEntrypoint`
|
|
1777
|
+
* method call the drive's caller makes. The entrypoint is constructed anew
|
|
1778
|
+
* for each call, as the runtime does (Cloudflare, Workers RPC: a new
|
|
1779
|
+
* instance of the class for every call), and its return value or the error
|
|
1780
|
+
* it threw is the response the caller sees.
|
|
1570
1781
|
*/
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
column
|
|
1579
|
-
};
|
|
1580
|
-
}
|
|
1581
|
-
function workflow(binding, className, options = {}) {
|
|
1582
|
-
return {
|
|
1583
|
-
kind: "workflow",
|
|
1584
|
-
binding,
|
|
1585
|
-
className,
|
|
1586
|
-
...options.name === void 0 ? {} : { name: options.name }
|
|
1587
|
-
};
|
|
1782
|
+
/**
|
|
1783
|
+
* An error as the caller sees it over RPC: a new error object with the
|
|
1784
|
+
* name and message (Cloudflare, RPC error handling), nothing of its class.
|
|
1785
|
+
*/
|
|
1786
|
+
function describeError(error) {
|
|
1787
|
+
if (error instanceof Error) return `${error.name}: ${error.message}`;
|
|
1788
|
+
return typeof error === "string" ? error : JSON.stringify(toJson(error));
|
|
1588
1789
|
}
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1790
|
+
/** One attempt of a call, under the caller's retry policy and deadline. */
|
|
1791
|
+
async function deliverCall(event, hooks, spec, drive, invocation, cls, env) {
|
|
1792
|
+
const call = event.data;
|
|
1793
|
+
const target = rpcTarget(drive, call.method);
|
|
1794
|
+
const inv = hooks.startInvocation(invocation);
|
|
1795
|
+
const background = [];
|
|
1796
|
+
const args = {
|
|
1797
|
+
callId: event.id,
|
|
1798
|
+
method: call.method,
|
|
1799
|
+
args: call.args
|
|
1595
1800
|
};
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1801
|
+
const caller = startCaller(event, hooks, spec, drive, target, {
|
|
1802
|
+
callId: event.id,
|
|
1803
|
+
attempts: event.attempt
|
|
1804
|
+
});
|
|
1805
|
+
const ran = await runInvocation(hooks, inv, () => callMethod(cls, call, executionContext(background), env));
|
|
1806
|
+
let status = ran.status;
|
|
1807
|
+
let late = caller.isLate();
|
|
1808
|
+
let answer = null;
|
|
1809
|
+
if (ran.status === "completed") {
|
|
1810
|
+
if (!isPlainData(ran.value)) hooks.unsupported(`Rpc ${call.method}: the result is not plain data (a stub, a function or a stream); RPC capabilities are not modelled`);
|
|
1811
|
+
const s = {
|
|
1812
|
+
ok: true,
|
|
1813
|
+
value: toJson(ran.value)
|
|
1814
|
+
};
|
|
1815
|
+
try {
|
|
1816
|
+
hooks.effectSync({
|
|
1817
|
+
invocation,
|
|
1818
|
+
target,
|
|
1819
|
+
op: "response",
|
|
1820
|
+
args,
|
|
1821
|
+
allowed: caller.responseFaults
|
|
1822
|
+
}, () => s, (v) => v);
|
|
1823
|
+
answer = s;
|
|
1824
|
+
} catch (err) {
|
|
1825
|
+
if (err instanceof CrashSignal) status = "crashed";
|
|
1826
|
+
else if (err instanceof InjectedEffectError) {
|
|
1827
|
+
answer = s;
|
|
1828
|
+
late = true;
|
|
1829
|
+
} else throw err;
|
|
1830
|
+
}
|
|
1831
|
+
} else if (ran.status === "errored") {
|
|
1832
|
+
const s = {
|
|
1833
|
+
ok: false,
|
|
1834
|
+
error: describeError(ran.error)
|
|
1835
|
+
};
|
|
1836
|
+
hooks.effectSync({
|
|
1837
|
+
invocation,
|
|
1838
|
+
target,
|
|
1839
|
+
op: "response",
|
|
1840
|
+
args,
|
|
1841
|
+
allowed: []
|
|
1842
|
+
}, () => s, (v) => v);
|
|
1843
|
+
answer = s;
|
|
1844
|
+
}
|
|
1845
|
+
caller.settle(answer !== null && !late && answer.ok, late);
|
|
1846
|
+
if (await drainBackground(hooks, inv, invocation, target, background)) status = "crashed";
|
|
1599
1847
|
return {
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
kind: "result"
|
|
1848
|
+
status,
|
|
1849
|
+
followUps: []
|
|
1603
1850
|
};
|
|
1604
1851
|
}
|
|
1605
|
-
/**
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1852
|
+
/**
|
|
1853
|
+
* The class an RPC drive calls: the named export, or the Worker's default
|
|
1854
|
+
* export (the class passed as the handler, or `exports.default`). Not
|
|
1855
|
+
* necessarily a class: the platform reports what it found instead.
|
|
1856
|
+
*/
|
|
1857
|
+
function entrypointClass(handler, exports, entrypoint) {
|
|
1858
|
+
if (entrypoint !== void 0) return exports?.[entrypoint];
|
|
1859
|
+
return typeof handler === "function" ? handler : exports?.["default"];
|
|
1613
1860
|
}
|
|
1614
|
-
/**
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1861
|
+
/**
|
|
1862
|
+
* The method RPC exposes under a name: one the class or a superclass defines
|
|
1863
|
+
* on its prototype. An instance property, even a function, and Object's own
|
|
1864
|
+
* methods are not callable (workerd: "The RPC receiver does not implement the
|
|
1865
|
+
* method").
|
|
1866
|
+
*/
|
|
1867
|
+
function rpcMethod(instance, name) {
|
|
1868
|
+
for (let proto = Object.getPrototypeOf(instance); proto !== null && proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) {
|
|
1869
|
+
const own = Object.getOwnPropertyDescriptor(proto, name);
|
|
1870
|
+
if (!own) continue;
|
|
1871
|
+
return typeof own.value === "function" && name !== "constructor" ? own.value : void 0;
|
|
1872
|
+
}
|
|
1625
1873
|
}
|
|
1626
1874
|
/**
|
|
1627
|
-
*
|
|
1628
|
-
*
|
|
1875
|
+
* Construct the entrypoint for one call and invoke the method, as the
|
|
1876
|
+
* runtime does per call. The arguments are copied, as RPC copies them: a
|
|
1877
|
+
* method that mutates one changes neither the scenario nor a later attempt.
|
|
1629
1878
|
*/
|
|
1630
|
-
function
|
|
1631
|
-
const
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
where
|
|
1636
|
-
} : {
|
|
1637
|
-
target,
|
|
1638
|
-
table: object
|
|
1639
|
-
};
|
|
1879
|
+
function callMethod(cls, call, ctx, env) {
|
|
1880
|
+
const instance = constructEntrypoint(cls, "WorkerEntrypoint", ctx, env);
|
|
1881
|
+
const method = rpcMethod(instance, call.method);
|
|
1882
|
+
if (!method) throw new TypeError(`The RPC receiver does not implement the method "${call.method}".`);
|
|
1883
|
+
return method.apply(instance, structuredClone(call.args));
|
|
1640
1884
|
}
|
|
1885
|
+
// packages/cloudflare/src/services.ts
|
|
1641
1886
|
/**
|
|
1642
|
-
*
|
|
1643
|
-
*
|
|
1644
|
-
*
|
|
1887
|
+
* Service bindings with the callee scripted. A Worker reaches a peer through
|
|
1888
|
+
* `env.BINDING`, by RPC method or by `fetch()`; Cloudflare routes the call on
|
|
1889
|
+
* the same thread and retries nothing (Workers, service bindings). The real
|
|
1890
|
+
* binding is never called here: the scenario's `service()` setup scripts the
|
|
1891
|
+
* replies, and each call is one effect with the faults of a Durable Object
|
|
1892
|
+
* stub call, where `crash_before` and `error` mean the call never reached
|
|
1893
|
+
* the callee, `ambiguous` that it acted and the answer was lost, and
|
|
1894
|
+
* `crash_after` that the caller died after it. The stub itself (callable
|
|
1895
|
+
* methods, awaited properties, `fetch`, the pipelining guards) is shared
|
|
1896
|
+
* with the callee that runs for real (`callees.ts`).
|
|
1645
1897
|
*/
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1898
|
+
/** Marks of the other kinds of binding, which a service binding's duck type must not carry. */
|
|
1899
|
+
const otherKinds = [
|
|
1900
|
+
"prepare",
|
|
1901
|
+
"idFromName",
|
|
1902
|
+
"head",
|
|
1903
|
+
"createBatch"
|
|
1904
|
+
];
|
|
1905
|
+
/**
|
|
1906
|
+
* Whether an env value is a service binding (the runtime's `Fetcher`). In
|
|
1907
|
+
* workerd it is an RPC stub whose every property read yields a callable, so
|
|
1908
|
+
* duck typing alone would take it for any other kind: the runtime's class is
|
|
1909
|
+
* checked first, and the duck type (fetch and connect, none of the other
|
|
1910
|
+
* kinds' marks) serves test doubles.
|
|
1911
|
+
*/
|
|
1912
|
+
function isServiceBinding(value) {
|
|
1913
|
+
if (typeof value !== "object" || value === null) return false;
|
|
1914
|
+
const fetcher = globalThis.Fetcher;
|
|
1915
|
+
if (typeof fetcher === "function" && value instanceof fetcher) return true;
|
|
1916
|
+
if ((Object.getPrototypeOf(value)?.constructor)?.name === "Fetcher") return true;
|
|
1917
|
+
const v = value;
|
|
1918
|
+
return typeof v["fetch"] === "function" && typeof v["connect"] === "function" && otherKinds.every((k) => typeof v[k] !== "function");
|
|
1657
1919
|
}
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1920
|
+
/** The built-in error classes RPC carries across as themselves (workerd keeps the type). */
|
|
1921
|
+
const builtInErrors = {
|
|
1922
|
+
Error,
|
|
1923
|
+
EvalError,
|
|
1924
|
+
RangeError,
|
|
1925
|
+
ReferenceError,
|
|
1926
|
+
SyntaxError,
|
|
1927
|
+
TypeError,
|
|
1928
|
+
URIError
|
|
1929
|
+
};
|
|
1930
|
+
/**
|
|
1931
|
+
* The error the caller sees for a `throws` reply, `"<Name>: <message>"`: a
|
|
1932
|
+
* built-in error class is that class, so `instanceof` holds as it does over
|
|
1933
|
+
* RPC; any other name is an `Error` carrying the name.
|
|
1934
|
+
*/
|
|
1935
|
+
function scriptedError(spec) {
|
|
1936
|
+
const at = spec.indexOf(": ");
|
|
1937
|
+
if (at < 0) return new Error(spec);
|
|
1938
|
+
const name = spec.slice(0, at);
|
|
1939
|
+
const message = spec.slice(at + 2);
|
|
1940
|
+
const builtIn = builtInErrors[name];
|
|
1941
|
+
if (builtIn) return new builtIn(message);
|
|
1942
|
+
const error = new Error(message);
|
|
1943
|
+
error.name = name;
|
|
1944
|
+
return error;
|
|
1667
1945
|
}
|
|
1668
|
-
|
|
1946
|
+
/** Read a request for the log without consuming it: the callee may still read the body. */
|
|
1947
|
+
async function recordRequest(request) {
|
|
1948
|
+
const method = request.method.toUpperCase();
|
|
1949
|
+
const headers = {};
|
|
1950
|
+
request.headers.forEach((value, name) => {
|
|
1951
|
+
headers[name.toLowerCase()] = value;
|
|
1952
|
+
});
|
|
1953
|
+
const body = parseBody(await request.clone().text());
|
|
1669
1954
|
return {
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1955
|
+
url: request.url,
|
|
1956
|
+
method,
|
|
1957
|
+
headers,
|
|
1958
|
+
body
|
|
1673
1959
|
};
|
|
1674
1960
|
}
|
|
1675
1961
|
/**
|
|
1676
|
-
*
|
|
1677
|
-
*
|
|
1678
|
-
*
|
|
1679
|
-
* A committed write is a `result` whose `result.changes` is at least 1.
|
|
1962
|
+
* The stub a Worker sees under a service binding's name: methods callable
|
|
1963
|
+
* and awaitable, `fetch`, and the guards against what is not modelled
|
|
1964
|
+
* (promise pipelining, `connect()`), with the answers supplied.
|
|
1680
1965
|
*/
|
|
1681
|
-
function
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1966
|
+
function serviceStub(binding, ctx, answers) {
|
|
1967
|
+
const unsupported = (what) => {
|
|
1968
|
+
const reason = `service binding ${binding}: ${what}`;
|
|
1969
|
+
ctx.hooks.unsupported(reason);
|
|
1970
|
+
throw new Error(`eutaxy: ${reason}`);
|
|
1971
|
+
};
|
|
1972
|
+
/**
|
|
1973
|
+
* The promise a call returns. On the real stub it is an RPC promise that
|
|
1974
|
+
* pipelines property reads (`stub.charge().id`); this one is not, so a read
|
|
1975
|
+
* on it makes the run UNSUPPORTED instead of yielding undefined.
|
|
1976
|
+
*/
|
|
1977
|
+
const pipelineGuard = (promise, method) => new Proxy(promise, { get(target, prop) {
|
|
1978
|
+
if (typeof prop === "symbol" || prop === "then" || prop === "catch" || prop === "finally") {
|
|
1979
|
+
const value = Reflect.get(target, prop, target);
|
|
1980
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
1981
|
+
}
|
|
1982
|
+
ctx.hooks.unsupported(`service binding ${binding}: RPC promise pipelining (reading .${prop} on ${method}()'s promise) is not supported; await the call first`);
|
|
1983
|
+
} });
|
|
1984
|
+
/** One call: `stub.method(...)`, or `await stub.property` (an RPC getter). */
|
|
1985
|
+
const call = (method) => {
|
|
1986
|
+
const invoke = (...args) => pipelineGuard(answers.call(method, args), method);
|
|
1987
|
+
const awaitable = (onFulfilled, onRejected) => answers.property(method).then(onFulfilled, onRejected);
|
|
1988
|
+
return new Proxy(invoke, { get(fn, key) {
|
|
1989
|
+
if (key === "then") return awaitable;
|
|
1990
|
+
if (typeof key === "symbol") return Reflect.get(fn, key);
|
|
1991
|
+
ctx.hooks.unsupported(`service binding ${binding}: RPC promise pipelining (reading .${method}.${key}) is not supported; await .${method} first`);
|
|
1992
|
+
} });
|
|
1687
1993
|
};
|
|
1994
|
+
const fetchThrough = async (input, init) => answers.fetch(new Request(input, init));
|
|
1995
|
+
return new Proxy({}, { get(_stub, prop) {
|
|
1996
|
+
if (prop === "then" || typeof prop === "symbol") return void 0;
|
|
1997
|
+
if (prop === "fetch") return fetchThrough;
|
|
1998
|
+
if (prop === "connect") return () => unsupported("connect() (a raw TCP socket) is not modelled");
|
|
1999
|
+
return call(prop);
|
|
2000
|
+
} });
|
|
1688
2001
|
}
|
|
1689
|
-
/**
|
|
1690
|
-
function
|
|
1691
|
-
|
|
1692
|
-
|
|
2002
|
+
/** The scripted stub a Worker sees under a service binding's name. */
|
|
2003
|
+
function proxyService(binding, ctx, script) {
|
|
2004
|
+
const target = `Service:${binding}`;
|
|
2005
|
+
const point = (op, args) => ({
|
|
2006
|
+
invocation: ctx.currentInvocation(),
|
|
2007
|
+
target,
|
|
1693
2008
|
op,
|
|
1694
|
-
|
|
2009
|
+
args,
|
|
2010
|
+
allowed: writeFaults
|
|
2011
|
+
});
|
|
2012
|
+
const unsupported = (what) => {
|
|
2013
|
+
const reason = `service binding ${binding}: ${what}`;
|
|
2014
|
+
ctx.hooks.unsupported(reason);
|
|
2015
|
+
throw new Error(`eutaxy: ${reason}`);
|
|
1695
2016
|
};
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
* effect. The core function's module must be listed in the scenario's
|
|
1707
|
-
* `specs`, which is what records its calls.
|
|
1708
|
-
*/
|
|
1709
|
-
function refines(name, decision, effect, options = {}) {
|
|
1710
|
-
return {
|
|
1711
|
-
kind: "refines",
|
|
1712
|
-
name,
|
|
1713
|
-
decision,
|
|
1714
|
-
effect,
|
|
1715
|
-
...options
|
|
2017
|
+
/** The scripted reply to a method, by name; a method the script lacks cannot be answered. */
|
|
2018
|
+
const replyTo = (method) => {
|
|
2019
|
+
if (script.methods === void 0) return { returns: null };
|
|
2020
|
+
if (!Object.hasOwn(script.methods, method)) return unsupported(`no scripted reply for method ${method}; add it to the service(${JSON.stringify(binding)}) setup's methods`);
|
|
2021
|
+
return script.methods[method];
|
|
2022
|
+
};
|
|
2023
|
+
const answer = (method) => {
|
|
2024
|
+
const reply = replyTo(method);
|
|
2025
|
+
if ("throws" in reply) throw scriptedError(reply.throws);
|
|
2026
|
+
return structuredClone(reply.returns);
|
|
1716
2027
|
};
|
|
2028
|
+
const summarize = (value) => ({ value: toJson(value) });
|
|
2029
|
+
return serviceStub(binding, ctx, {
|
|
2030
|
+
call: (method, args) => ctx.hooks.effect(point(method, { args: args.map((a) => toJson(a)) }), async () => answer(method), summarize),
|
|
2031
|
+
property: (method) => ctx.hooks.effect(point(method, { property: true }), async () => answer(method), summarize),
|
|
2032
|
+
async fetch(request) {
|
|
2033
|
+
const url = new URL(request.url);
|
|
2034
|
+
const { method, headers, body } = await recordRequest(request);
|
|
2035
|
+
const reply = await ctx.hooks.effect(point(method, {
|
|
2036
|
+
url: request.url,
|
|
2037
|
+
method,
|
|
2038
|
+
headers,
|
|
2039
|
+
body
|
|
2040
|
+
}), async () => {
|
|
2041
|
+
const found = findResponse({
|
|
2042
|
+
name: binding,
|
|
2043
|
+
host: url.host,
|
|
2044
|
+
guarantees: {},
|
|
2045
|
+
...script.fetch === void 0 ? {} : { responses: script.fetch }
|
|
2046
|
+
}, method, url.pathname);
|
|
2047
|
+
if (found === void 0) return unsupported(`no scripted reply for fetch ${method} ${url.pathname}; add it to the service(${JSON.stringify(binding)}) setup's fetch`);
|
|
2048
|
+
const reply = replyOf(found);
|
|
2049
|
+
if (isRedirect(reply.status) && request.redirect !== "manual") return unsupported(`the scripted reply to ${method} ${url.pathname} is a ${reply.status} redirect, which the runtime would follow; script the final reply or fetch with redirect: "manual"`);
|
|
2050
|
+
return reply;
|
|
2051
|
+
}, (r) => ({ status: r.status }));
|
|
2052
|
+
return toResponse(reply);
|
|
2053
|
+
}
|
|
2054
|
+
});
|
|
1717
2055
|
}
|
|
2056
|
+
// packages/cloudflare/src/callees.ts
|
|
1718
2057
|
/**
|
|
1719
|
-
*
|
|
1720
|
-
*
|
|
1721
|
-
*
|
|
1722
|
-
*
|
|
2058
|
+
* Service bindings with the callee real. A scenario names the Worker behind a
|
|
2059
|
+
* binding (`callee(binding, { entry, config })`), and the test gives the
|
|
2060
|
+
* platform its module and the name from its wrangler config; the callee's
|
|
2061
|
+
* code then runs in the same simulation as the caller's, in the same
|
|
2062
|
+
* isolate, as Cloudflare runs both Workers on one thread (Workers, service
|
|
2063
|
+
* bindings). Each RPC method call or `fetch()` through the binding is one
|
|
2064
|
+
* effect, `Service:<binding>`, with the faults of a call in the network
|
|
2065
|
+
* (`crash_before`: it never reached the callee; `ambiguous`: the callee
|
|
2066
|
+
* acted and the answer was lost; `crash_after`: the caller died after it);
|
|
2067
|
+
* `error` is not among them, since what the callee throws is real. The
|
|
2068
|
+
* effect hosts the callee's invocation (`<caller invocation>/<binding>.<method>`,
|
|
2069
|
+
* `#<n>` for the n-th call of that method from the same caller invocation):
|
|
2070
|
+
* the entrypoint is constructed anew with a fresh `ExecutionContext` and the
|
|
2071
|
+
* callee's `env`, a view of the scenario's env under the callee's own names
|
|
2072
|
+
* (`DB` for `orders/DB`), so its code runs unchanged while its effects are
|
|
2073
|
+
* recorded under its own invocation, interleave as turns and take faults by
|
|
2074
|
+
* their position within it. What the callee throws reaches the caller as a
|
|
2075
|
+
* new error with its name, message and serializable own properties, a
|
|
2076
|
+
* built-in class as itself (Workers RPC, error handling); a fault that
|
|
2077
|
+
* crashes the callee ends its invocation and the caller sees an `Error`
|
|
2078
|
+
* thrown from the call. The callee's `waitUntil` work finishes before its
|
|
2079
|
+
* answer crosses: one of the orders the runtime allows.
|
|
1723
2080
|
*/
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
if (drive.kind === "rpc") {
|
|
1737
|
-
const calls = drive.calls.map((c) => ({
|
|
1738
|
-
id: c.id,
|
|
1739
|
-
body: c.args
|
|
1740
|
-
}));
|
|
1741
|
-
return {
|
|
1742
|
-
...atLeastOncePerMessage$1(name, calls, effect, key, bodyKey),
|
|
1743
|
-
perMessage: { bodyKey: bodyKey === "" ? "args" : `args.${bodyKey}` }
|
|
1744
|
-
};
|
|
1745
|
-
}
|
|
1746
|
-
if (drive.kind === "websocket") {
|
|
1747
|
-
if (bodyKey !== "") throw new Error(`atLeastOncePerMessage ${JSON.stringify(name)}: a websocket drive keys each connection by its path; bodyKey must be ""`);
|
|
1748
|
-
const conns = drive.connections.map((c) => ({
|
|
1749
|
-
id: c.id,
|
|
1750
|
-
body: c.path
|
|
1751
|
-
}));
|
|
1752
|
-
return {
|
|
1753
|
-
...atLeastOncePerMessage$1(name, conns, effect, key, ""),
|
|
1754
|
-
perMessage: { bodyKey: "path" }
|
|
1755
|
-
};
|
|
2081
|
+
/** The faults a call to a real callee admits; `error` is the callee's own to throw. */
|
|
2082
|
+
const callFaults = [
|
|
2083
|
+
"crash_before",
|
|
2084
|
+
"ambiguous",
|
|
2085
|
+
"crash_after"
|
|
2086
|
+
];
|
|
2087
|
+
/** What the platform keeps per run about its callees; cleared before each run. */
|
|
2088
|
+
var CalleeState = class {
|
|
2089
|
+
/** Calls so far per caller invocation, binding and method, to name each hosted invocation. */
|
|
2090
|
+
counts = /* @__PURE__ */ new Map();
|
|
2091
|
+
clear() {
|
|
2092
|
+
this.counts.clear();
|
|
1756
2093
|
}
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
2094
|
+
};
|
|
2095
|
+
/**
|
|
2096
|
+
* The callee's `env`: the scenario's env seen under the callee's own names,
|
|
2097
|
+
* each mapped onto `<name>/<key>`. Over the platform's proxied env the
|
|
2098
|
+
* entries are the proxies, so the callee's effects are recorded under their
|
|
2099
|
+
* qualified targets, and an alias (`<name>/STOCK` for the caller's `STOCK`)
|
|
2100
|
+
* is already resolved; over workerd's raw env (a callee's Durable Object,
|
|
2101
|
+
* which the runtime constructs with the main Worker's env) the aliases are
|
|
2102
|
+
* given here, so the shared binding is there under the callee's name too.
|
|
2103
|
+
*/
|
|
2104
|
+
function calleeEnv(name, env, aliases = {}) {
|
|
2105
|
+
const prefix = `${name}/`;
|
|
2106
|
+
const source = env;
|
|
2107
|
+
/** The key of `env` a property of the view reads: the qualified name, or the binding it is an alias of. */
|
|
2108
|
+
const keyOf = (prop) => {
|
|
2109
|
+
if (typeof prop !== "string") return void 0;
|
|
2110
|
+
const qualified = `${prefix}${prop}`;
|
|
2111
|
+
return qualified in source ? qualified : aliases[qualified] ?? qualified;
|
|
1764
2112
|
};
|
|
2113
|
+
const aliasKeys = Object.keys(aliases).filter((a) => a.startsWith(prefix) && (aliases[a] ?? "") in source);
|
|
2114
|
+
return new Proxy(Object.create(null), {
|
|
2115
|
+
get(_t, prop) {
|
|
2116
|
+
const key = keyOf(prop);
|
|
2117
|
+
return key === void 0 ? void 0 : source[key];
|
|
2118
|
+
},
|
|
2119
|
+
has(_t, prop) {
|
|
2120
|
+
const key = keyOf(prop);
|
|
2121
|
+
return key !== void 0 && key in source;
|
|
2122
|
+
},
|
|
2123
|
+
ownKeys: () => [...new Set([...Reflect.ownKeys(source).filter((k) => typeof k === "string"), ...aliasKeys].filter((k) => k.startsWith(prefix)).map((k) => k.slice(prefix.length)))],
|
|
2124
|
+
getOwnPropertyDescriptor(_t, prop) {
|
|
2125
|
+
const key = keyOf(prop);
|
|
2126
|
+
if (key === void 0 || !(key in source)) return void 0;
|
|
2127
|
+
return {
|
|
2128
|
+
value: source[key],
|
|
2129
|
+
enumerable: true,
|
|
2130
|
+
configurable: true,
|
|
2131
|
+
writable: false
|
|
2132
|
+
};
|
|
2133
|
+
}
|
|
2134
|
+
});
|
|
1765
2135
|
}
|
|
1766
2136
|
/**
|
|
1767
|
-
*
|
|
1768
|
-
*
|
|
1769
|
-
*
|
|
2137
|
+
* The error the caller sees for what the callee threw: a new error with the
|
|
2138
|
+
* name and message, a built-in class as itself, and the serializable own
|
|
2139
|
+
* properties the thrown error carried (Workers RPC, error handling, enhanced
|
|
2140
|
+
* error serialization). Nothing of the original's identity or stack.
|
|
1770
2141
|
*/
|
|
1771
|
-
function
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
2142
|
+
function crossingError(error) {
|
|
2143
|
+
const crossed = scriptedError(describeError(error));
|
|
2144
|
+
if (error instanceof Error) for (const key of Object.keys(error)) {
|
|
2145
|
+
if (key === "name" || key === "message" || key === "stack") continue;
|
|
2146
|
+
try {
|
|
2147
|
+
Object.defineProperty(crossed, key, {
|
|
2148
|
+
value: structuredClone(error[key]),
|
|
2149
|
+
enumerable: true,
|
|
2150
|
+
configurable: true,
|
|
2151
|
+
writable: true
|
|
2152
|
+
});
|
|
2153
|
+
} catch {}
|
|
2154
|
+
}
|
|
2155
|
+
return crossed;
|
|
1777
2156
|
}
|
|
1778
2157
|
/**
|
|
1779
|
-
*
|
|
1780
|
-
*
|
|
1781
|
-
*
|
|
2158
|
+
* The fetch handler the binding reaches: the named entrypoint's method when
|
|
2159
|
+
* the setup names one, else the default export's (a handler object's `fetch`,
|
|
2160
|
+
* or an entrypoint class's method).
|
|
1782
2161
|
*/
|
|
1783
|
-
function
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
2162
|
+
function fetchHandlerOf(exports, entrypoint, ctx, env) {
|
|
2163
|
+
const def = entrypoint === void 0 ? exports["default"] : exports[entrypoint];
|
|
2164
|
+
if (typeof def === "function") {
|
|
2165
|
+
const instance = constructEntrypoint(def, "WorkerEntrypoint", ctx, env);
|
|
2166
|
+
return typeof instance.fetch === "function" ? instance.fetch.bind(instance) : void 0;
|
|
2167
|
+
}
|
|
2168
|
+
if (typeof def === "object" && def !== null) {
|
|
2169
|
+
const handler = def;
|
|
2170
|
+
return typeof handler.fetch === "function" ? (request) => handler.fetch?.call(handler, request, env, ctx) : void 0;
|
|
2171
|
+
}
|
|
1790
2172
|
}
|
|
1791
2173
|
/**
|
|
1792
|
-
*
|
|
1793
|
-
*
|
|
1794
|
-
*
|
|
2174
|
+
* The getter RPC exposes under a name: one the class or a superclass defines
|
|
2175
|
+
* on its prototype. An instance field is not reachable over RPC (workerd:
|
|
2176
|
+
* "The RPC receiver does not implement the method").
|
|
1795
2177
|
*/
|
|
1796
|
-
function
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
};
|
|
2178
|
+
function rpcGetter(instance, name) {
|
|
2179
|
+
for (let proto = Object.getPrototypeOf(instance); proto !== null && proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) {
|
|
2180
|
+
const own = Object.getOwnPropertyDescriptor(proto, name);
|
|
2181
|
+
if (!own) continue;
|
|
2182
|
+
return typeof own.get === "function" ? own.get : void 0;
|
|
2183
|
+
}
|
|
1803
2184
|
}
|
|
1804
|
-
/**
|
|
1805
|
-
function
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
2185
|
+
/** The stub a Worker sees under a service binding whose callee runs for real. */
|
|
2186
|
+
function proxyCallee(binding, ctx, setup, module, env, state) {
|
|
2187
|
+
const target = `Service:${binding}`;
|
|
2188
|
+
const view = calleeEnv(module.name, env);
|
|
2189
|
+
const entrypointName = setup.entrypoint ?? module.entrypoint;
|
|
2190
|
+
const props = module.props ?? {};
|
|
2191
|
+
const unsupported = (what) => {
|
|
2192
|
+
const reason = `callee ${binding}: ${what}`;
|
|
2193
|
+
ctx.hooks.unsupported(reason);
|
|
2194
|
+
throw new Error(`eutaxy: ${reason}`);
|
|
1813
2195
|
};
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
2196
|
+
const point = (op, args) => ({
|
|
2197
|
+
invocation: ctx.currentInvocation(),
|
|
2198
|
+
target,
|
|
2199
|
+
op,
|
|
2200
|
+
args,
|
|
2201
|
+
allowed: callFaults
|
|
2202
|
+
});
|
|
2203
|
+
/** The hosted invocation's id: the n-th call of a method from one caller invocation is `#n`. */
|
|
2204
|
+
const invocationId = (method) => {
|
|
2205
|
+
const key = `${ctx.currentInvocation()}/${binding}.${method}`;
|
|
2206
|
+
const n = (state.counts.get(key) ?? 0) + 1;
|
|
2207
|
+
state.counts.set(key, n);
|
|
2208
|
+
return n === 1 ? key : `${key}#${n}`;
|
|
1822
2209
|
};
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
2210
|
+
/** The callee's code as an invocation of its own inside the call: the handler, then its background work. */
|
|
2211
|
+
const invoke = (method, work) => {
|
|
2212
|
+
const hooks = ctx.hooks;
|
|
2213
|
+
const id = invocationId(method);
|
|
2214
|
+
return hostInvocation(hooks, id, async (inv) => {
|
|
2215
|
+
const background = [];
|
|
2216
|
+
const ran = await runInvocation(hooks, inv, () => work(executionContext(background, void 0, props)));
|
|
2217
|
+
if (ran.status !== "crashed") await drainBackground(hooks, inv, id, target, background);
|
|
2218
|
+
return ran;
|
|
2219
|
+
});
|
|
1831
2220
|
};
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
name,
|
|
1838
|
-
when,
|
|
1839
|
-
key,
|
|
1840
|
-
state,
|
|
1841
|
-
column
|
|
2221
|
+
/** What the caller gets out of the callee's outcome: the value, the error as RPC carries it, or an error for a crash. */
|
|
2222
|
+
const answer = (outcome, method) => {
|
|
2223
|
+
if (outcome.status === "completed") return outcome.value;
|
|
2224
|
+
if (outcome.status === "errored") throw crossingError(outcome.error);
|
|
2225
|
+
throw new Error(`the Worker behind service binding ${binding} crashed while handling ${method}`);
|
|
1842
2226
|
};
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
2227
|
+
/**
|
|
2228
|
+
* Arguments travel by copy, as plain data: a function, a stub or a stream is
|
|
2229
|
+
* a capability the model lacks, and a class instance is what RPC refuses
|
|
2230
|
+
* (structuredClone would silently make a plain object of it).
|
|
2231
|
+
*/
|
|
2232
|
+
const copied = (method, args) => {
|
|
2233
|
+
if (!args.every((a) => isPlainData(a))) return unsupported(`the arguments of ${method} are not plain data (a stub, a function, a stream or a class instance); RPC carries plain data only`);
|
|
2234
|
+
try {
|
|
2235
|
+
return structuredClone([...args]);
|
|
2236
|
+
} catch {
|
|
2237
|
+
return unsupported(`the arguments of ${method} cannot be copied as RPC copies them`);
|
|
2238
|
+
}
|
|
2239
|
+
};
|
|
2240
|
+
/** A result passed back to the caller, by copy; one that is not plain data cannot be followed. */
|
|
2241
|
+
const plain = (method, value) => {
|
|
2242
|
+
if (!isPlainData(value)) unsupported(`${method} returned something that is not plain data (a stub, a function or a stream); RPC capabilities are not modelled`);
|
|
2243
|
+
try {
|
|
2244
|
+
return structuredClone(value);
|
|
2245
|
+
} catch {
|
|
2246
|
+
return value;
|
|
2247
|
+
}
|
|
2248
|
+
};
|
|
2249
|
+
const entrypoint = () => {
|
|
2250
|
+
const cls = entrypointClass(void 0, module.exports, entrypointName);
|
|
2251
|
+
if (typeof cls !== "function") unsupported(`${entrypointName === void 0 ? "the default export" : `export ${entrypointName}`} of ${module.name} is not a WorkerEntrypoint class`);
|
|
2252
|
+
return cls;
|
|
1851
2253
|
};
|
|
2254
|
+
const summarize = (value) => ({ value: toJson(value) });
|
|
2255
|
+
return serviceStub(binding, ctx, {
|
|
2256
|
+
call: (method, args) => {
|
|
2257
|
+
let copy;
|
|
2258
|
+
try {
|
|
2259
|
+
copy = copied(method, args);
|
|
2260
|
+
} catch (err) {
|
|
2261
|
+
return Promise.reject(err);
|
|
2262
|
+
}
|
|
2263
|
+
return ctx.hooks.effect(point(method, { args: args.map((a) => toJson(a)) }), async () => {
|
|
2264
|
+
const cls = entrypoint();
|
|
2265
|
+
const outcome = await invoke(method, (executionContext) => {
|
|
2266
|
+
const instance = constructEntrypoint(cls, "WorkerEntrypoint", executionContext, view);
|
|
2267
|
+
const fn = rpcMethod(instance, method);
|
|
2268
|
+
if (!fn) throw new TypeError(`The RPC receiver does not implement the method "${method}".`);
|
|
2269
|
+
return fn.apply(instance, copy);
|
|
2270
|
+
});
|
|
2271
|
+
return plain(method, answer(outcome, method));
|
|
2272
|
+
}, summarize);
|
|
2273
|
+
},
|
|
2274
|
+
property: (name) => ctx.hooks.effect(point(name, { property: true }), async () => {
|
|
2275
|
+
const cls = entrypoint();
|
|
2276
|
+
const outcome = await invoke(name, (executionContext) => {
|
|
2277
|
+
const instance = constructEntrypoint(cls, "WorkerEntrypoint", executionContext, view);
|
|
2278
|
+
const getter = rpcGetter(instance, name);
|
|
2279
|
+
if (!getter) throw new TypeError(`The RPC receiver does not implement the method "${name}".`);
|
|
2280
|
+
return getter.call(instance);
|
|
2281
|
+
});
|
|
2282
|
+
return plain(name, answer(outcome, name));
|
|
2283
|
+
}, summarize),
|
|
2284
|
+
async fetch(request) {
|
|
2285
|
+
const { method, headers, body } = await recordRequest(request);
|
|
2286
|
+
return ctx.hooks.effect(point(method, {
|
|
2287
|
+
url: request.url,
|
|
2288
|
+
method,
|
|
2289
|
+
headers,
|
|
2290
|
+
body
|
|
2291
|
+
}), async () => {
|
|
2292
|
+
const outcome = await invoke("fetch", (executionContext) => {
|
|
2293
|
+
const handler = fetchHandlerOf(module.exports, entrypointName, executionContext, view);
|
|
2294
|
+
if (!handler) return unsupported(`${entrypointName === void 0 ? module.name : `export ${entrypointName} of ${module.name}`} has no fetch handler`);
|
|
2295
|
+
return handler(request);
|
|
2296
|
+
});
|
|
2297
|
+
const response = answer(outcome, "fetch");
|
|
2298
|
+
if (!(response instanceof Response)) return unsupported(`${module.name}'s fetch handler returned something that is not a Response`);
|
|
2299
|
+
if (isRedirect(response.status) && request.redirect !== "manual") return unsupported(`${module.name} answered ${method} ${new URL(request.url).pathname} with a ${response.status} redirect, which the runtime would follow; fetch with redirect: "manual"`);
|
|
2300
|
+
return response;
|
|
2301
|
+
}, (r) => ({ status: r.status }));
|
|
2302
|
+
}
|
|
2303
|
+
});
|
|
2304
|
+
}
|
|
2305
|
+
// packages/cloudflare/src/check.ts
|
|
2306
|
+
/** Explore a scenario on a platform and return its verdict. */
|
|
2307
|
+
function check(spec, platform, options = { seed: spec.name }) {
|
|
2308
|
+
return explore(spec, platform, options);
|
|
2309
|
+
}
|
|
2310
|
+
/** For use from a test: passes only when the scenario is BOUNDED. */
|
|
2311
|
+
async function expectHolds(spec, platform, options) {
|
|
2312
|
+
const verdict = await check(spec, platform, options);
|
|
2313
|
+
if (verdict.kind !== "BOUNDED") throw new Error(describeVerdict(verdict));
|
|
1852
2314
|
}
|
|
2315
|
+
// packages/cloudflare/src/d1.ts
|
|
1853
2316
|
/**
|
|
1854
|
-
*
|
|
1855
|
-
*
|
|
1856
|
-
*
|
|
1857
|
-
* idempotent at that service.
|
|
2317
|
+
* The D1 binding proxy. Every statement execution is an effect point: the
|
|
2318
|
+
* engine decides the fault, the real Miniflare-backed D1 performs the query,
|
|
2319
|
+
* and the log records call, result and fault in the documented shape.
|
|
1858
2320
|
*/
|
|
1859
|
-
|
|
2321
|
+
/** Whether a binding is a D1 database (what the proxies and the differential wrap). */
|
|
2322
|
+
function isD1(value) {
|
|
2323
|
+
return typeof value === "object" && value !== null && typeof value.prepare === "function" && typeof value.batch === "function";
|
|
2324
|
+
}
|
|
2325
|
+
function point(ctx, target, op, args, allowed) {
|
|
1860
2326
|
return {
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
2327
|
+
invocation: ctx.currentInvocation(),
|
|
2328
|
+
target,
|
|
2329
|
+
op,
|
|
2330
|
+
args,
|
|
2331
|
+
allowed
|
|
1865
2332
|
};
|
|
1866
2333
|
}
|
|
1867
|
-
|
|
1868
|
-
* Selects the requests to an external that took effect: a request replayed
|
|
1869
|
-
* under a dedupe key the external had already seen is not counted.
|
|
1870
|
-
*/
|
|
1871
|
-
function fetchCall(externalName, method) {
|
|
2334
|
+
function metaOf(result) {
|
|
1872
2335
|
return {
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
kind: "result",
|
|
1876
|
-
where: { "result.effective": true }
|
|
2336
|
+
changes: result.meta.changes ?? 0,
|
|
2337
|
+
lastRowId: result.meta.last_row_id ?? null
|
|
1877
2338
|
};
|
|
1878
2339
|
}
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
});
|
|
1892
|
-
return errors;
|
|
1893
|
-
}
|
|
1894
|
-
function validateHttpDrive(drive) {
|
|
1895
|
-
const errors = [];
|
|
1896
|
-
if (drive.requests.length === 0) errors.push("http drive needs at least one request");
|
|
1897
|
-
const ids = /* @__PURE__ */ new Set();
|
|
1898
|
-
drive.requests.forEach((r, i) => {
|
|
1899
|
-
if (!r.path.startsWith("/")) errors.push(`requests[${i}].path must start with "/"`);
|
|
1900
|
-
if (!r.method) errors.push(`requests[${i}].method must not be empty`);
|
|
1901
|
-
if (ids.has(r.id)) errors.push(`duplicate request id ${JSON.stringify(r.id)}`);
|
|
1902
|
-
ids.add(r.id);
|
|
1903
|
-
if ((r.method === "GET" || r.method === "HEAD") && r.body !== void 0) errors.push(`requests[${i}] is a ${r.method} and cannot carry a body`);
|
|
1904
|
-
});
|
|
1905
|
-
errors.push(...validateCaller("http", drive));
|
|
1906
|
-
return errors;
|
|
1907
|
-
}
|
|
1908
|
-
/** The caller's policy, as both drives a caller resends declare it. */
|
|
1909
|
-
function validateCaller(kind, drive) {
|
|
1910
|
-
const errors = [];
|
|
1911
|
-
if (!(Number.isInteger(drive.retries) && drive.retries >= 0)) errors.push(`${kind} drive retries must be a non-negative integer`);
|
|
1912
|
-
(drive.delaysMs ?? []).forEach((d, i) => {
|
|
1913
|
-
if (!(Number.isInteger(d) && d >= 0)) errors.push(`${kind} drive delaysMs[${i}] must be a non-negative integer`);
|
|
1914
|
-
});
|
|
1915
|
-
if (drive.deadlineMs !== void 0 && !(Number.isInteger(drive.deadlineMs) && drive.deadlineMs > 0)) errors.push(`${kind} drive deadlineMs must be a positive integer`);
|
|
1916
|
-
return errors;
|
|
1917
|
-
}
|
|
1918
|
-
function validateCronDrive(drive) {
|
|
1919
|
-
const errors = [];
|
|
1920
|
-
try {
|
|
1921
|
-
parseCron(drive.cron);
|
|
1922
|
-
} catch (err) {
|
|
1923
|
-
errors.push(`cron drive: ${err.message}`);
|
|
2340
|
+
var StatementProxy = class StatementProxy {
|
|
2341
|
+
real;
|
|
2342
|
+
target;
|
|
2343
|
+
ctx;
|
|
2344
|
+
sql;
|
|
2345
|
+
params;
|
|
2346
|
+
constructor(real, target, ctx, sql, params) {
|
|
2347
|
+
this.real = real;
|
|
2348
|
+
this.target = target;
|
|
2349
|
+
this.ctx = ctx;
|
|
2350
|
+
this.sql = sql;
|
|
2351
|
+
this.params = params;
|
|
1924
2352
|
}
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
|
|
2353
|
+
/** The real statement, for `batch()`. */
|
|
2354
|
+
get statement() {
|
|
2355
|
+
return this.real;
|
|
2356
|
+
}
|
|
2357
|
+
args() {
|
|
2358
|
+
return {
|
|
2359
|
+
sql: this.sql,
|
|
2360
|
+
params: toJson(this.params)
|
|
2361
|
+
};
|
|
2362
|
+
}
|
|
2363
|
+
bind(...values) {
|
|
2364
|
+
return new StatementProxy(this.real.bind(...values), this.target, this.ctx, this.sql, values);
|
|
2365
|
+
}
|
|
2366
|
+
run() {
|
|
2367
|
+
return this.ctx.hooks.effect(point(this.ctx, this.target, "run", this.args(), writeFaults), () => this.real.run(), (r) => metaOf(r));
|
|
2368
|
+
}
|
|
2369
|
+
all() {
|
|
2370
|
+
return this.ctx.hooks.effect(point(this.ctx, this.target, "all", this.args(), readFaults), () => this.real.all(), (r) => ({
|
|
2371
|
+
rows: r.results.length,
|
|
2372
|
+
changes: r.meta.changes ?? 0
|
|
2373
|
+
}));
|
|
2374
|
+
}
|
|
2375
|
+
first(colName) {
|
|
2376
|
+
return this.ctx.hooks.effect(point(this.ctx, this.target, "first", {
|
|
2377
|
+
...this.args(),
|
|
2378
|
+
column: colName ?? null
|
|
2379
|
+
}, readFaults), () => colName === void 0 ? this.real.first() : this.real.first(colName), (r) => ({ row: toJson(r) }));
|
|
2380
|
+
}
|
|
2381
|
+
raw(options) {
|
|
2382
|
+
return this.ctx.hooks.effect(point(this.ctx, this.target, "raw", this.args(), readFaults), () => options ? this.real.raw(options) : this.real.raw(), (r) => ({ rows: r.length }));
|
|
2383
|
+
}
|
|
2384
|
+
};
|
|
2385
|
+
/** Wrap a D1 binding. Methods not modelled fall through to the real binding and mark the run unsupported. */
|
|
2386
|
+
function proxyD1(real, binding, ctx) {
|
|
2387
|
+
const target = `D1:${binding}`;
|
|
2388
|
+
const modelled = {
|
|
2389
|
+
prepare(sql) {
|
|
2390
|
+
return new StatementProxy(real.prepare(sql), target, ctx, sql, []);
|
|
2391
|
+
},
|
|
2392
|
+
batch(statements) {
|
|
2393
|
+
const unwrapped = statements.map((s) => s instanceof StatementProxy ? s.statement : s);
|
|
2394
|
+
const args = { statements: statements.map((s) => s instanceof StatementProxy ? {
|
|
2395
|
+
sql: s.sql,
|
|
2396
|
+
params: toJson(s.params)
|
|
2397
|
+
} : "<unproxied statement>") };
|
|
2398
|
+
return ctx.hooks.effect(point(ctx, target, "batch", args, writeFaults), () => real.batch(unwrapped), (rs) => ({
|
|
2399
|
+
changes: rs.reduce((n, r) => n + (r.meta.changes ?? 0), 0),
|
|
2400
|
+
statements: rs.length
|
|
2401
|
+
}));
|
|
2402
|
+
},
|
|
2403
|
+
exec(sql) {
|
|
2404
|
+
return ctx.hooks.effect(point(ctx, target, "exec", { sql }, writeFaults), () => real.exec(sql), (r) => ({
|
|
2405
|
+
count: r.count,
|
|
2406
|
+
duration: 0
|
|
2407
|
+
}));
|
|
2408
|
+
}
|
|
2409
|
+
};
|
|
2410
|
+
return new Proxy(real, { get(obj, prop, receiver) {
|
|
2411
|
+
if (prop in modelled) return modelled[prop];
|
|
2412
|
+
const value = Reflect.get(obj, prop, receiver);
|
|
2413
|
+
if (typeof value === "function") {
|
|
2414
|
+
ctx.hooks.unsupported(`D1 ${binding}.${String(prop)} is not modelled`);
|
|
2415
|
+
return value.bind(obj);
|
|
2416
|
+
}
|
|
2417
|
+
return value;
|
|
2418
|
+
} });
|
|
1950
2419
|
}
|
|
1951
2420
|
/**
|
|
1952
|
-
*
|
|
1953
|
-
*
|
|
1954
|
-
*
|
|
2421
|
+
* Statements in a schema file. Splits on semicolons outside string literals,
|
|
2422
|
+
* quoted identifiers and comments, and keeps CREATE TRIGGER bodies (and CASE
|
|
2423
|
+
* expressions) whole by tracking BEGIN/CASE ... END nesting.
|
|
1955
2424
|
*/
|
|
1956
|
-
function
|
|
1957
|
-
const
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
2425
|
+
function splitSql(sql) {
|
|
2426
|
+
const out = [];
|
|
2427
|
+
let cur = "";
|
|
2428
|
+
let depth = 0;
|
|
2429
|
+
let i = 0;
|
|
2430
|
+
const isWordChar = (c) => c !== void 0 && /[A-Za-z0-9_]/.test(c);
|
|
2431
|
+
while (i < sql.length) {
|
|
2432
|
+
const c = sql[i];
|
|
2433
|
+
const next = sql[i + 1];
|
|
2434
|
+
if (c === "-" && next === "-") {
|
|
2435
|
+
while (i < sql.length && sql[i] !== "\n") i++;
|
|
2436
|
+
continue;
|
|
2437
|
+
}
|
|
2438
|
+
if (c === "/" && next === "*") {
|
|
2439
|
+
const end = sql.indexOf("*/", i + 2);
|
|
2440
|
+
i = end === -1 ? sql.length : end + 2;
|
|
2441
|
+
cur += " ";
|
|
2442
|
+
continue;
|
|
2443
|
+
}
|
|
2444
|
+
if (c === "'" || c === "\"" || c === "`" || c === "[") {
|
|
2445
|
+
const close = c === "[" ? "]" : c;
|
|
2446
|
+
let j = i + 1;
|
|
2447
|
+
for (;;) {
|
|
2448
|
+
const k = sql.indexOf(close, j);
|
|
2449
|
+
if (k === -1) {
|
|
2450
|
+
j = sql.length;
|
|
2451
|
+
break;
|
|
2452
|
+
}
|
|
2453
|
+
if (close !== "]" && sql[k + 1] === close) {
|
|
2454
|
+
j = k + 2;
|
|
2455
|
+
continue;
|
|
2456
|
+
}
|
|
2457
|
+
j = k + 1;
|
|
2458
|
+
break;
|
|
1967
2459
|
}
|
|
2460
|
+
cur += sql.slice(i, j);
|
|
2461
|
+
i = j;
|
|
2462
|
+
continue;
|
|
2463
|
+
}
|
|
2464
|
+
if (isWordChar(c) && !isWordChar(sql[i - 1])) {
|
|
2465
|
+
let j = i;
|
|
2466
|
+
while (isWordChar(sql[j])) j++;
|
|
2467
|
+
const word = sql.slice(i, j);
|
|
2468
|
+
const upper = word.toUpperCase();
|
|
2469
|
+
if (upper === "BEGIN" || upper === "CASE") depth++;
|
|
2470
|
+
else if (upper === "END" && depth > 0) depth--;
|
|
2471
|
+
cur += word;
|
|
2472
|
+
i = j;
|
|
2473
|
+
continue;
|
|
2474
|
+
}
|
|
2475
|
+
if (c === ";" && depth === 0) {
|
|
2476
|
+
const statement = cur.trim();
|
|
2477
|
+
if (statement.length > 0) out.push(statement);
|
|
2478
|
+
cur = "";
|
|
2479
|
+
i++;
|
|
2480
|
+
continue;
|
|
1968
2481
|
}
|
|
2482
|
+
cur += c;
|
|
2483
|
+
i++;
|
|
1969
2484
|
}
|
|
1970
|
-
|
|
2485
|
+
const last = cur.trim();
|
|
2486
|
+
if (last.length > 0) out.push(last);
|
|
2487
|
+
return out;
|
|
1971
2488
|
}
|
|
1972
|
-
/**
|
|
1973
|
-
function
|
|
1974
|
-
const
|
|
1975
|
-
const
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
if (errors.length > 0) throw new Error(`invalid scenario ${JSON.stringify(input.name)}:\n- ${errors.join("\n- ")}`);
|
|
1999
|
-
return spec;
|
|
2489
|
+
/** Drop every user table and re-apply the schema, using the real binding (not an effect). */
|
|
2490
|
+
async function resetD1(real, schema) {
|
|
2491
|
+
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();
|
|
2492
|
+
const quote = (n) => `"${n.replace(/"/g, "\"\"")}"`;
|
|
2493
|
+
const triggers = await real.prepare("SELECT name FROM sqlite_master WHERE type = 'trigger'").all();
|
|
2494
|
+
for (const { name } of triggers.results) await real.prepare(`DROP TRIGGER IF EXISTS ${quote(name)}`).run();
|
|
2495
|
+
const parents = /* @__PURE__ */ new Map();
|
|
2496
|
+
for (const { name } of tables.results) {
|
|
2497
|
+
const keys = await real.prepare(`PRAGMA foreign_key_list(${quote(name)})`).all();
|
|
2498
|
+
parents.set(name, new Set(keys.results.map((k) => k.table).filter((t) => t !== name)));
|
|
2499
|
+
}
|
|
2500
|
+
const left = new Set(parents.keys());
|
|
2501
|
+
for (;;) {
|
|
2502
|
+
const leaves = [...left].filter((t) => ![...left].some((o) => parents.get(o)?.has(t)));
|
|
2503
|
+
if (leaves.length === 0) break;
|
|
2504
|
+
for (const t of leaves) {
|
|
2505
|
+
await real.prepare(`DROP TABLE IF EXISTS ${quote(t)}`).run();
|
|
2506
|
+
left.delete(t);
|
|
2507
|
+
}
|
|
2508
|
+
}
|
|
2509
|
+
if (left.size > 0) {
|
|
2510
|
+
const cycle = [...left];
|
|
2511
|
+
await real.batch([real.prepare("PRAGMA defer_foreign_keys = on"), ...cycle.map((t) => real.prepare(`DELETE FROM ${quote(t)}`))]);
|
|
2512
|
+
await real.batch([real.prepare("PRAGMA defer_foreign_keys = on"), ...cycle.map((t) => real.prepare(`DROP TABLE IF EXISTS ${quote(t)}`))]);
|
|
2513
|
+
}
|
|
2514
|
+
for (const statement of splitSql(schema)) await real.prepare(statement).run();
|
|
2000
2515
|
}
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
*
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
* the callee, `ambiguous` that it acted and the answer was lost, and
|
|
2010
|
-
* `crash_after` that the caller died after it.
|
|
2011
|
-
*/
|
|
2012
|
-
/** Marks of the other kinds of binding, which a service binding's duck type must not carry. */
|
|
2013
|
-
const otherKinds = [
|
|
2014
|
-
"prepare",
|
|
2015
|
-
"idFromName",
|
|
2016
|
-
"head",
|
|
2017
|
-
"createBatch"
|
|
2018
|
-
];
|
|
2516
|
+
/** Every user table's rows, sorted canonically, read through the real binding (not an effect). */
|
|
2517
|
+
async function snapshotD1(real) {
|
|
2518
|
+
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();
|
|
2519
|
+
const out = {};
|
|
2520
|
+
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);
|
|
2521
|
+
return out;
|
|
2522
|
+
}
|
|
2523
|
+
// packages/cloudflare/src/r2.ts
|
|
2019
2524
|
/**
|
|
2020
|
-
*
|
|
2021
|
-
*
|
|
2022
|
-
*
|
|
2023
|
-
*
|
|
2024
|
-
*
|
|
2525
|
+
* The R2 binding proxy. Every `put`, `delete`, `get`, `head` and `list` is
|
|
2526
|
+
* an effect point against the real Miniflare-backed bucket. A body is read
|
|
2527
|
+
* inside its `get`'s effect and handed back in an object with the same
|
|
2528
|
+
* fields and body methods: reading it later would be I/O the run cannot
|
|
2529
|
+
* see. An object's random `version` and wall-clock `uploaded` are replaced
|
|
2530
|
+
* by stand-ins (see `VersionBook`), so traces stay byte-identical.
|
|
2025
2531
|
*/
|
|
2026
|
-
|
|
2532
|
+
/** Whether a binding is an R2 bucket (Miniflare's `R2Bucket`). */
|
|
2533
|
+
function isR2(value) {
|
|
2027
2534
|
if (typeof value !== "object" || value === null) return false;
|
|
2028
|
-
const fetcher = globalThis.Fetcher;
|
|
2029
|
-
if (typeof fetcher === "function" && value instanceof fetcher) return true;
|
|
2030
|
-
if ((Object.getPrototypeOf(value)?.constructor)?.name === "Fetcher") return true;
|
|
2031
2535
|
const v = value;
|
|
2032
|
-
return
|
|
2536
|
+
return [
|
|
2537
|
+
"head",
|
|
2538
|
+
"get",
|
|
2539
|
+
"put",
|
|
2540
|
+
"delete",
|
|
2541
|
+
"list",
|
|
2542
|
+
"createMultipartUpload"
|
|
2543
|
+
].every((m) => typeof v[m] === "function");
|
|
2544
|
+
}
|
|
2545
|
+
/**
|
|
2546
|
+
* Stand-ins for the version and upload time of each object version the run
|
|
2547
|
+
* sees, in the order it first sees them: versions count up, and the time is
|
|
2548
|
+
* the virtual time it was first seen.
|
|
2549
|
+
*/
|
|
2550
|
+
var VersionBook = class {
|
|
2551
|
+
seen = /* @__PURE__ */ new Map();
|
|
2552
|
+
clear() {
|
|
2553
|
+
this.seen.clear();
|
|
2554
|
+
}
|
|
2555
|
+
standIn(realVersion, at) {
|
|
2556
|
+
let s = this.seen.get(realVersion);
|
|
2557
|
+
if (!s) {
|
|
2558
|
+
s = {
|
|
2559
|
+
version: (this.seen.size + 1).toString(16).padStart(32, "0"),
|
|
2560
|
+
uploaded: new Date(at)
|
|
2561
|
+
};
|
|
2562
|
+
this.seen.set(realVersion, s);
|
|
2563
|
+
}
|
|
2564
|
+
return {
|
|
2565
|
+
version: s.version,
|
|
2566
|
+
uploaded: new Date(s.uploaded.getTime())
|
|
2567
|
+
};
|
|
2568
|
+
}
|
|
2569
|
+
};
|
|
2570
|
+
/** An object's metadata, with stand-ins for its version and upload time. */
|
|
2571
|
+
function metadata(real, book, at) {
|
|
2572
|
+
const { version, uploaded } = book.standIn(real.version, at);
|
|
2573
|
+
return {
|
|
2574
|
+
key: real.key,
|
|
2575
|
+
version,
|
|
2576
|
+
size: real.size,
|
|
2577
|
+
etag: real.etag,
|
|
2578
|
+
httpEtag: real.httpEtag,
|
|
2579
|
+
uploaded,
|
|
2580
|
+
httpMetadata: real.httpMetadata,
|
|
2581
|
+
customMetadata: real.customMetadata,
|
|
2582
|
+
range: real.range,
|
|
2583
|
+
checksums: real.checksums,
|
|
2584
|
+
storageClass: real.storageClass,
|
|
2585
|
+
ssecKeyMd5: real.ssecKeyMd5,
|
|
2586
|
+
writeHttpMetadata: (headers) => real.writeHttpMetadata(headers)
|
|
2587
|
+
};
|
|
2033
2588
|
}
|
|
2034
|
-
/** The built-in error classes RPC carries across as themselves (workerd keeps the type). */
|
|
2035
|
-
const builtInErrors = {
|
|
2036
|
-
Error,
|
|
2037
|
-
EvalError,
|
|
2038
|
-
RangeError,
|
|
2039
|
-
ReferenceError,
|
|
2040
|
-
SyntaxError,
|
|
2041
|
-
TypeError,
|
|
2042
|
-
URIError
|
|
2043
|
-
};
|
|
2044
2589
|
/**
|
|
2045
|
-
* The
|
|
2046
|
-
*
|
|
2047
|
-
*
|
|
2590
|
+
* The bytes behind each body stream the proxy hands out. The stream itself
|
|
2591
|
+
* has no known length, which the runtime's put requires, so a put given one
|
|
2592
|
+
* (copying an object) is given its bytes instead.
|
|
2048
2593
|
*/
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2594
|
+
const buffered = /* @__PURE__ */ new WeakMap();
|
|
2595
|
+
/**
|
|
2596
|
+
* An object with its body, already read: the stream and the body methods
|
|
2597
|
+
* share one consumption, as a real body's do. A method fails once the
|
|
2598
|
+
* stream is read, cancelled or locked by a reader; the stream ends empty
|
|
2599
|
+
* once a method has read the body.
|
|
2600
|
+
*/
|
|
2601
|
+
function withBody(meta, bytes) {
|
|
2602
|
+
let used = false;
|
|
2603
|
+
let stream;
|
|
2604
|
+
const take = () => {
|
|
2605
|
+
if (used || stream?.locked) throw new TypeError("Body has already been used");
|
|
2606
|
+
used = true;
|
|
2607
|
+
return bytes.slice();
|
|
2608
|
+
};
|
|
2609
|
+
return Object.defineProperties(meta, {
|
|
2610
|
+
body: {
|
|
2611
|
+
enumerable: true,
|
|
2612
|
+
get: () => {
|
|
2613
|
+
stream ??= new ReadableStream({
|
|
2614
|
+
pull(controller) {
|
|
2615
|
+
if (!used) controller.enqueue(bytes.slice());
|
|
2616
|
+
used = true;
|
|
2617
|
+
controller.close();
|
|
2618
|
+
},
|
|
2619
|
+
cancel() {
|
|
2620
|
+
used = true;
|
|
2621
|
+
}
|
|
2622
|
+
}, { highWaterMark: 0 });
|
|
2623
|
+
buffered.set(stream, take);
|
|
2624
|
+
return stream;
|
|
2625
|
+
}
|
|
2626
|
+
},
|
|
2627
|
+
bodyUsed: {
|
|
2628
|
+
enumerable: true,
|
|
2629
|
+
get: () => used
|
|
2630
|
+
},
|
|
2631
|
+
arrayBuffer: { value: async () => take().buffer },
|
|
2632
|
+
bytes: { value: async () => take() },
|
|
2633
|
+
text: { value: async () => new TextDecoder().decode(take()) },
|
|
2634
|
+
json: { value: async () => JSON.parse(new TextDecoder().decode(take())) },
|
|
2635
|
+
blob: { value: async () => new Blob([take()]) }
|
|
2636
|
+
});
|
|
2059
2637
|
}
|
|
2060
|
-
/**
|
|
2061
|
-
function
|
|
2062
|
-
|
|
2063
|
-
|
|
2638
|
+
/** Conditions as the trace keeps them: a `Headers` object by its entries. */
|
|
2639
|
+
function conditions(onlyIf) {
|
|
2640
|
+
if (onlyIf === void 0) return {};
|
|
2641
|
+
return { onlyIf: onlyIf instanceof Headers ? Object.fromEntries(onlyIf.entries()) : onlyIf };
|
|
2642
|
+
}
|
|
2643
|
+
/** What the trace keeps of a get's options: the conditions and range, never an encryption key. */
|
|
2644
|
+
function getArgs(key, options) {
|
|
2645
|
+
return toJson({
|
|
2646
|
+
key,
|
|
2647
|
+
...conditions(options?.onlyIf),
|
|
2648
|
+
...options?.range === void 0 ? {} : { range: options.range }
|
|
2649
|
+
});
|
|
2650
|
+
}
|
|
2651
|
+
/** What the trace keeps of a put's options: the conditions and metadata, not checksums or keys. */
|
|
2652
|
+
function putArgs(options) {
|
|
2653
|
+
if (!options) return {};
|
|
2654
|
+
return toJson({
|
|
2655
|
+
...conditions(options.onlyIf),
|
|
2656
|
+
...options.customMetadata === void 0 ? {} : { customMetadata: options.customMetadata },
|
|
2657
|
+
...options.httpMetadata === void 0 ? {} : { httpMetadata: options.httpMetadata }
|
|
2658
|
+
});
|
|
2659
|
+
}
|
|
2660
|
+
function proxyR2(real, binding, ctx, book) {
|
|
2661
|
+
const target = `R2:${binding}`;
|
|
2662
|
+
const point = (op, args, allowed) => ({
|
|
2064
2663
|
invocation: ctx.currentInvocation(),
|
|
2065
2664
|
target,
|
|
2066
2665
|
op,
|
|
2067
2666
|
args,
|
|
2068
|
-
allowed
|
|
2667
|
+
allowed
|
|
2069
2668
|
});
|
|
2070
|
-
const
|
|
2071
|
-
const reason = `
|
|
2669
|
+
const notModelled = (what) => {
|
|
2670
|
+
const reason = `R2 ${binding}: ${what} is not modelled`;
|
|
2072
2671
|
ctx.hooks.unsupported(reason);
|
|
2073
2672
|
throw new Error(`eutaxy: ${reason}`);
|
|
2074
2673
|
};
|
|
2075
|
-
/**
|
|
2076
|
-
const
|
|
2077
|
-
if (
|
|
2078
|
-
if (!Object.hasOwn(script.methods, method)) return unsupported(`no scripted reply for method ${method}; add it to the service(${JSON.stringify(binding)}) setup's methods`);
|
|
2079
|
-
return script.methods[method];
|
|
2080
|
-
};
|
|
2081
|
-
const answer = (method) => {
|
|
2082
|
-
const reply = replyTo(method);
|
|
2083
|
-
if ("throws" in reply) throw scriptedError(reply.throws);
|
|
2084
|
-
return structuredClone(reply.returns);
|
|
2674
|
+
/** Date conditions compare the store's real upload time, not the stand-in the Worker saw. */
|
|
2675
|
+
const checkConditions = (onlyIf) => {
|
|
2676
|
+
if (onlyIf instanceof Headers ? ["if-modified-since", "if-unmodified-since"].some((h) => onlyIf.has(h)) : typeof onlyIf === "object" && onlyIf !== null && ("uploadedBefore" in onlyIf || "uploadedAfter" in onlyIf)) ctx.hooks.unsupported(`R2 ${binding}: conditions on the upload time are not modelled`);
|
|
2085
2677
|
};
|
|
2086
|
-
const
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
request.headers.forEach((value, name) => {
|
|
2092
|
-
headers[name.toLowerCase()] = value;
|
|
2093
|
-
});
|
|
2094
|
-
const body = parseBody(await request.text());
|
|
2095
|
-
const reply = await ctx.hooks.effect(point(method, {
|
|
2096
|
-
url: request.url,
|
|
2097
|
-
method,
|
|
2098
|
-
headers,
|
|
2099
|
-
body
|
|
2100
|
-
}), async () => {
|
|
2101
|
-
const found = findResponse({
|
|
2102
|
-
name: binding,
|
|
2103
|
-
host: url.host,
|
|
2104
|
-
guarantees: {},
|
|
2105
|
-
...script.fetch === void 0 ? {} : { responses: script.fetch }
|
|
2106
|
-
}, method, url.pathname);
|
|
2107
|
-
if (found === void 0) return unsupported(`no scripted reply for fetch ${method} ${url.pathname}; add it to the service(${JSON.stringify(binding)}) setup's fetch`);
|
|
2108
|
-
const reply = replyOf(found);
|
|
2109
|
-
if (isRedirect(reply.status) && request.redirect !== "manual") return unsupported(`the scripted reply to ${method} ${url.pathname} is a ${reply.status} redirect, which the runtime would follow; script the final reply or fetch with redirect: "manual"`);
|
|
2110
|
-
return reply;
|
|
2111
|
-
}, (r) => ({ status: r.status }));
|
|
2112
|
-
return toResponse(reply);
|
|
2678
|
+
const described = (o) => o === null ? { found: false } : {
|
|
2679
|
+
found: true,
|
|
2680
|
+
key: o.key,
|
|
2681
|
+
size: o.size,
|
|
2682
|
+
etag: o.etag
|
|
2113
2683
|
};
|
|
2114
|
-
|
|
2115
|
-
|
|
2116
|
-
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
|
|
2121
|
-
const
|
|
2122
|
-
return
|
|
2123
|
-
}
|
|
2124
|
-
|
|
2125
|
-
|
|
2126
|
-
|
|
2127
|
-
|
|
2128
|
-
|
|
2129
|
-
|
|
2130
|
-
|
|
2131
|
-
|
|
2132
|
-
if (
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
|
|
2684
|
+
return {
|
|
2685
|
+
put: (key, value, options) => ctx.hooks.effect(point("put", {
|
|
2686
|
+
key,
|
|
2687
|
+
...putArgs(options)
|
|
2688
|
+
}, writeFaults), async () => {
|
|
2689
|
+
checkConditions(options?.onlyIf);
|
|
2690
|
+
const read = value instanceof ReadableStream ? buffered.get(value) : void 0;
|
|
2691
|
+
const stored = await real.put(key, read ? read() : value, options);
|
|
2692
|
+
return stored === null ? null : metadata(stored, book, Date.now());
|
|
2693
|
+
}, (o) => o === null ? { stored: false } : {
|
|
2694
|
+
stored: true,
|
|
2695
|
+
size: o.size,
|
|
2696
|
+
etag: o.etag
|
|
2697
|
+
}),
|
|
2698
|
+
delete: (keys) => ctx.hooks.effect(point("delete", { keys: typeof keys === "string" ? [keys] : [...keys] }, writeFaults), () => real.delete(keys), () => null),
|
|
2699
|
+
get: (key, options) => ctx.hooks.effect(point("get", getArgs(key, options), readFaults), async () => {
|
|
2700
|
+
checkConditions(options?.onlyIf);
|
|
2701
|
+
const o = await real.get(key, options);
|
|
2702
|
+
if (o === null) return null;
|
|
2703
|
+
const meta = metadata(o, book, Date.now());
|
|
2704
|
+
if (!("body" in o)) return meta;
|
|
2705
|
+
return withBody(meta, new Uint8Array(await o.arrayBuffer()));
|
|
2706
|
+
}, (o) => ({
|
|
2707
|
+
...described(o),
|
|
2708
|
+
...o !== null ? { body: "body" in o } : {}
|
|
2709
|
+
})),
|
|
2710
|
+
head: (key) => ctx.hooks.effect(point("head", { key }, readFaults), async () => {
|
|
2711
|
+
const o = await real.head(key);
|
|
2712
|
+
return o === null ? null : metadata(o, book, Date.now());
|
|
2713
|
+
}, described),
|
|
2714
|
+
list: (options) => ctx.hooks.effect(point("list", toJson(options ?? {}), readFaults), async () => {
|
|
2715
|
+
const listed = await real.list(options);
|
|
2716
|
+
const at = Date.now();
|
|
2717
|
+
return {
|
|
2718
|
+
...listed,
|
|
2719
|
+
objects: listed.objects.map((o) => metadata(o, book, at))
|
|
2720
|
+
};
|
|
2721
|
+
}, (l) => ({
|
|
2722
|
+
keys: l.objects.map((o) => o.key),
|
|
2723
|
+
truncated: l.truncated,
|
|
2724
|
+
delimitedPrefixes: l.delimitedPrefixes
|
|
2725
|
+
})),
|
|
2726
|
+
createMultipartUpload: () => notModelled("createMultipartUpload()"),
|
|
2727
|
+
resumeMultipartUpload: () => notModelled("resumeMultipartUpload()")
|
|
2136
2728
|
};
|
|
2137
|
-
return new Proxy({}, { get(_stub, prop) {
|
|
2138
|
-
if (prop === "then" || typeof prop === "symbol") return void 0;
|
|
2139
|
-
if (prop === "fetch") return fetchThrough;
|
|
2140
|
-
if (prop === "connect") return () => unsupported("connect() (a raw TCP socket) is not modelled");
|
|
2141
|
-
return call(prop);
|
|
2142
|
-
} });
|
|
2143
2729
|
}
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
* models make themselves.
|
|
2149
|
-
*/
|
|
2150
|
-
/** Sets `ctx` and `env` as the runtime's base classes do, for the one `new` workerd would refuse. */
|
|
2151
|
-
var StandInEntrypoint = class {
|
|
2152
|
-
ctx;
|
|
2153
|
-
env;
|
|
2154
|
-
constructor(ctx, env) {
|
|
2155
|
-
this.ctx = ctx;
|
|
2156
|
-
this.env = env;
|
|
2157
|
-
}
|
|
2158
|
-
};
|
|
2159
|
-
/**
|
|
2160
|
-
* Construct a subclass of the entrypoint base class named `base`. workerd's
|
|
2161
|
-
* base constructors accept only a native ExecutionContext, so for this one
|
|
2162
|
-
* synchronous `new` the class that extends the base directly extends a
|
|
2163
|
-
* stand-in instead; its own constructor and field initialisers run as
|
|
2164
|
-
* written, and the base is put back before anything else can run.
|
|
2165
|
-
*/
|
|
2166
|
-
function constructEntrypoint(cls, base, ctx, env) {
|
|
2167
|
-
if (typeof cls !== "function") throw new TypeError("not a class");
|
|
2168
|
-
let direct = cls;
|
|
2730
|
+
/** Every object of the bucket, through all pages of a listing. */
|
|
2731
|
+
async function allObjects(real) {
|
|
2732
|
+
const out = [];
|
|
2733
|
+
let cursor;
|
|
2169
2734
|
for (;;) {
|
|
2170
|
-
const
|
|
2171
|
-
|
|
2172
|
-
|
|
2173
|
-
|
|
2735
|
+
const page = await real.list({
|
|
2736
|
+
include: ["customMetadata", "httpMetadata"],
|
|
2737
|
+
...cursor === void 0 ? {} : { cursor }
|
|
2738
|
+
});
|
|
2739
|
+
out.push(...page.objects);
|
|
2740
|
+
if (!page.truncated) return out;
|
|
2741
|
+
cursor = page.cursor;
|
|
2174
2742
|
}
|
|
2175
|
-
|
|
2176
|
-
|
|
2177
|
-
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2743
|
+
}
|
|
2744
|
+
/** Empty the bucket and put its seeds, before a run. */
|
|
2745
|
+
async function resetR2(real, seeds) {
|
|
2746
|
+
const keys = (await allObjects(real)).map((o) => o.key);
|
|
2747
|
+
for (let i = 0; i < keys.length; i += 1e3) await real.delete(keys.slice(i, i + 1e3));
|
|
2748
|
+
for (const [key, seed] of Object.entries(seeds)) if (typeof seed === "string") await real.put(key, seed);
|
|
2749
|
+
else await real.put(key, seed.value, {
|
|
2750
|
+
...seed.customMetadata ? { customMetadata: { ...seed.customMetadata } } : {},
|
|
2751
|
+
...seed.httpMetadata ? { httpMetadata: { ...seed.httpMetadata } } : {}
|
|
2752
|
+
});
|
|
2753
|
+
}
|
|
2754
|
+
/** Largest object whose text the snapshot keeps. */
|
|
2755
|
+
const snapshotTextLimit = 4096;
|
|
2756
|
+
/**
|
|
2757
|
+
* The bucket's objects as rows `{ key, size, etag, customMetadata,
|
|
2758
|
+
* httpMetadata, text? }` by key, `text` for an object of up to 4 KiB that is
|
|
2759
|
+
* valid UTF-8. Versions and upload times are left out: they are the store's,
|
|
2760
|
+
* not the Worker's.
|
|
2761
|
+
*/
|
|
2762
|
+
async function snapshotR2(real) {
|
|
2763
|
+
const rows = [];
|
|
2764
|
+
const objects = (await allObjects(real)).sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
|
|
2765
|
+
for (const o of objects) {
|
|
2766
|
+
let text;
|
|
2767
|
+
if (o.size <= snapshotTextLimit) {
|
|
2768
|
+
const body = await real.get(o.key);
|
|
2769
|
+
if (body && "body" in body) try {
|
|
2770
|
+
text = new TextDecoder("utf-8", {
|
|
2771
|
+
fatal: true,
|
|
2772
|
+
ignoreBOM: false
|
|
2773
|
+
}).decode(await body.arrayBuffer());
|
|
2774
|
+
} catch {}
|
|
2775
|
+
}
|
|
2776
|
+
rows.push(toJson({
|
|
2777
|
+
key: o.key,
|
|
2778
|
+
size: o.size,
|
|
2779
|
+
etag: o.etag,
|
|
2780
|
+
customMetadata: o.customMetadata ?? {},
|
|
2781
|
+
httpMetadata: o.httpMetadata ?? {},
|
|
2782
|
+
...text === void 0 ? {} : { text }
|
|
2783
|
+
}));
|
|
2181
2784
|
}
|
|
2785
|
+
return rows;
|
|
2182
2786
|
}
|
|
2183
2787
|
// packages/cloudflare/src/workflows.ts
|
|
2184
2788
|
/**
|
|
@@ -2386,13 +2990,12 @@ function validEventType(type) {
|
|
|
2386
2990
|
if (typeof type === "string" && type.length <= 100 && /^[a-zA-Z0-9_][a-zA-Z0-9-_]*$/.test(type)) return type;
|
|
2387
2991
|
throw new Error(`(workflow.invalid_event_type) event type must be up to 100 letters, digits, - or _, got ${JSON.stringify(type)}`);
|
|
2388
2992
|
}
|
|
2389
|
-
/**
|
|
2390
|
-
|
|
2391
|
-
|
|
2392
|
-
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
};
|
|
2993
|
+
/**
|
|
2994
|
+
* A promise that never settles: what a step call gives once its instance hibernated. The engine stops a
|
|
2995
|
+
* waiting instance's code where it is, so nothing after the wait runs, caught or not, until a wake re-runs
|
|
2996
|
+
* `run()` from the start.
|
|
2997
|
+
*/
|
|
2998
|
+
const hibernated = () => new Promise(() => {});
|
|
2396
2999
|
/**
|
|
2397
3000
|
* Whether a run event wakes the instance: not a wake at all, the restart of a
|
|
2398
3001
|
* run a wake began (its first delivery resumed the instance), or the wake of
|
|
@@ -2533,7 +3136,7 @@ async function deliverWorkflow(event, hooks, d) {
|
|
|
2533
3136
|
b,
|
|
2534
3137
|
c
|
|
2535
3138
|
];
|
|
2536
|
-
if (suspending !== void 0)
|
|
3139
|
+
if (suspending !== void 0) return alongsideWait("step.do");
|
|
2537
3140
|
if (options?.rollback !== void 0) {
|
|
2538
3141
|
hooks.unsupported(`Workflow ${d.binding}: rollback handlers are not modelled`);
|
|
2539
3142
|
throw new Error("eutaxy: rollback handlers are not modelled");
|
|
@@ -2673,7 +3276,7 @@ async function deliverWorkflow(event, hooks, d) {
|
|
|
2673
3276
|
retries: { ...resolved.retries }
|
|
2674
3277
|
}
|
|
2675
3278
|
};
|
|
2676
|
-
wait = await retryDelayMs
|
|
3279
|
+
wait = await retryDelayMs(retries, attempt, delayContext, thrown);
|
|
2677
3280
|
} catch (err) {
|
|
2678
3281
|
hooks.unsupported(`Workflow ${d.binding}: step "${name}"'s retry delay function threw (${String(err)})`);
|
|
2679
3282
|
throw err;
|
|
@@ -2698,7 +3301,7 @@ async function deliverWorkflow(event, hooks, d) {
|
|
|
2698
3301
|
await sleepStep(k, name, Math.max(0, at - Date.now()), at);
|
|
2699
3302
|
},
|
|
2700
3303
|
waitForEvent: async (name, options = {}) => {
|
|
2701
|
-
if (suspending !== void 0)
|
|
3304
|
+
if (suspending !== void 0) return alongsideWait("step.waitForEvent");
|
|
2702
3305
|
const type = validEventType(options.type);
|
|
2703
3306
|
const timeoutMs = durationMs(options.timeout ?? "24 hours");
|
|
2704
3307
|
if (!(timeoutMs >= 1e3 && timeoutMs <= 31536e6)) {
|
|
@@ -2772,18 +3375,24 @@ async function deliverWorkflow(event, hooks, d) {
|
|
|
2772
3375
|
gen,
|
|
2773
3376
|
deadline
|
|
2774
3377
|
};
|
|
2775
|
-
|
|
3378
|
+
hibernate();
|
|
3379
|
+
return hibernated();
|
|
2776
3380
|
}
|
|
2777
3381
|
};
|
|
2778
|
-
/** Set once a wait
|
|
3382
|
+
/** Set once a wait hibernated this run; the run then ends with the wait, wherever its code was. */
|
|
2779
3383
|
let suspending;
|
|
2780
|
-
|
|
2781
|
-
|
|
2782
|
-
|
|
2783
|
-
|
|
3384
|
+
/**
|
|
3385
|
+
* A step call once a wait hibernated the run. Code after the wait never runs (its promise never
|
|
3386
|
+
* settles), so the call comes from code running in parallel with the wait (`Promise.all` of a wait and
|
|
3387
|
+
* a step), which the engine would run while the wait is pending: not modelled, so reported, and the
|
|
3388
|
+
* call never settles, as the hibernated run's other calls.
|
|
3389
|
+
*/
|
|
3390
|
+
const alongsideWait = (what) => {
|
|
3391
|
+
hooks.unsupported(`Workflow ${d.binding}: ${what} started alongside step.waitForEvent; steps running in parallel with a wait are not modelled`);
|
|
3392
|
+
return hibernated();
|
|
2784
3393
|
};
|
|
2785
3394
|
async function sleepStep(k, name, ms, until) {
|
|
2786
|
-
if (suspending !== void 0)
|
|
3395
|
+
if (suspending !== void 0) return alongsideWait("step.sleep");
|
|
2787
3396
|
if (instance.persisted.has(k)) return;
|
|
2788
3397
|
const pending = instance.deadlines.get(k);
|
|
2789
3398
|
if (pending !== void 0) {
|
|
@@ -2813,6 +3422,10 @@ async function deliverWorkflow(event, hooks, d) {
|
|
|
2813
3422
|
value: null
|
|
2814
3423
|
});
|
|
2815
3424
|
}
|
|
3425
|
+
let hibernate = () => {};
|
|
3426
|
+
const hibernation = new Promise((resolve) => {
|
|
3427
|
+
hibernate = () => resolve(void 0);
|
|
3428
|
+
});
|
|
2816
3429
|
const ran = await runInvocation(hooks, inv, () => {
|
|
2817
3430
|
const flow = constructWorkflow(d.cls, executionContext(background), d.env);
|
|
2818
3431
|
const workflowEvent = {
|
|
@@ -2827,7 +3440,7 @@ async function deliverWorkflow(event, hooks, d) {
|
|
|
2827
3440
|
hooks.unsupported(`Workflow ${d.binding}: event.workflowName needs the Workflow's name, workflow(binding, className, { name })`);
|
|
2828
3441
|
}
|
|
2829
3442
|
});
|
|
2830
|
-
return flow.run(workflowEvent, step);
|
|
3443
|
+
return Promise.race([flow.run(workflowEvent, step), hibernation]);
|
|
2831
3444
|
});
|
|
2832
3445
|
const serialised = (value) => {
|
|
2833
3446
|
try {
|
|
@@ -2844,13 +3457,10 @@ async function deliverWorkflow(event, hooks, d) {
|
|
|
2844
3457
|
}
|
|
2845
3458
|
};
|
|
2846
3459
|
let result = ran.status === "completed" ? serialised(ran.value) : ran;
|
|
2847
|
-
if (suspending !== void 0) {
|
|
2848
|
-
|
|
2849
|
-
|
|
2850
|
-
|
|
2851
|
-
value: void 0
|
|
2852
|
-
};
|
|
2853
|
-
}
|
|
3460
|
+
if (suspending !== void 0 && ran.status !== "crashed") result = {
|
|
3461
|
+
status: "completed",
|
|
3462
|
+
value: void 0
|
|
3463
|
+
};
|
|
2854
3464
|
let status = result.status;
|
|
2855
3465
|
if (suspending !== void 0 && result.status === "completed") {
|
|
2856
3466
|
instance.status = "waiting";
|
|
@@ -2924,7 +3534,7 @@ async function deliverWorkflow(event, hooks, d) {
|
|
|
2924
3534
|
};
|
|
2925
3535
|
}
|
|
2926
3536
|
/** The delay before the next attempt (Workflows, Sleeping and retrying; a delay function is called). */
|
|
2927
|
-
async function retryDelayMs
|
|
3537
|
+
async function retryDelayMs(retries, attempt, ctx, error) {
|
|
2928
3538
|
const base = durationMs(typeof retries.delay === "function" ? await retries.delay({
|
|
2929
3539
|
ctx,
|
|
2930
3540
|
error
|
|
@@ -3134,10 +3744,11 @@ function workflowBinding(deps) {
|
|
|
3134
3744
|
followUps: []
|
|
3135
3745
|
};
|
|
3136
3746
|
const className = setup.className;
|
|
3137
|
-
const
|
|
3747
|
+
const callee = deps.calleeOf?.(binding);
|
|
3748
|
+
const cls = (callee?.exports ?? deps.exports)?.[className];
|
|
3138
3749
|
const instance = registryFor(binding).instances.get(id);
|
|
3139
3750
|
if (typeof cls !== "function" || !instance) {
|
|
3140
|
-
hooks.unsupported(`Workflow ${binding}: class ${className} is not among the Worker module's exports; pass them as createCloudflarePlatform({ ..., exports })`);
|
|
3751
|
+
hooks.unsupported(callee ? `Workflow ${binding}: class ${className} is not among the exports of the callee ${callee.name}` : `Workflow ${binding}: class ${className} is not among the Worker module's exports; pass them as createCloudflarePlatform({ ..., exports })`);
|
|
3141
3752
|
return {
|
|
3142
3753
|
status: "errored",
|
|
3143
3754
|
followUps: []
|
|
@@ -3148,7 +3759,7 @@ function workflowBinding(deps) {
|
|
|
3148
3759
|
...setup.name === void 0 ? {} : { name: setup.name },
|
|
3149
3760
|
instance,
|
|
3150
3761
|
cls,
|
|
3151
|
-
env: deps.env(),
|
|
3762
|
+
env: callee ? calleeEnv(callee.name, deps.env()) : deps.env(),
|
|
3152
3763
|
maxFaultsPerRun: spec.bounds.maxFaultsPerRun,
|
|
3153
3764
|
maxRedeliveries: spec.bounds.maxRedeliveries
|
|
3154
3765
|
});
|
|
@@ -3156,6 +3767,54 @@ function workflowBinding(deps) {
|
|
|
3156
3767
|
};
|
|
3157
3768
|
}
|
|
3158
3769
|
/**
|
|
3770
|
+
* A service binding whose callee runs for real (a `callee` setup step): a
|
|
3771
|
+
* stub running the callee's module inside each call. Never the real binding.
|
|
3772
|
+
* Nothing to reset or snapshot of its own: the callee's bindings have their
|
|
3773
|
+
* own steps under their qualified names. A binding without a `callee` step
|
|
3774
|
+
* is not this record's.
|
|
3775
|
+
*/
|
|
3776
|
+
function calleeBinding(deps) {
|
|
3777
|
+
/** The bindings the current scenario names a callee for. */
|
|
3778
|
+
let setups = /* @__PURE__ */ new Map();
|
|
3779
|
+
const proxies = /* @__PURE__ */ new Map();
|
|
3780
|
+
const state = new CalleeState();
|
|
3781
|
+
return {
|
|
3782
|
+
kind: "callee",
|
|
3783
|
+
target: "Service",
|
|
3784
|
+
is: isServiceBinding,
|
|
3785
|
+
proxy(name, _real, ctx) {
|
|
3786
|
+
const setup = setups.get(name);
|
|
3787
|
+
if (!setup) return void 0;
|
|
3788
|
+
let p = proxies.get(name);
|
|
3789
|
+
if (!p) {
|
|
3790
|
+
const module = deps.callees?.[name];
|
|
3791
|
+
if (!module) {
|
|
3792
|
+
ctx.hooks.unsupported(`callee ${name}: the platform was not given its module; pass createCloudflarePlatform({ ..., callees: { ${name}: { name, exports } } }), as eutaxy check does from the callee() step`);
|
|
3793
|
+
return proxyService(name, ctx, {
|
|
3794
|
+
kind: "service",
|
|
3795
|
+
binding: name,
|
|
3796
|
+
methods: {}
|
|
3797
|
+
});
|
|
3798
|
+
}
|
|
3799
|
+
p = proxyCallee(name, ctx, setup, module, deps.env(), state);
|
|
3800
|
+
proxies.set(name, p);
|
|
3801
|
+
}
|
|
3802
|
+
return p;
|
|
3803
|
+
},
|
|
3804
|
+
clear() {
|
|
3805
|
+
setups = /* @__PURE__ */ new Map();
|
|
3806
|
+
proxies.clear();
|
|
3807
|
+
state.clear();
|
|
3808
|
+
},
|
|
3809
|
+
async reset(step) {
|
|
3810
|
+
setups.set(step.binding, step);
|
|
3811
|
+
},
|
|
3812
|
+
async snapshot() {
|
|
3813
|
+
return null;
|
|
3814
|
+
}
|
|
3815
|
+
};
|
|
3816
|
+
}
|
|
3817
|
+
/**
|
|
3159
3818
|
* A service binding: never the real binding, a stub answering from the
|
|
3160
3819
|
* scenario's `service` setup; each call one effect. Nothing to reset or
|
|
3161
3820
|
* snapshot, the callee is scripted.
|
|
@@ -3205,75 +3864,19 @@ function serviceBinding() {
|
|
|
3205
3864
|
*/
|
|
3206
3865
|
function ownedSetups(setup, bindings) {
|
|
3207
3866
|
const out = [];
|
|
3867
|
+
const databases = /* @__PURE__ */ new Set();
|
|
3208
3868
|
for (const step of setup) {
|
|
3209
3869
|
const binding = bindings.find((b) => b.kind === step.kind);
|
|
3210
|
-
if (binding)
|
|
3870
|
+
if (!binding) continue;
|
|
3871
|
+
if (step.kind === "d1") {
|
|
3872
|
+
const name = String(step["binding"]);
|
|
3873
|
+
if (databases.has(name)) continue;
|
|
3874
|
+
databases.add(name);
|
|
3875
|
+
}
|
|
3876
|
+
out.push([binding, step]);
|
|
3211
3877
|
}
|
|
3212
3878
|
return out;
|
|
3213
3879
|
}
|
|
3214
|
-
// packages/cloudflare/src/caller.ts
|
|
3215
|
-
/**
|
|
3216
|
-
* The caller of an inbound request or RPC call. Cloudflare retries neither,
|
|
3217
|
-
* so resends follow the policy the drive declares for the caller: how many
|
|
3218
|
-
* times it resends, the virtual delay before each resend, and how long it
|
|
3219
|
-
* waits for an answer. The decision is the caller's and is made once per
|
|
3220
|
-
* attempt: at the response point, or at its deadline if the handler has
|
|
3221
|
-
* not answered by then.
|
|
3222
|
-
*/
|
|
3223
|
-
/** The response point: a crash before it is a response the caller never saw. */
|
|
3224
|
-
const RESPOND = ["crash_before"];
|
|
3225
|
-
/**
|
|
3226
|
-
* With a caller deadline the answer can also arrive too late: `ambiguous`
|
|
3227
|
-
* here means it was sent, the caller counted it as failed, and the handler
|
|
3228
|
-
* carried on.
|
|
3229
|
-
*/
|
|
3230
|
-
const RESPOND_WITH_DEADLINE = ["crash_before", "ambiguous"];
|
|
3231
|
-
/** The virtual delay before resend number `resend` (1 for the first), per the policy. */
|
|
3232
|
-
function retryDelayMs(policy, resend) {
|
|
3233
|
-
const delays = policy.delaysMs ?? [];
|
|
3234
|
-
return delays[Math.min(resend, delays.length) - 1] ?? 0;
|
|
3235
|
-
}
|
|
3236
|
-
/**
|
|
3237
|
-
* Start waiting for the attempt's answer. With a deadline, a virtual timer
|
|
3238
|
-
* makes the caller give up at it whatever the handler is doing, so a resend
|
|
3239
|
-
* can start while the first attempt still runs. `gaveUp` is what the
|
|
3240
|
-
* `gave_up` effect records when the retries are spent.
|
|
3241
|
-
*/
|
|
3242
|
-
function startCaller(event, hooks, spec, policy, target, gaveUp) {
|
|
3243
|
-
const started = Date.now();
|
|
3244
|
-
const deadline = policy.deadlineMs;
|
|
3245
|
-
const lateAt = deadline === void 0 ? void 0 : started + deadline;
|
|
3246
|
-
/** The caller decides once: it accepts the answer, or gives up at `at` and resends or stops. */
|
|
3247
|
-
let decided = false;
|
|
3248
|
-
const giveUp = (at) => {
|
|
3249
|
-
if (decided) return;
|
|
3250
|
-
decided = true;
|
|
3251
|
-
const next = redelivery(event, policy.retries, spec.bounds);
|
|
3252
|
-
if (next) {
|
|
3253
|
-
const resendAt = Math.max(at + retryDelayMs(policy, event.attempt), Date.now());
|
|
3254
|
-
hooks.enqueue({
|
|
3255
|
-
...next,
|
|
3256
|
-
...resendAt > Date.now() ? { at: resendAt } : {}
|
|
3257
|
-
});
|
|
3258
|
-
} else hooks.effectSync({
|
|
3259
|
-
invocation: hooks.bookkeeping(),
|
|
3260
|
-
target,
|
|
3261
|
-
op: "gave_up",
|
|
3262
|
-
args: gaveUp,
|
|
3263
|
-
allowed: []
|
|
3264
|
-
}, () => null, () => null);
|
|
3265
|
-
};
|
|
3266
|
-
const deadlineTimer = lateAt === void 0 ? void 0 : setTimeout(() => giveUp(lateAt), deadline);
|
|
3267
|
-
return {
|
|
3268
|
-
responseFaults: deadline === void 0 ? RESPOND : RESPOND_WITH_DEADLINE,
|
|
3269
|
-
isLate: () => lateAt !== void 0 && Date.now() > lateAt,
|
|
3270
|
-
settle(accepted, late) {
|
|
3271
|
-
if (deadlineTimer !== void 0) clearTimeout(deadlineTimer);
|
|
3272
|
-
if (accepted) decided = true;
|
|
3273
|
-
else giveUp(late && lateAt !== void 0 ? lateAt : Date.now());
|
|
3274
|
-
}
|
|
3275
|
-
};
|
|
3276
|
-
}
|
|
3277
3880
|
// packages/cloudflare/src/http.ts
|
|
3278
3881
|
/** The URL inbound requests are addressed to; handlers read only the path. */
|
|
3279
3882
|
const requestOrigin = "https://worker.test";
|
|
@@ -3464,117 +4067,6 @@ async function deliverMessage$1(event, hooks, spec, drive, invocation, worker, m
|
|
|
3464
4067
|
followUps
|
|
3465
4068
|
};
|
|
3466
4069
|
}
|
|
3467
|
-
// packages/cloudflare/src/rpc.ts
|
|
3468
|
-
/**
|
|
3469
|
-
* Inbound RPC delivery: one invocation per attempt of a `WorkerEntrypoint`
|
|
3470
|
-
* method call the drive's caller makes. The entrypoint is constructed anew
|
|
3471
|
-
* for each call, as the runtime does (Cloudflare, Workers RPC: a new
|
|
3472
|
-
* instance of the class for every call), and its return value or the error
|
|
3473
|
-
* it threw is the response the caller sees.
|
|
3474
|
-
*/
|
|
3475
|
-
/**
|
|
3476
|
-
* An error as the caller sees it over RPC: a new error object with the
|
|
3477
|
-
* name and message (Cloudflare, RPC error handling), nothing of its class.
|
|
3478
|
-
*/
|
|
3479
|
-
function describeError(error) {
|
|
3480
|
-
if (error instanceof Error) return `${error.name}: ${error.message}`;
|
|
3481
|
-
return typeof error === "string" ? error : JSON.stringify(toJson(error));
|
|
3482
|
-
}
|
|
3483
|
-
/** One attempt of a call, under the caller's retry policy and deadline. */
|
|
3484
|
-
async function deliverCall(event, hooks, spec, drive, invocation, cls, env) {
|
|
3485
|
-
const call = event.data;
|
|
3486
|
-
const target = rpcTarget(drive, call.method);
|
|
3487
|
-
const inv = hooks.startInvocation(invocation);
|
|
3488
|
-
const background = [];
|
|
3489
|
-
const args = {
|
|
3490
|
-
callId: event.id,
|
|
3491
|
-
method: call.method,
|
|
3492
|
-
args: call.args
|
|
3493
|
-
};
|
|
3494
|
-
const caller = startCaller(event, hooks, spec, drive, target, {
|
|
3495
|
-
callId: event.id,
|
|
3496
|
-
attempts: event.attempt
|
|
3497
|
-
});
|
|
3498
|
-
const ran = await runInvocation(hooks, inv, () => callMethod(cls, call, executionContext(background), env));
|
|
3499
|
-
let status = ran.status;
|
|
3500
|
-
let late = caller.isLate();
|
|
3501
|
-
let answer = null;
|
|
3502
|
-
if (ran.status === "completed") {
|
|
3503
|
-
if (!isPlainData(ran.value)) hooks.unsupported(`Rpc ${call.method}: the result is not plain data (a stub, a function or a stream); RPC capabilities are not modelled`);
|
|
3504
|
-
const s = {
|
|
3505
|
-
ok: true,
|
|
3506
|
-
value: toJson(ran.value)
|
|
3507
|
-
};
|
|
3508
|
-
try {
|
|
3509
|
-
hooks.effectSync({
|
|
3510
|
-
invocation,
|
|
3511
|
-
target,
|
|
3512
|
-
op: "response",
|
|
3513
|
-
args,
|
|
3514
|
-
allowed: caller.responseFaults
|
|
3515
|
-
}, () => s, (v) => v);
|
|
3516
|
-
answer = s;
|
|
3517
|
-
} catch (err) {
|
|
3518
|
-
if (err instanceof CrashSignal) status = "crashed";
|
|
3519
|
-
else if (err instanceof InjectedEffectError) {
|
|
3520
|
-
answer = s;
|
|
3521
|
-
late = true;
|
|
3522
|
-
} else throw err;
|
|
3523
|
-
}
|
|
3524
|
-
} else if (ran.status === "errored") {
|
|
3525
|
-
const s = {
|
|
3526
|
-
ok: false,
|
|
3527
|
-
error: describeError(ran.error)
|
|
3528
|
-
};
|
|
3529
|
-
hooks.effectSync({
|
|
3530
|
-
invocation,
|
|
3531
|
-
target,
|
|
3532
|
-
op: "response",
|
|
3533
|
-
args,
|
|
3534
|
-
allowed: []
|
|
3535
|
-
}, () => s, (v) => v);
|
|
3536
|
-
answer = s;
|
|
3537
|
-
}
|
|
3538
|
-
caller.settle(answer !== null && !late && answer.ok, late);
|
|
3539
|
-
if (await drainBackground(hooks, inv, invocation, target, background)) status = "crashed";
|
|
3540
|
-
return {
|
|
3541
|
-
status,
|
|
3542
|
-
followUps: []
|
|
3543
|
-
};
|
|
3544
|
-
}
|
|
3545
|
-
/**
|
|
3546
|
-
* The class an RPC drive calls: the named export, or the Worker's default
|
|
3547
|
-
* export (the class passed as the handler, or `exports.default`). Not
|
|
3548
|
-
* necessarily a class: the platform reports what it found instead.
|
|
3549
|
-
*/
|
|
3550
|
-
function entrypointClass(handler, exports, entrypoint) {
|
|
3551
|
-
if (entrypoint !== void 0) return exports?.[entrypoint];
|
|
3552
|
-
return typeof handler === "function" ? handler : exports?.["default"];
|
|
3553
|
-
}
|
|
3554
|
-
/**
|
|
3555
|
-
* The method RPC exposes under a name: one the class or a superclass defines
|
|
3556
|
-
* on its prototype. An instance property, even a function, and Object's own
|
|
3557
|
-
* methods are not callable (workerd: "The RPC receiver does not implement the
|
|
3558
|
-
* method").
|
|
3559
|
-
*/
|
|
3560
|
-
function rpcMethod(instance, name) {
|
|
3561
|
-
for (let proto = Object.getPrototypeOf(instance); proto !== null && proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) {
|
|
3562
|
-
const own = Object.getOwnPropertyDescriptor(proto, name);
|
|
3563
|
-
if (!own) continue;
|
|
3564
|
-
return typeof own.value === "function" && name !== "constructor" ? own.value : void 0;
|
|
3565
|
-
}
|
|
3566
|
-
}
|
|
3567
|
-
/**
|
|
3568
|
-
* Construct the entrypoint for one call and invoke the method, as the
|
|
3569
|
-
* runtime does per call. The arguments are copied, as RPC copies them: a
|
|
3570
|
-
* method that mutates one changes neither the scenario nor a later attempt.
|
|
3571
|
-
*/
|
|
3572
|
-
function callMethod(cls, call, ctx, env) {
|
|
3573
|
-
const instance = constructEntrypoint(cls, "WorkerEntrypoint", ctx, env);
|
|
3574
|
-
const method = rpcMethod(instance, call.method);
|
|
3575
|
-
if (!method) throw new TypeError(`The RPC receiver does not implement the method "${call.method}".`);
|
|
3576
|
-
return method.apply(instance, structuredClone(call.args));
|
|
3577
|
-
}
|
|
3578
4070
|
// packages/cloudflare/src/scheduled.ts
|
|
3579
4071
|
/**
|
|
3580
4072
|
* Cron Trigger delivery: one invocation of the Worker's `scheduled()` handler
|
|
@@ -4158,7 +4650,9 @@ const assumptions = [
|
|
|
4158
4650
|
"D1 statements run against Miniflare's SQLite; each run/first/all/raw/batch/exec is one effect",
|
|
4159
4651
|
"message.timestamp is the virtual clock's time at delivery",
|
|
4160
4652
|
"only D1, Durable Object, R2, Workflow and scripted service bindings are proxied; touching any other binding makes the run UNSUPPORTED",
|
|
4161
|
-
"service bindings are scripted callees: the Worker behind a binding is never called; each RPC method call or fetch() through it is one effect answered from the scenario's service() setup, where crash_before and error mean the call never reached the callee, ambiguous that it acted and the answer was lost, and crash_after that the caller died after it (developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/); Cloudflare does not retry such a call",
|
|
4653
|
+
"service bindings are scripted callees unless the scenario names a callee for them: the Worker behind a scripted binding is never called; each RPC method call or fetch() through it is one effect answered from the scenario's service() setup, where crash_before and error mean the call never reached the callee, ambiguous that it acted and the answer was lost, and crash_after that the caller died after it (developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/); Cloudflare does not retry such a call",
|
|
4654
|
+
"a binding named as an alias of another (the same database, the same Durable Object namespace, in two Workers' configs) is that binding: its effects and snapshot carry the other's name, and a callee's Workflow runs the callee's class with the callee's env",
|
|
4655
|
+
"a service binding with a callee() setup runs that Worker's real code in the caller's simulation, in the same isolate, as Cloudflare runs both Workers on one thread (developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/): each RPC method call or fetch() through it is one effect hosting the callee's invocation (<caller invocation>/<binding>.<method>), which constructs the entrypoint anew with a fresh ExecutionContext and the callee's env (its bindings under <worker name>/<binding>) and answers with the return value, plain data by copy, or the Response as it is; what the callee throws reaches the caller as a new error with its name, message and serializable own properties, a built-in class as itself (developers.cloudflare.com/workers/runtime-apis/rpc/error-handling/); the callee's waitUntil work finishes before its answer crosses; crash_before means the call never reached the callee, ambiguous that it acted and the answer was lost, crash_after that the caller died after it, and a fault that crashes the callee ends its invocation and throws an Error to the caller; Cloudflare retries nothing",
|
|
4162
4656
|
"R2 buckets are Miniflare's real ones, emptied and seeded before each run and snapshotted after it; R2 is strongly consistent and the last writer wins (developers.cloudflare.com/r2/reference/consistency/); each put, delete, get, head and list is one effect, a body is read inside its get, and an object's version and upload time are stand-ins so traces repeat; multipart uploads and conditions on the upload time are not modelled",
|
|
4163
4657
|
"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/)",
|
|
4164
4658
|
"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)",
|
|
@@ -4170,8 +4664,16 @@ const assumptions = [
|
|
|
4170
4664
|
"cron triggers: each tick of the drive's expression is one invocation of scheduled(), with scheduledTime the tick's virtual time (UTC, the expression's matches from the virtual epoch on, in Cloudflare's dialect where weekdays run 1 = Sunday to 7 = Saturday; L, W and # are not modelled) and cron the expression (developers.cloudflare.com/workers/runtime-apis/handlers/scheduled/, /workers/configuration/cron-triggers/); Cloudflare documents noRetry() but no retry count, so the drive declares how many times a tick whose handler failed is re-run, and none after noRetry()",
|
|
4171
4665
|
"inbound RPC: one invocation per call attempt, the entrypoint constructed anew for each with a fresh ExecutionContext (developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/rpc/); the return value is the response effect, and an exception reaches the caller as a new error with its name and message (developers.cloudflare.com/workers/runtime-apis/rpc/error-handling/); Cloudflare does not retry a call, so the drive's caller resends a call that threw or got no answer as the http drive's caller does; a result that is not plain data (a stub, a function, a stream) makes the run UNSUPPORTED"
|
|
4172
4666
|
];
|
|
4667
|
+
/**
|
|
4668
|
+
* The Cloudflare platform for `check`, run inside workerd under the Cloudflare Vitest plugin: the scenario's
|
|
4669
|
+
* drive delivered to the Worker's handlers, its bindings proxied so every call is an effect that faults can
|
|
4670
|
+
* hit, and the setup's resources reset before each run and snapshotted after it.
|
|
4671
|
+
*/
|
|
4173
4672
|
function createCloudflarePlatform(options) {
|
|
4174
4673
|
const env = options.env;
|
|
4674
|
+
const aliases = options.aliases ?? {};
|
|
4675
|
+
/** The name a binding is known by: itself, or the name it is an alias of. */
|
|
4676
|
+
const canonical = (name) => aliases[name] ?? name;
|
|
4175
4677
|
const maxRetries = options.maxRetries ?? 3;
|
|
4176
4678
|
let hooksRef = null;
|
|
4177
4679
|
const connections = new Connections();
|
|
@@ -4185,8 +4687,8 @@ function createCloudflarePlatform(options) {
|
|
|
4185
4687
|
};
|
|
4186
4688
|
/**
|
|
4187
4689
|
* The kinds of binding modelled, in the order an env value is tried against
|
|
4188
|
-
* them:
|
|
4189
|
-
* type (
|
|
4690
|
+
* them: service bindings first (a callee's, then scripted), since in workerd
|
|
4691
|
+
* they answer every duck type (their property reads are RPC stubs).
|
|
4190
4692
|
*/
|
|
4191
4693
|
const durable = durableObjectBinding({
|
|
4192
4694
|
ctx,
|
|
@@ -4194,31 +4696,56 @@ function createCloudflarePlatform(options) {
|
|
|
4194
4696
|
real: (name) => env[name]
|
|
4195
4697
|
});
|
|
4196
4698
|
const bindings = [
|
|
4699
|
+
calleeBinding({
|
|
4700
|
+
callees: options.callees,
|
|
4701
|
+
env: () => proxiedEnv
|
|
4702
|
+
}),
|
|
4197
4703
|
serviceBinding(),
|
|
4198
4704
|
d1Binding(options.schemas),
|
|
4199
4705
|
durable,
|
|
4200
4706
|
r2Binding(),
|
|
4201
4707
|
workflowBinding({
|
|
4202
4708
|
exports: options.exports,
|
|
4203
|
-
env: () => proxiedEnv
|
|
4709
|
+
env: () => proxiedEnv,
|
|
4710
|
+
calleeOf: (binding) => {
|
|
4711
|
+
const at = binding.indexOf("/");
|
|
4712
|
+
if (at < 0) return void 0;
|
|
4713
|
+
const name = binding.slice(0, at);
|
|
4714
|
+
return Object.values(options.callees ?? {}).find((c) => c.name === name);
|
|
4715
|
+
}
|
|
4204
4716
|
})
|
|
4205
4717
|
];
|
|
4206
4718
|
const own = (prop) => typeof prop !== "string" || !prop.startsWith("__VITEST_POOL_WORKERS_");
|
|
4719
|
+
const aliasKeys = Object.keys(aliases).filter((a) => canonical(a) in env);
|
|
4207
4720
|
const proxiedEnv = new Proxy(env, {
|
|
4208
4721
|
get(target, prop, receiver) {
|
|
4209
4722
|
if (!own(prop)) return void 0;
|
|
4210
|
-
|
|
4211
|
-
|
|
4212
|
-
|
|
4213
|
-
|
|
4723
|
+
if (typeof prop !== "string") return Reflect.get(target, prop, receiver);
|
|
4724
|
+
const name = canonical(prop);
|
|
4725
|
+
const value = Reflect.get(target, name, receiver);
|
|
4726
|
+
for (const binding of bindings) {
|
|
4727
|
+
if (!binding.is(value)) continue;
|
|
4728
|
+
const proxied = binding.proxy(name, value, ctx);
|
|
4729
|
+
if (proxied !== void 0) return proxied;
|
|
4730
|
+
}
|
|
4731
|
+
if (isBindingLike(value)) ctx.hooks.unsupported(`binding ${name} is not proxied`);
|
|
4214
4732
|
return value;
|
|
4215
4733
|
},
|
|
4216
|
-
has: (target, prop) => own(prop) && Reflect.has(target, prop),
|
|
4217
|
-
ownKeys: (target) => Reflect.ownKeys(target).filter(own),
|
|
4218
|
-
getOwnPropertyDescriptor: (target, prop) =>
|
|
4734
|
+
has: (target, prop) => own(prop) && (Reflect.has(target, prop) || typeof prop === "string" && aliasKeys.includes(prop)),
|
|
4735
|
+
ownKeys: (target) => [.../* @__PURE__ */ new Set([...Reflect.ownKeys(target).filter(own), ...aliasKeys])],
|
|
4736
|
+
getOwnPropertyDescriptor: (target, prop) => {
|
|
4737
|
+
if (!own(prop)) return void 0;
|
|
4738
|
+
if (typeof prop === "string" && aliasKeys.includes(prop)) return {
|
|
4739
|
+
value: env[canonical(prop)],
|
|
4740
|
+
enumerable: true,
|
|
4741
|
+
configurable: true,
|
|
4742
|
+
writable: false
|
|
4743
|
+
};
|
|
4744
|
+
return Reflect.getOwnPropertyDescriptor(target, prop);
|
|
4745
|
+
}
|
|
4219
4746
|
});
|
|
4220
4747
|
const worker = {
|
|
4221
|
-
handler: typeof options.handler === "function" ?
|
|
4748
|
+
handler: typeof options.handler === "function" ? entrypointHandler(options.handler) : options.handler,
|
|
4222
4749
|
env: proxiedEnv
|
|
4223
4750
|
};
|
|
4224
4751
|
return {
|
|
@@ -4228,7 +4755,10 @@ function createCloudflarePlatform(options) {
|
|
|
4228
4755
|
async reset(spec) {
|
|
4229
4756
|
await connections.clear();
|
|
4230
4757
|
for (const binding of bindings) binding.clear();
|
|
4231
|
-
for (const [binding, setup] of ownedSetups(spec.setup, bindings))
|
|
4758
|
+
for (const [binding, setup] of ownedSetups(spec.setup, bindings)) {
|
|
4759
|
+
if (setup.binding in aliases) throw new Error(`binding ${setup.binding} is an alias of ${canonical(setup.binding)}: set it up and read it as ${canonical(setup.binding)}`);
|
|
4760
|
+
await binding.reset(setup, env[setup.binding]);
|
|
4761
|
+
}
|
|
4232
4762
|
},
|
|
4233
4763
|
restrictEvents(spec, keepIds) {
|
|
4234
4764
|
return {
|
|
@@ -4615,6 +5145,7 @@ async function rawSide(spec, options) {
|
|
|
4615
5145
|
/** Run both sides and compare. The Eutaxy side runs first; both start from the schema. */
|
|
4616
5146
|
async function runDifferential(spec, options) {
|
|
4617
5147
|
if ((spec.drive.kind === "http" || spec.drive.kind === "rpc") && ("delaysMs" in spec.drive || "deadlineMs" in spec.drive)) throw new Error("runDifferential does not model the caller's delaysMs or deadlineMs yet");
|
|
5148
|
+
if (spec.setup.some((s) => s.kind === "callee")) throw new Error("runDifferential keeps to the binding proxies: a scenario with a callee() has no raw side; script the service for the differential entry");
|
|
4618
5149
|
const { unsupported, ...eutaxy } = await eutaxySide(spec, options);
|
|
4619
5150
|
const raw = await rawSide(spec, options);
|
|
4620
5151
|
const differences = compareSides({
|
|
@@ -4649,7 +5180,10 @@ function globKey(path) {
|
|
|
4649
5180
|
* meta, which the CLI reads back. It imports nothing that needs Node, so
|
|
4650
5181
|
* the Cloudflare Vitest plugin can load it.
|
|
4651
5182
|
*/
|
|
4652
|
-
/**
|
|
5183
|
+
/**
|
|
5184
|
+
* Each D1 binding's schema, read from the `.sql` files next to the scenario. Several `d1Schema` steps
|
|
5185
|
+
* on one binding (a migration per file) are joined in setup order, each file its own statements.
|
|
5186
|
+
*/
|
|
4653
5187
|
function schemasFor(scenario, sqlFiles) {
|
|
4654
5188
|
const schemas = {};
|
|
4655
5189
|
for (const step of scenario.setup) {
|
|
@@ -4657,7 +5191,9 @@ function schemasFor(scenario, sqlFiles) {
|
|
|
4657
5191
|
const file = String(step["schemaFile"]);
|
|
4658
5192
|
const sql = sqlFiles[globKey(file)];
|
|
4659
5193
|
if (sql === void 0) throw new Error(`schema file ${file} not found next to the scenario`);
|
|
4660
|
-
|
|
5194
|
+
const binding = String(step["binding"]);
|
|
5195
|
+
const earlier = schemas[binding];
|
|
5196
|
+
schemas[binding] = earlier === void 0 ? sql : `${earlier}\n;\n${sql}`;
|
|
4661
5197
|
}
|
|
4662
5198
|
return schemas;
|
|
4663
5199
|
}
|
|
@@ -4725,7 +5261,10 @@ async function selectSpecModules(scenario, modules, specEntries) {
|
|
|
4725
5261
|
/** Run the scenario's check, with its specs observed, and return what the CLI reads back. */
|
|
4726
5262
|
async function checkInWorkerd(input) {
|
|
4727
5263
|
const { scenario } = input;
|
|
4728
|
-
const schemas = schemasFor(scenario,
|
|
5264
|
+
const schemas = schemasFor(scenario, {
|
|
5265
|
+
...input.sqlFiles,
|
|
5266
|
+
...input.extraSql
|
|
5267
|
+
});
|
|
4729
5268
|
const load = input.modules[globKey(scenario.worker.entry)];
|
|
4730
5269
|
if (!load) throw new Error(`worker entry ${scenario.worker.entry} not found next to the scenario`);
|
|
4731
5270
|
const worker = await load();
|
|
@@ -4734,13 +5273,21 @@ async function checkInWorkerd(input) {
|
|
|
4734
5273
|
handler: worker.default,
|
|
4735
5274
|
schemas,
|
|
4736
5275
|
durableObjects: input.durableObjects,
|
|
4737
|
-
exports: worker
|
|
5276
|
+
exports: worker,
|
|
5277
|
+
...input.callees === void 0 ? {} : { callees: input.callees },
|
|
5278
|
+
...input.aliases === void 0 ? {} : { aliases: input.aliases }
|
|
4738
5279
|
});
|
|
4739
5280
|
const { selected, specErrors } = await selectSpecModules(scenario, input.modules, input.specEntries);
|
|
4740
5281
|
const transportBase = {
|
|
4741
5282
|
worker: scenario.worker,
|
|
4742
5283
|
setup: scenario.setup,
|
|
4743
|
-
drive: scenario.drive
|
|
5284
|
+
drive: scenario.drive,
|
|
5285
|
+
...input.callees === void 0 ? {} : { callees: Object.fromEntries(Object.entries(input.callees).map(([binding, c]) => [binding, {
|
|
5286
|
+
name: c.name,
|
|
5287
|
+
...c.entrypoint === void 0 ? {} : { entrypoint: c.entrypoint },
|
|
5288
|
+
...c.props === void 0 ? {} : { props: c.props }
|
|
5289
|
+
}])) },
|
|
5290
|
+
...input.aliases === void 0 ? {} : { aliases: input.aliases }
|
|
4744
5291
|
};
|
|
4745
5292
|
if (specErrors.length > 0) return {
|
|
4746
5293
|
report: null,
|
|
@@ -4769,6 +5316,6 @@ async function checkInWorkerd(input) {
|
|
|
4769
5316
|
}))
|
|
4770
5317
|
};
|
|
4771
5318
|
}
|
|
4772
|
-
export {
|
|
5319
|
+
export { r2Bucket as A, webSocketReceived as B, external as C, implies as D, httpResponse as E, rpc as F, cloudflareRegressionTest as G, workflow as H, rpcResponse as I, service as L, r2Rows as M, references as N, queue as O, refines as P, serviceCall as R, everyRow as S, http as T, workflowRows as U, websocket as V, workflowStep as W, d1Write as _, createCloudflarePlatform as a, durableObjectRows as b, expectHolds as c, callee as d, cron as f, d1Schema as g, d1Rows as h, runDifferential as i, r2Op as j, queueAck as k, calleeEnv as l, d1Read as m, globKey as n, snapshotD1 as o, d1Param as p, specKey as r, check as s, checkInWorkerd as t, atLeastOncePerMessage as u, defineScenario as v, fetchCall as w, durableObjectTable as x, durableObject as y, unique as z };
|
|
4773
5320
|
|
|
4774
|
-
//# sourceMappingURL=workerd-
|
|
5321
|
+
//# sourceMappingURL=workerd-Be43_PZo.mjs.map
|