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,413 @@
1
+ // Type declarations for dynamo-bao/remote.
2
+ //
3
+ // These are the contract the application compiles against. ProcedureContext,
4
+ // Actor, the outcome tags (ok / error / unknown) and the replay classes
5
+ // (idempotent / conditional / needs-ledger) are frozen: see
6
+ // tutorials/11-remote-procedures.md. A change to any of them is a breaking
7
+ // change to this entry point.
8
+
9
+ /** Plain JSON: what crosses the executor boundary. */
10
+ export type JsonValue =
11
+ | null
12
+ | boolean
13
+ | number
14
+ | string
15
+ | JsonValue[]
16
+ | { [key: string]: JsonValue };
17
+
18
+ /** What a resend after an `unknown` outcome does. */
19
+ export type ReplayClass = "idempotent" | "conditional" | "needs-ledger";
20
+
21
+ /** Which model sets a procedure receives. */
22
+ export type Scope = "app" | "admin" | "both";
23
+
24
+ export const REPLAY_CLASSES: readonly ["idempotent", "conditional", "needs-ledger"];
25
+ export const SCOPES: readonly ["app", "admin", "both"];
26
+
27
+ /**
28
+ * Who is calling. The executor reads only `appId` (it must equal the call's
29
+ * tenant, or the call is refused); every other field passes through to the
30
+ * procedure untouched and uninterpreted.
31
+ */
32
+ export interface Actor {
33
+ kind: "user" | "system" | "admin";
34
+ /** Attribution. Ids a procedure acts on are arguments, not this. */
35
+ userId?: string;
36
+ /** Must equal the call's tenant. */
37
+ appId: string;
38
+ /** What the caller's own authority check answered for appId. */
39
+ systemAuthority: boolean;
40
+ /** "A person started this." */
41
+ preAuthenticated: boolean;
42
+ /** The admin partition the caller resolved, for scope "admin" | "both". */
43
+ adminPartition?: string;
44
+ }
45
+
46
+ export interface Logger {
47
+ debug(message: string, detail?: unknown): void;
48
+ info(message: string, detail?: unknown): void;
49
+ warn(message: string, detail?: unknown): void;
50
+ error(message: string, detail?: unknown): void;
51
+ }
52
+
53
+ /** Flags and settings, deep-frozen. Never bindings. */
54
+ export type ReadonlyEnvConfig = { readonly [key: string]: DeepReadonly<JsonValue> };
55
+ type DeepReadonly<T> = T extends (infer U)[]
56
+ ? readonly DeepReadonly<U>[]
57
+ : T extends object
58
+ ? { readonly [K in keyof T]: DeepReadonly<T[K]> }
59
+ : T;
60
+
61
+ /** Read and write capacity units a call consumed. */
62
+ export interface Capacity {
63
+ read: number;
64
+ write: number;
65
+ }
66
+
67
+ /** What a procedure's `run` receives. */
68
+ export interface ProcedureContext<Models = any, AdminModels = any> {
69
+ /** The call tenant's models, batching on. */
70
+ readonly models: Models;
71
+ /** Only for scope "admin" | "both", bound to the resolver's admin partition. */
72
+ readonly adminModels?: AdminModels;
73
+ /** The call tenant, read-only; also a value, since rows store appId. */
74
+ readonly tenant: string;
75
+ /** The envelope's actor: the only ambient authority inside the executor. */
76
+ readonly actor: Readonly<Actor>;
77
+ readonly requestId: string;
78
+ /** The envelope's replay unit; key a needs-ledger marker by it. */
79
+ readonly operationId: string;
80
+ /** Bound to requestId and tenant. */
81
+ readonly logger: Logger;
82
+ /** The call's clock (epoch ms). */
83
+ now(): number;
84
+ /** Nested batch context for a re-read after a lost conditional write. */
85
+ fresh<T>(fn: () => Promise<T>): Promise<T>;
86
+ /** Deferred work next to DynamoDB, 30 s cap, awaited past the response. */
87
+ waitUntil(promise: Promise<unknown>): void;
88
+ readonly config: ReadonlyEnvConfig;
89
+ }
90
+
91
+ /** What the executor passes to the application's context resolver. */
92
+ export interface ResolverCall {
93
+ /** The call's id within its envelope. */
94
+ id: string;
95
+ /** "name@version". */
96
+ proc: string;
97
+ name: string;
98
+ version: number;
99
+ tenant: string;
100
+ scope: Scope;
101
+ replay: ReplayClass;
102
+ actor: Actor;
103
+ requestId: string;
104
+ operationId: string;
105
+ }
106
+
107
+ /** What the application's context resolver returns. */
108
+ export interface ResolvedContext<Models = any, AdminModels = any> {
109
+ models: Models;
110
+ /** Required for scope "admin" | "both"; dropped for scope "app". */
111
+ adminModels?: AdminModels;
112
+ /** Tenant adminModels are bound to. Required for admin and both scopes: a call without it is refused with ScopeError. */
113
+ adminPartition?: string;
114
+ config?: { [key: string]: JsonValue };
115
+ }
116
+
117
+ /**
118
+ * The application's hook: build the models and settings for one call. Runs
119
+ * inside the call's tenant and batch context, once per call.
120
+ */
121
+ export type ContextResolver<Env = unknown, Models = any, AdminModels = any> = (
122
+ call: ResolverCall,
123
+ env: Env,
124
+ ) => ResolvedContext<Models, AdminModels> | Promise<ResolvedContext<Models, AdminModels>>;
125
+
126
+ /** A registered procedure; also what a caller passes to `call`. */
127
+ export interface ProcedureDescriptor<Args = any, Result = any> {
128
+ /** "name@version". */
129
+ readonly id: string;
130
+ readonly name: string;
131
+ readonly version: number;
132
+ readonly scope: Scope;
133
+ readonly replay: ReplayClass;
134
+ readonly args: JsonValue | null;
135
+ readonly run: (ctx: ProcedureContext, args: Args) => Promise<Result>;
136
+ }
137
+
138
+ export interface ProcedureSpec<Args, Result, Models, AdminModels> {
139
+ name: string;
140
+ version: number;
141
+ scope: Scope;
142
+ replay: ReplayClass;
143
+ /** JSON description of the arguments, published by manifest(). */
144
+ args?: JsonValue;
145
+ run(ctx: ProcedureContext<Models, AdminModels>, args: Args): Promise<Result>;
146
+ }
147
+
148
+ /** A model instance as the codec sees it: anything with save(). It crosses as an EncodedRow. */
149
+ export interface RowLike {
150
+ save(...args: any[]): unknown;
151
+ }
152
+
153
+ /** Values the codec refuses wherever they appear in a result. */
154
+ export type NotJson =
155
+ | Date
156
+ | Map<any, any>
157
+ | Set<any>
158
+ | Function
159
+ | bigint
160
+ | symbol
161
+ | RegExp
162
+ | ArrayBuffer
163
+ | ArrayBufferView
164
+ | Promise<any>;
165
+
166
+ type IsAny<T> = 0 extends 1 & T ? true : false;
167
+
168
+ /**
169
+ * What a value becomes on the wire: model instances (RowLike) become
170
+ * EncodedRow, JSON stays as it is, and anything in NotJson becomes never.
171
+ */
172
+ export type Wire<T> =
173
+ IsAny<T> extends true
174
+ ? any
175
+ : unknown extends T
176
+ ? unknown
177
+ : T extends JsonValue | undefined
178
+ ? T
179
+ : T extends NotJson
180
+ ? never
181
+ : T extends RowLike
182
+ ? EncodedRow
183
+ : T extends readonly (infer U)[]
184
+ ? Wire<U>[]
185
+ : T extends object
186
+ ? { [K in keyof T]: Wire<T[K]> }
187
+ : never;
188
+
189
+ /** What a caller receives as `ok`: a result of undefined (or none) arrives as null. */
190
+ export type WireResult<T> = Wire<Exclude<T, undefined | void>> | (undefined extends T ? null : never);
191
+
192
+ /** true if a NotJson value can appear anywhere in T. */
193
+ type HasNotJson<T> =
194
+ IsAny<T> extends true
195
+ ? false
196
+ : unknown extends T
197
+ ? false
198
+ : T extends JsonValue | undefined | void
199
+ ? false
200
+ : T extends NotJson
201
+ ? true
202
+ : T extends RowLike
203
+ ? false
204
+ : T extends readonly (infer U)[]
205
+ ? HasNotJson<U>
206
+ : T extends object
207
+ ? HasNotJson<T[keyof T]>
208
+ : true;
209
+
210
+ /** Makes defineProcedure a type error when run's result can hold a value that isn't JSON. */
211
+ export type ResultCheck<Result> = true extends HasNotJson<Result>
212
+ ? { "run's result is not JSON: return epoch ms, not a Date, and plain objects and arrays, not a Map, Set or function": never }
213
+ : unknown;
214
+
215
+ export function defineProcedure<Args = any, Result = any, Models = any, AdminModels = any>(
216
+ spec: ProcedureSpec<Args, Result, Models, AdminModels> & ResultCheck<Result>,
217
+ ): ProcedureDescriptor<Args, Result>;
218
+
219
+ export interface ManifestEntry {
220
+ id: string;
221
+ name: string;
222
+ version: number;
223
+ scope: Scope;
224
+ replay: ReplayClass;
225
+ args: JsonValue | null;
226
+ }
227
+
228
+ export class ProcedureRegistry {
229
+ constructor(descriptors: ProcedureDescriptor<any, any>[]);
230
+ get(id: string): ProcedureDescriptor | undefined;
231
+ has(id: string): boolean;
232
+ versions(name: string): number[];
233
+ latest(name: string): ProcedureDescriptor | undefined;
234
+ manifest(): ManifestEntry[];
235
+ }
236
+
237
+ /** The error part of an outcome. */
238
+ export interface RemoteError {
239
+ name: string;
240
+ message: string;
241
+ code?: string | number;
242
+ /** The procedure did not start (executor refusal or resolver failure). */
243
+ refused?: true;
244
+ /** An AWS error, with its HTTP status. */
245
+ infrastructure?: true;
246
+ httpStatusCode?: number;
247
+ /**
248
+ * The procedure ran to completion and its writes, if any, committed; the
249
+ * result was then lost (ResponseTooLarge, or a CodecError from encoding it).
250
+ */
251
+ executed?: true;
252
+ }
253
+
254
+ /** Where the executor ran: the Cloudflare colo (null in process) and its configured region. */
255
+ export interface Placement {
256
+ colo: string | null;
257
+ region: string | null;
258
+ }
259
+
260
+ export interface OkOutcome<T> {
261
+ ok: T;
262
+ capacity: Capacity;
263
+ ms: number;
264
+ /** Absent only if the executor sent none. */
265
+ placement?: Placement;
266
+ }
267
+ export interface ErrorOutcome {
268
+ error: RemoteError;
269
+ capacity?: Capacity;
270
+ ms?: number;
271
+ /** Absent when no executor answered for the call (an envelope refusal). */
272
+ placement?: Placement;
273
+ }
274
+ /** The caller's transport failed after sending. Only the client produces this. */
275
+ export interface UnknownOutcome {
276
+ unknown: true;
277
+ reason: string;
278
+ }
279
+ export type Outcome<T> = OkOutcome<T> | ErrorOutcome | UnknownOutcome;
280
+
281
+ /** A model row on the wire; hydrate it with `Model.fromRemote(row)`. */
282
+ export interface EncodedRow {
283
+ $model: string;
284
+ data: { [field: string]: JsonValue };
285
+ }
286
+
287
+ export class CodecError extends Error {}
288
+ export class DetachedInstanceError extends Error {
289
+ modelName: string;
290
+ method: string;
291
+ }
292
+
293
+ /**
294
+ * Encode a value as plain JSON: model instances become EncodedRow (or are
295
+ * refused with `models: "refuse"`); Date, Map, Set, Buffer and other
296
+ * non-JSON values throw CodecError naming their path.
297
+ */
298
+ export function encodeValue(value: unknown, options?: { models?: "encode" | "refuse" }): JsonValue;
299
+
300
+ /** Decode an EncodedRow to the model's stored representation. */
301
+ export function decodeRow(
302
+ ModelClass: { name: string; fields: Record<string, unknown> },
303
+ encoded: EncodedRow,
304
+ ): Record<string, unknown>;
305
+
306
+ export interface CreateContextOptions<Models, AdminModels> {
307
+ tenant: string;
308
+ actor: Actor;
309
+ models: Models;
310
+ scope?: Scope;
311
+ adminModels?: AdminModels;
312
+ adminPartition?: string;
313
+ requestId?: string;
314
+ operationId?: string;
315
+ config?: { [key: string]: JsonValue };
316
+ logger?: Partial<Logger>;
317
+ now?: () => number;
318
+ waitUntil?: (promise: Promise<void>) => void;
319
+ waitUntilCapMs?: number;
320
+ }
321
+
322
+ /** Build a ProcedureContext; procedure unit tests call it directly. */
323
+ export function createContext<Models = any, AdminModels = any>(
324
+ options: CreateContextOptions<Models, AdminModels>,
325
+ ): ProcedureContext<Models, AdminModels>;
326
+
327
+ /** Run fn in a nested batch context; merge its capacity and cache back. */
328
+ export function fresh<T>(fn: () => Promise<T>): Promise<T>;
329
+
330
+ /** Model classes that always operate in tenantId. */
331
+ export function bindModelsToTenant<M extends Record<string, unknown>>(models: M, tenantId: string): M;
332
+
333
+ export interface Budget {
334
+ maxCalls?: number;
335
+ maxRequestBytes?: number;
336
+ maxResponseBytes?: number;
337
+ }
338
+
339
+ export interface WaitUntilContext {
340
+ waitUntil(promise: Promise<unknown>): void;
341
+ }
342
+
343
+ export interface ExecutorOptions<Env> {
344
+ procedures: ProcedureRegistry;
345
+ context: ContextResolver<Env>;
346
+ /** Decide whether a request may use the executor at all. */
347
+ ingress(request: Request, env: Env): boolean | Promise<boolean>;
348
+ budget?: Budget;
349
+ /** Echoed as placement.region. */
350
+ region?: string;
351
+ logger?: Partial<Logger>;
352
+ now?: () => number;
353
+ /** A model instance in a result is an error. Turn on in tests. */
354
+ plainReturns?: boolean;
355
+ waitUntilCapMs?: number;
356
+ }
357
+
358
+ export interface Executor<Env = unknown> {
359
+ fetch(request: Request, env?: Env, ctx?: WaitUntilContext): Promise<Response>;
360
+ /** Resolve once all deferred work has settled. */
361
+ drain(): Promise<void>;
362
+ readonly procedures: ProcedureRegistry;
363
+ readonly budget: Readonly<Required<Budget>>;
364
+ }
365
+
366
+ export function createExecutor<Env = unknown>(options: ExecutorOptions<Env>): Executor<Env>;
367
+
368
+ /** A service binding, inProcess(executor), or anything with this fetch. */
369
+ export interface Transport {
370
+ fetch(request: Request): Promise<Response>;
371
+ }
372
+
373
+ export interface RemoteOptions {
374
+ actor?: Actor;
375
+ /** Resends after a transport failure; never for needs-ledger. Default 0. */
376
+ retries?: number;
377
+ url?: string;
378
+ headers?: Record<string, string>;
379
+ }
380
+
381
+ export interface CallOptions {
382
+ tenant: string;
383
+ actor?: Actor;
384
+ operationId?: string;
385
+ requestId?: string;
386
+ }
387
+
388
+ export interface BatchCall<Args = any> {
389
+ id?: string;
390
+ procedure: ProcedureDescriptor<Args, any>;
391
+ args?: Args;
392
+ tenant: string;
393
+ actor?: Actor;
394
+ }
395
+
396
+ export interface RemoteClient {
397
+ call<Args, Result>(
398
+ procedure: ProcedureDescriptor<Args, Result>,
399
+ args: Args,
400
+ options: CallOptions,
401
+ ): Promise<Outcome<WireResult<Result>>>;
402
+ batch(
403
+ calls: BatchCall[],
404
+ options?: { operationId?: string; requestId?: string },
405
+ ): Promise<Record<string, Outcome<unknown>>>;
406
+ }
407
+
408
+ export function remote(transport: Transport, options?: RemoteOptions): RemoteClient;
409
+
410
+ export function inProcess<Env>(
411
+ executor: Executor<Env>,
412
+ options?: { env?: Env; headers?: Record<string, string>; ctx?: WaitUntilContext },
413
+ ): Transport;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * dynamo-bao/remote: run named, versioned procedures next to DynamoDB and
3
+ * call them from far away in one round trip.
4
+ *
5
+ * See tutorials/11-remote-procedures.md for the frozen contract
6
+ * (ProcedureContext, Actor, outcome tags, replay classes).
7
+ * @module dynamo-bao/remote
8
+ */
9
+ const {
10
+ defineProcedure,
11
+ ProcedureRegistry,
12
+ REPLAY_CLASSES,
13
+ SCOPES,
14
+ } = require("./procedures");
15
+ const { createContext, fresh, bindModelsToTenant } = require("./context");
16
+ const { encodeValue, decodeRow, CodecError } = require("./codec");
17
+ const { createExecutor } = require("./executor");
18
+ const { remote, inProcess } = require("./client");
19
+ const { DetachedInstanceError } = require("../exceptions");
20
+
21
+ module.exports = {
22
+ defineProcedure,
23
+ ProcedureRegistry,
24
+ REPLAY_CLASSES,
25
+ SCOPES,
26
+ createContext,
27
+ fresh,
28
+ bindModelsToTenant,
29
+ encodeValue,
30
+ decodeRow,
31
+ CodecError,
32
+ createExecutor,
33
+ remote,
34
+ inProcess,
35
+ DetachedInstanceError,
36
+ };
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Plain-JSON checks shared by the remote modules. A value is plain JSON when
3
+ * JSON.stringify followed by JSON.parse returns an equal value: null,
4
+ * booleans, finite numbers, strings, arrays of plain JSON, and objects whose
5
+ * prototype is Object.prototype or null with plain-JSON values. Anything else
6
+ * (Date, Map, Set, Buffer, class instances, functions, undefined inside an
7
+ * array, NaN, Infinity, bigint, symbol, cycles) is not, because
8
+ * JSON.stringify either drops it, throws, or changes its type silently.
9
+ * @module remote/json
10
+ * @private
11
+ */
12
+
13
+ function describe(value) {
14
+ if (value === undefined) return "undefined";
15
+ if (typeof value === "number") return String(value);
16
+ if (typeof value === "bigint") return "a bigint";
17
+ if (typeof value === "symbol") return "a symbol";
18
+ if (typeof value === "function") return "a function";
19
+ const ctor = Object.getPrototypeOf(value)?.constructor?.name;
20
+ return ctor ? `a ${ctor}` : "an object with a custom prototype";
21
+ }
22
+
23
+ /**
24
+ * Return null when `value` is plain JSON, otherwise `{ path, found }`
25
+ * naming the first offending location ("$.a[2].b") and what was there.
26
+ * `allow(value)` may return true to accept a value the caller handles itself.
27
+ */
28
+ function findNonJson(value, path = "$", allow = null, seen = new Set()) {
29
+ if (allow && allow(value)) return null;
30
+ if (value === null) return null;
31
+ switch (typeof value) {
32
+ case "string":
33
+ case "boolean":
34
+ return null;
35
+ case "number":
36
+ return Number.isFinite(value) ? null : { path, found: describe(value) };
37
+ case "object":
38
+ break;
39
+ default:
40
+ return { path, found: describe(value) };
41
+ }
42
+ if (seen.has(value)) return { path, found: "a circular reference" };
43
+ seen.add(value);
44
+ try {
45
+ if (Array.isArray(value)) {
46
+ for (let i = 0; i < value.length; i++) {
47
+ if (!(i in value)) return { path: `${path}[${i}]`, found: "a hole" };
48
+ const bad = findNonJson(value[i], `${path}[${i}]`, allow, seen);
49
+ if (bad) return bad;
50
+ }
51
+ return null;
52
+ }
53
+ if (!isPlainObject(value)) {
54
+ return { path, found: describe(value) };
55
+ }
56
+ if (Object.getOwnPropertySymbols(value).length > 0) {
57
+ return { path, found: "an object with symbol keys" };
58
+ }
59
+ for (const key of Object.keys(value)) {
60
+ const child = value[key];
61
+ // JSON.stringify drops undefined object members; treat that as absent
62
+ // rather than an error, since `{ a: undefined }` round-trips to `{}`.
63
+ if (child === undefined) continue;
64
+ const bad = findNonJson(child, `${path}.${key}`, allow, seen);
65
+ if (bad) return bad;
66
+ }
67
+ return null;
68
+ } finally {
69
+ seen.delete(value);
70
+ }
71
+ }
72
+
73
+ /**
74
+ * True for `{}` literals and `Object.create(null)` objects, from any realm
75
+ * (a Worker, a vm context and Node each have their own Object.prototype).
76
+ */
77
+ function isPlainObject(value) {
78
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
79
+ return false;
80
+ }
81
+ const proto = Object.getPrototypeOf(value);
82
+ if (proto === null || proto === Object.prototype) return true;
83
+ return (
84
+ Object.getPrototypeOf(proto) === null &&
85
+ typeof proto.constructor === "function" &&
86
+ proto.constructor.name === "Object" &&
87
+ Object.prototype.toString.call(value) === "[object Object]"
88
+ );
89
+ }
90
+
91
+ /** Deep copy of a value already known to be plain JSON. */
92
+ function jsonClone(value) {
93
+ return value === undefined ? undefined : JSON.parse(JSON.stringify(value));
94
+ }
95
+
96
+ function deepFreeze(value) {
97
+ if (value && typeof value === "object" && !Object.isFrozen(value)) {
98
+ Object.freeze(value);
99
+ for (const key of Object.keys(value)) deepFreeze(value[key]);
100
+ }
101
+ return value;
102
+ }
103
+
104
+ module.exports = { findNonJson, isPlainObject, deepFreeze, jsonClone };