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.
@@ -0,0 +1,195 @@
1
+ /**
2
+ * Named, versioned procedures and the registry the executor serves them from.
3
+ * @module remote/procedures
4
+ */
5
+ const { findNonJson, deepFreeze, jsonClone } = require("./json");
6
+
7
+ /**
8
+ * What a resend after an `unknown` outcome does. Frozen vocabulary: see
9
+ * tutorials/11-remote-procedures.md.
10
+ * - `idempotent`: no writes, or writes whose repeat has no further effect.
11
+ * - `conditional`: every write is a guarded state transition, so a repeat
12
+ * fails its condition and the procedure reports that.
13
+ * - `needs-ledger`: an unguarded write or a counter; the procedure keeps its
14
+ * own marker keyed by `ctx.operationId`. The client never resends it.
15
+ */
16
+ const REPLAY_CLASSES = Object.freeze(["idempotent", "conditional", "needs-ledger"]);
17
+
18
+ /**
19
+ * Which model sets a procedure receives. `app`: `ctx.models` only. `admin` and
20
+ * `both`: also `ctx.adminModels`, bound to the admin partition the context
21
+ * resolver names.
22
+ */
23
+ const SCOPES = Object.freeze(["app", "admin", "both"]);
24
+
25
+ const NAME = /^[A-Za-z][A-Za-z0-9_.-]*$/;
26
+ const ID = /^([A-Za-z][A-Za-z0-9_.-]*)@([1-9][0-9]*)$/;
27
+ const DESCRIPTOR_KEYS = new Set(["name", "version", "scope", "replay", "args", "run"]);
28
+ const DESCRIPTORS = new WeakSet();
29
+
30
+ /**
31
+ * Define a procedure. The returned descriptor is what the registry serves and
32
+ * what a caller passes to `remote(...).call`.
33
+ * @param {Object} spec
34
+ * @param {string} spec.name - Dotted name, e.g. "rateLimit.reserve". No "@".
35
+ * @param {number} spec.version - Positive integer. Bump it when args or the
36
+ * result shape change; keep the previous descriptor registered for one
37
+ * deploy so callers built against it keep working.
38
+ * @param {"app"|"admin"|"both"} spec.scope
39
+ * @param {"idempotent"|"conditional"|"needs-ledger"} spec.replay
40
+ * @param {Object} [spec.args] - JSON description of the arguments (for
41
+ * example a JSON Schema). Not interpreted; published by `manifest()`.
42
+ * @param {function(Object, *): Promise<*>} spec.run
43
+ * @returns {Readonly<Object>} The descriptor.
44
+ */
45
+ function defineProcedure(spec) {
46
+ if (!spec || typeof spec !== "object") {
47
+ throw new TypeError("defineProcedure needs a descriptor object");
48
+ }
49
+ for (const key of Object.keys(spec)) {
50
+ if (!DESCRIPTOR_KEYS.has(key)) {
51
+ throw new TypeError(
52
+ `defineProcedure: unknown key "${key}"; expected ${[...DESCRIPTOR_KEYS].join(", ")}`,
53
+ );
54
+ }
55
+ }
56
+ const { name, version, scope, replay, args = null, run } = spec;
57
+ if (typeof name !== "string" || !NAME.test(name)) {
58
+ throw new TypeError(
59
+ `defineProcedure: name ${JSON.stringify(name)} must start with a letter and contain only letters, digits, ".", "_" or "-"`,
60
+ );
61
+ }
62
+ if (!Number.isInteger(version) || version < 1) {
63
+ throw new TypeError(`defineProcedure ${name}: version must be a positive integer`);
64
+ }
65
+ if (!SCOPES.includes(scope)) {
66
+ throw new TypeError(
67
+ `defineProcedure ${name}@${version}: scope must be one of ${SCOPES.join(", ")}`,
68
+ );
69
+ }
70
+ if (!REPLAY_CLASSES.includes(replay)) {
71
+ throw new TypeError(
72
+ `defineProcedure ${name}@${version}: replay class must be one of ${REPLAY_CLASSES.join(", ")}`,
73
+ );
74
+ }
75
+ if (typeof run !== "function") {
76
+ throw new TypeError(`defineProcedure ${name}@${version}: run must be a function`);
77
+ }
78
+ const bad = args === null ? null : findNonJson(args);
79
+ if (bad || (args !== null && typeof args !== "object")) {
80
+ throw new TypeError(
81
+ `defineProcedure ${name}@${version}: args must be a plain JSON description${bad ? ` (found ${bad.found} at ${bad.path})` : ""}`,
82
+ );
83
+ }
84
+ const descriptor = Object.freeze({
85
+ id: `${name}@${version}`,
86
+ name,
87
+ version,
88
+ scope,
89
+ replay,
90
+ args: args === null ? null : deepFreeze(jsonClone(args)),
91
+ run,
92
+ });
93
+ DESCRIPTORS.add(descriptor);
94
+ return descriptor;
95
+ }
96
+
97
+ function isDescriptor(value) {
98
+ return DESCRIPTORS.has(value);
99
+ }
100
+
101
+ /**
102
+ * The set of procedures one deployment serves.
103
+ *
104
+ * Previous-version serving is the application's obligation: the registry
105
+ * serves `name@1` beside `name@2` only while both descriptors are passed in.
106
+ * Keep the previous version registered for one deploy of the callers, then
107
+ * drop it. Versions of one name must be contiguous; a gap is refused so a
108
+ * dropped middle version can't go unnoticed.
109
+ */
110
+ class ProcedureRegistry {
111
+ /** @param {Object[]} descriptors - Results of defineProcedure. */
112
+ constructor(descriptors) {
113
+ if (!Array.isArray(descriptors)) {
114
+ throw new TypeError("ProcedureRegistry needs an array of descriptors");
115
+ }
116
+ const byId = new Map();
117
+ const byName = new Map();
118
+ for (const d of descriptors) {
119
+ if (!isDescriptor(d)) {
120
+ throw new TypeError(
121
+ "ProcedureRegistry: every entry must come from defineProcedure",
122
+ );
123
+ }
124
+ if (byId.has(d.id)) {
125
+ throw new Error(`ProcedureRegistry: ${d.id} is registered twice`);
126
+ }
127
+ byId.set(d.id, d);
128
+ if (!byName.has(d.name)) byName.set(d.name, []);
129
+ byName.get(d.name).push(d.version);
130
+ }
131
+ for (const [name, versions] of byName) {
132
+ versions.sort((a, b) => a - b);
133
+ for (let i = 1; i < versions.length; i++) {
134
+ if (versions[i] !== versions[i - 1] + 1) {
135
+ throw new Error(
136
+ `ProcedureRegistry: version gap for ${name}: has ${versions.join(", ")}, missing ${versions[i - 1] + 1}`,
137
+ );
138
+ }
139
+ }
140
+ Object.freeze(versions);
141
+ }
142
+ this._byId = byId;
143
+ this._byName = byName;
144
+ Object.freeze(this);
145
+ }
146
+
147
+ /** @returns {Object|undefined} The descriptor for "name@version". */
148
+ get(id) {
149
+ if (typeof id !== "string" || !ID.test(id)) return undefined;
150
+ return this._byId.get(id);
151
+ }
152
+
153
+ has(id) {
154
+ return this.get(id) !== undefined;
155
+ }
156
+
157
+ /** @returns {number[]} Registered versions of `name`, ascending. */
158
+ versions(name) {
159
+ return [...(this._byName.get(name) || [])];
160
+ }
161
+
162
+ /** @returns {Object|undefined} The highest registered version of `name`. */
163
+ latest(name) {
164
+ const versions = this._byName.get(name);
165
+ return versions ? this._byId.get(`${name}@${versions[versions.length - 1]}`) : undefined;
166
+ }
167
+
168
+ /**
169
+ * Plain-JSON listing of every registered procedure, sorted by id, for a
170
+ * build step that publishes argument schemas across bundles.
171
+ * @returns {Array<{id: string, name: string, version: number, scope: string, replay: string, args: ?Object}>}
172
+ */
173
+ manifest() {
174
+ return [...this._byId.values()]
175
+ .sort((a, b) =>
176
+ a.name === b.name ? a.version - b.version : a.name < b.name ? -1 : 1,
177
+ )
178
+ .map(({ id, name, version, scope, replay, args }) => ({
179
+ id,
180
+ name,
181
+ version,
182
+ scope,
183
+ replay,
184
+ args: args === null ? null : jsonClone(args),
185
+ }));
186
+ }
187
+ }
188
+
189
+ module.exports = {
190
+ defineProcedure,
191
+ ProcedureRegistry,
192
+ REPLAY_CLASSES,
193
+ SCOPES,
194
+ isDescriptor,
195
+ };
@@ -70,6 +70,9 @@ class TenantContext {
70
70
  */
71
71
  static getCurrentTenant() {
72
72
  const store = this._asyncStorage.getStore();
73
+ if (store?.exact) {
74
+ return store.tenantId;
75
+ }
73
76
  if (store?.tenantId) {
74
77
  return store.tenantId;
75
78
  }
@@ -118,6 +121,19 @@ class TenantContext {
118
121
  return this._asyncStorage.run({ tenantId }, callback);
119
122
  }
120
123
 
124
+ /**
125
+ * Run a callback pinned to an exact tenant value (including `null` for
126
+ * untenant-scoped operations), preventing fallback to a batch-context tenant,
127
+ * registered resolvers, or the process-wide fallback tenant.
128
+ * @private
129
+ */
130
+ static _runWithExactTenant(tenantId, callback) {
131
+ return this._asyncStorage.run(
132
+ { tenantId: tenantId ?? null, exact: true },
133
+ callback,
134
+ );
135
+ }
136
+
121
137
  /**
122
138
  * Explicit tenant override for cross-tenant operations.
123
139
  * Alias for runWithTenant for better readability in cross-tenant scenarios.
@@ -0,0 +1,367 @@
1
+ const { ulid } = require("ulid");
2
+ const { TransactWriteCommand } = require("./dynamodb-client");
3
+ const { defaultLogger: logger } = require("./utils/logger");
4
+ const { pluginManager } = require("./plugin-manager");
5
+ const { retryOperation } = require("./utils/retry-helper");
6
+ const { TenantContext } = require("./tenant-context");
7
+ const { _accumulateCapacityToContext } = require("./mixins/batch-loading-mixin");
8
+ const {
9
+ ValidationError,
10
+ ConfigurationError,
11
+ TransactionCanceledError,
12
+ } = require("./exceptions");
13
+
14
+ const TRANSACT_OP = Symbol("dynamo-bao.transactOp");
15
+ const MAX_TRANSACT_ITEMS = 100;
16
+ const MAX_TOKEN_LENGTH = 36;
17
+ const DEFAULT_MAX_ATTEMPTS = 3;
18
+ const DEFAULT_BASE_DELAY_MS = 25;
19
+
20
+ function runInCapturedTenant(tenantId, fn) {
21
+ return TenantContext._runWithExactTenant(tenantId ?? null, fn);
22
+ }
23
+
24
+ function getTransactItemKey(item) {
25
+ if (item.Put) {
26
+ return {
27
+ tableName: item.Put.TableName,
28
+ pk: item.Put.Item._pk,
29
+ sk: item.Put.Item._sk,
30
+ };
31
+ }
32
+ if (item.Update) {
33
+ return {
34
+ tableName: item.Update.TableName,
35
+ pk: item.Update.Key._pk,
36
+ sk: item.Update.Key._sk,
37
+ };
38
+ }
39
+ if (item.Delete) {
40
+ return {
41
+ tableName: item.Delete.TableName,
42
+ pk: item.Delete.Key._pk,
43
+ sk: item.Delete.Key._sk,
44
+ };
45
+ }
46
+ if (item.ConditionCheck) {
47
+ return {
48
+ tableName: item.ConditionCheck.TableName,
49
+ pk: item.ConditionCheck.Key._pk,
50
+ sk: item.ConditionCheck.Key._sk,
51
+ };
52
+ }
53
+ throw new ValidationError("Unknown TransactWrite item shape");
54
+ }
55
+
56
+ function formatFailureSummary(failure) {
57
+ const target =
58
+ failure.role === "unique_create" || failure.role === "unique_delete"
59
+ ? `${failure.model}.${failure.operation}, unique constraint "${failure.constraintField}"`
60
+ : `${failure.model}.${failure.operation}${failure.primaryId ? ` id=${failure.primaryId}` : ""}`;
61
+ const detail = failure.itemNotFound ? " (item not found)" : "";
62
+ return `op ${failure.opIndex} (${target}): ${failure.code}${detail}`;
63
+ }
64
+
65
+ function mapCancellationReasons(cancellationReasons, itemMapping) {
66
+ const failures = [];
67
+ if (!Array.isArray(cancellationReasons)) {
68
+ return failures;
69
+ }
70
+
71
+ for (let i = 0; i < cancellationReasons.length; i++) {
72
+ const reason = cancellationReasons[i];
73
+ if (!reason || !reason.Code || reason.Code === "None") {
74
+ continue;
75
+ }
76
+
77
+ const meta = itemMapping[i];
78
+ const hasItem = reason.Item !== undefined && reason.Item !== null;
79
+ const itemNotFound =
80
+ reason.Code === "ConditionalCheckFailed" &&
81
+ Boolean(meta?.hasExistsGuard) &&
82
+ !hasItem;
83
+
84
+ failures.push({
85
+ opIndex: meta ? meta.opIndex : i,
86
+ itemIndex: i,
87
+ model: meta ? meta.model.name : null,
88
+ primaryId: meta ? meta.primaryId : null,
89
+ operation: meta ? meta.operation : null,
90
+ role: meta ? meta.role : "main",
91
+ constraintField: meta?.constraintField || null,
92
+ code: reason.Code,
93
+ message: reason.Message || null,
94
+ item: hasItem ? reason.Item : undefined,
95
+ itemNotFound,
96
+ });
97
+ }
98
+
99
+ return failures;
100
+ }
101
+
102
+ function sleep(ms) {
103
+ return new Promise((resolve) => setTimeout(resolve, ms));
104
+ }
105
+
106
+ function computeJitteredBackoff(baseDelayMs, attempt) {
107
+ const ceiling = baseDelayMs * Math.pow(2, attempt - 1);
108
+ return Math.max(1, Math.round(ceiling * (0.5 + Math.random())));
109
+ }
110
+
111
+ /**
112
+ * Commit multiple model operations atomically in a single DynamoDB
113
+ * TransactWriteItems call.
114
+ *
115
+ * @param {Array} ops - Array of op descriptors returned by Model.createOp,
116
+ * Model.updateOp, Model.deleteOp, or Model.conditionCheckOp.
117
+ * @param {Object} [options]
118
+ * @param {string} [options.clientRequestToken] - Optional idempotency token
119
+ * (1-36 characters). Defaults to a generated ULID.
120
+ * @param {number} [options.maxAttempts=3] - Total attempts on TransactionConflict.
121
+ * @param {number} [options.baseDelayMs=25] - Base backoff delay (ms) for jittered
122
+ * exponential backoff on TransactionConflict.
123
+ * @returns {Promise<Array>} Per-op results aligned with `ops`.
124
+ */
125
+ async function transact(ops, options = {}) {
126
+ if (!Array.isArray(ops)) {
127
+ throw new ValidationError("transact() requires an array of operations");
128
+ }
129
+
130
+ const {
131
+ clientRequestToken,
132
+ maxAttempts = DEFAULT_MAX_ATTEMPTS,
133
+ baseDelayMs = DEFAULT_BASE_DELAY_MS,
134
+ } = options;
135
+
136
+ if (clientRequestToken !== undefined) {
137
+ if (
138
+ typeof clientRequestToken !== "string" ||
139
+ clientRequestToken.length === 0 ||
140
+ clientRequestToken.length > MAX_TOKEN_LENGTH
141
+ ) {
142
+ throw new ValidationError(
143
+ `clientRequestToken must be a string between 1 and ${MAX_TOKEN_LENGTH} characters`,
144
+ );
145
+ }
146
+ }
147
+
148
+ if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {
149
+ throw new ValidationError("maxAttempts must be a positive integer");
150
+ }
151
+
152
+ if (ops.length === 0) {
153
+ return [];
154
+ }
155
+
156
+ for (let i = 0; i < ops.length; i++) {
157
+ if (!ops[i] || ops[i][TRANSACT_OP] !== true) {
158
+ throw new ValidationError(
159
+ `transact() op at index ${i} must be created by Model.createOp, updateOp, deleteOp, or conditionCheckOp`,
160
+ );
161
+ }
162
+ }
163
+
164
+ // Enforce single-tenant transactions before doing any reads or writes
165
+ const expectedTenantId = ops[0].tenantId;
166
+ for (let i = 1; i < ops.length; i++) {
167
+ if (ops[i].tenantId !== expectedTenantId) {
168
+ throw new ConfigurationError(
169
+ `Cannot mix tenants in one transaction: op 0 has tenant ${JSON.stringify(expectedTenantId)} ` +
170
+ `but op ${i} has tenant ${JSON.stringify(ops[i].tenantId)}`,
171
+ );
172
+ }
173
+ }
174
+
175
+ const documentClient = ops[0].documentClient;
176
+ if (!documentClient) {
177
+ throw new ConfigurationError(
178
+ `Model ${ops[0].model.name} has no documentClient configured; call initModels() before transact()`,
179
+ );
180
+ }
181
+ for (let i = 1; i < ops.length; i++) {
182
+ if (ops[i].documentClient !== documentClient) {
183
+ throw new ConfigurationError(
184
+ `Cannot mix models using different DynamoDB clients in one transaction: ` +
185
+ `op 0 (${ops[0].model.name}) and op ${i} (${ops[i].model.name}) have different documentClient instances`,
186
+ );
187
+ }
188
+ }
189
+
190
+ // Prepare all ops in parallel under their captured tenant context
191
+ const preparedOps = await Promise.all(
192
+ ops.map((op) => runInCapturedTenant(op.tenantId, () => op._prepare())),
193
+ );
194
+
195
+ // Flatten items and build itemIndex -> logical op metadata
196
+ const flatItems = [];
197
+ const itemMapping = [];
198
+ const seenKeys = new Map();
199
+
200
+ for (let opIndex = 0; opIndex < preparedOps.length; opIndex++) {
201
+ const prepared = preparedOps[opIndex];
202
+ for (let j = 0; j < prepared.transactItems.length; j++) {
203
+ const transactItem = prepared.transactItems[j];
204
+ const meta = prepared.itemMeta[j] || { role: "main" };
205
+ const { tableName, pk, sk } = getTransactItemKey(transactItem);
206
+ const keyId = `${tableName}\0${pk}\0${sk}`;
207
+
208
+ if (seenKeys.has(keyId)) {
209
+ const prev = seenKeys.get(keyId);
210
+ const detail =
211
+ meta.role === "unique_create" || meta.role === "unique_delete"
212
+ ? ` (unique constraint "${meta.constraintField}")`
213
+ : "";
214
+ throw new ValidationError(
215
+ `Transaction targets duplicate key (${pk}, ${sk})${detail}: ` +
216
+ `op ${prev.opIndex} (${prev.model}) and op ${opIndex} (${prepared.model.name})`,
217
+ );
218
+ }
219
+
220
+ seenKeys.set(keyId, { opIndex, model: prepared.model.name });
221
+ flatItems.push(transactItem);
222
+ itemMapping.push({
223
+ opIndex,
224
+ model: prepared.model,
225
+ primaryId: prepared.primaryId,
226
+ operation: prepared.type,
227
+ role: meta.role,
228
+ constraintField: meta.constraintField || null,
229
+ hasExistsGuard: Boolean(meta.hasExistsGuard),
230
+ });
231
+ }
232
+ }
233
+
234
+ if (flatItems.length > MAX_TRANSACT_ITEMS) {
235
+ throw new ValidationError(
236
+ `Transaction has ${flatItems.length} items (including unique-constraint items), ` +
237
+ `which exceeds DynamoDB's limit of ${MAX_TRANSACT_ITEMS} items`,
238
+ );
239
+ }
240
+
241
+ if (logger.isDebugEnabled()) {
242
+ logger.debug("transact() items", JSON.stringify(flatItems, null, 2));
243
+ }
244
+
245
+ // Generate token once before retries so both network retries and
246
+ // TransactionConflict retries resend the exact same payload and token.
247
+ const token = clientRequestToken ?? ulid();
248
+ const commandInput = {
249
+ TransactItems: flatItems,
250
+ ClientRequestToken: token,
251
+ ReturnConsumedCapacity: "TOTAL",
252
+ };
253
+
254
+ let response;
255
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
256
+ try {
257
+ response = await retryOperation(() =>
258
+ documentClient.send(new TransactWriteCommand(commandInput)),
259
+ );
260
+ break;
261
+ } catch (error) {
262
+ if (error.name !== "TransactionCanceledException") {
263
+ throw error;
264
+ }
265
+
266
+ const failures = mapCancellationReasons(
267
+ error.CancellationReasons,
268
+ itemMapping,
269
+ );
270
+ const isPureConflict =
271
+ failures.length > 0 &&
272
+ failures.every((f) => f.code === "TransactionConflict");
273
+
274
+ if (isPureConflict && attempt < maxAttempts) {
275
+ const delayMs = computeJitteredBackoff(baseDelayMs, attempt);
276
+ logger.debug(
277
+ `transact() conflict on attempt ${attempt}/${maxAttempts}, retrying in ${delayMs}ms`,
278
+ );
279
+ await sleep(delayMs);
280
+ continue;
281
+ }
282
+
283
+ const summary =
284
+ failures.length > 0
285
+ ? failures.map(formatFailureSummary).join("; ")
286
+ : error.message;
287
+ throw new TransactionCanceledError(`Transaction cancelled: ${summary}`, {
288
+ failures,
289
+ cancellationReasons: error.CancellationReasons || [],
290
+ cause: error,
291
+ });
292
+ }
293
+ }
294
+
295
+ // Accumulate consumed write capacity to the request batch context
296
+ if (response?.ConsumedCapacity) {
297
+ const capacityArray = [].concat(response.ConsumedCapacity);
298
+ for (const cap of capacityArray) {
299
+ _accumulateCapacityToContext(cap?.CapacityUnits || 0, "write");
300
+ }
301
+ }
302
+
303
+ // Invalidate request-scoped loader cache for every mutated item
304
+ for (const prepared of preparedOps) {
305
+ if (prepared.type === "conditionCheck") continue;
306
+ runInCapturedTenant(prepared.tenantId, () => {
307
+ prepared.model._evictFromLoaderContext(prepared.primaryId);
308
+ });
309
+ }
310
+
311
+ // Build per-op results and fire afterSave / afterDelete hooks in op order
312
+ const results = [];
313
+ for (const prepared of preparedOps) {
314
+ if (prepared.type === "create") {
315
+ await runInCapturedTenant(prepared.tenantId, () =>
316
+ pluginManager.executeHooks(
317
+ prepared.model.name,
318
+ "afterSave",
319
+ prepared.localResult,
320
+ prepared.hookOptions,
321
+ ),
322
+ );
323
+ results.push(prepared.localResult);
324
+ } else if (prepared.type === "update") {
325
+ let result = prepared.localResult;
326
+ if (pluginManager.hasHook(prepared.model.name, "afterSave")) {
327
+ if (!result) {
328
+ result = await runInCapturedTenant(prepared.tenantId, () =>
329
+ prepared.model.find(prepared.primaryId, {
330
+ batchDelay: 0,
331
+ bypassCache: true,
332
+ }),
333
+ );
334
+ }
335
+ await runInCapturedTenant(prepared.tenantId, () =>
336
+ pluginManager.executeHooks(
337
+ prepared.model.name,
338
+ "afterSave",
339
+ result,
340
+ prepared.hookOptions,
341
+ ),
342
+ );
343
+ }
344
+ results.push(result ?? { primaryId: prepared.primaryId });
345
+ } else if (prepared.type === "delete") {
346
+ await runInCapturedTenant(prepared.tenantId, () =>
347
+ pluginManager.executeHooks(
348
+ prepared.model.name,
349
+ "afterDelete",
350
+ prepared.primaryId,
351
+ prepared.hookOptions,
352
+ ),
353
+ );
354
+ results.push(prepared.localResult ?? { primaryId: prepared.primaryId });
355
+ } else {
356
+ results.push(null);
357
+ }
358
+ }
359
+
360
+ return results;
361
+ }
362
+
363
+ module.exports = {
364
+ transact,
365
+ TRANSACT_OP,
366
+ MAX_TRANSACT_ITEMS,
367
+ };