eutaxy 0.13.0 → 0.14.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 +5 -5
- package/dist/aws.mjs +2 -2
- package/dist/bin.mjs +1 -1
- package/dist/{cli-D3SPblWw.mjs → cli-BppjMaqL.mjs} +665 -95
- package/dist/cli-BppjMaqL.mjs.map +1 -0
- package/dist/cli.mjs +1 -1
- package/dist/cloudflare.d.mts +101 -7
- package/dist/cloudflare.d.mts.map +1 -1
- package/dist/cloudflare.mjs +3 -3
- package/dist/{delivery-invariants-Br29H7Rg.mjs → delivery-invariants-_T9ZMwOJ.mjs} +2 -2
- package/dist/{delivery-invariants-Br29H7Rg.mjs.map → delivery-invariants-_T9ZMwOJ.mjs.map} +1 -1
- package/dist/index.mjs +2 -2
- package/dist/{src-5pKRvj02.mjs → src-ClXnIi6O.mjs} +2 -2
- package/dist/{src-5pKRvj02.mjs.map → src-ClXnIi6O.mjs.map} +1 -1
- package/dist/{src-DGh7w877.mjs → src-DPCF2XGv.mjs} +103 -16
- package/dist/src-DPCF2XGv.mjs.map +1 -0
- package/dist/{workerd-BMJ-GKx8.mjs → workerd-DVJ8eCLI.mjs} +1798 -1372
- package/dist/workerd-DVJ8eCLI.mjs.map +1 -0
- package/package.json +1 -1
- package/dist/cli-D3SPblWw.mjs.map +0 -1
- package/dist/src-DGh7w877.mjs.map +0 -1
- package/dist/workerd-BMJ-GKx8.mjs.map +0 -1
|
@@ -1,26 +1,53 @@
|
|
|
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-DPCF2XGv.mjs";
|
|
2
|
+
import { a as redelivery, i as invocationOf, n as atLeastOncePerMessage$1 } from "./delivery-invariants-_T9ZMwOJ.mjs";
|
|
3
|
+
import { c as checkSpecModule, s as emitRegressionTest, t as renderJson, y as describeVerdict } from "./src-ClXnIi6O.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
|
+
const schemaIds = identifiers(bindings);
|
|
29
|
+
const calleeIds = identifiers(callees);
|
|
30
|
+
const ident = (binding) => schemaIds.get(binding) ?? calleeIds.get(binding) ?? binding;
|
|
8
31
|
const withExports = options.exports === true || options.workflows === true;
|
|
9
32
|
const imports = [
|
|
33
|
+
...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
34
|
"import { createCloudflarePlatform } from \"eutaxy/cloudflare\";",
|
|
11
35
|
"import { env } from \"cloudflare:workers\";",
|
|
12
36
|
...options.durableObjects ? ["import * as cloudflareTest from \"cloudflare:test\";"] : [],
|
|
13
37
|
`import scenario from ${JSON.stringify(options.scenarioPath)};`,
|
|
14
|
-
...bindings.map((b) => `import schema_${b} from ${JSON.stringify(`${options.schemaPaths[b]}?raw`)};`),
|
|
38
|
+
...bindings.map((b) => `import schema_${ident(b)} from ${JSON.stringify(`${options.schemaPaths[b]}?raw`)};`),
|
|
39
|
+
...callees.map((b) => `import * as callee_${calleeIds.get(b)} from ${JSON.stringify(options.callees?.[b]?.path)};`),
|
|
15
40
|
withExports ? `import * as worker from ${JSON.stringify(options.workerPath)};` : `import handler from ${JSON.stringify(options.workerPath)};`,
|
|
16
41
|
...(options.specModules ?? []).map((m, i) => `import * as core_${i} from ${JSON.stringify(m.path)};`)
|
|
17
42
|
];
|
|
18
|
-
const schemas = `{ ${bindings.map((b) => `${b}: schema_${b}`).join(", ")} }`;
|
|
43
|
+
const schemas = `{ ${bindings.map((b) => `${key(b)}: schema_${ident(b)}`).join(", ")} }`;
|
|
44
|
+
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
45
|
const retries = options.maxRetries === void 0 ? "" : `, maxRetries: ${options.maxRetries}`;
|
|
46
|
+
const aliases = options.aliases === void 0 || Object.keys(options.aliases).length === 0 ? "" : `, aliases: ${JSON.stringify(options.aliases)}`;
|
|
20
47
|
const objects = options.durableObjects ? ", durableObjects: cloudflareTest" : "";
|
|
21
48
|
return emitRegressionTest(verdict, {
|
|
22
49
|
imports,
|
|
23
|
-
platform: `createCloudflarePlatform({ env, ${withExports ? "handler: worker.default" : "handler"}, schemas: ${schemas}${retries}${objects}${withExports ? ", exports: worker" : ""} })`,
|
|
50
|
+
platform: `createCloudflarePlatform({ env, ${withExports ? "handler: worker.default" : "handler"}, schemas: ${schemas}${retries}${objects}${withExports ? ", exports: worker" : ""}${calleeOption}${aliases} })`,
|
|
24
51
|
scenario: options.budgetMs === void 0 ? "scenario" : `{ ...scenario, bounds: { ...scenario.bounds, budgetMs: ${options.budgetMs} } }`,
|
|
25
52
|
...options.expect ? { expect: options.expect } : {},
|
|
26
53
|
...options.engineModule ? { engineModule: options.engineModule } : {},
|
|
@@ -30,211 +57,16 @@ function cloudflareRegressionTest(verdict, options) {
|
|
|
30
57
|
})) } : {}
|
|
31
58
|
});
|
|
32
59
|
}
|
|
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
60
|
// packages/cloudflare/src/background.ts
|
|
230
61
|
const CUT_OFF = ["cut_off"];
|
|
231
62
|
/**
|
|
232
63
|
* The `ExecutionContext` handed to a handler; `waitUntil` work is collected to
|
|
233
|
-
* run after it returns
|
|
64
|
+
* run after it returns, and `props` is what the caller's binding carries
|
|
65
|
+
* (developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/rpc/, props). A rejection is kept in `failures` when given: a
|
|
234
66
|
* scheduled invocation's status is that of its first failed `waitUntil`
|
|
235
67
|
* (Cloudflare, Scheduled handler); a queue or HTTP delivery's is not.
|
|
236
68
|
*/
|
|
237
|
-
function executionContext(background, failures) {
|
|
69
|
+
function executionContext(background, failures, props = {}) {
|
|
238
70
|
return {
|
|
239
71
|
waitUntil: (promise) => {
|
|
240
72
|
background.push(promise.then(() => void 0, (error) => {
|
|
@@ -242,7 +74,7 @@ function executionContext(background, failures) {
|
|
|
242
74
|
}));
|
|
243
75
|
},
|
|
244
76
|
passThroughOnException: () => {},
|
|
245
|
-
props:
|
|
77
|
+
props: structuredClone(props)
|
|
246
78
|
};
|
|
247
79
|
}
|
|
248
80
|
/**
|
|
@@ -953,269 +785,107 @@ async function readTables(real, helpers, names, touched, objects, sql, seededSql
|
|
|
953
785
|
}
|
|
954
786
|
return out;
|
|
955
787
|
}
|
|
956
|
-
// packages/cloudflare/src/
|
|
788
|
+
// packages/cloudflare/src/entrypoint.ts
|
|
957
789
|
/**
|
|
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.
|
|
790
|
+
* Constructing an entrypoint class (`WorkerEntrypoint`, `WorkflowEntrypoint`)
|
|
791
|
+
* outside the runtime, for the one `new` per call or instance run that the
|
|
792
|
+
* models make themselves.
|
|
964
793
|
*/
|
|
965
|
-
/**
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
"list",
|
|
975
|
-
"createMultipartUpload"
|
|
976
|
-
].every((m) => typeof v[m] === "function");
|
|
977
|
-
}
|
|
794
|
+
/** Sets `ctx` and `env` as the runtime's base classes do, for the one `new` workerd would refuse. */
|
|
795
|
+
var StandInEntrypoint = class {
|
|
796
|
+
ctx;
|
|
797
|
+
env;
|
|
798
|
+
constructor(ctx, env) {
|
|
799
|
+
this.ctx = ctx;
|
|
800
|
+
this.env = env;
|
|
801
|
+
}
|
|
802
|
+
};
|
|
978
803
|
/**
|
|
979
|
-
*
|
|
980
|
-
*
|
|
981
|
-
* the
|
|
804
|
+
* Construct a subclass of the entrypoint base class named `base`. workerd's
|
|
805
|
+
* base constructors accept only a native ExecutionContext, so for this one
|
|
806
|
+
* synchronous `new` the class that extends the base directly extends a
|
|
807
|
+
* stand-in instead; its own constructor and field initialisers run as
|
|
808
|
+
* written, and the base is put back before anything else can run.
|
|
982
809
|
*/
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
810
|
+
function constructEntrypoint(cls, base, ctx, env) {
|
|
811
|
+
if (typeof cls !== "function") throw new TypeError("not a class");
|
|
812
|
+
let direct = cls;
|
|
813
|
+
for (;;) {
|
|
814
|
+
const parent = Object.getPrototypeOf(direct);
|
|
815
|
+
if (typeof parent !== "function" || parent === Function.prototype) throw new TypeError(`${cls.name} does not extend ${base}`);
|
|
816
|
+
if (parent.name === base) break;
|
|
817
|
+
direct = parent;
|
|
987
818
|
}
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
};
|
|
995
|
-
this.seen.set(realVersion, s);
|
|
996
|
-
}
|
|
997
|
-
return {
|
|
998
|
-
version: s.version,
|
|
999
|
-
uploaded: new Date(s.uploaded.getTime())
|
|
1000
|
-
};
|
|
819
|
+
const original = Object.getPrototypeOf(direct);
|
|
820
|
+
Object.setPrototypeOf(direct, StandInEntrypoint);
|
|
821
|
+
try {
|
|
822
|
+
return Reflect.construct(cls, [ctx, env]);
|
|
823
|
+
} finally {
|
|
824
|
+
Object.setPrototypeOf(direct, original);
|
|
1001
825
|
}
|
|
1002
|
-
};
|
|
1003
|
-
/** An object's metadata, with stand-ins for its version and upload time. */
|
|
1004
|
-
function metadata(real, book, at) {
|
|
1005
|
-
const { version, uploaded } = book.standIn(real.version, at);
|
|
1006
|
-
return {
|
|
1007
|
-
key: real.key,
|
|
1008
|
-
version,
|
|
1009
|
-
size: real.size,
|
|
1010
|
-
etag: real.etag,
|
|
1011
|
-
httpEtag: real.httpEtag,
|
|
1012
|
-
uploaded,
|
|
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)
|
|
1020
|
-
};
|
|
1021
826
|
}
|
|
827
|
+
// packages/cloudflare/src/caller.ts
|
|
1022
828
|
/**
|
|
1023
|
-
* The
|
|
1024
|
-
*
|
|
1025
|
-
*
|
|
829
|
+
* The caller of an inbound request or RPC call. Cloudflare retries neither,
|
|
830
|
+
* so resends follow the policy the drive declares for the caller: how many
|
|
831
|
+
* times it resends, the virtual delay before each resend, and how long it
|
|
832
|
+
* waits for an answer. The decision is the caller's and is made once per
|
|
833
|
+
* attempt: at the response point, or at its deadline if the handler has
|
|
834
|
+
* not answered by then.
|
|
1026
835
|
*/
|
|
1027
|
-
|
|
836
|
+
/** The response point: a crash before it is a response the caller never saw. */
|
|
837
|
+
const RESPOND = ["crash_before"];
|
|
1028
838
|
/**
|
|
1029
|
-
*
|
|
1030
|
-
*
|
|
1031
|
-
*
|
|
1032
|
-
* once a method has read the body.
|
|
839
|
+
* With a caller deadline the answer can also arrive too late: `ambiguous`
|
|
840
|
+
* here means it was sent, the caller counted it as failed, and the handler
|
|
841
|
+
* carried on.
|
|
1033
842
|
*/
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
const
|
|
1038
|
-
|
|
1039
|
-
used = true;
|
|
1040
|
-
return bytes.slice();
|
|
1041
|
-
};
|
|
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
|
-
}
|
|
1071
|
-
/** Conditions as the trace keeps them: a `Headers` object by its entries. */
|
|
1072
|
-
function conditions(onlyIf) {
|
|
1073
|
-
if (onlyIf === void 0) return {};
|
|
1074
|
-
return { onlyIf: onlyIf instanceof Headers ? Object.fromEntries(onlyIf.entries()) : onlyIf };
|
|
1075
|
-
}
|
|
1076
|
-
/** What the trace keeps of a get's options: the conditions and range, never an encryption key. */
|
|
1077
|
-
function getArgs(key, options) {
|
|
1078
|
-
return toJson({
|
|
1079
|
-
key,
|
|
1080
|
-
...conditions(options?.onlyIf),
|
|
1081
|
-
...options?.range === void 0 ? {} : { range: options.range }
|
|
1082
|
-
});
|
|
1083
|
-
}
|
|
1084
|
-
/** What the trace keeps of a put's options: the conditions and metadata, not checksums or keys. */
|
|
1085
|
-
function putArgs(options) {
|
|
1086
|
-
if (!options) return {};
|
|
1087
|
-
return toJson({
|
|
1088
|
-
...conditions(options.onlyIf),
|
|
1089
|
-
...options.customMetadata === void 0 ? {} : { customMetadata: options.customMetadata },
|
|
1090
|
-
...options.httpMetadata === void 0 ? {} : { httpMetadata: options.httpMetadata }
|
|
1091
|
-
});
|
|
1092
|
-
}
|
|
1093
|
-
function proxyR2(real, binding, ctx, book) {
|
|
1094
|
-
const target = `R2:${binding}`;
|
|
1095
|
-
const point = (op, args, allowed) => ({
|
|
1096
|
-
invocation: ctx.currentInvocation(),
|
|
1097
|
-
target,
|
|
1098
|
-
op,
|
|
1099
|
-
args,
|
|
1100
|
-
allowed
|
|
1101
|
-
});
|
|
1102
|
-
const notModelled = (what) => {
|
|
1103
|
-
const reason = `R2 ${binding}: ${what} is not modelled`;
|
|
1104
|
-
ctx.hooks.unsupported(reason);
|
|
1105
|
-
throw new Error(`eutaxy: ${reason}`);
|
|
1106
|
-
};
|
|
1107
|
-
/** Date conditions compare the store's real upload time, not the stand-in the Worker saw. */
|
|
1108
|
-
const checkConditions = (onlyIf) => {
|
|
1109
|
-
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`);
|
|
1110
|
-
};
|
|
1111
|
-
const described = (o) => o === null ? { found: false } : {
|
|
1112
|
-
found: true,
|
|
1113
|
-
key: o.key,
|
|
1114
|
-
size: o.size,
|
|
1115
|
-
etag: o.etag
|
|
1116
|
-
};
|
|
1117
|
-
return {
|
|
1118
|
-
put: (key, value, options) => ctx.hooks.effect(point("put", {
|
|
1119
|
-
key,
|
|
1120
|
-
...putArgs(options)
|
|
1121
|
-
}, writeFaults), async () => {
|
|
1122
|
-
checkConditions(options?.onlyIf);
|
|
1123
|
-
const read = value instanceof ReadableStream ? buffered.get(value) : void 0;
|
|
1124
|
-
const stored = await real.put(key, read ? read() : value, options);
|
|
1125
|
-
return stored === null ? null : metadata(stored, book, Date.now());
|
|
1126
|
-
}, (o) => o === null ? { stored: false } : {
|
|
1127
|
-
stored: true,
|
|
1128
|
-
size: o.size,
|
|
1129
|
-
etag: o.etag
|
|
1130
|
-
}),
|
|
1131
|
-
delete: (keys) => ctx.hooks.effect(point("delete", { keys: typeof keys === "string" ? [keys] : [...keys] }, writeFaults), () => real.delete(keys), () => null),
|
|
1132
|
-
get: (key, options) => ctx.hooks.effect(point("get", getArgs(key, options), readFaults), async () => {
|
|
1133
|
-
checkConditions(options?.onlyIf);
|
|
1134
|
-
const o = await real.get(key, options);
|
|
1135
|
-
if (o === null) return null;
|
|
1136
|
-
const meta = metadata(o, book, Date.now());
|
|
1137
|
-
if (!("body" in o)) return meta;
|
|
1138
|
-
return withBody(meta, new Uint8Array(await o.arrayBuffer()));
|
|
1139
|
-
}, (o) => ({
|
|
1140
|
-
...described(o),
|
|
1141
|
-
...o !== null ? { body: "body" in o } : {}
|
|
1142
|
-
})),
|
|
1143
|
-
head: (key) => ctx.hooks.effect(point("head", { key }, readFaults), async () => {
|
|
1144
|
-
const o = await real.head(key);
|
|
1145
|
-
return o === null ? null : metadata(o, book, Date.now());
|
|
1146
|
-
}, described),
|
|
1147
|
-
list: (options) => ctx.hooks.effect(point("list", toJson(options ?? {}), readFaults), async () => {
|
|
1148
|
-
const listed = await real.list(options);
|
|
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()")
|
|
1161
|
-
};
|
|
1162
|
-
}
|
|
1163
|
-
/** Every object of the bucket, through all pages of a listing. */
|
|
1164
|
-
async function allObjects(real) {
|
|
1165
|
-
const out = [];
|
|
1166
|
-
let cursor;
|
|
1167
|
-
for (;;) {
|
|
1168
|
-
const page = await real.list({
|
|
1169
|
-
include: ["customMetadata", "httpMetadata"],
|
|
1170
|
-
...cursor === void 0 ? {} : { cursor }
|
|
1171
|
-
});
|
|
1172
|
-
out.push(...page.objects);
|
|
1173
|
-
if (!page.truncated) return out;
|
|
1174
|
-
cursor = page.cursor;
|
|
1175
|
-
}
|
|
1176
|
-
}
|
|
1177
|
-
/** Empty the bucket and put its seeds, before a run. */
|
|
1178
|
-
async function resetR2(real, seeds) {
|
|
1179
|
-
const keys = (await allObjects(real)).map((o) => o.key);
|
|
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
|
-
});
|
|
843
|
+
const RESPOND_WITH_DEADLINE = ["crash_before", "ambiguous"];
|
|
844
|
+
/** The virtual delay before resend number `resend` (1 for the first), per the policy. */
|
|
845
|
+
function retryDelayMs$1(policy, resend) {
|
|
846
|
+
const delays = policy.delaysMs ?? [];
|
|
847
|
+
return delays[Math.min(resend, delays.length) - 1] ?? 0;
|
|
1186
848
|
}
|
|
1187
|
-
/** Largest object whose text the snapshot keeps. */
|
|
1188
|
-
const snapshotTextLimit = 4096;
|
|
1189
849
|
/**
|
|
1190
|
-
*
|
|
1191
|
-
*
|
|
1192
|
-
*
|
|
1193
|
-
*
|
|
850
|
+
* Start waiting for the attempt's answer. With a deadline, a virtual timer
|
|
851
|
+
* makes the caller give up at it whatever the handler is doing, so a resend
|
|
852
|
+
* can start while the first attempt still runs. `gaveUp` is what the
|
|
853
|
+
* `gave_up` effect records when the retries are spent.
|
|
1194
854
|
*/
|
|
1195
|
-
|
|
1196
|
-
const
|
|
1197
|
-
const
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
855
|
+
function startCaller(event, hooks, spec, policy, target, gaveUp) {
|
|
856
|
+
const started = Date.now();
|
|
857
|
+
const deadline = policy.deadlineMs;
|
|
858
|
+
const lateAt = deadline === void 0 ? void 0 : started + deadline;
|
|
859
|
+
/** The caller decides once: it accepts the answer, or gives up at `at` and resends or stops. */
|
|
860
|
+
let decided = false;
|
|
861
|
+
const giveUp = (at) => {
|
|
862
|
+
if (decided) return;
|
|
863
|
+
decided = true;
|
|
864
|
+
const next = redelivery(event, policy.retries, spec.bounds);
|
|
865
|
+
if (next) {
|
|
866
|
+
const resendAt = Math.max(at + retryDelayMs$1(policy, event.attempt), Date.now());
|
|
867
|
+
hooks.enqueue({
|
|
868
|
+
...next,
|
|
869
|
+
...resendAt > Date.now() ? { at: resendAt } : {}
|
|
870
|
+
});
|
|
871
|
+
} else hooks.effectSync({
|
|
872
|
+
invocation: hooks.bookkeeping(),
|
|
873
|
+
target,
|
|
874
|
+
op: "gave_up",
|
|
875
|
+
args: gaveUp,
|
|
876
|
+
allowed: []
|
|
877
|
+
}, () => null, () => null);
|
|
878
|
+
};
|
|
879
|
+
const deadlineTimer = lateAt === void 0 ? void 0 : setTimeout(() => giveUp(lateAt), deadline);
|
|
880
|
+
return {
|
|
881
|
+
responseFaults: deadline === void 0 ? RESPOND : RESPOND_WITH_DEADLINE,
|
|
882
|
+
isLate: () => lateAt !== void 0 && Date.now() > lateAt,
|
|
883
|
+
settle(accepted, late) {
|
|
884
|
+
if (deadlineTimer !== void 0) clearTimeout(deadlineTimer);
|
|
885
|
+
if (accepted) decided = true;
|
|
886
|
+
else giveUp(late && lateAt !== void 0 ? lateAt : Date.now());
|
|
1208
887
|
}
|
|
1209
|
-
|
|
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;
|
|
888
|
+
};
|
|
1219
889
|
}
|
|
1220
890
|
// packages/cloudflare/src/cron.ts
|
|
1221
891
|
const fields = [
|
|
@@ -1309,876 +979,1712 @@ function parseField(text, field) {
|
|
|
1309
979
|
from = value(rangeText, field);
|
|
1310
980
|
to = stepText === void 0 ? from : field.max;
|
|
1311
981
|
}
|
|
1312
|
-
for (let v = from; v <= to; v += step) out.add(v);
|
|
982
|
+
for (let v = from; v <= to; v += step) out.add(v);
|
|
983
|
+
}
|
|
984
|
+
return out;
|
|
985
|
+
}
|
|
986
|
+
/** Parse an expression; throws with the field and the problem when it is not one Cloudflare accepts. */
|
|
987
|
+
function parseCron(expression) {
|
|
988
|
+
const parts = expression.trim().split(/\s+/);
|
|
989
|
+
if (parts.length !== 5) throw new Error(`a cron expression has five fields, got ${parts.length}: ${JSON.stringify(expression)}`);
|
|
990
|
+
const [minute, hour, dom, month, weekday] = parts;
|
|
991
|
+
return {
|
|
992
|
+
minutes: parseField(minute, fields[0]),
|
|
993
|
+
hours: parseField(hour, fields[1]),
|
|
994
|
+
daysOfMonth: parseField(dom, fields[2]),
|
|
995
|
+
months: parseField(month, fields[3]),
|
|
996
|
+
weekdays: parseField(weekday, fields[4]),
|
|
997
|
+
anyDayOfMonth: dom === "*",
|
|
998
|
+
anyWeekday: weekday === "*"
|
|
999
|
+
};
|
|
1000
|
+
}
|
|
1001
|
+
/** Whether the minute starting at `time` (ms since the epoch, UTC) matches. */
|
|
1002
|
+
function cronMatches(schedule, time) {
|
|
1003
|
+
const d = new Date(time);
|
|
1004
|
+
if (!schedule.minutes.has(d.getUTCMinutes()) || !schedule.hours.has(d.getUTCHours())) return false;
|
|
1005
|
+
if (!schedule.months.has(d.getUTCMonth() + 1)) return false;
|
|
1006
|
+
const dayOk = schedule.daysOfMonth.has(d.getUTCDate());
|
|
1007
|
+
const weekdayOk = schedule.weekdays.has(d.getUTCDay() + 1);
|
|
1008
|
+
if (!schedule.anyDayOfMonth && !schedule.anyWeekday) return dayOk || weekdayOk;
|
|
1009
|
+
return dayOk && weekdayOk;
|
|
1010
|
+
}
|
|
1011
|
+
const minuteMs = 6e4;
|
|
1012
|
+
/**
|
|
1013
|
+
* Between two matches of any expression Cloudflare accepts lie at most eight
|
|
1014
|
+
* years (the 29th of February across a century's missing leap year); an
|
|
1015
|
+
* expression with no match in that span never fires.
|
|
1016
|
+
*/
|
|
1017
|
+
const longestGapMs = 4743360 * minuteMs;
|
|
1018
|
+
/** The first `count` tick times at or after `from`, each the start of a matching minute. */
|
|
1019
|
+
function cronTicks(expression, from, count) {
|
|
1020
|
+
const schedule = parseCron(expression);
|
|
1021
|
+
const out = [];
|
|
1022
|
+
let t = Math.ceil(from / minuteMs) * minuteMs;
|
|
1023
|
+
let horizon = t + longestGapMs;
|
|
1024
|
+
while (out.length < count) {
|
|
1025
|
+
if (t > horizon) throw new Error(`${JSON.stringify(expression)} never fires`);
|
|
1026
|
+
if (cronMatches(schedule, t)) {
|
|
1027
|
+
out.push(t);
|
|
1028
|
+
horizon = t + longestGapMs;
|
|
1029
|
+
}
|
|
1030
|
+
t += minuteMs;
|
|
1031
|
+
}
|
|
1032
|
+
return out;
|
|
1033
|
+
}
|
|
1034
|
+
// packages/cloudflare/src/scenario.ts
|
|
1035
|
+
/**
|
|
1036
|
+
* Typed construction of scenario specs for Cloudflare Workers. Everything here
|
|
1037
|
+
* produces the plain-data `ScenarioSpec` from core; this module only knows the
|
|
1038
|
+
* Cloudflare shapes (queues, D1 bindings) and the effect conventions the
|
|
1039
|
+
* proxies follow.
|
|
1040
|
+
*/
|
|
1041
|
+
function http(requests, options = {}) {
|
|
1042
|
+
return {
|
|
1043
|
+
kind: "http",
|
|
1044
|
+
requests: requests.map((r, i) => ({
|
|
1045
|
+
id: r.id ?? `req-${i + 1}`,
|
|
1046
|
+
method: (r.method ?? (r.body === void 0 ? "GET" : "POST")).toUpperCase(),
|
|
1047
|
+
path: r.path,
|
|
1048
|
+
headers: r.headers ?? {},
|
|
1049
|
+
...r.body === void 0 ? {} : { body: r.body }
|
|
1050
|
+
})),
|
|
1051
|
+
retries: options.retries ?? 3,
|
|
1052
|
+
retryOn: options.retryOn ?? "non-2xx",
|
|
1053
|
+
...options.delaysMs === void 0 ? {} : { delaysMs: [...options.delaysMs] },
|
|
1054
|
+
...options.deadlineMs === void 0 ? {} : { deadlineMs: options.deadlineMs }
|
|
1055
|
+
};
|
|
1056
|
+
}
|
|
1057
|
+
function websocket(connections) {
|
|
1058
|
+
return {
|
|
1059
|
+
kind: "websocket",
|
|
1060
|
+
connections: connections.map((c, i) => {
|
|
1061
|
+
const id = c.id ?? `conn-${i + 1}`;
|
|
1062
|
+
return {
|
|
1063
|
+
id,
|
|
1064
|
+
path: c.path,
|
|
1065
|
+
headers: c.headers ?? {},
|
|
1066
|
+
messages: (c.messages ?? []).map((m, j) => ({
|
|
1067
|
+
id: m.id ?? `${id}:${j + 1}`,
|
|
1068
|
+
data: m.data
|
|
1069
|
+
}))
|
|
1070
|
+
};
|
|
1071
|
+
})
|
|
1072
|
+
};
|
|
1073
|
+
}
|
|
1074
|
+
function rpc(calls, options = {}) {
|
|
1075
|
+
return {
|
|
1076
|
+
kind: "rpc",
|
|
1077
|
+
...options.entrypoint === void 0 ? {} : { entrypoint: options.entrypoint },
|
|
1078
|
+
calls: calls.map((c, i) => ({
|
|
1079
|
+
id: c.id ?? `call-${i + 1}`,
|
|
1080
|
+
method: c.method,
|
|
1081
|
+
args: [...c.args ?? []]
|
|
1082
|
+
})),
|
|
1083
|
+
retries: options.retries ?? 0,
|
|
1084
|
+
...options.delaysMs === void 0 ? {} : { delaysMs: [...options.delaysMs] },
|
|
1085
|
+
...options.deadlineMs === void 0 ? {} : { deadlineMs: options.deadlineMs }
|
|
1086
|
+
};
|
|
1087
|
+
}
|
|
1088
|
+
/** The target of a call's effects: the method, under the entrypoint's name when the drive names one. */
|
|
1089
|
+
function rpcTarget(drive, method) {
|
|
1090
|
+
return `Rpc:${drive.entrypoint === void 0 ? method : `${drive.entrypoint}.${method}`}`;
|
|
1091
|
+
}
|
|
1092
|
+
function cron(expression, options = {}) {
|
|
1093
|
+
const count = options.ticks ?? 1;
|
|
1094
|
+
return {
|
|
1095
|
+
kind: "cron",
|
|
1096
|
+
cron: expression,
|
|
1097
|
+
ticks: (Number.isInteger(count) && count >= 1 ? cronTicks(expression, virtualEpoch, count) : []).map((at, i) => ({
|
|
1098
|
+
id: `tick-${i + 1}`,
|
|
1099
|
+
at
|
|
1100
|
+
})),
|
|
1101
|
+
retries: options.retries ?? 0
|
|
1102
|
+
};
|
|
1103
|
+
}
|
|
1104
|
+
/** The drive's events as they are first delivered: one per message, request or call, attempt 1. */
|
|
1105
|
+
function driveEvents(drive) {
|
|
1106
|
+
switch (drive.kind) {
|
|
1107
|
+
case "queue": return drive.messages.map((m) => ({
|
|
1108
|
+
id: m.id,
|
|
1109
|
+
attempt: 1,
|
|
1110
|
+
data: m.body
|
|
1111
|
+
}));
|
|
1112
|
+
case "http": return drive.requests.map((r) => ({
|
|
1113
|
+
id: r.id,
|
|
1114
|
+
attempt: 1,
|
|
1115
|
+
data: r
|
|
1116
|
+
}));
|
|
1117
|
+
case "rpc": return drive.calls.map((c) => ({
|
|
1118
|
+
id: c.id,
|
|
1119
|
+
attempt: 1,
|
|
1120
|
+
data: c
|
|
1121
|
+
}));
|
|
1122
|
+
case "cron": return drive.ticks.map((t) => ({
|
|
1123
|
+
id: t.id,
|
|
1124
|
+
attempt: 1,
|
|
1125
|
+
data: {
|
|
1126
|
+
cron: drive.cron,
|
|
1127
|
+
scheduledTime: t.at
|
|
1128
|
+
},
|
|
1129
|
+
at: t.at
|
|
1130
|
+
}));
|
|
1131
|
+
case "websocket": {
|
|
1132
|
+
const opens = drive.connections.map((c) => ({
|
|
1133
|
+
id: c.id,
|
|
1134
|
+
attempt: 1,
|
|
1135
|
+
data: {
|
|
1136
|
+
kind: "open",
|
|
1137
|
+
connection: c.id,
|
|
1138
|
+
path: c.path,
|
|
1139
|
+
headers: c.headers
|
|
1140
|
+
}
|
|
1141
|
+
}));
|
|
1142
|
+
const rounds = Math.max(0, ...drive.connections.map((c) => c.messages.length));
|
|
1143
|
+
const messages = [];
|
|
1144
|
+
for (let i = 0; i < rounds; i++) for (const c of drive.connections) {
|
|
1145
|
+
const m = c.messages[i];
|
|
1146
|
+
if (m) messages.push({
|
|
1147
|
+
id: m.id,
|
|
1148
|
+
attempt: 1,
|
|
1149
|
+
data: {
|
|
1150
|
+
kind: "message",
|
|
1151
|
+
connection: c.id,
|
|
1152
|
+
message: m.id,
|
|
1153
|
+
index: i,
|
|
1154
|
+
data: m.data
|
|
1155
|
+
}
|
|
1156
|
+
});
|
|
1157
|
+
}
|
|
1158
|
+
return [...opens, ...messages];
|
|
1159
|
+
}
|
|
1313
1160
|
}
|
|
1314
|
-
return out;
|
|
1315
1161
|
}
|
|
1316
|
-
/**
|
|
1317
|
-
function
|
|
1318
|
-
const
|
|
1319
|
-
|
|
1320
|
-
|
|
1162
|
+
/** The drive with only the named events kept, for shrinking. */
|
|
1163
|
+
function restrictDrive(drive, keepIds) {
|
|
1164
|
+
const keep = (id) => keepIds.includes(id);
|
|
1165
|
+
switch (drive.kind) {
|
|
1166
|
+
case "queue": return {
|
|
1167
|
+
...drive,
|
|
1168
|
+
messages: drive.messages.filter((m) => keep(m.id))
|
|
1169
|
+
};
|
|
1170
|
+
case "http": return {
|
|
1171
|
+
...drive,
|
|
1172
|
+
requests: drive.requests.filter((r) => keep(r.id))
|
|
1173
|
+
};
|
|
1174
|
+
case "rpc": return {
|
|
1175
|
+
...drive,
|
|
1176
|
+
calls: drive.calls.filter((c) => keep(c.id))
|
|
1177
|
+
};
|
|
1178
|
+
case "cron": return {
|
|
1179
|
+
...drive,
|
|
1180
|
+
ticks: drive.ticks.filter((t) => keep(t.id))
|
|
1181
|
+
};
|
|
1182
|
+
case "websocket": return {
|
|
1183
|
+
...drive,
|
|
1184
|
+
connections: drive.connections.filter((c) => keep(c.id)).map((c) => ({
|
|
1185
|
+
...c,
|
|
1186
|
+
messages: c.messages.filter((m) => keep(m.id))
|
|
1187
|
+
}))
|
|
1188
|
+
};
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
function durableObject(binding, objects = {}, options = {}) {
|
|
1321
1192
|
return {
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
anyDayOfMonth: dom === "*",
|
|
1328
|
-
anyWeekday: weekday === "*"
|
|
1193
|
+
kind: "durable_object",
|
|
1194
|
+
binding,
|
|
1195
|
+
objects,
|
|
1196
|
+
...options.alarmsPerObject === void 0 ? {} : { alarmsPerObject: options.alarmsPerObject },
|
|
1197
|
+
...options.sql === void 0 ? {} : { sql: options.sql }
|
|
1329
1198
|
};
|
|
1330
1199
|
}
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
const weekdayOk = schedule.weekdays.has(d.getUTCDay() + 1);
|
|
1338
|
-
if (!schedule.anyDayOfMonth && !schedule.anyWeekday) return dayOk || weekdayOk;
|
|
1339
|
-
return dayOk && weekdayOk;
|
|
1200
|
+
function r2Bucket(binding, objects = {}) {
|
|
1201
|
+
return {
|
|
1202
|
+
kind: "r2",
|
|
1203
|
+
binding,
|
|
1204
|
+
objects
|
|
1205
|
+
};
|
|
1340
1206
|
}
|
|
1341
|
-
const minuteMs = 6e4;
|
|
1342
1207
|
/**
|
|
1343
|
-
*
|
|
1344
|
-
*
|
|
1345
|
-
*
|
|
1208
|
+
* Selects an R2 bucket's operations that completed, a `put` by default; a
|
|
1209
|
+
* put whose `onlyIf` failed stored nothing and is not selected, as a D1
|
|
1210
|
+
* write that changed no row is not.
|
|
1346
1211
|
*/
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1212
|
+
function r2Op(binding, op = "put") {
|
|
1213
|
+
const target = `R2:${binding}`;
|
|
1214
|
+
return op === "put" ? {
|
|
1215
|
+
target,
|
|
1216
|
+
op,
|
|
1217
|
+
kind: "result",
|
|
1218
|
+
where: { "result.stored": true }
|
|
1219
|
+
} : {
|
|
1220
|
+
target,
|
|
1221
|
+
op,
|
|
1222
|
+
kind: "result"
|
|
1223
|
+
};
|
|
1224
|
+
}
|
|
1225
|
+
/** A bucket's objects at the end of the run as rows `{ key, size, etag, customMetadata, httpMetadata, text? }`. */
|
|
1226
|
+
function r2Rows(binding, where) {
|
|
1227
|
+
const target = `R2:${binding}`;
|
|
1228
|
+
return where ? {
|
|
1229
|
+
target,
|
|
1230
|
+
table: "objects",
|
|
1231
|
+
where
|
|
1232
|
+
} : {
|
|
1233
|
+
target,
|
|
1234
|
+
table: "objects"
|
|
1235
|
+
};
|
|
1236
|
+
}
|
|
1237
|
+
/**
|
|
1238
|
+
* Every row the query returns is named by some row of `in` (its `column`
|
|
1239
|
+
* equals the row's value at `path`), as with a foreign key.
|
|
1240
|
+
*/
|
|
1241
|
+
function references(name, query, path, inQuery, column) {
|
|
1242
|
+
return {
|
|
1243
|
+
kind: "references",
|
|
1244
|
+
name,
|
|
1245
|
+
query,
|
|
1246
|
+
path,
|
|
1247
|
+
in: inQuery,
|
|
1248
|
+
column
|
|
1249
|
+
};
|
|
1250
|
+
}
|
|
1251
|
+
function workflow(binding, className, options = {}) {
|
|
1252
|
+
return {
|
|
1253
|
+
kind: "workflow",
|
|
1254
|
+
binding,
|
|
1255
|
+
className,
|
|
1256
|
+
...options.name === void 0 ? {} : { name: options.name }
|
|
1257
|
+
};
|
|
1258
|
+
}
|
|
1259
|
+
function service(binding, options = {}) {
|
|
1260
|
+
return {
|
|
1261
|
+
kind: "service",
|
|
1262
|
+
binding,
|
|
1263
|
+
...options.methods === void 0 ? {} : { methods: options.methods },
|
|
1264
|
+
...options.fetch === void 0 ? {} : { fetch: [...options.fetch] }
|
|
1265
|
+
};
|
|
1266
|
+
}
|
|
1267
|
+
function callee(binding, worker) {
|
|
1268
|
+
return {
|
|
1269
|
+
kind: "callee",
|
|
1270
|
+
binding,
|
|
1271
|
+
entry: worker.entry,
|
|
1272
|
+
config: worker.config,
|
|
1273
|
+
...worker.entrypoint === void 0 ? {} : { entrypoint: worker.entrypoint }
|
|
1274
|
+
};
|
|
1275
|
+
}
|
|
1276
|
+
/** A callee and a script for one binding would contradict each other; a callee needs both files named. */
|
|
1277
|
+
function validateCalleeSetups(setup) {
|
|
1278
|
+
const errors = [];
|
|
1279
|
+
const scripted = new Set(setup.filter((s) => s.kind === "service").map((s) => String(s["binding"])));
|
|
1280
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1281
|
+
for (const step of setup) {
|
|
1282
|
+
if (step.kind !== "callee") continue;
|
|
1283
|
+
const binding = String(step["binding"]);
|
|
1284
|
+
if (!step["binding"]) errors.push("callee() needs a binding name");
|
|
1285
|
+
if (!step["entry"]) errors.push(`callee(${JSON.stringify(binding)}) needs the callee's entry`);
|
|
1286
|
+
if (!step["config"]) errors.push(`callee(${JSON.stringify(binding)}) needs the callee's wrangler config`);
|
|
1287
|
+
if (scripted.has(binding)) errors.push(`service binding ${JSON.stringify(binding)} has both a service() script and a callee(); keep one`);
|
|
1288
|
+
if (seen.has(binding)) errors.push(`service binding ${JSON.stringify(binding)} has two callee() steps`);
|
|
1289
|
+
seen.add(binding);
|
|
1361
1290
|
}
|
|
1362
|
-
return
|
|
1291
|
+
return errors;
|
|
1292
|
+
}
|
|
1293
|
+
/** Selects the calls through a service binding that completed (scripted or a callee's), one method's or all. */
|
|
1294
|
+
function serviceCall(binding, method) {
|
|
1295
|
+
return {
|
|
1296
|
+
target: `Service:${binding}`,
|
|
1297
|
+
...method === void 0 ? {} : { op: method },
|
|
1298
|
+
kind: "result"
|
|
1299
|
+
};
|
|
1300
|
+
}
|
|
1301
|
+
/** Selects a Workflow's step attempts, optionally of one step; a failed attempt's result carries its error. */
|
|
1302
|
+
function workflowStep(binding, step) {
|
|
1303
|
+
return {
|
|
1304
|
+
target: `Workflow:${binding}`,
|
|
1305
|
+
op: "step_result",
|
|
1306
|
+
kind: "result",
|
|
1307
|
+
...step === void 0 ? {} : { where: { "args.step": step } }
|
|
1308
|
+
};
|
|
1309
|
+
}
|
|
1310
|
+
/** A Workflow's instances at the end of the run as rows `{ id, status, params, output?, error? }`. */
|
|
1311
|
+
function workflowRows(binding, where) {
|
|
1312
|
+
const target = `Workflow:${binding}`;
|
|
1313
|
+
return where ? {
|
|
1314
|
+
target,
|
|
1315
|
+
table: "instances",
|
|
1316
|
+
where
|
|
1317
|
+
} : {
|
|
1318
|
+
target,
|
|
1319
|
+
table: "instances"
|
|
1320
|
+
};
|
|
1363
1321
|
}
|
|
1364
|
-
// packages/cloudflare/src/scenario.ts
|
|
1365
1322
|
/**
|
|
1366
|
-
*
|
|
1367
|
-
*
|
|
1368
|
-
* Cloudflare shapes (queues, D1 bindings) and the effect conventions the
|
|
1369
|
-
* proxies follow.
|
|
1323
|
+
* The storage of one object (by the name its id was made from) as rows
|
|
1324
|
+
* `{ key, value }`, for state invariants.
|
|
1370
1325
|
*/
|
|
1371
|
-
function
|
|
1326
|
+
function durableObjectRows(binding, object, where) {
|
|
1327
|
+
const target = `DO:${binding}`;
|
|
1328
|
+
return where ? {
|
|
1329
|
+
target,
|
|
1330
|
+
table: object,
|
|
1331
|
+
where
|
|
1332
|
+
} : {
|
|
1333
|
+
target,
|
|
1334
|
+
table: object
|
|
1335
|
+
};
|
|
1336
|
+
}
|
|
1337
|
+
/**
|
|
1338
|
+
* One SQL table of a SQLite-backed object (by the name its id was made
|
|
1339
|
+
* from) at the end of the run, its rows as the table holds them, for state
|
|
1340
|
+
* invariants. The snapshot names it `<object>/<table>`.
|
|
1341
|
+
*/
|
|
1342
|
+
function durableObjectTable(binding, object, table, where) {
|
|
1343
|
+
const target = `DO:${binding}`;
|
|
1344
|
+
const name = `${object}/${table}`;
|
|
1345
|
+
return where ? {
|
|
1346
|
+
target,
|
|
1347
|
+
table: name,
|
|
1348
|
+
where
|
|
1349
|
+
} : {
|
|
1350
|
+
target,
|
|
1351
|
+
table: name
|
|
1352
|
+
};
|
|
1353
|
+
}
|
|
1354
|
+
function queue(name, messages) {
|
|
1372
1355
|
return {
|
|
1373
|
-
kind: "
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
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 }
|
|
1356
|
+
kind: "queue",
|
|
1357
|
+
queue: name,
|
|
1358
|
+
messages: messages.map((m, i) => ({
|
|
1359
|
+
id: m.id ?? `msg-${i + 1}`,
|
|
1360
|
+
body: m.body
|
|
1361
|
+
}))
|
|
1385
1362
|
};
|
|
1386
1363
|
}
|
|
1387
|
-
function
|
|
1364
|
+
function d1Schema(binding, schemaFile) {
|
|
1388
1365
|
return {
|
|
1389
|
-
kind: "
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
return {
|
|
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
|
-
})
|
|
1366
|
+
kind: "d1",
|
|
1367
|
+
binding,
|
|
1368
|
+
schemaFile
|
|
1402
1369
|
};
|
|
1403
1370
|
}
|
|
1404
|
-
|
|
1371
|
+
/**
|
|
1372
|
+
* Effect conventions for D1 (what the proxies record):
|
|
1373
|
+
* call payload { args: { sql, params } }
|
|
1374
|
+
* result payload { args: { sql, params }, result: { changes, lastRowId } }
|
|
1375
|
+
* A committed write is a `result` whose `result.changes` is at least 1.
|
|
1376
|
+
*/
|
|
1377
|
+
function d1Write(binding, op = "run") {
|
|
1405
1378
|
return {
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
method: c.method,
|
|
1411
|
-
args: [...c.args ?? []]
|
|
1412
|
-
})),
|
|
1413
|
-
retries: options.retries ?? 0,
|
|
1414
|
-
...options.delaysMs === void 0 ? {} : { delaysMs: [...options.delaysMs] },
|
|
1415
|
-
...options.deadlineMs === void 0 ? {} : { deadlineMs: options.deadlineMs }
|
|
1379
|
+
target: `D1:${binding}`,
|
|
1380
|
+
op,
|
|
1381
|
+
kind: "result",
|
|
1382
|
+
atLeast: { "result.changes": 1 }
|
|
1416
1383
|
};
|
|
1417
1384
|
}
|
|
1418
|
-
/**
|
|
1419
|
-
function
|
|
1420
|
-
return
|
|
1385
|
+
/** Reads of a D1 binding: `first` (result payload `{ row }`), `all` or `raw`. */
|
|
1386
|
+
function d1Read(binding, op = "first") {
|
|
1387
|
+
return {
|
|
1388
|
+
target: `D1:${binding}`,
|
|
1389
|
+
op,
|
|
1390
|
+
kind: "result"
|
|
1391
|
+
};
|
|
1421
1392
|
}
|
|
1422
|
-
|
|
1423
|
-
|
|
1393
|
+
/** Dot path to the Nth bound parameter of a D1 statement, in an effect payload. */
|
|
1394
|
+
function d1Param(index) {
|
|
1395
|
+
return `args.params.${index}`;
|
|
1396
|
+
}
|
|
1397
|
+
/**
|
|
1398
|
+
* The shell follows the core function `decision` (see the `refines`
|
|
1399
|
+
* invariant): every selected effect carries out the latest decision of its
|
|
1400
|
+
* invocation, agrees with it on `follows`, and, with `state`, was not made
|
|
1401
|
+
* stale by another invocation's write between the read it rests on and the
|
|
1402
|
+
* effect. The core function's module must be listed in the scenario's
|
|
1403
|
+
* `specs`, which is what records its calls.
|
|
1404
|
+
*/
|
|
1405
|
+
function refines(name, decision, effect, options = {}) {
|
|
1424
1406
|
return {
|
|
1425
|
-
kind: "
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
})),
|
|
1431
|
-
retries: options.retries ?? 0
|
|
1407
|
+
kind: "refines",
|
|
1408
|
+
name,
|
|
1409
|
+
decision,
|
|
1410
|
+
effect,
|
|
1411
|
+
...options
|
|
1432
1412
|
};
|
|
1433
1413
|
}
|
|
1434
|
-
/**
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
attempt: 1,
|
|
1445
|
-
data: r
|
|
1446
|
-
}));
|
|
1447
|
-
case "rpc": return drive.calls.map((c) => ({
|
|
1448
|
-
id: c.id,
|
|
1449
|
-
attempt: 1,
|
|
1450
|
-
data: c
|
|
1451
|
-
}));
|
|
1452
|
-
case "cron": return drive.ticks.map((t) => ({
|
|
1414
|
+
/**
|
|
1415
|
+
* Every message's (or request's, or call's) `bodyKey` value must appear at
|
|
1416
|
+
* least once as `key` in a selected effect: nothing the drive delivered may
|
|
1417
|
+
* be lost. For an RPC drive `bodyKey` is a path into the call's arguments
|
|
1418
|
+
* (`"0.orderId"`).
|
|
1419
|
+
*/
|
|
1420
|
+
function atLeastOncePerMessage(name, drive, effect, key, bodyKey) {
|
|
1421
|
+
if (drive.kind === "queue") return atLeastOncePerMessage$1(name, drive.messages, effect, key, bodyKey);
|
|
1422
|
+
if (drive.kind === "cron") {
|
|
1423
|
+
const ticks = drive.ticks.map((t) => ({
|
|
1453
1424
|
id: t.id,
|
|
1454
|
-
|
|
1455
|
-
data: {
|
|
1425
|
+
body: {
|
|
1456
1426
|
cron: drive.cron,
|
|
1457
1427
|
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
1428
|
}
|
|
1488
|
-
|
|
1489
|
-
|
|
1429
|
+
}));
|
|
1430
|
+
return atLeastOncePerMessage$1(name, ticks, effect, key, bodyKey);
|
|
1490
1431
|
}
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
...
|
|
1498
|
-
|
|
1499
|
-
};
|
|
1500
|
-
case "http": return {
|
|
1501
|
-
...drive,
|
|
1502
|
-
requests: drive.requests.filter((r) => keep(r.id))
|
|
1503
|
-
};
|
|
1504
|
-
case "rpc": return {
|
|
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))
|
|
1432
|
+
if (drive.kind === "rpc") {
|
|
1433
|
+
const calls = drive.calls.map((c) => ({
|
|
1434
|
+
id: c.id,
|
|
1435
|
+
body: c.args
|
|
1436
|
+
}));
|
|
1437
|
+
return {
|
|
1438
|
+
...atLeastOncePerMessage$1(name, calls, effect, key, bodyKey),
|
|
1439
|
+
perMessage: { bodyKey: bodyKey === "" ? "args" : `args.${bodyKey}` }
|
|
1511
1440
|
};
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1441
|
+
}
|
|
1442
|
+
if (drive.kind === "websocket") {
|
|
1443
|
+
if (bodyKey !== "") throw new Error(`atLeastOncePerMessage ${JSON.stringify(name)}: a websocket drive keys each connection by its path; bodyKey must be ""`);
|
|
1444
|
+
const conns = drive.connections.map((c) => ({
|
|
1445
|
+
id: c.id,
|
|
1446
|
+
body: c.path
|
|
1447
|
+
}));
|
|
1448
|
+
return {
|
|
1449
|
+
...atLeastOncePerMessage$1(name, conns, effect, key, ""),
|
|
1450
|
+
perMessage: { bodyKey: "path" }
|
|
1518
1451
|
};
|
|
1519
1452
|
}
|
|
1453
|
+
const requests = drive.requests.map((r) => ({
|
|
1454
|
+
id: r.id,
|
|
1455
|
+
body: r.body ?? null
|
|
1456
|
+
}));
|
|
1457
|
+
return {
|
|
1458
|
+
...atLeastOncePerMessage$1(name, requests, effect, key, bodyKey),
|
|
1459
|
+
perMessage: { bodyKey: bodyKey === "" ? "body" : `body.${bodyKey}` }
|
|
1460
|
+
};
|
|
1520
1461
|
}
|
|
1521
|
-
|
|
1462
|
+
/**
|
|
1463
|
+
* Selects the frames the Worker sent on a connection (`WebSocket:<connection>`,
|
|
1464
|
+
* op `message`), each recorded at the end of the run, in arrival order, with
|
|
1465
|
+
* its data (JSON where it parses, text otherwise).
|
|
1466
|
+
*/
|
|
1467
|
+
function webSocketReceived(connection) {
|
|
1522
1468
|
return {
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
...options.alarmsPerObject === void 0 ? {} : { alarmsPerObject: options.alarmsPerObject },
|
|
1527
|
-
...options.sql === void 0 ? {} : { sql: options.sql }
|
|
1469
|
+
target: `WebSocket:${connection}`,
|
|
1470
|
+
op: "message",
|
|
1471
|
+
kind: "result"
|
|
1528
1472
|
};
|
|
1529
1473
|
}
|
|
1530
|
-
|
|
1474
|
+
/**
|
|
1475
|
+
* Selects the responses the Worker returned for a path (`ok` narrows to 2xx
|
|
1476
|
+
* or to everything else). One `result` per attempt: a crash before the
|
|
1477
|
+
* response leaves none, a thrown error records status 500.
|
|
1478
|
+
*/
|
|
1479
|
+
function httpResponse(path, options = {}) {
|
|
1531
1480
|
return {
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1481
|
+
target: `Http:${path}`,
|
|
1482
|
+
op: "response",
|
|
1483
|
+
kind: "result",
|
|
1484
|
+
...options.ok === void 0 ? {} : { where: { "result.ok": options.ok } }
|
|
1535
1485
|
};
|
|
1536
1486
|
}
|
|
1537
1487
|
/**
|
|
1538
|
-
* Selects
|
|
1539
|
-
*
|
|
1540
|
-
*
|
|
1488
|
+
* Selects the answers an RPC method gave (`ok` narrows to values returned
|
|
1489
|
+
* or to errors thrown). One `result` per attempt: a crash before the
|
|
1490
|
+
* response leaves none.
|
|
1541
1491
|
*/
|
|
1542
|
-
function
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
op,
|
|
1492
|
+
function rpcResponse(method, options = {}) {
|
|
1493
|
+
return {
|
|
1494
|
+
target: rpcTarget(options, method),
|
|
1495
|
+
op: "response",
|
|
1547
1496
|
kind: "result",
|
|
1548
|
-
where: { "result.
|
|
1549
|
-
} : {
|
|
1550
|
-
target,
|
|
1551
|
-
op,
|
|
1552
|
-
kind: "result"
|
|
1497
|
+
...options.ok === void 0 ? {} : { where: { "result.ok": options.ok } }
|
|
1553
1498
|
};
|
|
1554
1499
|
}
|
|
1555
|
-
/**
|
|
1556
|
-
function
|
|
1557
|
-
const target = `R2:${binding}`;
|
|
1500
|
+
/** Rows of a D1 table in the end-of-run snapshot, optionally filtered. */
|
|
1501
|
+
function d1Rows(binding, table, where) {
|
|
1558
1502
|
return where ? {
|
|
1559
|
-
target
|
|
1560
|
-
table
|
|
1503
|
+
target: `D1:${binding}`,
|
|
1504
|
+
table,
|
|
1561
1505
|
where
|
|
1562
1506
|
} : {
|
|
1563
|
-
target
|
|
1564
|
-
table
|
|
1507
|
+
target: `D1:${binding}`,
|
|
1508
|
+
table
|
|
1565
1509
|
};
|
|
1566
1510
|
}
|
|
1567
|
-
/**
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1511
|
+
/** Every row the query selects satisfies all conditions. */
|
|
1512
|
+
function everyRow(name, query, holds) {
|
|
1513
|
+
return {
|
|
1514
|
+
kind: "everyRow",
|
|
1515
|
+
name,
|
|
1516
|
+
query,
|
|
1517
|
+
holds
|
|
1518
|
+
};
|
|
1519
|
+
}
|
|
1520
|
+
/** No two rows the query selects share the value at `path` (a column, or a dot path into the row). */
|
|
1521
|
+
function unique(name, query, path) {
|
|
1572
1522
|
return {
|
|
1573
|
-
kind: "
|
|
1523
|
+
kind: "unique",
|
|
1574
1524
|
name,
|
|
1575
1525
|
query,
|
|
1576
|
-
path
|
|
1577
|
-
in: inQuery,
|
|
1578
|
-
column
|
|
1526
|
+
path
|
|
1579
1527
|
};
|
|
1580
1528
|
}
|
|
1581
|
-
|
|
1529
|
+
/** Every selected effect has a row whose column equals the effect's key. */
|
|
1530
|
+
function implies(name, when, key, state, column) {
|
|
1582
1531
|
return {
|
|
1583
|
-
kind: "
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1532
|
+
kind: "implies",
|
|
1533
|
+
name,
|
|
1534
|
+
when,
|
|
1535
|
+
key,
|
|
1536
|
+
state,
|
|
1537
|
+
column
|
|
1587
1538
|
};
|
|
1588
1539
|
}
|
|
1589
|
-
|
|
1540
|
+
/** Selects the acknowledgement that took effect for each message (explicit or implicit; not one ignored after a retry). */
|
|
1541
|
+
function queueAck(queueName) {
|
|
1590
1542
|
return {
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1543
|
+
target: `Queue:${queueName}`,
|
|
1544
|
+
op: "ack",
|
|
1545
|
+
kind: "result",
|
|
1546
|
+
where: { "result.effective": true }
|
|
1595
1547
|
};
|
|
1596
1548
|
}
|
|
1597
|
-
/**
|
|
1598
|
-
|
|
1549
|
+
/**
|
|
1550
|
+
* Declare an external service: requests to `host` are answered from
|
|
1551
|
+
* `responses` (every request gets 200 and an empty body when omitted), and
|
|
1552
|
+
* `dedupeBy` names the header whose value makes repeated requests
|
|
1553
|
+
* idempotent at that service.
|
|
1554
|
+
*/
|
|
1555
|
+
function external(name, host, options = {}) {
|
|
1599
1556
|
return {
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1557
|
+
name,
|
|
1558
|
+
host,
|
|
1559
|
+
guarantees: options.dedupeBy ? { dedupeBy: options.dedupeBy } : {},
|
|
1560
|
+
...options.responses ? { responses: options.responses } : {}
|
|
1603
1561
|
};
|
|
1604
1562
|
}
|
|
1605
|
-
/**
|
|
1606
|
-
|
|
1563
|
+
/**
|
|
1564
|
+
* Selects the requests to an external that took effect: a request replayed
|
|
1565
|
+
* under a dedupe key the external had already seen is not counted.
|
|
1566
|
+
*/
|
|
1567
|
+
function fetchCall(externalName, method) {
|
|
1607
1568
|
return {
|
|
1608
|
-
target: `
|
|
1609
|
-
op:
|
|
1569
|
+
target: `Fetch:${externalName}`,
|
|
1570
|
+
...method ? { op: method.toUpperCase() } : {},
|
|
1610
1571
|
kind: "result",
|
|
1611
|
-
|
|
1572
|
+
where: { "result.effective": true }
|
|
1612
1573
|
};
|
|
1613
1574
|
}
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1575
|
+
function validateWebSocketDrive(drive) {
|
|
1576
|
+
const errors = [];
|
|
1577
|
+
if (drive.connections.length === 0) errors.push("websocket drive needs at least one connection");
|
|
1578
|
+
const ids = /* @__PURE__ */ new Set();
|
|
1579
|
+
drive.connections.forEach((c, i) => {
|
|
1580
|
+
if (!c.path.startsWith("/")) errors.push(`connections[${i}].path must start with "/"`);
|
|
1581
|
+
if (ids.has(c.id)) errors.push(`duplicate connection id ${JSON.stringify(c.id)}`);
|
|
1582
|
+
ids.add(c.id);
|
|
1583
|
+
for (const m of c.messages) {
|
|
1584
|
+
if (ids.has(m.id)) errors.push(`duplicate message id ${JSON.stringify(m.id)}`);
|
|
1585
|
+
ids.add(m.id);
|
|
1586
|
+
}
|
|
1587
|
+
});
|
|
1588
|
+
return errors;
|
|
1589
|
+
}
|
|
1590
|
+
function validateHttpDrive(drive) {
|
|
1591
|
+
const errors = [];
|
|
1592
|
+
if (drive.requests.length === 0) errors.push("http drive needs at least one request");
|
|
1593
|
+
const ids = /* @__PURE__ */ new Set();
|
|
1594
|
+
drive.requests.forEach((r, i) => {
|
|
1595
|
+
if (!r.path.startsWith("/")) errors.push(`requests[${i}].path must start with "/"`);
|
|
1596
|
+
if (!r.method) errors.push(`requests[${i}].method must not be empty`);
|
|
1597
|
+
if (ids.has(r.id)) errors.push(`duplicate request id ${JSON.stringify(r.id)}`);
|
|
1598
|
+
ids.add(r.id);
|
|
1599
|
+
if ((r.method === "GET" || r.method === "HEAD") && r.body !== void 0) errors.push(`requests[${i}] is a ${r.method} and cannot carry a body`);
|
|
1600
|
+
});
|
|
1601
|
+
errors.push(...validateCaller("http", drive));
|
|
1602
|
+
return errors;
|
|
1603
|
+
}
|
|
1604
|
+
/** The caller's policy, as both drives a caller resends declare it. */
|
|
1605
|
+
function validateCaller(kind, drive) {
|
|
1606
|
+
const errors = [];
|
|
1607
|
+
if (!(Number.isInteger(drive.retries) && drive.retries >= 0)) errors.push(`${kind} drive retries must be a non-negative integer`);
|
|
1608
|
+
(drive.delaysMs ?? []).forEach((d, i) => {
|
|
1609
|
+
if (!(Number.isInteger(d) && d >= 0)) errors.push(`${kind} drive delaysMs[${i}] must be a non-negative integer`);
|
|
1610
|
+
});
|
|
1611
|
+
if (drive.deadlineMs !== void 0 && !(Number.isInteger(drive.deadlineMs) && drive.deadlineMs > 0)) errors.push(`${kind} drive deadlineMs must be a positive integer`);
|
|
1612
|
+
return errors;
|
|
1613
|
+
}
|
|
1614
|
+
function validateCronDrive(drive) {
|
|
1615
|
+
const errors = [];
|
|
1616
|
+
try {
|
|
1617
|
+
parseCron(drive.cron);
|
|
1618
|
+
} catch (err) {
|
|
1619
|
+
errors.push(`cron drive: ${err.message}`);
|
|
1620
|
+
}
|
|
1621
|
+
if (drive.ticks.length === 0) errors.push("cron drive ticks must be a positive integer");
|
|
1622
|
+
const ids = /* @__PURE__ */ new Set();
|
|
1623
|
+
drive.ticks.forEach((t, i) => {
|
|
1624
|
+
if (ids.has(t.id)) errors.push(`duplicate tick id ${JSON.stringify(t.id)}`);
|
|
1625
|
+
ids.add(t.id);
|
|
1626
|
+
const previous = drive.ticks[i - 1];
|
|
1627
|
+
if (previous && !(t.at > previous.at)) errors.push(`ticks[${i}] does not come after ticks[${i - 1}]`);
|
|
1628
|
+
});
|
|
1629
|
+
if (!(Number.isInteger(drive.retries) && drive.retries >= 0)) errors.push("cron drive retries must be a non-negative integer");
|
|
1630
|
+
return errors;
|
|
1631
|
+
}
|
|
1632
|
+
/** A method name the entrypoint can have: an identifier that is not the constructor. */
|
|
1633
|
+
const methodName = /^[A-Za-z_$][\w$]*$/;
|
|
1634
|
+
function validateRpcDrive(drive) {
|
|
1635
|
+
const errors = [];
|
|
1636
|
+
if (drive.entrypoint !== void 0 && !methodName.test(drive.entrypoint)) errors.push("rpc drive entrypoint must be an exported class name");
|
|
1637
|
+
const ids = /* @__PURE__ */ new Set();
|
|
1638
|
+
drive.calls.forEach((c, i) => {
|
|
1639
|
+
if (!methodName.test(c.method) || c.method === "constructor") errors.push(`calls[${i}].method must be a method name`);
|
|
1640
|
+
if (!Array.isArray(c.args)) errors.push(`calls[${i}].args must be an array`);
|
|
1641
|
+
if (ids.has(c.id)) errors.push(`duplicate call id ${JSON.stringify(c.id)}`);
|
|
1642
|
+
ids.add(c.id);
|
|
1643
|
+
});
|
|
1644
|
+
errors.push(...validateCaller("rpc", drive));
|
|
1645
|
+
return errors;
|
|
1646
|
+
}
|
|
1647
|
+
/**
|
|
1648
|
+
* Durable Object setups: an object's or a SQL table's name may not hold
|
|
1649
|
+
* "/", since the snapshot names a table `<object>/<table>` and a selector
|
|
1650
|
+
* must read back to one place.
|
|
1651
|
+
*/
|
|
1652
|
+
function validateDurableObjectSetups(setup) {
|
|
1653
|
+
const errors = [];
|
|
1654
|
+
for (const step of setup) {
|
|
1655
|
+
if (step["kind"] !== "durable_object") continue;
|
|
1656
|
+
const s = step;
|
|
1657
|
+
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`);
|
|
1658
|
+
for (const [name, seed] of Object.entries(s.sql ?? {})) {
|
|
1659
|
+
if (typeof seed.schema !== "string" || seed.schema.trim() === "") errors.push(`durableObject ${s.binding}: object ${JSON.stringify(name)} has a sql seed without a schema`);
|
|
1660
|
+
for (const [table, rows] of Object.entries(seed.rows ?? {})) {
|
|
1661
|
+
if (table.includes("/")) errors.push(`durableObject ${s.binding}: table name ${JSON.stringify(table)} of ${JSON.stringify(name)} holds "/"`);
|
|
1662
|
+
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`);
|
|
1663
|
+
}
|
|
1664
|
+
}
|
|
1665
|
+
}
|
|
1666
|
+
return errors;
|
|
1667
|
+
}
|
|
1668
|
+
/** Build and validate a scenario spec; throws with every problem listed. */
|
|
1669
|
+
function defineScenario(input) {
|
|
1670
|
+
const drive = input.drive.kind === "queue" ? queue(input.drive.queue, input.drive.messages) : input.drive;
|
|
1671
|
+
const spec = {
|
|
1672
|
+
version: 1,
|
|
1673
|
+
name: input.name,
|
|
1674
|
+
platform: "cloudflare",
|
|
1675
|
+
worker: input.worker,
|
|
1676
|
+
drive,
|
|
1677
|
+
setup: input.setup ?? [],
|
|
1678
|
+
externals: input.externals ?? [],
|
|
1679
|
+
invariants: input.invariants,
|
|
1680
|
+
bounds: {
|
|
1681
|
+
...defaultBounds,
|
|
1682
|
+
...input.bounds
|
|
1683
|
+
},
|
|
1684
|
+
...input.specs ? { specs: input.specs } : {}
|
|
1685
|
+
};
|
|
1686
|
+
const errors = [
|
|
1687
|
+
...validateScenario(spec),
|
|
1688
|
+
...validateDurableObjectSetups(spec.setup),
|
|
1689
|
+
...validateCalleeSetups(spec.setup),
|
|
1690
|
+
...drive.kind === "http" ? validateHttpDrive(drive) : [],
|
|
1691
|
+
...drive.kind === "rpc" ? validateRpcDrive(drive) : [],
|
|
1692
|
+
...drive.kind === "cron" ? validateCronDrive(drive) : [],
|
|
1693
|
+
...drive.kind === "websocket" ? validateWebSocketDrive(drive) : []
|
|
1694
|
+
];
|
|
1695
|
+
if (errors.length > 0) throw new Error(`invalid scenario ${JSON.stringify(input.name)}:\n- ${errors.join("\n- ")}`);
|
|
1696
|
+
return spec;
|
|
1697
|
+
}
|
|
1698
|
+
// packages/cloudflare/src/rpc.ts
|
|
1699
|
+
/**
|
|
1700
|
+
* Inbound RPC delivery: one invocation per attempt of a `WorkerEntrypoint`
|
|
1701
|
+
* method call the drive's caller makes. The entrypoint is constructed anew
|
|
1702
|
+
* for each call, as the runtime does (Cloudflare, Workers RPC: a new
|
|
1703
|
+
* instance of the class for every call), and its return value or the error
|
|
1704
|
+
* it threw is the response the caller sees.
|
|
1705
|
+
*/
|
|
1706
|
+
/**
|
|
1707
|
+
* An error as the caller sees it over RPC: a new error object with the
|
|
1708
|
+
* name and message (Cloudflare, RPC error handling), nothing of its class.
|
|
1709
|
+
*/
|
|
1710
|
+
function describeError(error) {
|
|
1711
|
+
if (error instanceof Error) return `${error.name}: ${error.message}`;
|
|
1712
|
+
return typeof error === "string" ? error : JSON.stringify(toJson(error));
|
|
1713
|
+
}
|
|
1714
|
+
/** One attempt of a call, under the caller's retry policy and deadline. */
|
|
1715
|
+
async function deliverCall(event, hooks, spec, drive, invocation, cls, env) {
|
|
1716
|
+
const call = event.data;
|
|
1717
|
+
const target = rpcTarget(drive, call.method);
|
|
1718
|
+
const inv = hooks.startInvocation(invocation);
|
|
1719
|
+
const background = [];
|
|
1720
|
+
const args = {
|
|
1721
|
+
callId: event.id,
|
|
1722
|
+
method: call.method,
|
|
1723
|
+
args: call.args
|
|
1724
|
+
};
|
|
1725
|
+
const caller = startCaller(event, hooks, spec, drive, target, {
|
|
1726
|
+
callId: event.id,
|
|
1727
|
+
attempts: event.attempt
|
|
1728
|
+
});
|
|
1729
|
+
const ran = await runInvocation(hooks, inv, () => callMethod(cls, call, executionContext(background), env));
|
|
1730
|
+
let status = ran.status;
|
|
1731
|
+
let late = caller.isLate();
|
|
1732
|
+
let answer = null;
|
|
1733
|
+
if (ran.status === "completed") {
|
|
1734
|
+
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`);
|
|
1735
|
+
const s = {
|
|
1736
|
+
ok: true,
|
|
1737
|
+
value: toJson(ran.value)
|
|
1738
|
+
};
|
|
1739
|
+
try {
|
|
1740
|
+
hooks.effectSync({
|
|
1741
|
+
invocation,
|
|
1742
|
+
target,
|
|
1743
|
+
op: "response",
|
|
1744
|
+
args,
|
|
1745
|
+
allowed: caller.responseFaults
|
|
1746
|
+
}, () => s, (v) => v);
|
|
1747
|
+
answer = s;
|
|
1748
|
+
} catch (err) {
|
|
1749
|
+
if (err instanceof CrashSignal) status = "crashed";
|
|
1750
|
+
else if (err instanceof InjectedEffectError) {
|
|
1751
|
+
answer = s;
|
|
1752
|
+
late = true;
|
|
1753
|
+
} else throw err;
|
|
1754
|
+
}
|
|
1755
|
+
} else if (ran.status === "errored") {
|
|
1756
|
+
const s = {
|
|
1757
|
+
ok: false,
|
|
1758
|
+
error: describeError(ran.error)
|
|
1759
|
+
};
|
|
1760
|
+
hooks.effectSync({
|
|
1761
|
+
invocation,
|
|
1762
|
+
target,
|
|
1763
|
+
op: "response",
|
|
1764
|
+
args,
|
|
1765
|
+
allowed: []
|
|
1766
|
+
}, () => s, (v) => v);
|
|
1767
|
+
answer = s;
|
|
1768
|
+
}
|
|
1769
|
+
caller.settle(answer !== null && !late && answer.ok, late);
|
|
1770
|
+
if (await drainBackground(hooks, inv, invocation, target, background)) status = "crashed";
|
|
1771
|
+
return {
|
|
1772
|
+
status,
|
|
1773
|
+
followUps: []
|
|
1624
1774
|
};
|
|
1625
1775
|
}
|
|
1626
1776
|
/**
|
|
1627
|
-
* The
|
|
1628
|
-
*
|
|
1777
|
+
* The class an RPC drive calls: the named export, or the Worker's default
|
|
1778
|
+
* export (the class passed as the handler, or `exports.default`). Not
|
|
1779
|
+
* necessarily a class: the platform reports what it found instead.
|
|
1629
1780
|
*/
|
|
1630
|
-
function
|
|
1631
|
-
|
|
1632
|
-
return
|
|
1633
|
-
target,
|
|
1634
|
-
table: object,
|
|
1635
|
-
where
|
|
1636
|
-
} : {
|
|
1637
|
-
target,
|
|
1638
|
-
table: object
|
|
1639
|
-
};
|
|
1781
|
+
function entrypointClass(handler, exports, entrypoint) {
|
|
1782
|
+
if (entrypoint !== void 0) return exports?.[entrypoint];
|
|
1783
|
+
return typeof handler === "function" ? handler : exports?.["default"];
|
|
1640
1784
|
}
|
|
1641
1785
|
/**
|
|
1642
|
-
*
|
|
1643
|
-
*
|
|
1644
|
-
*
|
|
1786
|
+
* The method RPC exposes under a name: one the class or a superclass defines
|
|
1787
|
+
* on its prototype. An instance property, even a function, and Object's own
|
|
1788
|
+
* methods are not callable (workerd: "The RPC receiver does not implement the
|
|
1789
|
+
* method").
|
|
1645
1790
|
*/
|
|
1646
|
-
function
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
where
|
|
1653
|
-
} : {
|
|
1654
|
-
target,
|
|
1655
|
-
table: name
|
|
1656
|
-
};
|
|
1791
|
+
function rpcMethod(instance, name) {
|
|
1792
|
+
for (let proto = Object.getPrototypeOf(instance); proto !== null && proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) {
|
|
1793
|
+
const own = Object.getOwnPropertyDescriptor(proto, name);
|
|
1794
|
+
if (!own) continue;
|
|
1795
|
+
return typeof own.value === "function" && name !== "constructor" ? own.value : void 0;
|
|
1796
|
+
}
|
|
1657
1797
|
}
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
};
|
|
1798
|
+
/**
|
|
1799
|
+
* Construct the entrypoint for one call and invoke the method, as the
|
|
1800
|
+
* runtime does per call. The arguments are copied, as RPC copies them: a
|
|
1801
|
+
* method that mutates one changes neither the scenario nor a later attempt.
|
|
1802
|
+
*/
|
|
1803
|
+
function callMethod(cls, call, ctx, env) {
|
|
1804
|
+
const instance = constructEntrypoint(cls, "WorkerEntrypoint", ctx, env);
|
|
1805
|
+
const method = rpcMethod(instance, call.method);
|
|
1806
|
+
if (!method) throw new TypeError(`The RPC receiver does not implement the method "${call.method}".`);
|
|
1807
|
+
return method.apply(instance, structuredClone(call.args));
|
|
1667
1808
|
}
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1809
|
+
// packages/cloudflare/src/services.ts
|
|
1810
|
+
/**
|
|
1811
|
+
* Service bindings with the callee scripted. A Worker reaches a peer through
|
|
1812
|
+
* `env.BINDING`, by RPC method or by `fetch()`; Cloudflare routes the call on
|
|
1813
|
+
* the same thread and retries nothing (Workers, service bindings). The real
|
|
1814
|
+
* binding is never called here: the scenario's `service()` setup scripts the
|
|
1815
|
+
* replies, and each call is one effect with the faults of a Durable Object
|
|
1816
|
+
* stub call, where `crash_before` and `error` mean the call never reached
|
|
1817
|
+
* the callee, `ambiguous` that it acted and the answer was lost, and
|
|
1818
|
+
* `crash_after` that the caller died after it. The stub itself (callable
|
|
1819
|
+
* methods, awaited properties, `fetch`, the pipelining guards) is shared
|
|
1820
|
+
* with the callee that runs for real (`callees.ts`).
|
|
1821
|
+
*/
|
|
1822
|
+
/** Marks of the other kinds of binding, which a service binding's duck type must not carry. */
|
|
1823
|
+
const otherKinds = [
|
|
1824
|
+
"prepare",
|
|
1825
|
+
"idFromName",
|
|
1826
|
+
"head",
|
|
1827
|
+
"createBatch"
|
|
1828
|
+
];
|
|
1829
|
+
/**
|
|
1830
|
+
* Whether an env value is a service binding (the runtime's `Fetcher`). In
|
|
1831
|
+
* workerd it is an RPC stub whose every property read yields a callable, so
|
|
1832
|
+
* duck typing alone would take it for any other kind: the runtime's class is
|
|
1833
|
+
* checked first, and the duck type (fetch and connect, none of the other
|
|
1834
|
+
* kinds' marks) serves test doubles.
|
|
1835
|
+
*/
|
|
1836
|
+
function isServiceBinding(value) {
|
|
1837
|
+
if (typeof value !== "object" || value === null) return false;
|
|
1838
|
+
const fetcher = globalThis.Fetcher;
|
|
1839
|
+
if (typeof fetcher === "function" && value instanceof fetcher) return true;
|
|
1840
|
+
if ((Object.getPrototypeOf(value)?.constructor)?.name === "Fetcher") return true;
|
|
1841
|
+
const v = value;
|
|
1842
|
+
return typeof v["fetch"] === "function" && typeof v["connect"] === "function" && otherKinds.every((k) => typeof v[k] !== "function");
|
|
1674
1843
|
}
|
|
1844
|
+
/** The built-in error classes RPC carries across as themselves (workerd keeps the type). */
|
|
1845
|
+
const builtInErrors = {
|
|
1846
|
+
Error,
|
|
1847
|
+
EvalError,
|
|
1848
|
+
RangeError,
|
|
1849
|
+
ReferenceError,
|
|
1850
|
+
SyntaxError,
|
|
1851
|
+
TypeError,
|
|
1852
|
+
URIError
|
|
1853
|
+
};
|
|
1675
1854
|
/**
|
|
1676
|
-
*
|
|
1677
|
-
*
|
|
1678
|
-
*
|
|
1679
|
-
* A committed write is a `result` whose `result.changes` is at least 1.
|
|
1855
|
+
* The error the caller sees for a `throws` reply, `"<Name>: <message>"`: a
|
|
1856
|
+
* built-in error class is that class, so `instanceof` holds as it does over
|
|
1857
|
+
* RPC; any other name is an `Error` carrying the name.
|
|
1680
1858
|
*/
|
|
1681
|
-
function
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1859
|
+
function scriptedError(spec) {
|
|
1860
|
+
const at = spec.indexOf(": ");
|
|
1861
|
+
if (at < 0) return new Error(spec);
|
|
1862
|
+
const name = spec.slice(0, at);
|
|
1863
|
+
const message = spec.slice(at + 2);
|
|
1864
|
+
const builtIn = builtInErrors[name];
|
|
1865
|
+
if (builtIn) return new builtIn(message);
|
|
1866
|
+
const error = new Error(message);
|
|
1867
|
+
error.name = name;
|
|
1868
|
+
return error;
|
|
1688
1869
|
}
|
|
1689
|
-
/**
|
|
1690
|
-
function
|
|
1870
|
+
/** Read a request for the log without consuming it: the callee may still read the body. */
|
|
1871
|
+
async function recordRequest(request) {
|
|
1872
|
+
const method = request.method.toUpperCase();
|
|
1873
|
+
const headers = {};
|
|
1874
|
+
request.headers.forEach((value, name) => {
|
|
1875
|
+
headers[name.toLowerCase()] = value;
|
|
1876
|
+
});
|
|
1877
|
+
const body = parseBody(await request.clone().text());
|
|
1691
1878
|
return {
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1879
|
+
url: request.url,
|
|
1880
|
+
method,
|
|
1881
|
+
headers,
|
|
1882
|
+
body
|
|
1695
1883
|
};
|
|
1696
1884
|
}
|
|
1697
|
-
/** Dot path to the Nth bound parameter of a D1 statement, in an effect payload. */
|
|
1698
|
-
function d1Param(index) {
|
|
1699
|
-
return `args.params.${index}`;
|
|
1700
|
-
}
|
|
1701
1885
|
/**
|
|
1702
|
-
* The
|
|
1703
|
-
*
|
|
1704
|
-
*
|
|
1705
|
-
* stale by another invocation's write between the read it rests on and the
|
|
1706
|
-
* effect. The core function's module must be listed in the scenario's
|
|
1707
|
-
* `specs`, which is what records its calls.
|
|
1886
|
+
* The stub a Worker sees under a service binding's name: methods callable
|
|
1887
|
+
* and awaitable, `fetch`, and the guards against what is not modelled
|
|
1888
|
+
* (promise pipelining, `connect()`), with the answers supplied.
|
|
1708
1889
|
*/
|
|
1709
|
-
function
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1890
|
+
function serviceStub(binding, ctx, answers) {
|
|
1891
|
+
const unsupported = (what) => {
|
|
1892
|
+
const reason = `service binding ${binding}: ${what}`;
|
|
1893
|
+
ctx.hooks.unsupported(reason);
|
|
1894
|
+
throw new Error(`eutaxy: ${reason}`);
|
|
1895
|
+
};
|
|
1896
|
+
/**
|
|
1897
|
+
* The promise a call returns. On the real stub it is an RPC promise that
|
|
1898
|
+
* pipelines property reads (`stub.charge().id`); this one is not, so a read
|
|
1899
|
+
* on it makes the run UNSUPPORTED instead of yielding undefined.
|
|
1900
|
+
*/
|
|
1901
|
+
const pipelineGuard = (promise, method) => new Proxy(promise, { get(target, prop) {
|
|
1902
|
+
if (typeof prop === "symbol" || prop === "then" || prop === "catch" || prop === "finally") {
|
|
1903
|
+
const value = Reflect.get(target, prop, target);
|
|
1904
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
1905
|
+
}
|
|
1906
|
+
ctx.hooks.unsupported(`service binding ${binding}: RPC promise pipelining (reading .${prop} on ${method}()'s promise) is not supported; await the call first`);
|
|
1907
|
+
} });
|
|
1908
|
+
/** One call: `stub.method(...)`, or `await stub.property` (an RPC getter). */
|
|
1909
|
+
const call = (method) => {
|
|
1910
|
+
const invoke = (...args) => pipelineGuard(answers.call(method, args), method);
|
|
1911
|
+
const awaitable = (onFulfilled, onRejected) => answers.property(method).then(onFulfilled, onRejected);
|
|
1912
|
+
return new Proxy(invoke, { get(fn, key) {
|
|
1913
|
+
if (key === "then") return awaitable;
|
|
1914
|
+
if (typeof key === "symbol") return Reflect.get(fn, key);
|
|
1915
|
+
ctx.hooks.unsupported(`service binding ${binding}: RPC promise pipelining (reading .${method}.${key}) is not supported; await .${method} first`);
|
|
1916
|
+
} });
|
|
1716
1917
|
};
|
|
1918
|
+
const fetchThrough = async (input, init) => answers.fetch(new Request(input, init));
|
|
1919
|
+
return new Proxy({}, { get(_stub, prop) {
|
|
1920
|
+
if (prop === "then" || typeof prop === "symbol") return void 0;
|
|
1921
|
+
if (prop === "fetch") return fetchThrough;
|
|
1922
|
+
if (prop === "connect") return () => unsupported("connect() (a raw TCP socket) is not modelled");
|
|
1923
|
+
return call(prop);
|
|
1924
|
+
} });
|
|
1717
1925
|
}
|
|
1718
|
-
/**
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
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
|
-
};
|
|
1756
|
-
}
|
|
1757
|
-
const requests = drive.requests.map((r) => ({
|
|
1758
|
-
id: r.id,
|
|
1759
|
-
body: r.body ?? null
|
|
1760
|
-
}));
|
|
1761
|
-
return {
|
|
1762
|
-
...atLeastOncePerMessage$1(name, requests, effect, key, bodyKey),
|
|
1763
|
-
perMessage: { bodyKey: bodyKey === "" ? "body" : `body.${bodyKey}` }
|
|
1926
|
+
/** The scripted stub a Worker sees under a service binding's name. */
|
|
1927
|
+
function proxyService(binding, ctx, script) {
|
|
1928
|
+
const target = `Service:${binding}`;
|
|
1929
|
+
const point = (op, args) => ({
|
|
1930
|
+
invocation: ctx.currentInvocation(),
|
|
1931
|
+
target,
|
|
1932
|
+
op,
|
|
1933
|
+
args,
|
|
1934
|
+
allowed: writeFaults
|
|
1935
|
+
});
|
|
1936
|
+
const unsupported = (what) => {
|
|
1937
|
+
const reason = `service binding ${binding}: ${what}`;
|
|
1938
|
+
ctx.hooks.unsupported(reason);
|
|
1939
|
+
throw new Error(`eutaxy: ${reason}`);
|
|
1940
|
+
};
|
|
1941
|
+
/** The scripted reply to a method, by name; a method the script lacks cannot be answered. */
|
|
1942
|
+
const replyTo = (method) => {
|
|
1943
|
+
if (script.methods === void 0) return { returns: null };
|
|
1944
|
+
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`);
|
|
1945
|
+
return script.methods[method];
|
|
1946
|
+
};
|
|
1947
|
+
const answer = (method) => {
|
|
1948
|
+
const reply = replyTo(method);
|
|
1949
|
+
if ("throws" in reply) throw scriptedError(reply.throws);
|
|
1950
|
+
return structuredClone(reply.returns);
|
|
1764
1951
|
};
|
|
1952
|
+
const summarize = (value) => ({ value: toJson(value) });
|
|
1953
|
+
return serviceStub(binding, ctx, {
|
|
1954
|
+
call: (method, args) => ctx.hooks.effect(point(method, { args: args.map((a) => toJson(a)) }), async () => answer(method), summarize),
|
|
1955
|
+
property: (method) => ctx.hooks.effect(point(method, { property: true }), async () => answer(method), summarize),
|
|
1956
|
+
async fetch(request) {
|
|
1957
|
+
const url = new URL(request.url);
|
|
1958
|
+
const { method, headers, body } = await recordRequest(request);
|
|
1959
|
+
const reply = await ctx.hooks.effect(point(method, {
|
|
1960
|
+
url: request.url,
|
|
1961
|
+
method,
|
|
1962
|
+
headers,
|
|
1963
|
+
body
|
|
1964
|
+
}), async () => {
|
|
1965
|
+
const found = findResponse({
|
|
1966
|
+
name: binding,
|
|
1967
|
+
host: url.host,
|
|
1968
|
+
guarantees: {},
|
|
1969
|
+
...script.fetch === void 0 ? {} : { responses: script.fetch }
|
|
1970
|
+
}, method, url.pathname);
|
|
1971
|
+
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`);
|
|
1972
|
+
const reply = replyOf(found);
|
|
1973
|
+
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"`);
|
|
1974
|
+
return reply;
|
|
1975
|
+
}, (r) => ({ status: r.status }));
|
|
1976
|
+
return toResponse(reply);
|
|
1977
|
+
}
|
|
1978
|
+
});
|
|
1765
1979
|
}
|
|
1980
|
+
// packages/cloudflare/src/callees.ts
|
|
1766
1981
|
/**
|
|
1767
|
-
*
|
|
1768
|
-
*
|
|
1769
|
-
* its
|
|
1982
|
+
* Service bindings with the callee real. A scenario names the Worker behind a
|
|
1983
|
+
* binding (`callee(binding, { entry, config })`), and the test gives the
|
|
1984
|
+
* platform its module and the name from its wrangler config; the callee's
|
|
1985
|
+
* code then runs in the same simulation as the caller's, in the same
|
|
1986
|
+
* isolate, as Cloudflare runs both Workers on one thread (Workers, service
|
|
1987
|
+
* bindings). Each RPC method call or `fetch()` through the binding is one
|
|
1988
|
+
* effect, `Service:<binding>`, with the faults of a call in the network
|
|
1989
|
+
* (`crash_before`: it never reached the callee; `ambiguous`: the callee
|
|
1990
|
+
* acted and the answer was lost; `crash_after`: the caller died after it);
|
|
1991
|
+
* `error` is not among them, since what the callee throws is real. The
|
|
1992
|
+
* effect hosts the callee's invocation (`<caller invocation>/<binding>.<method>`,
|
|
1993
|
+
* `#<n>` for the n-th call of that method from the same caller invocation):
|
|
1994
|
+
* the entrypoint is constructed anew with a fresh `ExecutionContext` and the
|
|
1995
|
+
* callee's `env`, a view of the scenario's env under the callee's own names
|
|
1996
|
+
* (`DB` for `orders/DB`), so its code runs unchanged while its effects are
|
|
1997
|
+
* recorded under its own invocation, interleave as turns and take faults by
|
|
1998
|
+
* their position within it. What the callee throws reaches the caller as a
|
|
1999
|
+
* new error with its name, message and serializable own properties, a
|
|
2000
|
+
* built-in class as itself (Workers RPC, error handling); a fault that
|
|
2001
|
+
* crashes the callee ends its invocation and the caller sees an `Error`
|
|
2002
|
+
* thrown from the call. The callee's `waitUntil` work finishes before its
|
|
2003
|
+
* answer crosses: one of the orders the runtime allows.
|
|
1770
2004
|
*/
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
2005
|
+
/** The faults a call to a real callee admits; `error` is the callee's own to throw. */
|
|
2006
|
+
const callFaults = [
|
|
2007
|
+
"crash_before",
|
|
2008
|
+
"ambiguous",
|
|
2009
|
+
"crash_after"
|
|
2010
|
+
];
|
|
2011
|
+
/** What the platform keeps per run about its callees; cleared before each run. */
|
|
2012
|
+
var CalleeState = class {
|
|
2013
|
+
/** Calls so far per caller invocation, binding and method, to name each hosted invocation. */
|
|
2014
|
+
counts = /* @__PURE__ */ new Map();
|
|
2015
|
+
clear() {
|
|
2016
|
+
this.counts.clear();
|
|
2017
|
+
}
|
|
2018
|
+
};
|
|
2019
|
+
/**
|
|
2020
|
+
* The callee's `env`: the scenario's env seen under the callee's own names,
|
|
2021
|
+
* each mapped onto `<name>/<key>`. Over the platform's proxied env the
|
|
2022
|
+
* entries are the proxies, so the callee's effects are recorded under their
|
|
2023
|
+
* qualified targets, and an alias (`<name>/STOCK` for the caller's `STOCK`)
|
|
2024
|
+
* is already resolved; over workerd's raw env (a callee's Durable Object,
|
|
2025
|
+
* which the runtime constructs with the main Worker's env) the aliases are
|
|
2026
|
+
* given here, so the shared binding is there under the callee's name too.
|
|
2027
|
+
*/
|
|
2028
|
+
function calleeEnv(name, env, aliases = {}) {
|
|
2029
|
+
const prefix = `${name}/`;
|
|
2030
|
+
const source = env;
|
|
2031
|
+
/** The key of `env` a property of the view reads: the qualified name, or the binding it is an alias of. */
|
|
2032
|
+
const keyOf = (prop) => {
|
|
2033
|
+
if (typeof prop !== "string") return void 0;
|
|
2034
|
+
const qualified = `${prefix}${prop}`;
|
|
2035
|
+
return qualified in source ? qualified : aliases[qualified] ?? qualified;
|
|
1776
2036
|
};
|
|
2037
|
+
const aliasKeys = Object.keys(aliases).filter((a) => a.startsWith(prefix) && (aliases[a] ?? "") in source);
|
|
2038
|
+
return new Proxy(Object.create(null), {
|
|
2039
|
+
get(_t, prop) {
|
|
2040
|
+
const key = keyOf(prop);
|
|
2041
|
+
return key === void 0 ? void 0 : source[key];
|
|
2042
|
+
},
|
|
2043
|
+
has(_t, prop) {
|
|
2044
|
+
const key = keyOf(prop);
|
|
2045
|
+
return key !== void 0 && key in source;
|
|
2046
|
+
},
|
|
2047
|
+
ownKeys: () => [...new Set([...Reflect.ownKeys(source).filter((k) => typeof k === "string"), ...aliasKeys].filter((k) => k.startsWith(prefix)).map((k) => k.slice(prefix.length)))],
|
|
2048
|
+
getOwnPropertyDescriptor(_t, prop) {
|
|
2049
|
+
const key = keyOf(prop);
|
|
2050
|
+
if (key === void 0 || !(key in source)) return void 0;
|
|
2051
|
+
return {
|
|
2052
|
+
value: source[key],
|
|
2053
|
+
enumerable: true,
|
|
2054
|
+
configurable: true,
|
|
2055
|
+
writable: false
|
|
2056
|
+
};
|
|
2057
|
+
}
|
|
2058
|
+
});
|
|
1777
2059
|
}
|
|
1778
2060
|
/**
|
|
1779
|
-
*
|
|
1780
|
-
*
|
|
1781
|
-
*
|
|
2061
|
+
* The error the caller sees for what the callee threw: a new error with the
|
|
2062
|
+
* name and message, a built-in class as itself, and the serializable own
|
|
2063
|
+
* properties the thrown error carried (Workers RPC, error handling, enhanced
|
|
2064
|
+
* error serialization). Nothing of the original's identity or stack.
|
|
1782
2065
|
*/
|
|
1783
|
-
function
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
2066
|
+
function crossingError(error) {
|
|
2067
|
+
const crossed = scriptedError(describeError(error));
|
|
2068
|
+
if (error instanceof Error) for (const key of Object.keys(error)) {
|
|
2069
|
+
if (key === "name" || key === "message" || key === "stack") continue;
|
|
2070
|
+
try {
|
|
2071
|
+
Object.defineProperty(crossed, key, {
|
|
2072
|
+
value: structuredClone(error[key]),
|
|
2073
|
+
enumerable: true,
|
|
2074
|
+
configurable: true,
|
|
2075
|
+
writable: true
|
|
2076
|
+
});
|
|
2077
|
+
} catch {}
|
|
2078
|
+
}
|
|
2079
|
+
return crossed;
|
|
1790
2080
|
}
|
|
1791
2081
|
/**
|
|
1792
|
-
*
|
|
1793
|
-
*
|
|
1794
|
-
*
|
|
2082
|
+
* The fetch handler the binding reaches: the named entrypoint's method when
|
|
2083
|
+
* the setup names one, else the default export's (a handler object's `fetch`,
|
|
2084
|
+
* or an entrypoint class's method).
|
|
1795
2085
|
*/
|
|
1796
|
-
function
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
2086
|
+
function fetchHandlerOf(exports, entrypoint, ctx, env) {
|
|
2087
|
+
const def = entrypoint === void 0 ? exports["default"] : exports[entrypoint];
|
|
2088
|
+
if (typeof def === "function") {
|
|
2089
|
+
const instance = constructEntrypoint(def, "WorkerEntrypoint", ctx, env);
|
|
2090
|
+
return typeof instance.fetch === "function" ? instance.fetch.bind(instance) : void 0;
|
|
2091
|
+
}
|
|
2092
|
+
if (typeof def === "object" && def !== null) {
|
|
2093
|
+
const handler = def;
|
|
2094
|
+
return typeof handler.fetch === "function" ? (request) => handler.fetch?.call(handler, request, env, ctx) : void 0;
|
|
2095
|
+
}
|
|
1803
2096
|
}
|
|
1804
|
-
/**
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
2097
|
+
/**
|
|
2098
|
+
* The getter RPC exposes under a name: one the class or a superclass defines
|
|
2099
|
+
* on its prototype. An instance field is not reachable over RPC (workerd:
|
|
2100
|
+
* "The RPC receiver does not implement the method").
|
|
2101
|
+
*/
|
|
2102
|
+
function rpcGetter(instance, name) {
|
|
2103
|
+
for (let proto = Object.getPrototypeOf(instance); proto !== null && proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) {
|
|
2104
|
+
const own = Object.getOwnPropertyDescriptor(proto, name);
|
|
2105
|
+
if (!own) continue;
|
|
2106
|
+
return typeof own.get === "function" ? own.get : void 0;
|
|
2107
|
+
}
|
|
1814
2108
|
}
|
|
1815
|
-
/**
|
|
1816
|
-
function
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
2109
|
+
/** The stub a Worker sees under a service binding whose callee runs for real. */
|
|
2110
|
+
function proxyCallee(binding, ctx, setup, module, env, state) {
|
|
2111
|
+
const target = `Service:${binding}`;
|
|
2112
|
+
const view = calleeEnv(module.name, env);
|
|
2113
|
+
const entrypointName = setup.entrypoint ?? module.entrypoint;
|
|
2114
|
+
const props = module.props ?? {};
|
|
2115
|
+
const unsupported = (what) => {
|
|
2116
|
+
const reason = `callee ${binding}: ${what}`;
|
|
2117
|
+
ctx.hooks.unsupported(reason);
|
|
2118
|
+
throw new Error(`eutaxy: ${reason}`);
|
|
1822
2119
|
};
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
2120
|
+
const point = (op, args) => ({
|
|
2121
|
+
invocation: ctx.currentInvocation(),
|
|
2122
|
+
target,
|
|
2123
|
+
op,
|
|
2124
|
+
args,
|
|
2125
|
+
allowed: callFaults
|
|
2126
|
+
});
|
|
2127
|
+
/** The hosted invocation's id: the n-th call of a method from one caller invocation is `#n`. */
|
|
2128
|
+
const invocationId = (method) => {
|
|
2129
|
+
const key = `${ctx.currentInvocation()}/${binding}.${method}`;
|
|
2130
|
+
const n = (state.counts.get(key) ?? 0) + 1;
|
|
2131
|
+
state.counts.set(key, n);
|
|
2132
|
+
return n === 1 ? key : `${key}#${n}`;
|
|
2133
|
+
};
|
|
2134
|
+
/** The callee's code as an invocation of its own inside the call: the handler, then its background work. */
|
|
2135
|
+
const invoke = (method, work) => {
|
|
2136
|
+
const hooks = ctx.hooks;
|
|
2137
|
+
const id = invocationId(method);
|
|
2138
|
+
return hostInvocation(hooks, id, async (inv) => {
|
|
2139
|
+
const background = [];
|
|
2140
|
+
const ran = await runInvocation(hooks, inv, () => work(executionContext(background, void 0, props)));
|
|
2141
|
+
if (ran.status !== "crashed") await drainBackground(hooks, inv, id, target, background);
|
|
2142
|
+
return ran;
|
|
2143
|
+
});
|
|
2144
|
+
};
|
|
2145
|
+
/** What the caller gets out of the callee's outcome: the value, the error as RPC carries it, or an error for a crash. */
|
|
2146
|
+
const answer = (outcome, method) => {
|
|
2147
|
+
if (outcome.status === "completed") return outcome.value;
|
|
2148
|
+
if (outcome.status === "errored") throw crossingError(outcome.error);
|
|
2149
|
+
throw new Error(`the Worker behind service binding ${binding} crashed while handling ${method}`);
|
|
2150
|
+
};
|
|
2151
|
+
/**
|
|
2152
|
+
* Arguments travel by copy, as plain data: a function, a stub or a stream is
|
|
2153
|
+
* a capability the model lacks, and a class instance is what RPC refuses
|
|
2154
|
+
* (structuredClone would silently make a plain object of it).
|
|
2155
|
+
*/
|
|
2156
|
+
const copied = (method, args) => {
|
|
2157
|
+
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`);
|
|
2158
|
+
try {
|
|
2159
|
+
return structuredClone([...args]);
|
|
2160
|
+
} catch {
|
|
2161
|
+
return unsupported(`the arguments of ${method} cannot be copied as RPC copies them`);
|
|
2162
|
+
}
|
|
2163
|
+
};
|
|
2164
|
+
/** A result passed back to the caller, by copy; one that is not plain data cannot be followed. */
|
|
2165
|
+
const plain = (method, value) => {
|
|
2166
|
+
if (!isPlainData(value)) unsupported(`${method} returned something that is not plain data (a stub, a function or a stream); RPC capabilities are not modelled`);
|
|
2167
|
+
try {
|
|
2168
|
+
return structuredClone(value);
|
|
2169
|
+
} catch {
|
|
2170
|
+
return value;
|
|
2171
|
+
}
|
|
2172
|
+
};
|
|
2173
|
+
const entrypoint = () => {
|
|
2174
|
+
const cls = entrypointClass(void 0, module.exports, entrypointName);
|
|
2175
|
+
if (typeof cls !== "function") unsupported(`${entrypointName === void 0 ? "the default export" : `export ${entrypointName}`} of ${module.name} is not a WorkerEntrypoint class`);
|
|
2176
|
+
return cls;
|
|
1831
2177
|
};
|
|
2178
|
+
const summarize = (value) => ({ value: toJson(value) });
|
|
2179
|
+
return serviceStub(binding, ctx, {
|
|
2180
|
+
call: (method, args) => {
|
|
2181
|
+
let copy;
|
|
2182
|
+
try {
|
|
2183
|
+
copy = copied(method, args);
|
|
2184
|
+
} catch (err) {
|
|
2185
|
+
return Promise.reject(err);
|
|
2186
|
+
}
|
|
2187
|
+
return ctx.hooks.effect(point(method, { args: args.map((a) => toJson(a)) }), async () => {
|
|
2188
|
+
const cls = entrypoint();
|
|
2189
|
+
const outcome = await invoke(method, (executionContext) => {
|
|
2190
|
+
const instance = constructEntrypoint(cls, "WorkerEntrypoint", executionContext, view);
|
|
2191
|
+
const fn = rpcMethod(instance, method);
|
|
2192
|
+
if (!fn) throw new TypeError(`The RPC receiver does not implement the method "${method}".`);
|
|
2193
|
+
return fn.apply(instance, copy);
|
|
2194
|
+
});
|
|
2195
|
+
return plain(method, answer(outcome, method));
|
|
2196
|
+
}, summarize);
|
|
2197
|
+
},
|
|
2198
|
+
property: (name) => ctx.hooks.effect(point(name, { property: true }), async () => {
|
|
2199
|
+
const cls = entrypoint();
|
|
2200
|
+
const outcome = await invoke(name, (executionContext) => {
|
|
2201
|
+
const instance = constructEntrypoint(cls, "WorkerEntrypoint", executionContext, view);
|
|
2202
|
+
const getter = rpcGetter(instance, name);
|
|
2203
|
+
if (!getter) throw new TypeError(`The RPC receiver does not implement the method "${name}".`);
|
|
2204
|
+
return getter.call(instance);
|
|
2205
|
+
});
|
|
2206
|
+
return plain(name, answer(outcome, name));
|
|
2207
|
+
}, summarize),
|
|
2208
|
+
async fetch(request) {
|
|
2209
|
+
const { method, headers, body } = await recordRequest(request);
|
|
2210
|
+
return ctx.hooks.effect(point(method, {
|
|
2211
|
+
url: request.url,
|
|
2212
|
+
method,
|
|
2213
|
+
headers,
|
|
2214
|
+
body
|
|
2215
|
+
}), async () => {
|
|
2216
|
+
const outcome = await invoke("fetch", (executionContext) => {
|
|
2217
|
+
const handler = fetchHandlerOf(module.exports, entrypointName, executionContext, view);
|
|
2218
|
+
if (!handler) return unsupported(`${entrypointName === void 0 ? module.name : `export ${entrypointName} of ${module.name}`} has no fetch handler`);
|
|
2219
|
+
return handler(request);
|
|
2220
|
+
});
|
|
2221
|
+
const response = answer(outcome, "fetch");
|
|
2222
|
+
if (!(response instanceof Response)) return unsupported(`${module.name}'s fetch handler returned something that is not a Response`);
|
|
2223
|
+
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"`);
|
|
2224
|
+
return response;
|
|
2225
|
+
}, (r) => ({ status: r.status }));
|
|
2226
|
+
}
|
|
2227
|
+
});
|
|
1832
2228
|
}
|
|
1833
|
-
|
|
1834
|
-
|
|
2229
|
+
// packages/cloudflare/src/check.ts
|
|
2230
|
+
/** Explore a scenario on a platform and return its verdict. */
|
|
2231
|
+
function check(spec, platform, options = { seed: spec.name }) {
|
|
2232
|
+
return explore(spec, platform, options);
|
|
2233
|
+
}
|
|
2234
|
+
/** For use from a test: passes only when the scenario is BOUNDED. */
|
|
2235
|
+
async function expectHolds(spec, platform, options) {
|
|
2236
|
+
const verdict = await check(spec, platform, options);
|
|
2237
|
+
if (verdict.kind !== "BOUNDED") throw new Error(describeVerdict(verdict));
|
|
2238
|
+
}
|
|
2239
|
+
// packages/cloudflare/src/d1.ts
|
|
2240
|
+
/**
|
|
2241
|
+
* The D1 binding proxy. Every statement execution is an effect point: the
|
|
2242
|
+
* engine decides the fault, the real Miniflare-backed D1 performs the query,
|
|
2243
|
+
* and the log records call, result and fault in the documented shape.
|
|
2244
|
+
*/
|
|
2245
|
+
/** Whether a binding is a D1 database (what the proxies and the differential wrap). */
|
|
2246
|
+
function isD1(value) {
|
|
2247
|
+
return typeof value === "object" && value !== null && typeof value.prepare === "function" && typeof value.batch === "function";
|
|
2248
|
+
}
|
|
2249
|
+
function point(ctx, target, op, args, allowed) {
|
|
1835
2250
|
return {
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
column
|
|
2251
|
+
invocation: ctx.currentInvocation(),
|
|
2252
|
+
target,
|
|
2253
|
+
op,
|
|
2254
|
+
args,
|
|
2255
|
+
allowed
|
|
1842
2256
|
};
|
|
1843
2257
|
}
|
|
1844
|
-
|
|
1845
|
-
function queueAck(queueName) {
|
|
2258
|
+
function metaOf(result) {
|
|
1846
2259
|
return {
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
kind: "result",
|
|
1850
|
-
where: { "result.effective": true }
|
|
2260
|
+
changes: result.meta.changes ?? 0,
|
|
2261
|
+
lastRowId: result.meta.last_row_id ?? null
|
|
1851
2262
|
};
|
|
1852
2263
|
}
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
2264
|
+
var StatementProxy = class StatementProxy {
|
|
2265
|
+
real;
|
|
2266
|
+
target;
|
|
2267
|
+
ctx;
|
|
2268
|
+
sql;
|
|
2269
|
+
params;
|
|
2270
|
+
constructor(real, target, ctx, sql, params) {
|
|
2271
|
+
this.real = real;
|
|
2272
|
+
this.target = target;
|
|
2273
|
+
this.ctx = ctx;
|
|
2274
|
+
this.sql = sql;
|
|
2275
|
+
this.params = params;
|
|
2276
|
+
}
|
|
2277
|
+
/** The real statement, for `batch()`. */
|
|
2278
|
+
get statement() {
|
|
2279
|
+
return this.real;
|
|
2280
|
+
}
|
|
2281
|
+
args() {
|
|
2282
|
+
return {
|
|
2283
|
+
sql: this.sql,
|
|
2284
|
+
params: toJson(this.params)
|
|
2285
|
+
};
|
|
2286
|
+
}
|
|
2287
|
+
bind(...values) {
|
|
2288
|
+
return new StatementProxy(this.real.bind(...values), this.target, this.ctx, this.sql, values);
|
|
2289
|
+
}
|
|
2290
|
+
run() {
|
|
2291
|
+
return this.ctx.hooks.effect(point(this.ctx, this.target, "run", this.args(), writeFaults), () => this.real.run(), (r) => metaOf(r));
|
|
2292
|
+
}
|
|
2293
|
+
all() {
|
|
2294
|
+
return this.ctx.hooks.effect(point(this.ctx, this.target, "all", this.args(), readFaults), () => this.real.all(), (r) => ({
|
|
2295
|
+
rows: r.results.length,
|
|
2296
|
+
changes: r.meta.changes ?? 0
|
|
2297
|
+
}));
|
|
2298
|
+
}
|
|
2299
|
+
first(colName) {
|
|
2300
|
+
return this.ctx.hooks.effect(point(this.ctx, this.target, "first", {
|
|
2301
|
+
...this.args(),
|
|
2302
|
+
column: colName ?? null
|
|
2303
|
+
}, readFaults), () => colName === void 0 ? this.real.first() : this.real.first(colName), (r) => ({ row: toJson(r) }));
|
|
2304
|
+
}
|
|
2305
|
+
raw(options) {
|
|
2306
|
+
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 }));
|
|
2307
|
+
}
|
|
2308
|
+
};
|
|
2309
|
+
/** Wrap a D1 binding. Methods not modelled fall through to the real binding and mark the run unsupported. */
|
|
2310
|
+
function proxyD1(real, binding, ctx) {
|
|
2311
|
+
const target = `D1:${binding}`;
|
|
2312
|
+
const modelled = {
|
|
2313
|
+
prepare(sql) {
|
|
2314
|
+
return new StatementProxy(real.prepare(sql), target, ctx, sql, []);
|
|
2315
|
+
},
|
|
2316
|
+
batch(statements) {
|
|
2317
|
+
const unwrapped = statements.map((s) => s instanceof StatementProxy ? s.statement : s);
|
|
2318
|
+
const args = { statements: statements.map((s) => s instanceof StatementProxy ? {
|
|
2319
|
+
sql: s.sql,
|
|
2320
|
+
params: toJson(s.params)
|
|
2321
|
+
} : "<unproxied statement>") };
|
|
2322
|
+
return ctx.hooks.effect(point(ctx, target, "batch", args, writeFaults), () => real.batch(unwrapped), (rs) => ({
|
|
2323
|
+
changes: rs.reduce((n, r) => n + (r.meta.changes ?? 0), 0),
|
|
2324
|
+
statements: rs.length
|
|
2325
|
+
}));
|
|
2326
|
+
},
|
|
2327
|
+
exec(sql) {
|
|
2328
|
+
return ctx.hooks.effect(point(ctx, target, "exec", { sql }, writeFaults), () => real.exec(sql), (r) => ({
|
|
2329
|
+
count: r.count,
|
|
2330
|
+
duration: 0
|
|
2331
|
+
}));
|
|
2332
|
+
}
|
|
1865
2333
|
};
|
|
2334
|
+
return new Proxy(real, { get(obj, prop, receiver) {
|
|
2335
|
+
if (prop in modelled) return modelled[prop];
|
|
2336
|
+
const value = Reflect.get(obj, prop, receiver);
|
|
2337
|
+
if (typeof value === "function") {
|
|
2338
|
+
ctx.hooks.unsupported(`D1 ${binding}.${String(prop)} is not modelled`);
|
|
2339
|
+
return value.bind(obj);
|
|
2340
|
+
}
|
|
2341
|
+
return value;
|
|
2342
|
+
} });
|
|
1866
2343
|
}
|
|
1867
2344
|
/**
|
|
1868
|
-
*
|
|
1869
|
-
*
|
|
2345
|
+
* Statements in a schema file. Splits on semicolons outside string literals,
|
|
2346
|
+
* quoted identifiers and comments, and keeps CREATE TRIGGER bodies (and CASE
|
|
2347
|
+
* expressions) whole by tracking BEGIN/CASE ... END nesting.
|
|
1870
2348
|
*/
|
|
1871
|
-
function
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
drive.connections.forEach((c, i) => {
|
|
1884
|
-
if (!c.path.startsWith("/")) errors.push(`connections[${i}].path must start with "/"`);
|
|
1885
|
-
if (ids.has(c.id)) errors.push(`duplicate connection id ${JSON.stringify(c.id)}`);
|
|
1886
|
-
ids.add(c.id);
|
|
1887
|
-
for (const m of c.messages) {
|
|
1888
|
-
if (ids.has(m.id)) errors.push(`duplicate message id ${JSON.stringify(m.id)}`);
|
|
1889
|
-
ids.add(m.id);
|
|
2349
|
+
function splitSql(sql) {
|
|
2350
|
+
const out = [];
|
|
2351
|
+
let cur = "";
|
|
2352
|
+
let depth = 0;
|
|
2353
|
+
let i = 0;
|
|
2354
|
+
const isWordChar = (c) => c !== void 0 && /[A-Za-z0-9_]/.test(c);
|
|
2355
|
+
while (i < sql.length) {
|
|
2356
|
+
const c = sql[i];
|
|
2357
|
+
const next = sql[i + 1];
|
|
2358
|
+
if (c === "-" && next === "-") {
|
|
2359
|
+
while (i < sql.length && sql[i] !== "\n") i++;
|
|
2360
|
+
continue;
|
|
1890
2361
|
}
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
2362
|
+
if (c === "/" && next === "*") {
|
|
2363
|
+
const end = sql.indexOf("*/", i + 2);
|
|
2364
|
+
i = end === -1 ? sql.length : end + 2;
|
|
2365
|
+
continue;
|
|
2366
|
+
}
|
|
2367
|
+
if (c === "'" || c === "\"" || c === "`" || c === "[") {
|
|
2368
|
+
const close = c === "[" ? "]" : c;
|
|
2369
|
+
let j = i + 1;
|
|
2370
|
+
for (;;) {
|
|
2371
|
+
const k = sql.indexOf(close, j);
|
|
2372
|
+
if (k === -1) {
|
|
2373
|
+
j = sql.length;
|
|
2374
|
+
break;
|
|
2375
|
+
}
|
|
2376
|
+
if (close !== "]" && sql[k + 1] === close) {
|
|
2377
|
+
j = k + 2;
|
|
2378
|
+
continue;
|
|
2379
|
+
}
|
|
2380
|
+
j = k + 1;
|
|
2381
|
+
break;
|
|
2382
|
+
}
|
|
2383
|
+
cur += sql.slice(i, j);
|
|
2384
|
+
i = j;
|
|
2385
|
+
continue;
|
|
2386
|
+
}
|
|
2387
|
+
if (isWordChar(c) && !isWordChar(sql[i - 1])) {
|
|
2388
|
+
let j = i;
|
|
2389
|
+
while (isWordChar(sql[j])) j++;
|
|
2390
|
+
const word = sql.slice(i, j);
|
|
2391
|
+
const upper = word.toUpperCase();
|
|
2392
|
+
if (upper === "BEGIN" || upper === "CASE") depth++;
|
|
2393
|
+
else if (upper === "END" && depth > 0) depth--;
|
|
2394
|
+
cur += word;
|
|
2395
|
+
i = j;
|
|
2396
|
+
continue;
|
|
2397
|
+
}
|
|
2398
|
+
if (c === ";" && depth === 0) {
|
|
2399
|
+
const statement = cur.trim();
|
|
2400
|
+
if (statement.length > 0) out.push(statement);
|
|
2401
|
+
cur = "";
|
|
2402
|
+
i++;
|
|
2403
|
+
continue;
|
|
2404
|
+
}
|
|
2405
|
+
cur += c;
|
|
2406
|
+
i++;
|
|
2407
|
+
}
|
|
2408
|
+
const last = cur.trim();
|
|
2409
|
+
if (last.length > 0) out.push(last);
|
|
2410
|
+
return out;
|
|
1907
2411
|
}
|
|
1908
|
-
/**
|
|
1909
|
-
function
|
|
1910
|
-
const
|
|
1911
|
-
|
|
1912
|
-
(
|
|
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;
|
|
2412
|
+
/** Drop every user table and re-apply the schema, using the real binding (not an effect). */
|
|
2413
|
+
async function resetD1(real, schema) {
|
|
2414
|
+
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();
|
|
2415
|
+
for (const { name } of tables.results) await real.prepare(`DROP TABLE IF EXISTS "${name.replace(/"/g, "\"\"")}"`).run();
|
|
2416
|
+
for (const statement of splitSql(schema)) await real.prepare(statement).run();
|
|
1917
2417
|
}
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
}
|
|
1923
|
-
|
|
1924
|
-
}
|
|
1925
|
-
if (drive.ticks.length === 0) errors.push("cron drive ticks must be a positive integer");
|
|
1926
|
-
const ids = /* @__PURE__ */ new Set();
|
|
1927
|
-
drive.ticks.forEach((t, i) => {
|
|
1928
|
-
if (ids.has(t.id)) errors.push(`duplicate tick id ${JSON.stringify(t.id)}`);
|
|
1929
|
-
ids.add(t.id);
|
|
1930
|
-
const previous = drive.ticks[i - 1];
|
|
1931
|
-
if (previous && !(t.at > previous.at)) errors.push(`ticks[${i}] does not come after ticks[${i - 1}]`);
|
|
1932
|
-
});
|
|
1933
|
-
if (!(Number.isInteger(drive.retries) && drive.retries >= 0)) errors.push("cron drive retries must be a non-negative integer");
|
|
1934
|
-
return errors;
|
|
2418
|
+
/** Every user table's rows, sorted canonically, read through the real binding (not an effect). */
|
|
2419
|
+
async function snapshotD1(real) {
|
|
2420
|
+
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();
|
|
2421
|
+
const out = {};
|
|
2422
|
+
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);
|
|
2423
|
+
return out;
|
|
1935
2424
|
}
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
return
|
|
2425
|
+
// packages/cloudflare/src/r2.ts
|
|
2426
|
+
/**
|
|
2427
|
+
* The R2 binding proxy. Every `put`, `delete`, `get`, `head` and `list` is
|
|
2428
|
+
* an effect point against the real Miniflare-backed bucket. A body is read
|
|
2429
|
+
* inside its `get`'s effect and handed back in an object with the same
|
|
2430
|
+
* fields and body methods: reading it later would be I/O the run cannot
|
|
2431
|
+
* see. An object's random `version` and wall-clock `uploaded` are replaced
|
|
2432
|
+
* by stand-ins (see `VersionBook`), so traces stay byte-identical.
|
|
2433
|
+
*/
|
|
2434
|
+
/** Whether a binding is an R2 bucket (Miniflare's `R2Bucket`). */
|
|
2435
|
+
function isR2(value) {
|
|
2436
|
+
if (typeof value !== "object" || value === null) return false;
|
|
2437
|
+
const v = value;
|
|
2438
|
+
return [
|
|
2439
|
+
"head",
|
|
2440
|
+
"get",
|
|
2441
|
+
"put",
|
|
2442
|
+
"delete",
|
|
2443
|
+
"list",
|
|
2444
|
+
"createMultipartUpload"
|
|
2445
|
+
].every((m) => typeof v[m] === "function");
|
|
1950
2446
|
}
|
|
1951
2447
|
/**
|
|
1952
|
-
*
|
|
1953
|
-
*
|
|
1954
|
-
*
|
|
2448
|
+
* Stand-ins for the version and upload time of each object version the run
|
|
2449
|
+
* sees, in the order it first sees them: versions count up, and the time is
|
|
2450
|
+
* the virtual time it was first seen.
|
|
1955
2451
|
*/
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
}
|
|
2452
|
+
var VersionBook = class {
|
|
2453
|
+
seen = /* @__PURE__ */ new Map();
|
|
2454
|
+
clear() {
|
|
2455
|
+
this.seen.clear();
|
|
2456
|
+
}
|
|
2457
|
+
standIn(realVersion, at) {
|
|
2458
|
+
let s = this.seen.get(realVersion);
|
|
2459
|
+
if (!s) {
|
|
2460
|
+
s = {
|
|
2461
|
+
version: (this.seen.size + 1).toString(16).padStart(32, "0"),
|
|
2462
|
+
uploaded: new Date(at)
|
|
2463
|
+
};
|
|
2464
|
+
this.seen.set(realVersion, s);
|
|
1968
2465
|
}
|
|
2466
|
+
return {
|
|
2467
|
+
version: s.version,
|
|
2468
|
+
uploaded: new Date(s.uploaded.getTime())
|
|
2469
|
+
};
|
|
1969
2470
|
}
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
version
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
...input.specs ? { specs: input.specs } : {}
|
|
2471
|
+
};
|
|
2472
|
+
/** An object's metadata, with stand-ins for its version and upload time. */
|
|
2473
|
+
function metadata(real, book, at) {
|
|
2474
|
+
const { version, uploaded } = book.standIn(real.version, at);
|
|
2475
|
+
return {
|
|
2476
|
+
key: real.key,
|
|
2477
|
+
version,
|
|
2478
|
+
size: real.size,
|
|
2479
|
+
etag: real.etag,
|
|
2480
|
+
httpEtag: real.httpEtag,
|
|
2481
|
+
uploaded,
|
|
2482
|
+
httpMetadata: real.httpMetadata,
|
|
2483
|
+
customMetadata: real.customMetadata,
|
|
2484
|
+
range: real.range,
|
|
2485
|
+
checksums: real.checksums,
|
|
2486
|
+
storageClass: real.storageClass,
|
|
2487
|
+
ssecKeyMd5: real.ssecKeyMd5,
|
|
2488
|
+
writeHttpMetadata: (headers) => real.writeHttpMetadata(headers)
|
|
1989
2489
|
};
|
|
1990
|
-
const errors = [
|
|
1991
|
-
...validateScenario(spec),
|
|
1992
|
-
...validateDurableObjectSetups(spec.setup),
|
|
1993
|
-
...drive.kind === "http" ? validateHttpDrive(drive) : [],
|
|
1994
|
-
...drive.kind === "rpc" ? validateRpcDrive(drive) : [],
|
|
1995
|
-
...drive.kind === "cron" ? validateCronDrive(drive) : [],
|
|
1996
|
-
...drive.kind === "websocket" ? validateWebSocketDrive(drive) : []
|
|
1997
|
-
];
|
|
1998
|
-
if (errors.length > 0) throw new Error(`invalid scenario ${JSON.stringify(input.name)}:\n- ${errors.join("\n- ")}`);
|
|
1999
|
-
return spec;
|
|
2000
2490
|
}
|
|
2001
|
-
// packages/cloudflare/src/services.ts
|
|
2002
2491
|
/**
|
|
2003
|
-
*
|
|
2004
|
-
*
|
|
2005
|
-
*
|
|
2006
|
-
* binding is never called here: the scenario's `service()` setup scripts the
|
|
2007
|
-
* replies, and each call is one effect with the faults of a Durable Object
|
|
2008
|
-
* stub call, where `crash_before` and `error` mean the call never reached
|
|
2009
|
-
* the callee, `ambiguous` that it acted and the answer was lost, and
|
|
2010
|
-
* `crash_after` that the caller died after it.
|
|
2492
|
+
* The bytes behind each body stream the proxy hands out. The stream itself
|
|
2493
|
+
* has no known length, which the runtime's put requires, so a put given one
|
|
2494
|
+
* (copying an object) is given its bytes instead.
|
|
2011
2495
|
*/
|
|
2012
|
-
|
|
2013
|
-
const otherKinds = [
|
|
2014
|
-
"prepare",
|
|
2015
|
-
"idFromName",
|
|
2016
|
-
"head",
|
|
2017
|
-
"createBatch"
|
|
2018
|
-
];
|
|
2496
|
+
const buffered = /* @__PURE__ */ new WeakMap();
|
|
2019
2497
|
/**
|
|
2020
|
-
*
|
|
2021
|
-
*
|
|
2022
|
-
*
|
|
2023
|
-
*
|
|
2024
|
-
* kinds' marks) serves test doubles.
|
|
2498
|
+
* An object with its body, already read: the stream and the body methods
|
|
2499
|
+
* share one consumption, as a real body's do. A method fails once the
|
|
2500
|
+
* stream is read, cancelled or locked by a reader; the stream ends empty
|
|
2501
|
+
* once a method has read the body.
|
|
2025
2502
|
*/
|
|
2026
|
-
function
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2503
|
+
function withBody(meta, bytes) {
|
|
2504
|
+
let used = false;
|
|
2505
|
+
let stream;
|
|
2506
|
+
const take = () => {
|
|
2507
|
+
if (used || stream?.locked) throw new TypeError("Body has already been used");
|
|
2508
|
+
used = true;
|
|
2509
|
+
return bytes.slice();
|
|
2510
|
+
};
|
|
2511
|
+
return Object.defineProperties(meta, {
|
|
2512
|
+
body: {
|
|
2513
|
+
enumerable: true,
|
|
2514
|
+
get: () => {
|
|
2515
|
+
stream ??= new ReadableStream({
|
|
2516
|
+
pull(controller) {
|
|
2517
|
+
if (!used) controller.enqueue(bytes.slice());
|
|
2518
|
+
used = true;
|
|
2519
|
+
controller.close();
|
|
2520
|
+
},
|
|
2521
|
+
cancel() {
|
|
2522
|
+
used = true;
|
|
2523
|
+
}
|
|
2524
|
+
}, { highWaterMark: 0 });
|
|
2525
|
+
buffered.set(stream, take);
|
|
2526
|
+
return stream;
|
|
2527
|
+
}
|
|
2528
|
+
},
|
|
2529
|
+
bodyUsed: {
|
|
2530
|
+
enumerable: true,
|
|
2531
|
+
get: () => used
|
|
2532
|
+
},
|
|
2533
|
+
arrayBuffer: { value: async () => take().buffer },
|
|
2534
|
+
bytes: { value: async () => take() },
|
|
2535
|
+
text: { value: async () => new TextDecoder().decode(take()) },
|
|
2536
|
+
json: { value: async () => JSON.parse(new TextDecoder().decode(take())) },
|
|
2537
|
+
blob: { value: async () => new Blob([take()]) }
|
|
2538
|
+
});
|
|
2033
2539
|
}
|
|
2034
|
-
/**
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
RangeError,
|
|
2039
|
-
ReferenceError,
|
|
2040
|
-
SyntaxError,
|
|
2041
|
-
TypeError,
|
|
2042
|
-
URIError
|
|
2043
|
-
};
|
|
2044
|
-
/**
|
|
2045
|
-
* The error the caller sees for a `throws` reply, `"<Name>: <message>"`: a
|
|
2046
|
-
* built-in error class is that class, so `instanceof` holds as it does over
|
|
2047
|
-
* RPC; any other name is an `Error` carrying the name.
|
|
2048
|
-
*/
|
|
2049
|
-
function scriptedError(spec) {
|
|
2050
|
-
const at = spec.indexOf(": ");
|
|
2051
|
-
if (at < 0) return new Error(spec);
|
|
2052
|
-
const name = spec.slice(0, at);
|
|
2053
|
-
const message = spec.slice(at + 2);
|
|
2054
|
-
const builtIn = builtInErrors[name];
|
|
2055
|
-
if (builtIn) return new builtIn(message);
|
|
2056
|
-
const error = new Error(message);
|
|
2057
|
-
error.name = name;
|
|
2058
|
-
return error;
|
|
2540
|
+
/** Conditions as the trace keeps them: a `Headers` object by its entries. */
|
|
2541
|
+
function conditions(onlyIf) {
|
|
2542
|
+
if (onlyIf === void 0) return {};
|
|
2543
|
+
return { onlyIf: onlyIf instanceof Headers ? Object.fromEntries(onlyIf.entries()) : onlyIf };
|
|
2059
2544
|
}
|
|
2060
|
-
/**
|
|
2061
|
-
function
|
|
2062
|
-
|
|
2063
|
-
|
|
2545
|
+
/** What the trace keeps of a get's options: the conditions and range, never an encryption key. */
|
|
2546
|
+
function getArgs(key, options) {
|
|
2547
|
+
return toJson({
|
|
2548
|
+
key,
|
|
2549
|
+
...conditions(options?.onlyIf),
|
|
2550
|
+
...options?.range === void 0 ? {} : { range: options.range }
|
|
2551
|
+
});
|
|
2552
|
+
}
|
|
2553
|
+
/** What the trace keeps of a put's options: the conditions and metadata, not checksums or keys. */
|
|
2554
|
+
function putArgs(options) {
|
|
2555
|
+
if (!options) return {};
|
|
2556
|
+
return toJson({
|
|
2557
|
+
...conditions(options.onlyIf),
|
|
2558
|
+
...options.customMetadata === void 0 ? {} : { customMetadata: options.customMetadata },
|
|
2559
|
+
...options.httpMetadata === void 0 ? {} : { httpMetadata: options.httpMetadata }
|
|
2560
|
+
});
|
|
2561
|
+
}
|
|
2562
|
+
function proxyR2(real, binding, ctx, book) {
|
|
2563
|
+
const target = `R2:${binding}`;
|
|
2564
|
+
const point = (op, args, allowed) => ({
|
|
2064
2565
|
invocation: ctx.currentInvocation(),
|
|
2065
2566
|
target,
|
|
2066
2567
|
op,
|
|
2067
2568
|
args,
|
|
2068
|
-
allowed
|
|
2569
|
+
allowed
|
|
2069
2570
|
});
|
|
2070
|
-
const
|
|
2071
|
-
const reason = `
|
|
2571
|
+
const notModelled = (what) => {
|
|
2572
|
+
const reason = `R2 ${binding}: ${what} is not modelled`;
|
|
2072
2573
|
ctx.hooks.unsupported(reason);
|
|
2073
2574
|
throw new Error(`eutaxy: ${reason}`);
|
|
2074
2575
|
};
|
|
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);
|
|
2576
|
+
/** Date conditions compare the store's real upload time, not the stand-in the Worker saw. */
|
|
2577
|
+
const checkConditions = (onlyIf) => {
|
|
2578
|
+
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
2579
|
};
|
|
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);
|
|
2580
|
+
const described = (o) => o === null ? { found: false } : {
|
|
2581
|
+
found: true,
|
|
2582
|
+
key: o.key,
|
|
2583
|
+
size: o.size,
|
|
2584
|
+
etag: o.etag
|
|
2113
2585
|
};
|
|
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
|
-
|
|
2586
|
+
return {
|
|
2587
|
+
put: (key, value, options) => ctx.hooks.effect(point("put", {
|
|
2588
|
+
key,
|
|
2589
|
+
...putArgs(options)
|
|
2590
|
+
}, writeFaults), async () => {
|
|
2591
|
+
checkConditions(options?.onlyIf);
|
|
2592
|
+
const read = value instanceof ReadableStream ? buffered.get(value) : void 0;
|
|
2593
|
+
const stored = await real.put(key, read ? read() : value, options);
|
|
2594
|
+
return stored === null ? null : metadata(stored, book, Date.now());
|
|
2595
|
+
}, (o) => o === null ? { stored: false } : {
|
|
2596
|
+
stored: true,
|
|
2597
|
+
size: o.size,
|
|
2598
|
+
etag: o.etag
|
|
2599
|
+
}),
|
|
2600
|
+
delete: (keys) => ctx.hooks.effect(point("delete", { keys: typeof keys === "string" ? [keys] : [...keys] }, writeFaults), () => real.delete(keys), () => null),
|
|
2601
|
+
get: (key, options) => ctx.hooks.effect(point("get", getArgs(key, options), readFaults), async () => {
|
|
2602
|
+
checkConditions(options?.onlyIf);
|
|
2603
|
+
const o = await real.get(key, options);
|
|
2604
|
+
if (o === null) return null;
|
|
2605
|
+
const meta = metadata(o, book, Date.now());
|
|
2606
|
+
if (!("body" in o)) return meta;
|
|
2607
|
+
return withBody(meta, new Uint8Array(await o.arrayBuffer()));
|
|
2608
|
+
}, (o) => ({
|
|
2609
|
+
...described(o),
|
|
2610
|
+
...o !== null ? { body: "body" in o } : {}
|
|
2611
|
+
})),
|
|
2612
|
+
head: (key) => ctx.hooks.effect(point("head", { key }, readFaults), async () => {
|
|
2613
|
+
const o = await real.head(key);
|
|
2614
|
+
return o === null ? null : metadata(o, book, Date.now());
|
|
2615
|
+
}, described),
|
|
2616
|
+
list: (options) => ctx.hooks.effect(point("list", toJson(options ?? {}), readFaults), async () => {
|
|
2617
|
+
const listed = await real.list(options);
|
|
2618
|
+
const at = Date.now();
|
|
2619
|
+
return {
|
|
2620
|
+
...listed,
|
|
2621
|
+
objects: listed.objects.map((o) => metadata(o, book, at))
|
|
2622
|
+
};
|
|
2623
|
+
}, (l) => ({
|
|
2624
|
+
keys: l.objects.map((o) => o.key),
|
|
2625
|
+
truncated: l.truncated,
|
|
2626
|
+
delimitedPrefixes: l.delimitedPrefixes
|
|
2627
|
+
})),
|
|
2628
|
+
createMultipartUpload: () => notModelled("createMultipartUpload()"),
|
|
2629
|
+
resumeMultipartUpload: () => notModelled("resumeMultipartUpload()")
|
|
2136
2630
|
};
|
|
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
2631
|
}
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
|
|
2154
|
-
|
|
2155
|
-
|
|
2156
|
-
this.env = env;
|
|
2632
|
+
/** Every object of the bucket, through all pages of a listing. */
|
|
2633
|
+
async function allObjects(real) {
|
|
2634
|
+
const out = [];
|
|
2635
|
+
let cursor;
|
|
2636
|
+
for (;;) {
|
|
2637
|
+
const page = await real.list({
|
|
2638
|
+
include: ["customMetadata", "httpMetadata"],
|
|
2639
|
+
...cursor === void 0 ? {} : { cursor }
|
|
2640
|
+
});
|
|
2641
|
+
out.push(...page.objects);
|
|
2642
|
+
if (!page.truncated) return out;
|
|
2643
|
+
cursor = page.cursor;
|
|
2157
2644
|
}
|
|
2158
|
-
}
|
|
2645
|
+
}
|
|
2646
|
+
/** Empty the bucket and put its seeds, before a run. */
|
|
2647
|
+
async function resetR2(real, seeds) {
|
|
2648
|
+
const keys = (await allObjects(real)).map((o) => o.key);
|
|
2649
|
+
for (let i = 0; i < keys.length; i += 1e3) await real.delete(keys.slice(i, i + 1e3));
|
|
2650
|
+
for (const [key, seed] of Object.entries(seeds)) if (typeof seed === "string") await real.put(key, seed);
|
|
2651
|
+
else await real.put(key, seed.value, {
|
|
2652
|
+
...seed.customMetadata ? { customMetadata: { ...seed.customMetadata } } : {},
|
|
2653
|
+
...seed.httpMetadata ? { httpMetadata: { ...seed.httpMetadata } } : {}
|
|
2654
|
+
});
|
|
2655
|
+
}
|
|
2656
|
+
/** Largest object whose text the snapshot keeps. */
|
|
2657
|
+
const snapshotTextLimit = 4096;
|
|
2159
2658
|
/**
|
|
2160
|
-
*
|
|
2161
|
-
*
|
|
2162
|
-
*
|
|
2163
|
-
*
|
|
2164
|
-
* written, and the base is put back before anything else can run.
|
|
2659
|
+
* The bucket's objects as rows `{ key, size, etag, customMetadata,
|
|
2660
|
+
* httpMetadata, text? }` by key, `text` for an object of up to 4 KiB that is
|
|
2661
|
+
* valid UTF-8. Versions and upload times are left out: they are the store's,
|
|
2662
|
+
* not the Worker's.
|
|
2165
2663
|
*/
|
|
2166
|
-
function
|
|
2167
|
-
|
|
2168
|
-
|
|
2169
|
-
for (
|
|
2170
|
-
|
|
2171
|
-
if (
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
|
|
2177
|
-
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2664
|
+
async function snapshotR2(real) {
|
|
2665
|
+
const rows = [];
|
|
2666
|
+
const objects = (await allObjects(real)).sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
|
|
2667
|
+
for (const o of objects) {
|
|
2668
|
+
let text;
|
|
2669
|
+
if (o.size <= snapshotTextLimit) {
|
|
2670
|
+
const body = await real.get(o.key);
|
|
2671
|
+
if (body && "body" in body) try {
|
|
2672
|
+
text = new TextDecoder("utf-8", {
|
|
2673
|
+
fatal: true,
|
|
2674
|
+
ignoreBOM: false
|
|
2675
|
+
}).decode(await body.arrayBuffer());
|
|
2676
|
+
} catch {}
|
|
2677
|
+
}
|
|
2678
|
+
rows.push(toJson({
|
|
2679
|
+
key: o.key,
|
|
2680
|
+
size: o.size,
|
|
2681
|
+
etag: o.etag,
|
|
2682
|
+
customMetadata: o.customMetadata ?? {},
|
|
2683
|
+
httpMetadata: o.httpMetadata ?? {},
|
|
2684
|
+
...text === void 0 ? {} : { text }
|
|
2685
|
+
}));
|
|
2181
2686
|
}
|
|
2687
|
+
return rows;
|
|
2182
2688
|
}
|
|
2183
2689
|
// packages/cloudflare/src/workflows.ts
|
|
2184
2690
|
/**
|
|
@@ -2673,7 +3179,7 @@ async function deliverWorkflow(event, hooks, d) {
|
|
|
2673
3179
|
retries: { ...resolved.retries }
|
|
2674
3180
|
}
|
|
2675
3181
|
};
|
|
2676
|
-
wait = await retryDelayMs
|
|
3182
|
+
wait = await retryDelayMs(retries, attempt, delayContext, thrown);
|
|
2677
3183
|
} catch (err) {
|
|
2678
3184
|
hooks.unsupported(`Workflow ${d.binding}: step "${name}"'s retry delay function threw (${String(err)})`);
|
|
2679
3185
|
throw err;
|
|
@@ -2924,7 +3430,7 @@ async function deliverWorkflow(event, hooks, d) {
|
|
|
2924
3430
|
};
|
|
2925
3431
|
}
|
|
2926
3432
|
/** The delay before the next attempt (Workflows, Sleeping and retrying; a delay function is called). */
|
|
2927
|
-
async function retryDelayMs
|
|
3433
|
+
async function retryDelayMs(retries, attempt, ctx, error) {
|
|
2928
3434
|
const base = durationMs(typeof retries.delay === "function" ? await retries.delay({
|
|
2929
3435
|
ctx,
|
|
2930
3436
|
error
|
|
@@ -3134,10 +3640,11 @@ function workflowBinding(deps) {
|
|
|
3134
3640
|
followUps: []
|
|
3135
3641
|
};
|
|
3136
3642
|
const className = setup.className;
|
|
3137
|
-
const
|
|
3643
|
+
const callee = deps.calleeOf?.(binding);
|
|
3644
|
+
const cls = (callee?.exports ?? deps.exports)?.[className];
|
|
3138
3645
|
const instance = registryFor(binding).instances.get(id);
|
|
3139
3646
|
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 })`);
|
|
3647
|
+
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
3648
|
return {
|
|
3142
3649
|
status: "errored",
|
|
3143
3650
|
followUps: []
|
|
@@ -3148,7 +3655,7 @@ function workflowBinding(deps) {
|
|
|
3148
3655
|
...setup.name === void 0 ? {} : { name: setup.name },
|
|
3149
3656
|
instance,
|
|
3150
3657
|
cls,
|
|
3151
|
-
env: deps.env(),
|
|
3658
|
+
env: callee ? calleeEnv(callee.name, deps.env()) : deps.env(),
|
|
3152
3659
|
maxFaultsPerRun: spec.bounds.maxFaultsPerRun,
|
|
3153
3660
|
maxRedeliveries: spec.bounds.maxRedeliveries
|
|
3154
3661
|
});
|
|
@@ -3156,6 +3663,54 @@ function workflowBinding(deps) {
|
|
|
3156
3663
|
};
|
|
3157
3664
|
}
|
|
3158
3665
|
/**
|
|
3666
|
+
* A service binding whose callee runs for real (a `callee` setup step): a
|
|
3667
|
+
* stub running the callee's module inside each call. Never the real binding.
|
|
3668
|
+
* Nothing to reset or snapshot of its own: the callee's bindings have their
|
|
3669
|
+
* own steps under their qualified names. A binding without a `callee` step
|
|
3670
|
+
* is not this record's.
|
|
3671
|
+
*/
|
|
3672
|
+
function calleeBinding(deps) {
|
|
3673
|
+
/** The bindings the current scenario names a callee for. */
|
|
3674
|
+
let setups = /* @__PURE__ */ new Map();
|
|
3675
|
+
const proxies = /* @__PURE__ */ new Map();
|
|
3676
|
+
const state = new CalleeState();
|
|
3677
|
+
return {
|
|
3678
|
+
kind: "callee",
|
|
3679
|
+
target: "Service",
|
|
3680
|
+
is: isServiceBinding,
|
|
3681
|
+
proxy(name, _real, ctx) {
|
|
3682
|
+
const setup = setups.get(name);
|
|
3683
|
+
if (!setup) return void 0;
|
|
3684
|
+
let p = proxies.get(name);
|
|
3685
|
+
if (!p) {
|
|
3686
|
+
const module = deps.callees?.[name];
|
|
3687
|
+
if (!module) {
|
|
3688
|
+
ctx.hooks.unsupported(`callee ${name}: the platform was not given its module; pass createCloudflarePlatform({ ..., callees: { ${name}: { name, exports } } }) (eutaxy check does not load callees yet)`);
|
|
3689
|
+
return proxyService(name, ctx, {
|
|
3690
|
+
kind: "service",
|
|
3691
|
+
binding: name,
|
|
3692
|
+
methods: {}
|
|
3693
|
+
});
|
|
3694
|
+
}
|
|
3695
|
+
p = proxyCallee(name, ctx, setup, module, deps.env(), state);
|
|
3696
|
+
proxies.set(name, p);
|
|
3697
|
+
}
|
|
3698
|
+
return p;
|
|
3699
|
+
},
|
|
3700
|
+
clear() {
|
|
3701
|
+
setups = /* @__PURE__ */ new Map();
|
|
3702
|
+
proxies.clear();
|
|
3703
|
+
state.clear();
|
|
3704
|
+
},
|
|
3705
|
+
async reset(step) {
|
|
3706
|
+
setups.set(step.binding, step);
|
|
3707
|
+
},
|
|
3708
|
+
async snapshot() {
|
|
3709
|
+
return null;
|
|
3710
|
+
}
|
|
3711
|
+
};
|
|
3712
|
+
}
|
|
3713
|
+
/**
|
|
3159
3714
|
* A service binding: never the real binding, a stub answering from the
|
|
3160
3715
|
* scenario's `service` setup; each call one effect. Nothing to reset or
|
|
3161
3716
|
* snapshot, the callee is scripted.
|
|
@@ -3211,69 +3766,6 @@ function ownedSetups(setup, bindings) {
|
|
|
3211
3766
|
}
|
|
3212
3767
|
return out;
|
|
3213
3768
|
}
|
|
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
3769
|
// packages/cloudflare/src/http.ts
|
|
3278
3770
|
/** The URL inbound requests are addressed to; handlers read only the path. */
|
|
3279
3771
|
const requestOrigin = "https://worker.test";
|
|
@@ -3464,117 +3956,6 @@ async function deliverMessage$1(event, hooks, spec, drive, invocation, worker, m
|
|
|
3464
3956
|
followUps
|
|
3465
3957
|
};
|
|
3466
3958
|
}
|
|
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
3959
|
// packages/cloudflare/src/scheduled.ts
|
|
3579
3960
|
/**
|
|
3580
3961
|
* Cron Trigger delivery: one invocation of the Worker's `scheduled()` handler
|
|
@@ -4158,7 +4539,9 @@ const assumptions = [
|
|
|
4158
4539
|
"D1 statements run against Miniflare's SQLite; each run/first/all/raw/batch/exec is one effect",
|
|
4159
4540
|
"message.timestamp is the virtual clock's time at delivery",
|
|
4160
4541
|
"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",
|
|
4542
|
+
"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",
|
|
4543
|
+
"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",
|
|
4544
|
+
"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
4545
|
"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
4546
|
"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
4547
|
"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)",
|
|
@@ -4172,6 +4555,9 @@ const assumptions = [
|
|
|
4172
4555
|
];
|
|
4173
4556
|
function createCloudflarePlatform(options) {
|
|
4174
4557
|
const env = options.env;
|
|
4558
|
+
const aliases = options.aliases ?? {};
|
|
4559
|
+
/** The name a binding is known by: itself, or the name it is an alias of. */
|
|
4560
|
+
const canonical = (name) => aliases[name] ?? name;
|
|
4175
4561
|
const maxRetries = options.maxRetries ?? 3;
|
|
4176
4562
|
let hooksRef = null;
|
|
4177
4563
|
const connections = new Connections();
|
|
@@ -4185,8 +4571,8 @@ function createCloudflarePlatform(options) {
|
|
|
4185
4571
|
};
|
|
4186
4572
|
/**
|
|
4187
4573
|
* The kinds of binding modelled, in the order an env value is tried against
|
|
4188
|
-
* them:
|
|
4189
|
-
* type (
|
|
4574
|
+
* them: service bindings first (a callee's, then scripted), since in workerd
|
|
4575
|
+
* they answer every duck type (their property reads are RPC stubs).
|
|
4190
4576
|
*/
|
|
4191
4577
|
const durable = durableObjectBinding({
|
|
4192
4578
|
ctx,
|
|
@@ -4194,28 +4580,53 @@ function createCloudflarePlatform(options) {
|
|
|
4194
4580
|
real: (name) => env[name]
|
|
4195
4581
|
});
|
|
4196
4582
|
const bindings = [
|
|
4583
|
+
calleeBinding({
|
|
4584
|
+
callees: options.callees,
|
|
4585
|
+
env: () => proxiedEnv
|
|
4586
|
+
}),
|
|
4197
4587
|
serviceBinding(),
|
|
4198
4588
|
d1Binding(options.schemas),
|
|
4199
4589
|
durable,
|
|
4200
4590
|
r2Binding(),
|
|
4201
4591
|
workflowBinding({
|
|
4202
4592
|
exports: options.exports,
|
|
4203
|
-
env: () => proxiedEnv
|
|
4593
|
+
env: () => proxiedEnv,
|
|
4594
|
+
calleeOf: (binding) => {
|
|
4595
|
+
const at = binding.indexOf("/");
|
|
4596
|
+
if (at < 0) return void 0;
|
|
4597
|
+
const name = binding.slice(0, at);
|
|
4598
|
+
return Object.values(options.callees ?? {}).find((c) => c.name === name);
|
|
4599
|
+
}
|
|
4204
4600
|
})
|
|
4205
4601
|
];
|
|
4206
4602
|
const own = (prop) => typeof prop !== "string" || !prop.startsWith("__VITEST_POOL_WORKERS_");
|
|
4603
|
+
const aliasKeys = Object.keys(aliases).filter((a) => canonical(a) in env);
|
|
4207
4604
|
const proxiedEnv = new Proxy(env, {
|
|
4208
4605
|
get(target, prop, receiver) {
|
|
4209
4606
|
if (!own(prop)) return void 0;
|
|
4210
|
-
|
|
4211
|
-
|
|
4212
|
-
|
|
4213
|
-
|
|
4607
|
+
if (typeof prop !== "string") return Reflect.get(target, prop, receiver);
|
|
4608
|
+
const name = canonical(prop);
|
|
4609
|
+
const value = Reflect.get(target, name, receiver);
|
|
4610
|
+
for (const binding of bindings) {
|
|
4611
|
+
if (!binding.is(value)) continue;
|
|
4612
|
+
const proxied = binding.proxy(name, value, ctx);
|
|
4613
|
+
if (proxied !== void 0) return proxied;
|
|
4614
|
+
}
|
|
4615
|
+
if (isBindingLike(value)) ctx.hooks.unsupported(`binding ${name} is not proxied`);
|
|
4214
4616
|
return value;
|
|
4215
4617
|
},
|
|
4216
|
-
has: (target, prop) => own(prop) && Reflect.has(target, prop),
|
|
4217
|
-
ownKeys: (target) => Reflect.ownKeys(target).filter(own),
|
|
4218
|
-
getOwnPropertyDescriptor: (target, prop) =>
|
|
4618
|
+
has: (target, prop) => own(prop) && (Reflect.has(target, prop) || typeof prop === "string" && aliasKeys.includes(prop)),
|
|
4619
|
+
ownKeys: (target) => [.../* @__PURE__ */ new Set([...Reflect.ownKeys(target).filter(own), ...aliasKeys])],
|
|
4620
|
+
getOwnPropertyDescriptor: (target, prop) => {
|
|
4621
|
+
if (!own(prop)) return void 0;
|
|
4622
|
+
if (typeof prop === "string" && aliasKeys.includes(prop)) return {
|
|
4623
|
+
value: env[canonical(prop)],
|
|
4624
|
+
enumerable: true,
|
|
4625
|
+
configurable: true,
|
|
4626
|
+
writable: false
|
|
4627
|
+
};
|
|
4628
|
+
return Reflect.getOwnPropertyDescriptor(target, prop);
|
|
4629
|
+
}
|
|
4219
4630
|
});
|
|
4220
4631
|
const worker = {
|
|
4221
4632
|
handler: typeof options.handler === "function" ? {} : options.handler,
|
|
@@ -4228,7 +4639,10 @@ function createCloudflarePlatform(options) {
|
|
|
4228
4639
|
async reset(spec) {
|
|
4229
4640
|
await connections.clear();
|
|
4230
4641
|
for (const binding of bindings) binding.clear();
|
|
4231
|
-
for (const [binding, setup] of ownedSetups(spec.setup, bindings))
|
|
4642
|
+
for (const [binding, setup] of ownedSetups(spec.setup, bindings)) {
|
|
4643
|
+
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)}`);
|
|
4644
|
+
await binding.reset(setup, env[setup.binding]);
|
|
4645
|
+
}
|
|
4232
4646
|
},
|
|
4233
4647
|
restrictEvents(spec, keepIds) {
|
|
4234
4648
|
return {
|
|
@@ -4615,6 +5029,7 @@ async function rawSide(spec, options) {
|
|
|
4615
5029
|
/** Run both sides and compare. The Eutaxy side runs first; both start from the schema. */
|
|
4616
5030
|
async function runDifferential(spec, options) {
|
|
4617
5031
|
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");
|
|
5032
|
+
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
5033
|
const { unsupported, ...eutaxy } = await eutaxySide(spec, options);
|
|
4619
5034
|
const raw = await rawSide(spec, options);
|
|
4620
5035
|
const differences = compareSides({
|
|
@@ -4725,7 +5140,10 @@ async function selectSpecModules(scenario, modules, specEntries) {
|
|
|
4725
5140
|
/** Run the scenario's check, with its specs observed, and return what the CLI reads back. */
|
|
4726
5141
|
async function checkInWorkerd(input) {
|
|
4727
5142
|
const { scenario } = input;
|
|
4728
|
-
const schemas = schemasFor(scenario,
|
|
5143
|
+
const schemas = schemasFor(scenario, {
|
|
5144
|
+
...input.sqlFiles,
|
|
5145
|
+
...input.extraSql
|
|
5146
|
+
});
|
|
4729
5147
|
const load = input.modules[globKey(scenario.worker.entry)];
|
|
4730
5148
|
if (!load) throw new Error(`worker entry ${scenario.worker.entry} not found next to the scenario`);
|
|
4731
5149
|
const worker = await load();
|
|
@@ -4734,13 +5152,21 @@ async function checkInWorkerd(input) {
|
|
|
4734
5152
|
handler: worker.default,
|
|
4735
5153
|
schemas,
|
|
4736
5154
|
durableObjects: input.durableObjects,
|
|
4737
|
-
exports: worker
|
|
5155
|
+
exports: worker,
|
|
5156
|
+
...input.callees === void 0 ? {} : { callees: input.callees },
|
|
5157
|
+
...input.aliases === void 0 ? {} : { aliases: input.aliases }
|
|
4738
5158
|
});
|
|
4739
5159
|
const { selected, specErrors } = await selectSpecModules(scenario, input.modules, input.specEntries);
|
|
4740
5160
|
const transportBase = {
|
|
4741
5161
|
worker: scenario.worker,
|
|
4742
5162
|
setup: scenario.setup,
|
|
4743
|
-
drive: scenario.drive
|
|
5163
|
+
drive: scenario.drive,
|
|
5164
|
+
...input.callees === void 0 ? {} : { callees: Object.fromEntries(Object.entries(input.callees).map(([binding, c]) => [binding, {
|
|
5165
|
+
name: c.name,
|
|
5166
|
+
...c.entrypoint === void 0 ? {} : { entrypoint: c.entrypoint },
|
|
5167
|
+
...c.props === void 0 ? {} : { props: c.props }
|
|
5168
|
+
}])) },
|
|
5169
|
+
...input.aliases === void 0 ? {} : { aliases: input.aliases }
|
|
4744
5170
|
};
|
|
4745
5171
|
if (specErrors.length > 0) return {
|
|
4746
5172
|
report: null,
|
|
@@ -4769,6 +5195,6 @@ async function checkInWorkerd(input) {
|
|
|
4769
5195
|
}))
|
|
4770
5196
|
};
|
|
4771
5197
|
}
|
|
4772
|
-
export {
|
|
5198
|
+
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
5199
|
|
|
4774
|
-
//# sourceMappingURL=workerd-
|
|
5200
|
+
//# sourceMappingURL=workerd-DVJ8eCLI.mjs.map
|