dynamo-bao 0.10.0 → 0.12.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/src/model.js CHANGED
@@ -1449,6 +1449,11 @@ class BaoModel {
1449
1449
  */
1450
1450
  async save(options = {}) {
1451
1451
  assertAttached(this, "save");
1452
+ if (options.quiet) {
1453
+ throw new ValidationError(
1454
+ "quiet: true is only supported on update and updateOp",
1455
+ );
1456
+ }
1452
1457
  const { forceReindex = false, ...otherOptions } = options;
1453
1458
 
1454
1459
  if (!forceReindex && !this.hasChanges() && this.isLoaded()) {
@@ -19,6 +19,11 @@ class PluginManager {
19
19
  }
20
20
  }
21
21
 
22
+ hasHook(modelName, hookName) {
23
+ const plugins = this.plugins.get(modelName) || [];
24
+ return plugins.some((plugin) => typeof plugin[hookName] === "function");
25
+ }
26
+
22
27
  async executeHooks(modelName, hookName, ...args) {
23
28
  const plugins = this.plugins.get(modelName) || [];
24
29
  for (const plugin of plugins) {
@@ -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,370 @@
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 (
327
+ !prepared.quiet &&
328
+ pluginManager.hasHook(prepared.model.name, "afterSave")
329
+ ) {
330
+ if (!result) {
331
+ result = await runInCapturedTenant(prepared.tenantId, () =>
332
+ prepared.model.find(prepared.primaryId, {
333
+ batchDelay: 0,
334
+ bypassCache: true,
335
+ }),
336
+ );
337
+ }
338
+ await runInCapturedTenant(prepared.tenantId, () =>
339
+ pluginManager.executeHooks(
340
+ prepared.model.name,
341
+ "afterSave",
342
+ result,
343
+ prepared.hookOptions,
344
+ ),
345
+ );
346
+ }
347
+ results.push(result ?? { primaryId: prepared.primaryId });
348
+ } else if (prepared.type === "delete") {
349
+ await runInCapturedTenant(prepared.tenantId, () =>
350
+ pluginManager.executeHooks(
351
+ prepared.model.name,
352
+ "afterDelete",
353
+ prepared.primaryId,
354
+ prepared.hookOptions,
355
+ ),
356
+ );
357
+ results.push(prepared.localResult ?? { primaryId: prepared.primaryId });
358
+ } else {
359
+ results.push(null);
360
+ }
361
+ }
362
+
363
+ return results;
364
+ }
365
+
366
+ module.exports = {
367
+ transact,
368
+ TRANSACT_OP,
369
+ MAX_TRANSACT_ITEMS,
370
+ };