dynamo-bao 0.9.0 → 0.10.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.
@@ -0,0 +1,400 @@
1
+ /**
2
+ * The executor: a fetch handler that runs envelopes of procedure calls next
3
+ * to DynamoDB.
4
+ *
5
+ * Request: { v: 1, operationId, requestId?, actor?, calls: [{ id, proc, tenant, args?, actor?, scope? }] }
6
+ * Response: { v: 1, placement: { colo, region }, calls: { [id]: outcome } }
7
+ * Outcome: { ok: value, capacity, ms } | { error: { name, message, ... }, capacity, ms }
8
+ *
9
+ * Envelope-level failures (ingress, malformed envelope, budget) answer with
10
+ * a non-200 status and `{ v: 1, error: { name, message } }`; no call ran.
11
+ * @module remote/executor
12
+ */
13
+ const { ulid } = require("ulid");
14
+ const { ProcedureRegistry } = require("./procedures");
15
+ const { createContext, runInCall, WAIT_UNTIL_CAP_MS } = require("./context");
16
+ const { encodeValue } = require("./codec");
17
+ const { isPlainObject } = require("./json");
18
+
19
+ const PROTOCOL_VERSION = 1;
20
+ const DEFAULT_BUDGET = Object.freeze({
21
+ maxCalls: 8,
22
+ maxRequestBytes: 1_000_000,
23
+ maxResponseBytes: 1_000_000,
24
+ });
25
+ const TENANT = /^[^\]#]+$/;
26
+ const utf8 = new TextEncoder();
27
+ /** Budgets are in bytes on the wire, not UTF-16 code units. */
28
+ const byteLength = (text) => utf8.encode(text).length;
29
+
30
+ class EnvelopeError extends Error {
31
+ constructor(name, message, status) {
32
+ super(message);
33
+ this.name = name;
34
+ this.status = status;
35
+ }
36
+ }
37
+
38
+ // Errors the executor raised before a procedure started. Kept here rather
39
+ // than as a property so a procedure can't mark its own error "refused" and
40
+ // tell the caller a resend is safe after it wrote.
41
+ const REFUSALS = new WeakSet();
42
+ // Errors raised after run returned (encoding its result): its writes, if
43
+ // any, have committed, so the caller must not treat the call as not done.
44
+ const EXECUTED = new WeakSet();
45
+
46
+ /** An executor refusal: the procedure did not start, so a resend is safe. */
47
+ function refusal(name, message) {
48
+ const e = new Error(message);
49
+ e.name = name;
50
+ REFUSALS.add(e);
51
+ return e;
52
+ }
53
+
54
+ /** Mark whatever the context resolver threw as a refusal. */
55
+ function asRefusal(thrown) {
56
+ const e =
57
+ thrown instanceof Error
58
+ ? thrown
59
+ : Object.assign(new Error(typeof thrown === "string" ? thrown : String(thrown)), { name: "Error" });
60
+ REFUSALS.add(e);
61
+ return e;
62
+ }
63
+
64
+ function json(status, body) {
65
+ return new Response(JSON.stringify(body), {
66
+ status,
67
+ headers: { "content-type": "application/json; charset=utf-8" },
68
+ });
69
+ }
70
+
71
+ function envelopeFailure(error) {
72
+ return json(error.status, {
73
+ v: PROTOCOL_VERSION,
74
+ error: { name: error.name, message: error.message },
75
+ });
76
+ }
77
+
78
+ /**
79
+ * The error part of an outcome. Names, messages and string or number codes
80
+ * cross; stacks do not. AWS errors (they carry `$metadata`) are marked
81
+ * `infrastructure` with their HTTP status.
82
+ * @private
83
+ */
84
+ function encodeError(error) {
85
+ if (!(error instanceof Error)) {
86
+ return { name: "Error", message: typeof error === "string" ? error : String(error) };
87
+ }
88
+ const out = { name: error.name || "Error", message: error.message || "" };
89
+ if (typeof error.code === "string" || typeof error.code === "number") {
90
+ out.code = error.code;
91
+ }
92
+ if (error.$metadata && typeof error.$metadata === "object") {
93
+ out.infrastructure = true;
94
+ if (typeof error.$metadata.httpStatusCode === "number") {
95
+ out.httpStatusCode = error.$metadata.httpStatusCode;
96
+ }
97
+ }
98
+ if (REFUSALS.has(error)) out.refused = true;
99
+ if (EXECUTED.has(error)) out.executed = true;
100
+ return out;
101
+ }
102
+
103
+ function validateEnvelope(envelope, budget) {
104
+ if (!isPlainObject(envelope)) {
105
+ throw new EnvelopeError("EnvelopeError", "the envelope must be a JSON object", 400);
106
+ }
107
+ if (envelope.v !== PROTOCOL_VERSION) {
108
+ throw new EnvelopeError(
109
+ "UnsupportedVersion",
110
+ `protocol version ${JSON.stringify(envelope.v)} is not supported; this executor speaks v${PROTOCOL_VERSION}`,
111
+ 400,
112
+ );
113
+ }
114
+ const { calls, operationId, requestId, actor } = envelope;
115
+ if (!Array.isArray(calls) || calls.length === 0) {
116
+ throw new EnvelopeError("EnvelopeError", "calls must be a non-empty array", 400);
117
+ }
118
+ if (calls.length > budget.maxCalls) {
119
+ throw new EnvelopeError(
120
+ "BudgetExceeded",
121
+ `the envelope has ${calls.length} calls; the budget allows ${budget.maxCalls}`,
122
+ 413,
123
+ );
124
+ }
125
+ if (typeof operationId !== "string" || operationId === "") {
126
+ throw new EnvelopeError("EnvelopeError", "operationId must be a non-empty string", 400);
127
+ }
128
+ if (requestId !== undefined && (typeof requestId !== "string" || requestId === "")) {
129
+ throw new EnvelopeError("EnvelopeError", "requestId must be a non-empty string", 400);
130
+ }
131
+ if (actor !== undefined && !isPlainObject(actor)) {
132
+ throw new EnvelopeError("EnvelopeError", "actor must be an object", 400);
133
+ }
134
+ const ids = new Set();
135
+ calls.forEach((call, i) => {
136
+ const at = `calls[${i}]`;
137
+ const bad = (field, what) =>
138
+ new EnvelopeError("EnvelopeError", `${at}.${field} ${what}`, 400);
139
+ if (!isPlainObject(call)) {
140
+ throw new EnvelopeError("EnvelopeError", `${at} must be an object`, 400);
141
+ }
142
+ if (typeof call.id !== "string" || call.id === "") throw bad("id", "must be a non-empty string");
143
+ if (ids.has(call.id)) {
144
+ throw new EnvelopeError("EnvelopeError", `duplicate call id ${JSON.stringify(call.id)}`, 400);
145
+ }
146
+ ids.add(call.id);
147
+ if (typeof call.proc !== "string" || call.proc === "") {
148
+ throw bad("proc", "must be a procedure id, name@version");
149
+ }
150
+ if (typeof call.tenant !== "string" || !TENANT.test(call.tenant)) {
151
+ throw bad("tenant", 'must be a non-empty string without "]" or "#"');
152
+ }
153
+ if (call.actor !== undefined && !isPlainObject(call.actor)) {
154
+ throw bad("actor", "must be an object");
155
+ }
156
+ if (call.actor === undefined && actor === undefined) {
157
+ throw bad("actor", "is missing and the envelope has no actor");
158
+ }
159
+ if (call.scope !== undefined && typeof call.scope !== "string") {
160
+ throw bad("scope", "must be a string");
161
+ }
162
+ });
163
+ }
164
+
165
+ /**
166
+ * Create the executor.
167
+ * @param {Object} options
168
+ * @param {ProcedureRegistry} options.procedures - What this deployment serves.
169
+ * @param {Function} options.context - The application's context resolver:
170
+ * `(call, env) => ({ models, adminModels?, adminPartition?, config? })`,
171
+ * sync or async, called once per call inside the call's tenant and batch
172
+ * context.
173
+ * @param {function(Request, *): (boolean|Promise<boolean>)} options.ingress -
174
+ * Decides whether a request may use the executor at all (for example by
175
+ * checking a binding secret header). Required: there is no open default.
176
+ * @param {Object} [options.budget] - `{ maxCalls, maxRequestBytes, maxResponseBytes }`;
177
+ * defaults 8, 1 MB, 1 MB.
178
+ * @param {string} [options.region] - Echoed as `placement.region`.
179
+ * @param {Object} [options.logger] - Base logger for `ctx.logger`.
180
+ * @param {function(): number} [options.now] - Clock for `ctx.now()`.
181
+ * @param {boolean} [options.plainReturns=false] - When true, a model instance
182
+ * in a result is an error: procedures must return plain views or
183
+ * explicitly encoded rows. Turn it on in tests.
184
+ * @param {number} [options.waitUntilCapMs=30000]
185
+ * @returns {{fetch: function(Request, *=, Object=): Promise<Response>, drain: function(): Promise<void>, procedures: ProcedureRegistry, budget: Object}}
186
+ */
187
+ function createExecutor(options = {}) {
188
+ const {
189
+ procedures,
190
+ context: resolve,
191
+ ingress,
192
+ budget: budgetOption = {},
193
+ region = null,
194
+ logger = console,
195
+ now = Date.now,
196
+ plainReturns = false,
197
+ waitUntilCapMs = WAIT_UNTIL_CAP_MS,
198
+ } = options;
199
+ if (!(procedures instanceof ProcedureRegistry)) {
200
+ throw new TypeError("createExecutor: procedures must be a ProcedureRegistry");
201
+ }
202
+ if (typeof resolve !== "function") {
203
+ throw new TypeError("createExecutor: context must be a context resolver function");
204
+ }
205
+ if (typeof ingress !== "function") {
206
+ throw new TypeError(
207
+ "createExecutor: ingress must be a function; pass () => true only if nothing public can reach the route",
208
+ );
209
+ }
210
+ const budget = Object.freeze({ ...DEFAULT_BUDGET, ...budgetOption });
211
+ const pending = new Set();
212
+
213
+ async function runCall(call, envelope, requestId, env, sink) {
214
+ const started = Date.now();
215
+ const descriptor = procedures.get(call.proc);
216
+ const actor = call.actor ?? envelope.actor;
217
+ const settled = await runInCall(call.tenant, async () => {
218
+ if (!descriptor) {
219
+ const name = typeof call.proc === "string" ? call.proc.split("@")[0] : "";
220
+ const served = procedures.versions(name);
221
+ throw refusal(
222
+ "UnknownProcedure",
223
+ `no procedure ${call.proc}` +
224
+ (served.length ? `; versions of ${name} served: ${served.join(", ")}` : ""),
225
+ );
226
+ }
227
+ if (call.scope !== undefined && call.scope !== descriptor.scope) {
228
+ throw refusal(
229
+ "ScopeError",
230
+ `${descriptor.id} is scope "${descriptor.scope}", the call says "${call.scope}"`,
231
+ );
232
+ }
233
+ if (actor.appId !== call.tenant) {
234
+ throw refusal(
235
+ "ActorTenantMismatch",
236
+ `the actor's appId does not match the call tenant for ${descriptor.id}`,
237
+ );
238
+ }
239
+ let ctx;
240
+ try {
241
+ const resolved = await resolve(
242
+ {
243
+ id: call.id,
244
+ proc: descriptor.id,
245
+ name: descriptor.name,
246
+ version: descriptor.version,
247
+ tenant: call.tenant,
248
+ scope: descriptor.scope,
249
+ replay: descriptor.replay,
250
+ actor,
251
+ requestId,
252
+ operationId: envelope.operationId,
253
+ },
254
+ env,
255
+ );
256
+ if (!resolved || typeof resolved !== "object" || !resolved.models) {
257
+ throw new TypeError(`the context resolver returned no models for ${descriptor.id}`);
258
+ }
259
+ if (descriptor.scope !== "app" && !resolved.adminModels) {
260
+ throw refusal(
261
+ "ScopeError",
262
+ `${descriptor.id} is scope "${descriptor.scope}" but the context resolver returned no adminModels`,
263
+ );
264
+ }
265
+ if (descriptor.scope !== "app" && !resolved.adminPartition) {
266
+ throw refusal(
267
+ "ScopeError",
268
+ `${descriptor.id} is scope "${descriptor.scope}" but the context resolver returned no adminPartition; ` +
269
+ "unbound admin models would write in the call's tenant",
270
+ );
271
+ }
272
+ ctx = createContext({
273
+ tenant: call.tenant,
274
+ actor,
275
+ models: resolved.models,
276
+ scope: descriptor.scope,
277
+ adminModels: resolved.adminModels,
278
+ adminPartition: resolved.adminPartition,
279
+ config: resolved.config ?? {},
280
+ requestId,
281
+ operationId: envelope.operationId,
282
+ logger,
283
+ now,
284
+ waitUntil: sink,
285
+ waitUntilCapMs,
286
+ });
287
+ } catch (error) {
288
+ throw asRefusal(error);
289
+ }
290
+ const result = await descriptor.run(ctx, call.args === undefined ? null : call.args);
291
+ try {
292
+ return encodeValue(result, { models: plainReturns ? "refuse" : "encode" });
293
+ } catch (error) {
294
+ EXECUTED.add(error); // encodeValue throws only CodecError objects
295
+ throw error;
296
+ }
297
+ });
298
+ const ms = Date.now() - started;
299
+ return "error" in settled
300
+ ? { error: encodeError(settled.error), capacity: settled.capacity, ms }
301
+ : { ok: settled.value, capacity: settled.capacity, ms };
302
+ }
303
+
304
+ function fitResponse(body) {
305
+ let text = JSON.stringify(body);
306
+ if (byteLength(text) <= budget.maxResponseBytes) return text;
307
+ const sizes = Object.entries(body.calls)
308
+ .map(([id, outcome]) => [id, byteLength(JSON.stringify(outcome))])
309
+ .sort((a, b) => b[1] - a[1]);
310
+ for (const [id, bytes] of sizes) {
311
+ const { capacity, ms } = body.calls[id];
312
+ body.calls[id] = {
313
+ error: {
314
+ name: "ResponseTooLarge",
315
+ message: `the result was ${bytes} bytes; the response budget is ${budget.maxResponseBytes}`,
316
+ executed: true,
317
+ },
318
+ capacity,
319
+ ms,
320
+ };
321
+ text = JSON.stringify(body);
322
+ if (byteLength(text) <= budget.maxResponseBytes) break;
323
+ }
324
+ return text;
325
+ }
326
+
327
+ async function fetch(request, env, platform) {
328
+ let allowed = false;
329
+ try {
330
+ allowed = (await ingress(request, env)) === true;
331
+ } catch {
332
+ allowed = false;
333
+ }
334
+ if (!allowed) {
335
+ return envelopeFailure(
336
+ new EnvelopeError("IngressRefused", "this route only accepts calls from the data binding", 403),
337
+ );
338
+ }
339
+ if (request.method !== "POST") {
340
+ return envelopeFailure(new EnvelopeError("EnvelopeError", "use POST", 405));
341
+ }
342
+ let envelope;
343
+ try {
344
+ let text;
345
+ try {
346
+ text = await request.text();
347
+ } catch {
348
+ throw new EnvelopeError("EnvelopeError", "the request body could not be read", 400);
349
+ }
350
+ const bytes = byteLength(text);
351
+ if (bytes > budget.maxRequestBytes) {
352
+ throw new EnvelopeError(
353
+ "BudgetExceeded",
354
+ `the request is ${bytes} bytes; the budget allows ${budget.maxRequestBytes}`,
355
+ 413,
356
+ );
357
+ }
358
+ try {
359
+ envelope = JSON.parse(text);
360
+ } catch {
361
+ throw new EnvelopeError("EnvelopeError", "the body is not JSON", 400);
362
+ }
363
+ validateEnvelope(envelope, budget);
364
+ } catch (error) {
365
+ return envelopeFailure(error);
366
+ }
367
+
368
+ const requestId = envelope.requestId ?? ulid();
369
+ const sink = (promise) => {
370
+ pending.add(promise);
371
+ promise.finally(() => pending.delete(promise));
372
+ if (platform && typeof platform.waitUntil === "function") platform.waitUntil(promise);
373
+ };
374
+ const outcomes = await Promise.all(
375
+ envelope.calls.map((call) => runCall(call, envelope, requestId, env, sink)),
376
+ );
377
+ const body = {
378
+ v: PROTOCOL_VERSION,
379
+ placement: { colo: request.cf?.colo ?? null, region },
380
+ // fromEntries defines own properties, so an id such as "__proto__" keeps its outcome
381
+ calls: Object.fromEntries(envelope.calls.map((call, i) => [call.id, outcomes[i]])),
382
+ };
383
+ return new Response(fitResponse(body), {
384
+ status: 200,
385
+ headers: { "content-type": "application/json; charset=utf-8" },
386
+ });
387
+ }
388
+
389
+ return Object.freeze({
390
+ fetch,
391
+ /** Resolve once every deferred piece of work handed to ctx.waitUntil has settled. */
392
+ async drain() {
393
+ while (pending.size > 0) await Promise.all([...pending]);
394
+ },
395
+ procedures,
396
+ budget,
397
+ });
398
+ }
399
+
400
+ module.exports = { createExecutor, PROTOCOL_VERSION, DEFAULT_BUDGET };