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,234 @@
1
+ /**
2
+ * Wire codec for procedure arguments and results.
3
+ *
4
+ * Everything that crosses the executor boundary is plain JSON. Model rows
5
+ * travel as `{ $model: "<ModelName>", data: { <field>: <value> } }` holding
6
+ * only the model's declared fields, with:
7
+ * - DateTimeField, CreateDateField, ModifiedDateField, TtlField: epoch
8
+ * milliseconds (TtlField is stored in seconds and converted).
9
+ * - BinaryField: `{ $binary: "<base64>" }`.
10
+ * - StringSetField: an array of strings.
11
+ * - Every other built-in field: its stored value, which is already JSON.
12
+ * - A custom field: its stored value if that is plain JSON; otherwise the
13
+ * row is refused with a CodecError naming the model and field.
14
+ *
15
+ * Any other non-JSON value (Date, Map, Set, Buffer, class instance, function,
16
+ * NaN, ...) is refused rather than letting JSON.stringify change it silently.
17
+ * @module remote/codec
18
+ */
19
+ const fields = require("../fields");
20
+ const { findNonJson, isPlainObject } = require("./json");
21
+ const { ObjectNotFound } = require("../object-not-found");
22
+
23
+ class CodecError extends Error {
24
+ constructor(message) {
25
+ super(message);
26
+ this.name = "CodecError";
27
+ }
28
+ }
29
+
30
+ const DATE_FIELDS = [
31
+ fields.DateTimeFieldClass, // CreateDate, ModifiedDate and Ttl extend it
32
+ ];
33
+
34
+ function isDateField(field) {
35
+ return DATE_FIELDS.some((C) => field instanceof C);
36
+ }
37
+
38
+ function isModelInstance(value) {
39
+ // Lazy: model.js requires this module for fromRemote.
40
+ const { BaoModel } = require("../model");
41
+ return value instanceof BaoModel;
42
+ }
43
+
44
+ function isBinary(value) {
45
+ return value instanceof Uint8Array; // Buffer is a Uint8Array
46
+ }
47
+
48
+ function toBase64(bytes) {
49
+ if (typeof Buffer !== "undefined") return Buffer.from(bytes).toString("base64");
50
+ let s = "";
51
+ for (const b of bytes) s += String.fromCharCode(b);
52
+ return btoa(s);
53
+ }
54
+
55
+ function fromBase64(text) {
56
+ if (typeof Buffer !== "undefined") return Buffer.from(text, "base64");
57
+ return Uint8Array.from(atob(text), (c) => c.charCodeAt(0));
58
+ }
59
+
60
+ function encodeField(modelName, fieldName, field, dy) {
61
+ if (dy === undefined) return undefined;
62
+ if (dy === null) return null;
63
+ const where = `${modelName}.${fieldName}`;
64
+ if (field instanceof fields.TtlFieldClass) {
65
+ if (typeof dy !== "number") throw new CodecError(`${where}: stored TTL is not a number`);
66
+ return dy * 1000;
67
+ }
68
+ if (isDateField(field)) {
69
+ if (typeof dy !== "number") throw new CodecError(`${where}: stored date is not a number`);
70
+ return dy;
71
+ }
72
+ if (field instanceof fields.BinaryFieldClass) {
73
+ if (!isBinary(dy)) throw new CodecError(`${where}: stored binary is not bytes`);
74
+ return { $binary: toBase64(dy) };
75
+ }
76
+ if (field instanceof fields.StringSetFieldClass) {
77
+ const list = dy instanceof Set ? [...dy] : dy;
78
+ if (!Array.isArray(list) || list.some((s) => typeof s !== "string")) {
79
+ throw new CodecError(`${where}: stored string set is not an array of strings`);
80
+ }
81
+ return [...list];
82
+ }
83
+ const bad = findNonJson(dy);
84
+ if (bad) {
85
+ throw new CodecError(
86
+ `${where}: the stored value is not JSON (found ${bad.found}); the remote codec can't ship this field`,
87
+ );
88
+ }
89
+ return dy;
90
+ }
91
+
92
+ function decodeField(modelName, fieldName, field, wire) {
93
+ if (wire === undefined) return undefined;
94
+ if (wire === null) return null;
95
+ const where = `${modelName}.${fieldName}`;
96
+ if (field instanceof fields.TtlFieldClass) {
97
+ if (typeof wire !== "number" || !Number.isFinite(wire)) {
98
+ throw new CodecError(`${where}: expected epoch milliseconds`);
99
+ }
100
+ return Math.floor(wire / 1000);
101
+ }
102
+ if (isDateField(field)) {
103
+ if (typeof wire !== "number" || !Number.isFinite(wire)) {
104
+ throw new CodecError(`${where}: expected epoch milliseconds`);
105
+ }
106
+ return wire;
107
+ }
108
+ if (field instanceof fields.BinaryFieldClass) {
109
+ if (!isPlainObject(wire) || typeof wire.$binary !== "string") {
110
+ throw new CodecError(`${where}: expected { $binary: "<base64>" }`);
111
+ }
112
+ return fromBase64(wire.$binary);
113
+ }
114
+ if (field instanceof fields.StringSetFieldClass) {
115
+ if (!Array.isArray(wire) || wire.some((s) => typeof s !== "string")) {
116
+ throw new CodecError(`${where}: expected an array of strings`);
117
+ }
118
+ return [...wire];
119
+ }
120
+ const bad = findNonJson(wire);
121
+ if (bad) throw new CodecError(`${where}: expected JSON, found ${bad.found}`);
122
+ return wire;
123
+ }
124
+
125
+ /**
126
+ * Encode one model instance as `{ $model, data }`.
127
+ * @private
128
+ */
129
+ function encodeRow(instance) {
130
+ const Model = instance.constructor;
131
+ const data = {};
132
+ for (const [fieldName, field] of Object.entries(Model.fields)) {
133
+ const value = encodeField(Model.name, fieldName, field, instance._dyData[fieldName]);
134
+ if (value !== undefined) data[fieldName] = value;
135
+ }
136
+ return { $model: Model.name, data };
137
+ }
138
+
139
+ /**
140
+ * Encode a procedure argument or result as plain JSON.
141
+ * @param {any} value
142
+ * @param {Object} [options]
143
+ * @param {"encode"|"refuse"} [options.models="encode"] - What to do with a
144
+ * model instance found in `value`: encode it as `{ $model, data }`, or
145
+ * refuse it (the plain-view rule: a procedure must encode rows itself,
146
+ * with `encodeValue(row)`, so none crosses by accident).
147
+ * @returns {any} A plain-JSON copy. An `ObjectNotFound` becomes null; a
148
+ * top-level undefined becomes null.
149
+ * @throws {CodecError} Naming the path of the first value that is not JSON.
150
+ */
151
+ function encodeValue(value, { models = "encode" } = {}) {
152
+ return encodeAt(value, "$", models, new Set());
153
+ }
154
+
155
+ function encodeAt(value, path, models, seen) {
156
+ if (value === undefined) return null;
157
+ if (value === null || typeof value !== "object") {
158
+ const bad = findNonJson(value, path);
159
+ if (bad) throw nonJson(bad);
160
+ return value;
161
+ }
162
+ if (value instanceof ObjectNotFound) return null;
163
+ if (isModelInstance(value)) {
164
+ if (models === "refuse") {
165
+ throw new CodecError(
166
+ `${path}: a ${value.constructor.name} instance crossed the boundary; return encodeValue(row) or a plain view`,
167
+ );
168
+ }
169
+ return encodeRow(value);
170
+ }
171
+ if (seen.has(value)) throw new CodecError(`${path}: a circular reference is not JSON`);
172
+ seen.add(value);
173
+ try {
174
+ if (Array.isArray(value)) {
175
+ const out = new Array(value.length);
176
+ for (let i = 0; i < value.length; i++) {
177
+ if (!(i in value) || value[i] === undefined) {
178
+ throw nonJson({ path: `${path}[${i}]`, found: "undefined" });
179
+ }
180
+ out[i] = encodeAt(value[i], `${path}[${i}]`, models, seen);
181
+ }
182
+ return out;
183
+ }
184
+ if (!isPlainObject(value) || Object.getOwnPropertySymbols(value).length > 0) {
185
+ throw nonJson(findNonJson(value, path));
186
+ }
187
+ const out = {};
188
+ for (const key of Object.keys(value)) {
189
+ if (value[key] === undefined) continue;
190
+ out[key] = encodeAt(value[key], `${path}.${key}`, models, seen);
191
+ }
192
+ return out;
193
+ } finally {
194
+ seen.delete(value);
195
+ }
196
+ }
197
+
198
+ function nonJson({ path, found }) {
199
+ const hint = found === "a Date" ? "; send epoch milliseconds" : "";
200
+ return new CodecError(`${path}: ${found} is not JSON${hint}`);
201
+ }
202
+
203
+ /**
204
+ * Decode an encoded row into the model's stored representation (the shape
205
+ * of `instance._dyData`: dates as epoch ms, TTL in seconds, binary as bytes,
206
+ * string sets as arrays). `Model.fromRemote` builds on this.
207
+ * Fields the receiving model does not declare are dropped, so a row from a
208
+ * newer bundle still hydrates.
209
+ * @param {Function} ModelClass - A BaoModel subclass.
210
+ * @param {{$model: string, data: Object}} encoded
211
+ * @returns {Object}
212
+ * @throws {CodecError}
213
+ */
214
+ function decodeRow(ModelClass, encoded) {
215
+ if (!isPlainObject(encoded) || typeof encoded.$model !== "string") {
216
+ throw new CodecError(`decodeRow: expected { $model, data } for ${ModelClass.name}`);
217
+ }
218
+ if (encoded.$model !== ModelClass.name) {
219
+ throw new CodecError(
220
+ `decodeRow: the row is a ${encoded.$model}, not a ${ModelClass.name}`,
221
+ );
222
+ }
223
+ if (!isPlainObject(encoded.data)) {
224
+ throw new CodecError(`decodeRow: ${ModelClass.name} row has no data object`);
225
+ }
226
+ const dy = {};
227
+ for (const [fieldName, field] of Object.entries(ModelClass.fields)) {
228
+ const value = decodeField(ModelClass.name, fieldName, field, encoded.data[fieldName]);
229
+ if (value !== undefined) dy[fieldName] = value;
230
+ }
231
+ return dy;
232
+ }
233
+
234
+ module.exports = { encodeValue, decodeRow, CodecError };
@@ -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
+ };