dynamo-bao 0.9.0 → 0.11.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/CHANGELOG.md +135 -1
- package/README.md +60 -0
- package/bin/bao-create-table.js +0 -0
- package/package.json +16 -3
- package/src/dynamodb-client.js +23 -1
- package/src/exceptions.js +38 -0
- package/src/index.js +4 -0
- package/src/mixins/mutation-mixin.js +496 -132
- package/src/model.js +50 -0
- package/src/plugin-manager.js +5 -0
- package/src/remote/client.js +219 -0
- package/src/remote/codec.js +234 -0
- package/src/remote/context.js +299 -0
- package/src/remote/executor.js +400 -0
- package/src/remote/index.d.ts +413 -0
- package/src/remote/index.js +36 -0
- package/src/remote/json.js +104 -0
- package/src/remote/procedures.js +195 -0
- package/src/tenant-context.js +16 -0
- package/src/transact.js +367 -0
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The context a procedure runs with, and the call scope the executor enters
|
|
3
|
+
* for it.
|
|
4
|
+
* @module remote/context
|
|
5
|
+
*/
|
|
6
|
+
const { TenantContext } = require("../tenant-context");
|
|
7
|
+
const { ModelManager } = require("../model-manager");
|
|
8
|
+
const {
|
|
9
|
+
runWithBatchContext,
|
|
10
|
+
getBatchContextStore,
|
|
11
|
+
} = require("../mixins/batch-loading-mixin");
|
|
12
|
+
const { SCOPES } = require("./procedures");
|
|
13
|
+
const { findNonJson, isPlainObject, deepFreeze, jsonClone } = require("./json");
|
|
14
|
+
|
|
15
|
+
/** Default cap on one piece of deferred work, in milliseconds. */
|
|
16
|
+
const WAIT_UNTIL_CAP_MS = 30_000;
|
|
17
|
+
|
|
18
|
+
const LEVELS = ["debug", "info", "warn", "error"];
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* A loader cache that remembers which keys were deleted, so `fresh` can
|
|
22
|
+
* replay deletions onto the outer cache.
|
|
23
|
+
* @private
|
|
24
|
+
*/
|
|
25
|
+
class TrackingMap extends Map {
|
|
26
|
+
constructor() {
|
|
27
|
+
super();
|
|
28
|
+
this.deleted = new Set();
|
|
29
|
+
}
|
|
30
|
+
set(key, value) {
|
|
31
|
+
this.deleted.delete(key);
|
|
32
|
+
return super.set(key, value);
|
|
33
|
+
}
|
|
34
|
+
delete(key) {
|
|
35
|
+
this.deleted.add(key);
|
|
36
|
+
return super.delete(key);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Run `fn` in a nested batch context: its own loader cache (so reads go to
|
|
42
|
+
* DynamoDB, not the outer cache) and its own capacity accumulator. When it
|
|
43
|
+
* settles, its capacity is added to the outer context's total, and rows it
|
|
44
|
+
* read or wrote replace the outer cache's entries (rows it deleted are
|
|
45
|
+
* evicted), so a later `find` in the outer context sees them. This is the
|
|
46
|
+
* "re-read after a lost conditional write" pattern.
|
|
47
|
+
* @template T
|
|
48
|
+
* @param {function(): Promise<T>} fn
|
|
49
|
+
* @returns {Promise<T>}
|
|
50
|
+
*/
|
|
51
|
+
function fresh(fn) {
|
|
52
|
+
const outer = getBatchContextStore();
|
|
53
|
+
return runWithBatchContext(async () => {
|
|
54
|
+
const inner = getBatchContextStore();
|
|
55
|
+
const tracking = new TrackingMap();
|
|
56
|
+
if (inner) inner.loaderContext = tracking;
|
|
57
|
+
try {
|
|
58
|
+
return await fn();
|
|
59
|
+
} finally {
|
|
60
|
+
if (outer && inner) {
|
|
61
|
+
if (outer.capacityAccumulator && inner.capacityAccumulator) {
|
|
62
|
+
outer.capacityAccumulator.read += inner.capacityAccumulator.read;
|
|
63
|
+
outer.capacityAccumulator.write += inner.capacityAccumulator.write;
|
|
64
|
+
}
|
|
65
|
+
if (outer.loaderContext) {
|
|
66
|
+
for (const key of tracking.deleted) outer.loaderContext.delete(key);
|
|
67
|
+
for (const [key, value] of tracking) outer.loaderContext.set(key, value);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Run `fn` as one call: inside `tenant` and a new batch context. Never
|
|
76
|
+
* rejects; settles to `{ value, capacity }` or `{ error, capacity }`, with
|
|
77
|
+
* the capacity the call consumed either way.
|
|
78
|
+
* @param {string} tenant
|
|
79
|
+
* @param {function(): Promise<*>} fn
|
|
80
|
+
* @returns {Promise<Object>} `{value, capacity}` or `{error, capacity}`;
|
|
81
|
+
* capacity is `{read, write}`.
|
|
82
|
+
*/
|
|
83
|
+
function runInCall(tenant, fn) {
|
|
84
|
+
return TenantContext.runWithTenant(tenant, () =>
|
|
85
|
+
runWithBatchContext(async () => {
|
|
86
|
+
const store = getBatchContextStore();
|
|
87
|
+
const capacity = () =>
|
|
88
|
+
store?.capacityAccumulator
|
|
89
|
+
? { read: store.capacityAccumulator.read, write: store.capacityAccumulator.write }
|
|
90
|
+
: { read: 0, write: 0 };
|
|
91
|
+
try {
|
|
92
|
+
const value = await fn();
|
|
93
|
+
return { value, capacity: capacity() };
|
|
94
|
+
} catch (error) {
|
|
95
|
+
return { error, capacity: capacity() };
|
|
96
|
+
}
|
|
97
|
+
}),
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const BOUND = new WeakMap(); // base model -> Map(tenant -> bound model)
|
|
102
|
+
|
|
103
|
+
function boundManager(tenantId) {
|
|
104
|
+
const base = ModelManager.forTenant(tenantId);
|
|
105
|
+
const view = Object.create(base);
|
|
106
|
+
view.getModel = (name) => bindModel(base.getModel(name), tenantId);
|
|
107
|
+
return view;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function bindModel(Base, tenantId) {
|
|
111
|
+
let byTenant = BOUND.get(Base);
|
|
112
|
+
if (!byTenant) {
|
|
113
|
+
byTenant = new Map();
|
|
114
|
+
BOUND.set(Base, byTenant);
|
|
115
|
+
}
|
|
116
|
+
let Bound = byTenant.get(tenantId);
|
|
117
|
+
if (!Bound) {
|
|
118
|
+
Bound = class extends Base {
|
|
119
|
+
static get manager() {
|
|
120
|
+
return boundManager(tenantId);
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
Object.defineProperty(Bound, "name", { value: Base.name });
|
|
124
|
+
byTenant.set(tenantId, Bound);
|
|
125
|
+
}
|
|
126
|
+
return Bound;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Return model classes that always operate in `tenantId`, whatever tenant
|
|
131
|
+
* the surrounding code runs in. Statics, instances they return (`save`),
|
|
132
|
+
* related loads and batching all use `tenantId`; the base classes are not
|
|
133
|
+
* changed. This is how `ctx.adminModels` reaches the admin partition from
|
|
134
|
+
* inside an app-tenant call.
|
|
135
|
+
* @param {Object<string, Function>} models - Model classes by name.
|
|
136
|
+
* @param {string} tenantId
|
|
137
|
+
* @returns {Object<string, Function>}
|
|
138
|
+
*/
|
|
139
|
+
function bindModelsToTenant(models, tenantId) {
|
|
140
|
+
if (!tenantId || typeof tenantId !== "string") {
|
|
141
|
+
throw new TypeError("bindModelsToTenant needs a tenant id");
|
|
142
|
+
}
|
|
143
|
+
ModelManager.forTenant(tenantId); // rejects ids that could forge keys
|
|
144
|
+
const out = {};
|
|
145
|
+
for (const [name, Model] of Object.entries(models)) {
|
|
146
|
+
out[name] = typeof Model === "function" ? bindModel(Model, tenantId) : Model;
|
|
147
|
+
}
|
|
148
|
+
return Object.freeze(out);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function bindLogger(base, bound) {
|
|
152
|
+
const logger = {};
|
|
153
|
+
for (const level of LEVELS) {
|
|
154
|
+
const write =
|
|
155
|
+
typeof base?.[level] === "function"
|
|
156
|
+
? base[level].bind(base)
|
|
157
|
+
: typeof base?.info === "function"
|
|
158
|
+
? base.info.bind(base)
|
|
159
|
+
: () => {};
|
|
160
|
+
logger[level] = (message, detail) => {
|
|
161
|
+
const extra =
|
|
162
|
+
detail === undefined
|
|
163
|
+
? {}
|
|
164
|
+
: isPlainObject(detail) || (detail && typeof detail === "object" && !Array.isArray(detail))
|
|
165
|
+
? detail
|
|
166
|
+
: { detail };
|
|
167
|
+
write(message, { ...bound, ...extra });
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
return Object.freeze(logger);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function capped(promise, capMs, logger) {
|
|
174
|
+
let timer;
|
|
175
|
+
const timeout = new Promise((resolve) => {
|
|
176
|
+
timer = setTimeout(() => {
|
|
177
|
+
logger.warn(`deferred work exceeded ${capMs} ms and was abandoned`);
|
|
178
|
+
resolve();
|
|
179
|
+
}, capMs);
|
|
180
|
+
if (typeof timer?.unref === "function") timer.unref();
|
|
181
|
+
});
|
|
182
|
+
const work = Promise.resolve(promise).then(
|
|
183
|
+
() => {},
|
|
184
|
+
(error) =>
|
|
185
|
+
logger.error("deferred work failed", {
|
|
186
|
+
error: String((error && (error.stack || error.message)) || error),
|
|
187
|
+
}),
|
|
188
|
+
);
|
|
189
|
+
return Promise.race([work, timeout]).finally(() => clearTimeout(timer));
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Build the context a procedure receives.
|
|
194
|
+
*
|
|
195
|
+
* The executor calls this for every call with what the application's
|
|
196
|
+
* context resolver returned; procedure unit tests call it directly.
|
|
197
|
+
* @param {Object} options
|
|
198
|
+
* @param {string} options.tenant - The call tenant; also `ctx.tenant`.
|
|
199
|
+
* @param {Object} options.actor - The call's actor, passed through as is.
|
|
200
|
+
* @param {Object} options.models - The tenant's model classes.
|
|
201
|
+
* @param {"app"|"admin"|"both"} [options.scope="app"] - The procedure's scope.
|
|
202
|
+
* @param {Object} [options.adminModels] - Admin model classes; kept only for
|
|
203
|
+
* scope "admin" or "both", where they are required.
|
|
204
|
+
* @param {string} [options.adminPartition] - Tenant the admin models are
|
|
205
|
+
* bound to; required with adminModels. Unbound, they would run in the
|
|
206
|
+
* call's tenant and write admin rows into the app's partition.
|
|
207
|
+
* @param {string} [options.requestId]
|
|
208
|
+
* @param {string} [options.operationId] - The envelope's replay unit.
|
|
209
|
+
* @param {Object} [options.config] - Plain settings; deep-copied and frozen.
|
|
210
|
+
* @param {Object} [options.logger] - Base logger with debug/info/warn/error.
|
|
211
|
+
* @param {function(): number} [options.now] - Clock; defaults to Date.now.
|
|
212
|
+
* @param {function(Promise<void>)} [options.waitUntil] - Sink for
|
|
213
|
+
* deferred work (the platform's ExecutionContext.waitUntil).
|
|
214
|
+
* @param {number} [options.waitUntilCapMs=30000]
|
|
215
|
+
* @returns {Readonly<Object>} The ProcedureContext.
|
|
216
|
+
*/
|
|
217
|
+
function createContext(options) {
|
|
218
|
+
const {
|
|
219
|
+
tenant,
|
|
220
|
+
actor,
|
|
221
|
+
models,
|
|
222
|
+
scope = "app",
|
|
223
|
+
adminModels,
|
|
224
|
+
adminPartition,
|
|
225
|
+
requestId = "",
|
|
226
|
+
operationId = "",
|
|
227
|
+
config = {},
|
|
228
|
+
logger: baseLogger = console,
|
|
229
|
+
now = Date.now,
|
|
230
|
+
waitUntil: sink = () => {},
|
|
231
|
+
waitUntilCapMs = WAIT_UNTIL_CAP_MS,
|
|
232
|
+
} = options || {};
|
|
233
|
+
|
|
234
|
+
if (typeof tenant !== "string" || tenant === "") {
|
|
235
|
+
throw new TypeError("createContext: tenant must be a non-empty string");
|
|
236
|
+
}
|
|
237
|
+
if (!isPlainObject(actor)) {
|
|
238
|
+
throw new TypeError("createContext: actor is required and must be an object");
|
|
239
|
+
}
|
|
240
|
+
const badActor = findNonJson(actor, "actor");
|
|
241
|
+
if (badActor) {
|
|
242
|
+
throw new TypeError(`createContext: ${badActor.path} is ${badActor.found}; the actor must be JSON`);
|
|
243
|
+
}
|
|
244
|
+
if (!models || typeof models !== "object") {
|
|
245
|
+
throw new TypeError("createContext: models is required");
|
|
246
|
+
}
|
|
247
|
+
if (!SCOPES.includes(scope)) {
|
|
248
|
+
throw new TypeError(`createContext: unknown scope ${JSON.stringify(scope)}`);
|
|
249
|
+
}
|
|
250
|
+
const wantsAdmin = scope === "admin" || scope === "both";
|
|
251
|
+
if (wantsAdmin && (!adminModels || typeof adminModels !== "object")) {
|
|
252
|
+
throw new TypeError(
|
|
253
|
+
`createContext: scope "${scope}" needs adminModels from the context resolver`,
|
|
254
|
+
);
|
|
255
|
+
}
|
|
256
|
+
if (wantsAdmin && !adminPartition) {
|
|
257
|
+
throw new TypeError(
|
|
258
|
+
`createContext: scope "${scope}" needs an adminPartition to bind adminModels to; ` +
|
|
259
|
+
"unbound, they would write in the call's tenant",
|
|
260
|
+
);
|
|
261
|
+
}
|
|
262
|
+
const badConfig = findNonJson(config, "config");
|
|
263
|
+
if (badConfig || !isPlainObject(config)) {
|
|
264
|
+
throw new TypeError(
|
|
265
|
+
`createContext: config must be plain settings, no bindings${badConfig ? ` (${badConfig.path} is ${badConfig.found})` : ""}`,
|
|
266
|
+
);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
const logger = bindLogger(baseLogger, { requestId, tenant });
|
|
270
|
+
const ctx = {
|
|
271
|
+
models,
|
|
272
|
+
tenant,
|
|
273
|
+
actor: deepFreeze(jsonClone(actor)),
|
|
274
|
+
requestId,
|
|
275
|
+
operationId,
|
|
276
|
+
logger,
|
|
277
|
+
now: () => now(),
|
|
278
|
+
fresh,
|
|
279
|
+
waitUntil(promise) {
|
|
280
|
+
if (!promise || typeof promise.then !== "function") {
|
|
281
|
+
throw new TypeError("ctx.waitUntil needs a promise");
|
|
282
|
+
}
|
|
283
|
+
sink(capped(promise, waitUntilCapMs, logger));
|
|
284
|
+
},
|
|
285
|
+
config: deepFreeze(jsonClone(config)),
|
|
286
|
+
};
|
|
287
|
+
if (wantsAdmin) {
|
|
288
|
+
ctx.adminModels = bindModelsToTenant(adminModels, adminPartition);
|
|
289
|
+
}
|
|
290
|
+
return Object.freeze(ctx);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
module.exports = {
|
|
294
|
+
createContext,
|
|
295
|
+
fresh,
|
|
296
|
+
runInCall,
|
|
297
|
+
bindModelsToTenant,
|
|
298
|
+
WAIT_UNTIL_CAP_MS,
|
|
299
|
+
};
|
|
@@ -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 };
|