dynamo-bao 0.10.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 CHANGED
@@ -9,6 +9,52 @@ Each version heading links to the tag that was published to npm. Entries before
9
9
 
10
10
  ## [Unreleased]
11
11
 
12
+ ## [0.11.0] - 2026-12-03
13
+
14
+ Semver minor (0.11.0). Adds multi-model atomic transactions via
15
+ `transact([...ops])` and model op builders; nothing existing changes behavior.
16
+
17
+ **Key format: no key code changed.** Primary keys, GSI keys, unique
18
+ constraint keys, iteration keys, `_searchText`, and tenant prefixes are built
19
+ identically to 0.10.0.
20
+
21
+ ### Added
22
+
23
+ - **`transact(ops, options?)`** exported from the root `dynamo-bao` entry point
24
+ for committing writes across multiple models atomically in a single DynamoDB
25
+ `TransactWriteItems` call.
26
+ - Enforces single-tenant transactions (refusing mixed ambient tenants or
27
+ mixed app/admin tenant-bound models), matching `documentClient` instances,
28
+ DynamoDB's 100-item flattened limit (counting unique-constraint items), and
29
+ distinct flattened `(TableName, _pk, _sk)` keys before sending.
30
+ - Reuses a single `ClientRequestToken` (caller-supplied or generated ULID)
31
+ and frozen `TransactItems` payload across network retries and jittered
32
+ backoff retries on pure `TransactionConflict` cancellations (default
33
+ `maxAttempts: 3`, `baseDelayMs: 25`). Condition check failures and mixed
34
+ conflict/condition cancellations are not retried.
35
+ - Accumulates write capacity into `getBatchContextCapacity().write`,
36
+ invalidates request batch context loader cache entries for mutated items
37
+ (including clearing cached `ObjectNotFound` misses on `createOp` and
38
+ propagating out of `fresh()`), and fires `afterSave` / `afterDelete` hooks
39
+ once per op in order only after commit (avoiding read-back on blind/atomic
40
+ updates unless an `afterSave` hook is registered).
41
+ - **Model op builders**: `Model.createOp(data, options?)`,
42
+ `Model.updateOp(id, changes, options?)`, `Model.deleteOp(id, options?)`, and
43
+ `Model.conditionCheckOp(id, condition)`. Each snapshots the active tenant
44
+ context at construction time (failing closed when tenancy is enabled without
45
+ a tenant) and shares write preparation with single-item `create()`,
46
+ `update()`, and `delete()`.
47
+ - **`Model.create(data, options?)`** now accepts optional `{ condition }` for
48
+ symmetry with `createOp`.
49
+ - **`TransactionCanceledError`** (exported on `exceptions`), mapping DynamoDB's
50
+ flat `CancellationReasons` back to logical `opIndex` with `code`/`reason`,
51
+ `failures` (including `role`, `constraintField`, and `itemNotFound`), and the
52
+ unmarshalled `ReturnValuesOnConditionCheckFailure` `item`.
53
+ - **Bundled DynamoDB client** (`src/dynamodb-client.js`): added
54
+ `ConditionCheck` marshalling in `TransactWriteCommand` and unmarshalling of
55
+ `CancellationReasons[i].Item` on `TransactionCanceledException`.
56
+ - **`tutorials/12-transactions.md`** and README documentation.
57
+
12
58
  ## [0.10.0] - 2026-11-07
13
59
 
14
60
  Semver minor (0.10.0). Adds the `dynamo-bao/remote` entry point; nothing
@@ -653,7 +699,8 @@ Initial release: single-table models with fields, GSIs, unique constraints,
653
699
  related fields, counters, TTL, filters, pagination, batch loading, hooks,
654
700
  YAML codegen and a table creation tool.
655
701
 
656
- [Unreleased]: https://github.com/aag1024/dynamo-bao/compare/v0.10.0...HEAD
702
+ [Unreleased]: https://github.com/aag1024/dynamo-bao/compare/v0.11.0...HEAD
703
+ [0.11.0]: https://github.com/aag1024/dynamo-bao/compare/v0.10.0...v0.11.0
657
704
  [0.10.0]: https://github.com/aag1024/dynamo-bao/compare/v0.9.0...v0.10.0
658
705
  [0.9.0]: https://github.com/aag1024/dynamo-bao/compare/v0.8.2...v0.9.0
659
706
  [0.8.2]: https://github.com/aag1024/dynamo-bao/compare/v0.8.1...v0.8.2
package/README.md CHANGED
@@ -21,6 +21,7 @@ Release notes are in [CHANGELOG.md](https://github.com/aag1024/dynamo-bao/blob/m
21
21
  - Model 1:1, 1:N, N:M relationships between objects
22
22
  - Efficiently load data: load related objects in parallel, cache data using loading contexts
23
23
  - Minimize race conditions: save diffs, version checks on save, atomic counters
24
+ - Atomic multi-model transactions with `transact([...ops])`, op builders (`createOp`, `updateOp`, `deleteOp`, `conditionCheckOp`), and conflict retries
24
25
  - Enforce unique constraints and use them for lookups
25
26
  - Built-in multi-tenancy support with complete data isolation and concurrency safety
26
27
  - Return total read/write consumed capacity (even when multiple operations were performed)
@@ -219,6 +220,36 @@ if ("ok" in r) console.log(r.ok.name);
219
220
 
220
221
  See [tutorial 11](tutorials/11-remote-procedures.md) for the contract (context, actor, outcomes, replay classes) and [`examples/cloudflare-remote-executor/`](examples/cloudflare-remote-executor/) for a complete Worker. TypeScript declarations ship with the entry point.
221
222
 
223
+ ### Multi-Model Transactions (`transact`)
224
+
225
+ Commit changes across multiple models atomically in a single DynamoDB `TransactWriteItems` call using op builders (`createOp`, `updateOp`, `deleteOp`, `conditionCheckOp`):
226
+
227
+ ```javascript
228
+ const { transact } = require("dynamo-bao");
229
+ const { TransactionCanceledError } = require("dynamo-bao").exceptions;
230
+
231
+ try {
232
+ await transact([
233
+ Document.updateOp(
234
+ docId,
235
+ { directShareCount: "+1" },
236
+ { condition: { directShareCount: { $lt: 1000 } } },
237
+ ),
238
+ DocumentPermission.createOp({ docId, userId, role: "editor" }),
239
+ ]);
240
+ } catch (err) {
241
+ if (err instanceof TransactionCanceledError) {
242
+ console.log("Cancelled at op", err.opIndex, err.code, err.item);
243
+ }
244
+ }
245
+ ```
246
+
247
+ - All-or-nothing commit with unique-constraint items, GSI keys, iteration keys, generated fields, and tenant prefixes built identically to single-item writes.
248
+ - Maps `TransactionCanceledException` reasons back to logical op indexes (including `ReturnValuesOnConditionCheckFailure` items) and retries `TransactionConflict` with jittered backoff.
249
+ - Runs `afterSave`/`afterDelete` hooks once per op in order only after commit, invalidates the request batch context cache, and refuses mixed tenants, duplicate keys, or more than 100 items.
250
+
251
+ See [tutorial 12](tutorials/12-transactions.md) for full details, options, error shapes, and limits.
252
+
222
253
  ### Batch Context Configuration
223
254
 
224
255
  DynamoBao provides flexible batch context behavior that can be configured based on your application's needs:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dynamo-bao",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "Simple powerful data modeling primitives for DynamoDB in JavaScript.",
5
5
  "main": "src/index.js",
6
6
  "exports": {
@@ -238,7 +238,12 @@ class DynamoDBClient {
238
238
 
239
239
  // Add specific properties based on error type
240
240
  if (errorName === 'TransactionCanceledException' && errorBody.CancellationReasons) {
241
- error.CancellationReasons = errorBody.CancellationReasons;
241
+ error.CancellationReasons = errorBody.CancellationReasons.map(reason => {
242
+ if (reason && reason.Item) {
243
+ return { ...reason, Item: unmarshallItem(reason.Item) };
244
+ }
245
+ return reason;
246
+ });
242
247
  }
243
248
 
244
249
  // With ReturnValuesOnConditionCheckFailure, a failed condition check
@@ -421,6 +426,23 @@ class DynamoDBDocumentClient {
421
426
  newItem.Delete.ExpressionAttributeValues = marshalledValues;
422
427
  }
423
428
  }
429
+ if (item.ConditionCheck) {
430
+ const checkKey = {};
431
+ Object.keys(item.ConditionCheck.Key).forEach(key => {
432
+ checkKey[key] = marshall(item.ConditionCheck.Key[key]);
433
+ });
434
+ newItem.ConditionCheck = {
435
+ ...item.ConditionCheck,
436
+ Key: checkKey
437
+ };
438
+ if (item.ConditionCheck.ExpressionAttributeValues) {
439
+ const marshalledValues = {};
440
+ Object.keys(item.ConditionCheck.ExpressionAttributeValues).forEach(key => {
441
+ marshalledValues[key] = marshall(item.ConditionCheck.ExpressionAttributeValues[key]);
442
+ });
443
+ newItem.ConditionCheck.ExpressionAttributeValues = marshalledValues;
444
+ }
445
+ }
424
446
  return newItem;
425
447
  });
426
448
  }
package/src/exceptions.js CHANGED
@@ -102,6 +102,26 @@ class DetachedInstanceError extends BaoError {
102
102
  }
103
103
  }
104
104
 
105
+ /**
106
+ * Thrown when a DynamoDB TransactWriteItems call is cancelled (e.g.
107
+ * ConditionalCheckFailed, TransactionConflict). Maps DynamoDB's flat
108
+ * CancellationReasons back to the caller's logical op indexes.
109
+ */
110
+ class TransactionCanceledError extends BaoError {
111
+ constructor(message, { failures = [], cancellationReasons = [], cause = null } = {}) {
112
+ const primary = failures[0] || null;
113
+ super(message, primary ? primary.code : null);
114
+ this.failures = failures;
115
+ this.cancellationReasons = cancellationReasons;
116
+ this.opIndex = primary ? primary.opIndex : null;
117
+ this.reason = primary ? primary.code : null;
118
+ this.item = primary && primary.item !== undefined ? primary.item : undefined;
119
+ if (cause) {
120
+ this.cause = cause;
121
+ }
122
+ }
123
+ }
124
+
105
125
  module.exports = {
106
126
  BaoError,
107
127
  ConfigurationError,
@@ -111,4 +131,5 @@ module.exports = {
111
131
  ConditionalError,
112
132
  DataFormatError,
113
133
  DetachedInstanceError,
134
+ TransactionCanceledError,
114
135
  };
package/src/index.js CHANGED
@@ -21,6 +21,7 @@ const {
21
21
  runWithBatchContext,
22
22
  getBatchContextCapacity,
23
23
  } = require("./mixins/batch-loading-mixin");
24
+ const { transact } = require("./transact");
24
25
 
25
26
  function findModelFiles(dir) {
26
27
  let results = [];
@@ -229,6 +230,9 @@ const firstExport = {
229
230
  runWithBatchContext,
230
231
  getBatchContextCapacity,
231
232
 
233
+ // Multi-model transactions
234
+ transact,
235
+
232
236
  // Configurations
233
237
  PrimaryKeyConfig,
234
238
  IndexConfig,
@@ -18,6 +18,21 @@ const {
18
18
  } = require("../exceptions");
19
19
  const { computeSearchTextUpdate } = require("../utils/search-text");
20
20
  const { SEARCH_TEXT_FIELD, GID_SEPARATOR } = require("../constants");
21
+ const { TRANSACT_OP } = require("../transact");
22
+
23
+ function withReturnValuesOnFailure(transactItem) {
24
+ const [action] = Object.keys(transactItem);
25
+ const params = transactItem[action];
26
+ if (params && params.ConditionExpression) {
27
+ return {
28
+ [action]: {
29
+ ...params,
30
+ ReturnValuesOnConditionCheckFailure: "ALL_OLD",
31
+ },
32
+ };
33
+ }
34
+ return transactItem;
35
+ }
21
36
 
22
37
  /**
23
38
  * AND a guard onto an optional ConditionExpression. The existing expression
@@ -51,16 +66,26 @@ const MutationMethods = {
51
66
  * @param {Object} jsUpdates - The data to create the item with.
52
67
  * @returns {Promise<Object>} Returns a promise that resolves to the created item.
53
68
  */
54
- async create(jsUpdates) {
55
- await pluginManager.executeHooks(this.name, "beforeSave", jsUpdates, {
69
+ async create(jsUpdates, options = {}) {
70
+ const createOptions = {
56
71
  isNew: true,
57
- });
58
- const result = await this._saveItem(null, jsUpdates, { isNew: true });
72
+ ...options,
73
+ };
74
+ await pluginManager.executeHooks(
75
+ this.name,
76
+ "beforeSave",
77
+ jsUpdates,
78
+ createOptions,
79
+ );
80
+ const result = await this._saveItem(null, jsUpdates, createOptions);
59
81
 
60
82
  logger.debug("create() - result", result);
61
- await pluginManager.executeHooks(this.name, "afterSave", result, {
62
- isNew: true,
63
- });
83
+ await pluginManager.executeHooks(
84
+ this.name,
85
+ "afterSave",
86
+ result,
87
+ createOptions,
88
+ );
64
89
  return result;
65
90
  },
66
91
 
@@ -110,6 +135,91 @@ const MutationMethods = {
110
135
  return result;
111
136
  },
112
137
 
138
+ /**
139
+ * @private
140
+ */
141
+ async _prepareDelete(primaryId, options = {}) {
142
+ const canonicalId = this._canonicalPrimaryId(primaryId);
143
+
144
+ // The row is read first only when the delete needs its contents: to
145
+ // find unique-constraint values to clean up, or (mid key migration) to
146
+ // learn which key shape the row actually lives at. Otherwise the key is
147
+ // derived from the id and a single conditional DeleteItem does the work.
148
+ const uniqueConstraints = Object.values(this.uniqueConstraints || {});
149
+ const needsRead =
150
+ uniqueConstraints.length > 0 || this._writesInPlaceWhileMigrating();
151
+
152
+ let item = null;
153
+ let key;
154
+ if (needsRead) {
155
+ item = await this.find(primaryId, { batchDelay: 0 });
156
+ if (!item.exists()) {
157
+ throw new ItemNotFoundError("Item not found", primaryId);
158
+ }
159
+ key = { _pk: item._dyData._pk, _sk: item._dyData._sk };
160
+ } else {
161
+ key = this._getDyKeyForPkSk(this._parsePrimaryId(primaryId));
162
+ }
163
+
164
+ const deleteParams = {
165
+ TableName: this.table,
166
+ Key: key,
167
+ };
168
+
169
+ if (options.condition) {
170
+ const builder = new FilterExpressionBuilder();
171
+ const filterExpression = builder.build(options.condition, this);
172
+
173
+ if (filterExpression) {
174
+ deleteParams.ConditionExpression = filterExpression.FilterExpression;
175
+ deleteParams.ExpressionAttributeNames =
176
+ filterExpression.ExpressionAttributeNames;
177
+ deleteParams.ExpressionAttributeValues =
178
+ filterExpression.ExpressionAttributeValues;
179
+ }
180
+ }
181
+
182
+ let existsGuard = false;
183
+ if (!item) {
184
+ this._addExistsGuard(deleteParams);
185
+ existsGuard = true;
186
+ }
187
+
188
+ const uniqueTransactItems = [];
189
+ const uniqueItemMeta = [];
190
+ if (item !== null) {
191
+ for (const constraint of uniqueConstraints) {
192
+ const value = item[constraint.field];
193
+ if (value) {
194
+ const constraintOp = await this._removeUniqueConstraint(
195
+ constraint.field,
196
+ value,
197
+ item.getPrimaryId(),
198
+ constraint.constraintId,
199
+ );
200
+ uniqueTransactItems.push(constraintOp);
201
+ uniqueItemMeta.push({
202
+ role: "unique_delete",
203
+ constraintField: constraint.field,
204
+ hasExistsGuard: false,
205
+ });
206
+ }
207
+ }
208
+ }
209
+
210
+ const hasConstraintsToClean = uniqueTransactItems.length > 0;
211
+
212
+ return {
213
+ canonicalId,
214
+ item,
215
+ hasConstraintsToClean,
216
+ deleteParams,
217
+ existsGuard,
218
+ uniqueTransactItems,
219
+ uniqueItemMeta,
220
+ };
221
+ },
222
+
113
223
  /**
114
224
  *@memberof BaoModel
115
225
  * @description
@@ -150,33 +260,8 @@ const MutationMethods = {
150
260
  options,
151
261
  );
152
262
 
153
- // The row is read first only when the delete needs its contents: to
154
- // find unique-constraint values to clean up, or (mid key migration) to
155
- // learn which key shape the row actually lives at. Otherwise the key is
156
- // derived from the id and a single conditional DeleteItem does the work.
157
- const uniqueConstraints = Object.values(this.uniqueConstraints || {});
158
- const needsRead =
159
- uniqueConstraints.length > 0 || this._writesInPlaceWhileMigrating();
160
-
161
- let item = null;
162
- let key;
163
- if (needsRead) {
164
- item = await this.find(primaryId, { batchDelay: 0 });
165
- if (!item.exists()) {
166
- throw new ItemNotFoundError("Item not found", primaryId);
167
- }
168
- key = { _pk: item._dyData._pk, _sk: item._dyData._sk };
169
- } else {
170
- key = this._getDyKeyForPkSk(this._parsePrimaryId(primaryId));
171
- }
172
-
173
- // Check if we need to clean up any unique constraints
174
- const hasConstraintsToClean =
175
- item !== null &&
176
- uniqueConstraints.some((constraint) => {
177
- const value = item[constraint.field];
178
- return value != null;
179
- });
263
+ const { item, hasConstraintsToClean, deleteParams, uniqueTransactItems } =
264
+ await this._prepareDelete(primaryId, options);
180
265
 
181
266
  try {
182
267
  let response;
@@ -184,45 +269,10 @@ const MutationMethods = {
184
269
  if (hasConstraintsToClean) {
185
270
  // Transaction path - handle unique constraint cleanup
186
271
  const transactItems = [
187
- {
188
- Delete: {
189
- TableName: this.table,
190
- Key: key,
191
- },
192
- },
272
+ { Delete: deleteParams },
273
+ ...uniqueTransactItems,
193
274
  ];
194
275
 
195
- // Add condition if specified
196
- if (options.condition) {
197
- const builder = new FilterExpressionBuilder();
198
- const filterExpression = builder.build(options.condition, this);
199
-
200
- if (filterExpression) {
201
- transactItems[0].Delete = {
202
- ...transactItems[0].Delete,
203
- ConditionExpression: filterExpression.FilterExpression,
204
- ExpressionAttributeNames:
205
- filterExpression.ExpressionAttributeNames,
206
- ExpressionAttributeValues:
207
- filterExpression.ExpressionAttributeValues,
208
- };
209
- }
210
- }
211
-
212
- // Add unique constraint cleanup operations
213
- for (const constraint of uniqueConstraints) {
214
- const value = item[constraint.field];
215
- if (value) {
216
- const constraintOp = await this._removeUniqueConstraint(
217
- constraint.field,
218
- value,
219
- item.getPrimaryId(),
220
- constraint.constraintId,
221
- );
222
- transactItems.push(constraintOp);
223
- }
224
- }
225
-
226
276
  // The token makes a retry after a lost response a no-op instead of
227
277
  // applying the transaction twice.
228
278
  const clientRequestToken = ulid();
@@ -237,36 +287,14 @@ const MutationMethods = {
237
287
  );
238
288
  } else {
239
289
  // Fast path - simple delete
240
- const deleteParams = {
241
- TableName: this.table,
242
- Key: key,
243
- ReturnValues: "ALL_OLD",
244
- ReturnConsumedCapacity: "TOTAL",
245
- };
246
-
247
- // Add condition if specified
248
- if (options.condition) {
249
- const builder = new FilterExpressionBuilder();
250
- const filterExpression = builder.build(options.condition, this);
251
-
252
- if (filterExpression) {
253
- deleteParams.ConditionExpression =
254
- filterExpression.FilterExpression;
255
- deleteParams.ExpressionAttributeNames =
256
- filterExpression.ExpressionAttributeNames;
257
- deleteParams.ExpressionAttributeValues =
258
- filterExpression.ExpressionAttributeValues;
259
- }
260
- }
261
-
262
- // Without a pre-read, the item's existence is checked by the delete
263
- // itself; a failure is mapped to ItemNotFoundError in the catch below.
264
- if (!item) {
265
- this._addExistsGuard(deleteParams);
266
- }
267
-
268
290
  response = await retryOperation(() =>
269
- this.documentClient.send(new DeleteCommand(deleteParams)),
291
+ this.documentClient.send(
292
+ new DeleteCommand({
293
+ ...deleteParams,
294
+ ReturnValues: "ALL_OLD",
295
+ ReturnConsumedCapacity: "TOTAL",
296
+ }),
297
+ ),
270
298
  );
271
299
  }
272
300
 
@@ -545,18 +573,308 @@ const MutationMethods = {
545
573
  },
546
574
 
547
575
  /**
548
- *@memberof BaoModel
549
- * @private
576
+ * @memberof BaoModel
550
577
  * @description
551
- * Save an item to the database.
552
- * @param {string} primaryId - The primary ID of the item to save.
553
- * @param {Object} jsUpdates - The data to save the item with.
554
- * @param {Object} [options] - Additional options for the save operation.
555
- * @param {boolean} [options.isNew=false] - Whether this is a new item being created. Internal use only.
556
- * @param {Object} [options.instanceObj=null] - Existing model instance, if any. Internal use only.
557
- * @returns {Promise<Object>} Returns a promise that resolves to the saved item.
578
+ * Build a deferred create operation for use with {@link transact}.
579
+ * @param {Object} jsUpdates - Data to create the item with.
580
+ * @param {Object} [options] - Optional condition options.
581
+ * @returns {Object} Op descriptor for transact().
558
582
  */
559
- async _saveItem(primaryId, jsUpdates, options = {}) {
583
+ createOp(jsUpdates, options = {}) {
584
+ if (!jsUpdates || typeof jsUpdates !== "object" || Array.isArray(jsUpdates)) {
585
+ throw new ValidationError("createOp() requires a data object");
586
+ }
587
+ const tenantId = this.manager.getTenantId();
588
+ const model = this;
589
+ const table = this.table;
590
+ const documentClient = this.documentClient;
591
+ const dataCopy = { ...jsUpdates };
592
+ const opOptions = { ...options };
593
+
594
+ return {
595
+ [TRANSACT_OP]: true,
596
+ type: "create",
597
+ model,
598
+ tenantId,
599
+ table,
600
+ documentClient,
601
+ async _prepare() {
602
+ const hookOptions = { isNew: true, ...opOptions };
603
+ const working = { ...dataCopy };
604
+ await pluginManager.executeHooks(
605
+ model.name,
606
+ "beforeSave",
607
+ working,
608
+ hookOptions,
609
+ );
610
+ const prepared = await model._prepareSave(null, working, hookOptions);
611
+ const transactItems = [
612
+ ...prepared.uniqueTransactItems.map(withReturnValuesOnFailure),
613
+ withReturnValuesOnFailure({ Update: prepared.updateParams }),
614
+ ];
615
+ const itemMeta = [
616
+ ...prepared.uniqueItemMeta,
617
+ { role: "main", hasExistsGuard: false },
618
+ ];
619
+ const localResult = model._buildLocalSavedItem(
620
+ true,
621
+ null,
622
+ prepared.dyKey,
623
+ prepared.dyUpdatesToSave,
624
+ );
625
+ return {
626
+ type: "create",
627
+ model,
628
+ tenantId,
629
+ primaryId: prepared.primaryId,
630
+ transactItems,
631
+ itemMeta,
632
+ localResult,
633
+ hookOptions,
634
+ hasAtomicOps: prepared.hasAtomicOps,
635
+ };
636
+ },
637
+ };
638
+ },
639
+
640
+ /**
641
+ * @memberof BaoModel
642
+ * @description
643
+ * Build a deferred update operation for use with {@link transact}.
644
+ * @param {string|Object} primaryId - Primary ID of the item to update.
645
+ * @param {Object} jsUpdates - Changes to apply.
646
+ * @param {Object} [options] - Same options as {@link BaoModel.update}.
647
+ * @returns {Object} Op descriptor for transact().
648
+ */
649
+ updateOp(primaryId, jsUpdates, options = {}) {
650
+ if (primaryId === undefined || primaryId === null) {
651
+ throw new ValidationError("updateOp() requires a primaryId");
652
+ }
653
+ if (!jsUpdates || typeof jsUpdates !== "object" || Array.isArray(jsUpdates)) {
654
+ throw new ValidationError("updateOp() requires an updates object");
655
+ }
656
+ const tenantId = this.manager.getTenantId();
657
+ const model = this;
658
+ const table = this.table;
659
+ const documentClient = this.documentClient;
660
+ const updatesCopy = { ...jsUpdates };
661
+ const opOptions = { ...options };
662
+
663
+ return {
664
+ [TRANSACT_OP]: true,
665
+ type: "update",
666
+ model,
667
+ tenantId,
668
+ table,
669
+ documentClient,
670
+ async _prepare() {
671
+ const hookOptions = { isNew: false, ...opOptions };
672
+ const working = { ...updatesCopy };
673
+ await pluginManager.executeHooks(
674
+ model.name,
675
+ "beforeSave",
676
+ working,
677
+ hookOptions,
678
+ );
679
+ const prepared = await model._prepareSave(
680
+ primaryId,
681
+ working,
682
+ hookOptions,
683
+ );
684
+ const transactItems = [
685
+ ...prepared.uniqueTransactItems.map(withReturnValuesOnFailure),
686
+ withReturnValuesOnFailure({ Update: prepared.updateParams }),
687
+ ];
688
+ const itemMeta = [
689
+ ...prepared.uniqueItemMeta,
690
+ { role: "main", hasExistsGuard: prepared.existsGuard },
691
+ ];
692
+ const localResult =
693
+ prepared.currentItem && !prepared.hasAtomicOps
694
+ ? model._buildLocalSavedItem(
695
+ false,
696
+ prepared.currentItem,
697
+ prepared.dyKey,
698
+ prepared.dyUpdatesToSave,
699
+ )
700
+ : null;
701
+ return {
702
+ type: "update",
703
+ model,
704
+ tenantId,
705
+ primaryId: prepared.primaryId,
706
+ transactItems,
707
+ itemMeta,
708
+ localResult,
709
+ hookOptions,
710
+ hasAtomicOps: prepared.hasAtomicOps,
711
+ };
712
+ },
713
+ };
714
+ },
715
+
716
+ /**
717
+ * @memberof BaoModel
718
+ * @description
719
+ * Build a deferred delete operation for use with {@link transact}.
720
+ * @param {string|Object} primaryId - Primary ID of the item to delete.
721
+ * @param {Object} [options] - Same options as {@link BaoModel.delete}.
722
+ * @returns {Object} Op descriptor for transact().
723
+ */
724
+ deleteOp(primaryId, options = {}) {
725
+ if (primaryId === undefined || primaryId === null) {
726
+ throw new ValidationError("deleteOp() requires a primaryId");
727
+ }
728
+ const tenantId = this.manager.getTenantId();
729
+ const model = this;
730
+ const table = this.table;
731
+ const documentClient = this.documentClient;
732
+ const opOptions = { ...options };
733
+
734
+ return {
735
+ [TRANSACT_OP]: true,
736
+ type: "delete",
737
+ model,
738
+ tenantId,
739
+ table,
740
+ documentClient,
741
+ async _prepare() {
742
+ const canonicalId = model._canonicalPrimaryId(primaryId);
743
+ await pluginManager.executeHooks(
744
+ model.name,
745
+ "beforeDelete",
746
+ canonicalId,
747
+ opOptions,
748
+ );
749
+ const prepared = await model._prepareDelete(primaryId, opOptions);
750
+ const transactItems = [
751
+ withReturnValuesOnFailure({ Delete: prepared.deleteParams }),
752
+ ...prepared.uniqueTransactItems.map(withReturnValuesOnFailure),
753
+ ];
754
+ const itemMeta = [
755
+ { role: "main", hasExistsGuard: prepared.existsGuard },
756
+ ...prepared.uniqueItemMeta,
757
+ ];
758
+ return {
759
+ type: "delete",
760
+ model,
761
+ tenantId,
762
+ primaryId: prepared.canonicalId,
763
+ transactItems,
764
+ itemMeta,
765
+ localResult: prepared.item,
766
+ hookOptions: opOptions,
767
+ hasAtomicOps: false,
768
+ };
769
+ },
770
+ };
771
+ },
772
+
773
+ /**
774
+ * @memberof BaoModel
775
+ * @description
776
+ * Build a deferred ConditionCheck (read-only assertion) for use with {@link transact}.
777
+ * @param {string|Object} primaryId - Primary ID of the item to check.
778
+ * @param {Object} condition - Filter-style condition that must hold.
779
+ * @returns {Object} Op descriptor for transact().
780
+ */
781
+ conditionCheckOp(primaryId, condition) {
782
+ if (primaryId === undefined || primaryId === null) {
783
+ throw new ValidationError("conditionCheckOp() requires a primaryId");
784
+ }
785
+ if (
786
+ !condition ||
787
+ typeof condition !== "object" ||
788
+ Array.isArray(condition) ||
789
+ Object.keys(condition).length === 0
790
+ ) {
791
+ throw new ValidationError(
792
+ "conditionCheckOp() requires a non-empty condition object",
793
+ );
794
+ }
795
+ const tenantId = this.manager.getTenantId();
796
+ const model = this;
797
+ const table = this.table;
798
+ const documentClient = this.documentClient;
799
+
800
+ return {
801
+ [TRANSACT_OP]: true,
802
+ type: "conditionCheck",
803
+ model,
804
+ tenantId,
805
+ table,
806
+ documentClient,
807
+ async _prepare() {
808
+ const canonicalId = model._canonicalPrimaryId(primaryId);
809
+ let key;
810
+ if (model._writesInPlaceWhileMigrating()) {
811
+ const existing = await model.find(canonicalId, { batchDelay: 0 });
812
+ key = existing.exists()
813
+ ? { _pk: existing._dyData._pk, _sk: existing._dyData._sk }
814
+ : model._getDyKeyForPkSk(model._parsePrimaryId(canonicalId));
815
+ } else {
816
+ key = model._getDyKeyForPkSk(model._parsePrimaryId(canonicalId));
817
+ }
818
+
819
+ const builder = new FilterExpressionBuilder();
820
+ const filterExpression = builder.build(condition, model);
821
+ if (!filterExpression) {
822
+ throw new ValidationError(
823
+ "conditionCheckOp() requires a non-empty condition object",
824
+ );
825
+ }
826
+
827
+ const checkParams = {
828
+ TableName: model.table,
829
+ Key: key,
830
+ ConditionExpression: filterExpression.FilterExpression,
831
+ ReturnValuesOnConditionCheckFailure: "ALL_OLD",
832
+ };
833
+ if (Object.keys(filterExpression.ExpressionAttributeNames).length > 0) {
834
+ checkParams.ExpressionAttributeNames =
835
+ filterExpression.ExpressionAttributeNames;
836
+ }
837
+ if (
838
+ Object.keys(filterExpression.ExpressionAttributeValues).length > 0
839
+ ) {
840
+ checkParams.ExpressionAttributeValues =
841
+ filterExpression.ExpressionAttributeValues;
842
+ }
843
+
844
+ return {
845
+ type: "conditionCheck",
846
+ model,
847
+ tenantId,
848
+ primaryId: canonicalId,
849
+ transactItems: [{ ConditionCheck: checkParams }],
850
+ itemMeta: [{ role: "main", hasExistsGuard: false }],
851
+ localResult: null,
852
+ hookOptions: null,
853
+ hasAtomicOps: false,
854
+ };
855
+ },
856
+ };
857
+ },
858
+
859
+ _buildLocalSavedItem(isNew, currentItem, dyKey, dyUpdatesToSave) {
860
+ const base = isNew
861
+ ? {}
862
+ : currentItem.isLoaded()
863
+ ? currentItem._loadedDyData
864
+ : currentItem._dyData;
865
+ const storedItem = { ...base, ...dyKey };
866
+ for (const [key, value] of Object.entries(dyUpdatesToSave)) {
867
+ if (value === undefined) continue;
868
+ if (value === null) {
869
+ delete storedItem[key];
870
+ } else {
871
+ storedItem[key] = value;
872
+ }
873
+ }
874
+ return this._createFromDyItem(storedItem);
875
+ },
876
+
877
+ async _prepareSave(primaryId, jsUpdates, options = {}) {
560
878
  const { isNew = false, instanceObj = null, forceReindex = false } = options;
561
879
 
562
880
  // The id is used as a string below (iteration keys, the relatedId on
@@ -570,7 +888,8 @@ const MutationMethods = {
570
888
 
571
889
  let currentItem = isNew ? null : instanceObj;
572
890
 
573
- const transactItems = [];
891
+ const uniqueTransactItems = [];
892
+ const uniqueItemMeta = [];
574
893
  const dyUpdatesToSave = {};
575
894
  const indexComputationData = {};
576
895
  let hasUniqueConstraintChanges = false;
@@ -760,7 +1079,7 @@ const MutationMethods = {
760
1079
 
761
1080
  // Remove old constraint if updating
762
1081
  if (currentItem && dyCurrentValue) {
763
- transactItems.push(
1082
+ uniqueTransactItems.push(
764
1083
  await this._removeUniqueConstraint(
765
1084
  fieldName,
766
1085
  dyCurrentValue,
@@ -768,11 +1087,16 @@ const MutationMethods = {
768
1087
  constraint.constraintId,
769
1088
  ),
770
1089
  );
1090
+ uniqueItemMeta.push({
1091
+ role: "unique_delete",
1092
+ constraintField: fieldName,
1093
+ hasExistsGuard: false,
1094
+ });
771
1095
  }
772
1096
 
773
1097
  // Add new constraint unless value is null (clearing field removes constraint)
774
1098
  if (dyNewValue !== null) {
775
- transactItems.push(
1099
+ uniqueTransactItems.push(
776
1100
  await this._createUniqueConstraint(
777
1101
  fieldName,
778
1102
  dyNewValue,
@@ -780,6 +1104,11 @@ const MutationMethods = {
780
1104
  constraint.constraintId,
781
1105
  ),
782
1106
  );
1107
+ uniqueItemMeta.push({
1108
+ role: "unique_create",
1109
+ constraintField: fieldName,
1110
+ hasExistsGuard: false,
1111
+ });
783
1112
  }
784
1113
  } else if (dyNewValue !== undefined && currentItem) {
785
1114
  // Re-sending the unchanged value writes no constraint rows, so guard
@@ -855,7 +1184,6 @@ const MutationMethods = {
855
1184
  TableName: this.table,
856
1185
  Key: writeKey,
857
1186
  UpdateExpression: updateExpression,
858
- ReturnValues: "ALL_NEW",
859
1187
  };
860
1188
 
861
1189
  if (Object.keys(names).length > 0) {
@@ -956,14 +1284,58 @@ const MutationMethods = {
956
1284
  const dyKey = writeKey;
957
1285
  logger.debug("dyKey", dyKey);
958
1286
 
1287
+ return {
1288
+ primaryId,
1289
+ dyKey,
1290
+ dyUpdatesToSave,
1291
+ currentItem,
1292
+ consumedCapacity,
1293
+ hasUniqueConstraintChanges,
1294
+ uniqueTransactItems,
1295
+ uniqueItemMeta,
1296
+ updateParams,
1297
+ hasAtomicOps,
1298
+ existsGuard,
1299
+ };
1300
+ },
1301
+
1302
+ /**
1303
+ *@memberof BaoModel
1304
+ * @private
1305
+ * @description
1306
+ * Save an item to the database.
1307
+ * @param {string} primaryId - The primary ID of the item to save.
1308
+ * @param {Object} jsUpdates - The data to save the item with.
1309
+ * @param {Object} [options] - Additional options for the save operation.
1310
+ * @param {boolean} [options.isNew=false] - Whether this is a new item being created. Internal use only.
1311
+ * @param {Object} [options.instanceObj=null] - Existing model instance, if any. Internal use only.
1312
+ * @returns {Promise<Object>} Returns a promise that resolves to the saved item.
1313
+ */
1314
+ async _saveItem(primaryId, jsUpdates, options = {}) {
1315
+ const { isNew = false } = options;
1316
+ const prepared = await this._prepareSave(primaryId, jsUpdates, options);
1317
+ const {
1318
+ dyKey,
1319
+ dyUpdatesToSave,
1320
+ currentItem,
1321
+ consumedCapacity,
1322
+ hasUniqueConstraintChanges,
1323
+ uniqueTransactItems,
1324
+ updateParams,
1325
+ hasAtomicOps,
1326
+ existsGuard,
1327
+ } = prepared;
1328
+ primaryId = prepared.primaryId;
1329
+
959
1330
  try {
960
1331
  let response;
961
1332
 
962
1333
  if (hasUniqueConstraintChanges) {
963
1334
  // Use transaction if we have unique constraint changes
964
- transactItems.push({
965
- Update: updateParams,
966
- });
1335
+ const transactItems = [
1336
+ ...uniqueTransactItems,
1337
+ { Update: updateParams },
1338
+ ];
967
1339
 
968
1340
  if (logger.isDebugEnabled()) {
969
1341
  logger.debug("transactItems", JSON.stringify(transactItems, null, 2));
@@ -995,21 +1367,12 @@ const MutationMethods = {
995
1367
  // loader cache, which still holds the pre-update row.
996
1368
  let savedItem;
997
1369
  if (isNew || !hasAtomicOps) {
998
- const base = isNew
999
- ? {}
1000
- : currentItem.isLoaded()
1001
- ? currentItem._loadedDyData
1002
- : currentItem._dyData;
1003
- const storedItem = { ...base, ...dyKey };
1004
- for (const [key, value] of Object.entries(dyUpdatesToSave)) {
1005
- if (value === undefined) continue;
1006
- if (value === null) {
1007
- delete storedItem[key];
1008
- } else {
1009
- storedItem[key] = value;
1010
- }
1011
- }
1012
- savedItem = this._createFromDyItem(storedItem);
1370
+ savedItem = this._buildLocalSavedItem(
1371
+ isNew,
1372
+ currentItem,
1373
+ dyKey,
1374
+ dyUpdatesToSave,
1375
+ );
1013
1376
  } else {
1014
1377
  const readOptions = { batchDelay: 0, bypassCache: true };
1015
1378
  savedItem = await this.find(primaryId, readOptions);
@@ -1052,6 +1415,7 @@ const MutationMethods = {
1052
1415
  this.documentClient.send(
1053
1416
  new UpdateCommand({
1054
1417
  ...updateParams,
1418
+ ReturnValues: "ALL_NEW",
1055
1419
  ReturnConsumedCapacity: "TOTAL",
1056
1420
  }),
1057
1421
  );
@@ -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,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
+ };