dynamo-bao 0.7.0 → 0.7.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dynamo-bao",
3
- "version": "0.7.0",
3
+ "version": "0.7.2",
4
4
  "description": "Simple powerful data modeling primitives for DynamoDB in JavaScript.",
5
5
  "main": "src/index.js",
6
6
  "exports": {
@@ -32,7 +32,7 @@
32
32
  "license": "MIT",
33
33
  "repository": {
34
34
  "type": "git",
35
- "url": "https://github.com/aag1024/dynamo-bao"
35
+ "url": "git+https://github.com/aag1024/dynamo-bao.git"
36
36
  },
37
37
  "dependencies": {
38
38
  "aws4fetch": "^1.0.20",
@@ -53,12 +53,12 @@
53
53
  "prettier": "3.4.2"
54
54
  },
55
55
  "bin": {
56
- "bao-init": "./bin/dynamo-bao-create-table.js",
57
- "bao-create-table": "./bin/bao-create-table.js",
58
- "bao-codegen": "./bin/codegen.js",
59
- "bao-watch": "./bin/watch.js",
60
- "bao-update-table": "./bin/dynamo-bao-update-table.js",
61
- "bao-delete": "./bin/dynamo-bao-delete-table.js",
62
- "bao-rebuild-search-text": "./bin/bao-rebuild-search-text.js"
56
+ "bao-init": "bin/dynamo-bao-create-table.js",
57
+ "bao-create-table": "bin/bao-create-table.js",
58
+ "bao-codegen": "bin/codegen.js",
59
+ "bao-watch": "bin/watch.js",
60
+ "bao-update-table": "bin/dynamo-bao-update-table.js",
61
+ "bao-delete": "bin/dynamo-bao-delete-table.js",
62
+ "bao-rebuild-search-text": "bin/bao-rebuild-search-text.js"
63
63
  }
64
64
  }
package/src/fields.js CHANGED
@@ -179,11 +179,13 @@ class StringField extends BaoBaseField {
179
179
  */
180
180
  class DateTimeField extends BaoBaseField {
181
181
  validate(value) {
182
- if (this.required && value === undefined) {
182
+ if (this.required && (value === null || value === undefined)) {
183
183
  throw new ValidationError("Field is required", null, value);
184
184
  }
185
+ // null clears the field (toDy maps it to a REMOVE)
185
186
  if (
186
187
  value !== undefined &&
188
+ value !== null &&
187
189
  !(value instanceof Date) &&
188
190
  typeof value !== "number" &&
189
191
  typeof value !== "string"
@@ -115,6 +115,51 @@ const BatchLoadingMethods = {
115
115
  return !!(context && context.batchRequests);
116
116
  },
117
117
 
118
+ /**
119
+ * Key for the request-scoped loader cache. The cache is one Map per request
120
+ * shared by every model and tenant, so the key carries both, plus the
121
+ * canonical string id so a string id and its object form share an entry.
122
+ * @private
123
+ */
124
+ _loaderKey(primaryId) {
125
+ return JSON.stringify([
126
+ this.name,
127
+ this.manager.getTenantId() ?? null,
128
+ this._canonicalPrimaryId(primaryId),
129
+ ]);
130
+ },
131
+
132
+ /**
133
+ * Store a just-written instance in the request-scoped loader cache so a
134
+ * later find() in the same request returns the written row instead of a
135
+ * stale one. Caches a copy with no consumed capacity, so later operations
136
+ * that load it don't report this write's capacity as their own. No-op
137
+ * outside runWithBatchContext().
138
+ * @private
139
+ */
140
+ _primeLoaderContext(primaryId, instance) {
141
+ const loaderContext = batchContext?.getStore()?.loaderContext;
142
+ if (loaderContext) {
143
+ loaderContext.set(
144
+ this._loaderKey(primaryId),
145
+ this._createFromDyItem({ ...instance._dyData }),
146
+ );
147
+ }
148
+ },
149
+
150
+ /**
151
+ * Drop a just-deleted item from the request-scoped loader cache so a later
152
+ * find() in the same request doesn't return the deleted row. No-op outside
153
+ * runWithBatchContext().
154
+ * @private
155
+ */
156
+ _evictFromLoaderContext(primaryId) {
157
+ const loaderContext = batchContext?.getStore()?.loaderContext;
158
+ if (loaderContext) {
159
+ loaderContext.delete(this._loaderKey(primaryId));
160
+ }
161
+ },
162
+
118
163
  /**
119
164
  * @memberof BaoModel
120
165
  * @description
@@ -163,9 +208,10 @@ const BatchLoadingMethods = {
163
208
  // First check loaderContext for existing items
164
209
  if (loaderContext) {
165
210
  primaryIds.forEach((id) => {
166
- if (loaderContext.has(id)) {
211
+ const loaderKey = this._loaderKey(id);
212
+ if (loaderContext.has(loaderKey)) {
167
213
  const instance = this._createFromDyItem(
168
- loaderContext.get(id)._dyData,
214
+ loaderContext.get(loaderKey)._dyData,
169
215
  );
170
216
  results[id] = instance;
171
217
  } else {
@@ -222,7 +268,7 @@ const BatchLoadingMethods = {
222
268
 
223
269
  // Add to loader context if provided
224
270
  if (loaderContext) {
225
- loaderContext.set(primaryId, instance);
271
+ loaderContext.set(this._loaderKey(primaryId), instance);
226
272
  }
227
273
  });
228
274
  }
@@ -277,7 +323,7 @@ const BatchLoadingMethods = {
277
323
  if (fb.item) {
278
324
  const instance = this._createFromDyItem(fb.item);
279
325
  results[instance.getPrimaryId()] = instance;
280
- if (loaderContext) loaderContext.set(id, instance);
326
+ if (loaderContext) loaderContext.set(this._loaderKey(id), instance);
281
327
  }
282
328
  }
283
329
  }
@@ -342,13 +388,16 @@ const BatchLoadingMethods = {
342
388
  }
343
389
 
344
390
  // Check loader context first (unless bypassing cache)
345
- if (!bypassCache && loaderContext && loaderContext.has(primaryId)) {
346
- const cachedItem = loaderContext.get(primaryId);
391
+ const loaderKey = loaderContext ? this._loaderKey(primaryId) : null;
392
+ if (!bypassCache && loaderContext && loaderContext.has(loaderKey)) {
393
+ const cachedItem = loaderContext.get(loaderKey);
347
394
  // Return the exact same cached object instance for true caching
348
395
  return cachedItem;
349
396
  }
350
397
 
351
- if (batchDelay === 0) {
398
+ // bypassCache skips batching too: a batch resolves through batchFind,
399
+ // which reads the loader cache.
400
+ if (batchDelay === 0 || bypassCache) {
352
401
  // Direct DynamoDB request logic
353
402
  const pkSk = this._parsePrimaryId(primaryId);
354
403
  const dyKey = this._getDyKeyForPkSk(pkSk);
@@ -392,7 +441,7 @@ const BatchLoadingMethods = {
392
441
 
393
442
  // Add to loader context if provided (unless bypassing cache)
394
443
  if (!bypassCache && loaderContext) {
395
- loaderContext.set(primaryId, instance);
444
+ loaderContext.set(loaderKey, instance);
396
445
  }
397
446
 
398
447
  return instance;
@@ -400,7 +449,10 @@ const BatchLoadingMethods = {
400
449
 
401
450
  // Batch request logic
402
451
  return new Promise((resolve, reject) => {
403
- const batchKey = `${this.name}-${batchDelay}`;
452
+ // One batch per model, tenant and delay: the batch builds its keys in
453
+ // the first caller's async context, so it must not mix tenants.
454
+ const tenantId = this.manager.getTenantId() ?? "";
455
+ const batchKey = `${this.name}-${tenantId}-${batchDelay}`;
404
456
  const batchRequests = this._getBatchRequests();
405
457
  let batchRequest = batchRequests.get(batchKey);
406
458
 
@@ -225,6 +225,8 @@ const MutationMethods = {
225
225
  );
226
226
  }
227
227
 
228
+ this._evictFromLoaderContext(primaryId);
229
+
228
230
  await pluginManager.executeHooks(
229
231
  this.name,
230
232
  "afterDelete",
@@ -281,7 +283,7 @@ const MutationMethods = {
281
283
  * @param {string} primaryId - The record's logical primary id.
282
284
  * @param {Object} [options]
283
285
  * @param {boolean} [options.dryRun=false] - Inspect only; perform no writes.
284
- * @returns {Promise<{relocated: boolean, from: ?string, to: string, reason?: string}>}
286
+ * @returns {Promise<{relocated: boolean, from: ?string, to: string, reason: (string|undefined)}>}
285
287
  */
286
288
  async relocateToCanonicalKey(primaryId, options = {}) {
287
289
  const { dryRun = false } = options;
@@ -419,6 +421,12 @@ const MutationMethods = {
419
421
  forceReindex = false,
420
422
  } = options;
421
423
 
424
+ // The id is used as a string below (iteration keys, the relatedId on
425
+ // unique constraint rows), so accept an object id by normalizing it.
426
+ if (!isNew) {
427
+ primaryId = this._canonicalPrimaryId(primaryId);
428
+ }
429
+
422
430
  logger.debug("saveItem", primaryId, isNew, instanceObj);
423
431
  let consumedCapacity = [];
424
432
 
@@ -475,6 +483,44 @@ const MutationMethods = {
475
483
  }
476
484
  }
477
485
 
486
+ // A relative counter ("+3") is written with ADD, which DynamoDB applies
487
+ // at write time, but an index key built from it needs the resulting
488
+ // number. On a new item ADD just stores the delta, so write that. On an
489
+ // existing item, a counter that's part of an index key is written as
490
+ // the loaded value plus the delta, guarded on the loaded value, so a
491
+ // concurrent change fails the update (ConditionalError) instead of
492
+ // leaving the index key stale. Other counters keep the atomic ADD.
493
+ const counterGuards = [];
494
+ const { CounterFieldClass } = require("../fields");
495
+ for (const [key, field] of Object.entries(this.fields)) {
496
+ const dyValue = dyUpdatesToSave[key];
497
+ if (
498
+ !(field instanceof CounterFieldClass) ||
499
+ typeof dyValue !== "string"
500
+ ) {
501
+ continue;
502
+ }
503
+ const delta = parseInt(dyValue, 10);
504
+ let value;
505
+ if (isNew) {
506
+ value = delta;
507
+ } else if (
508
+ Object.values(this.indexes).some(
509
+ (index) =>
510
+ index.indexId !== undefined &&
511
+ (index.pk === key || index.sk === key),
512
+ )
513
+ ) {
514
+ const loadedValue = currentItem._loadedDyData[key];
515
+ value = Number(loadedValue ?? 0) + delta;
516
+ counterGuards.push({ fieldName: key, loadedValue });
517
+ } else {
518
+ continue;
519
+ }
520
+ dyUpdatesToSave[key] = value;
521
+ indexComputationData[key] = value;
522
+ }
523
+
478
524
  // Backfill from currentItem for GSI consistency
479
525
  if (!isNew && currentItem) {
480
526
  if (forceReindex) {
@@ -543,11 +589,9 @@ const MutationMethods = {
543
589
  }
544
590
  });
545
591
 
546
- // Validate unique constraints before attempting save
547
- await this._validateUniqueConstraints(
548
- jsUpdates,
549
- isNew ? null : primaryId,
550
- );
592
+ // No pre-save uniqueness read: each constraint Put in the transaction
593
+ // carries attribute_not_exists, and the catch block below runs
594
+ // _validateUniqueConstraints to name the colliding field.
551
595
 
552
596
  // Handle unique constraints
553
597
  for (const constraint of Object.values(this.uniqueConstraints || {})) {
@@ -689,12 +733,20 @@ const MutationMethods = {
689
733
  ...filterExpression.ExpressionAttributeValues,
690
734
  };
691
735
  }
692
- } else if (isNew) {
693
- // For new items, ensure they don't already exist
694
- updateParams.ConditionExpression = "attribute_not_exists(#pk)";
736
+ }
737
+
738
+ if (isNew) {
739
+ // For new items, ensure they don't already exist, ANDed with any
740
+ // caller-supplied condition. _buildUpdateExpression maps each field
741
+ // to "#<fieldName>"; user field names can't start with "_" and no
742
+ // system field starts with "__", so a "#__" placeholder can't clobber
743
+ // one.
744
+ updateParams.ConditionExpression = updateParams.ConditionExpression
745
+ ? `(${updateParams.ConditionExpression}) AND attribute_not_exists(#__newItemPk)`
746
+ : "attribute_not_exists(#__newItemPk)";
695
747
  updateParams.ExpressionAttributeNames = {
696
748
  ...updateParams.ExpressionAttributeNames,
697
- "#pk": "_pk",
749
+ "#__newItemPk": "_pk",
698
750
  };
699
751
  }
700
752
 
@@ -706,16 +758,35 @@ const MutationMethods = {
706
758
  // will then find and update the relocated canonical row. ANDed with any
707
759
  // caller-supplied condition.
708
760
  //
709
- // Use a dedicated placeholder (not "#pk") so we never clobber a user
710
- // field literally named `pk`, which _buildUpdateExpression maps to
711
- // "#pk".
761
+ // Use a "#__" placeholder so we never clobber a field placeholder
762
+ // (see the new-item guard above).
763
+ updateParams.ExpressionAttributeNames = {
764
+ ...updateParams.ExpressionAttributeNames,
765
+ "#__migExistsPk": "_pk",
766
+ };
767
+ updateParams.ConditionExpression = updateParams.ConditionExpression
768
+ ? `(${updateParams.ConditionExpression}) AND attribute_exists(#__migExistsPk)`
769
+ : "attribute_exists(#__migExistsPk)";
770
+ }
771
+
772
+ for (const { fieldName, loadedValue } of counterGuards) {
773
+ const name = `#__counterGuard_${fieldName}`;
774
+ const value = `:__counterGuard_${fieldName}`;
712
775
  updateParams.ExpressionAttributeNames = {
713
776
  ...updateParams.ExpressionAttributeNames,
714
- "#migExistsPk": "_pk",
777
+ [name]: fieldName,
715
778
  };
779
+ let guard = `attribute_not_exists(${name})`;
780
+ if (loadedValue != null) {
781
+ guard = `${name} = ${value}`;
782
+ updateParams.ExpressionAttributeValues = {
783
+ ...updateParams.ExpressionAttributeValues,
784
+ [value]: loadedValue,
785
+ };
786
+ }
716
787
  updateParams.ConditionExpression = updateParams.ConditionExpression
717
- ? `(${updateParams.ConditionExpression}) AND attribute_exists(#migExistsPk)`
718
- : "attribute_exists(#migExistsPk)";
788
+ ? `(${updateParams.ConditionExpression}) AND ${guard}`
789
+ : guard;
719
790
  }
720
791
 
721
792
  const dyKey = writeKey;
@@ -744,13 +815,28 @@ const MutationMethods = {
744
815
  logger.debug("transactItems response", response);
745
816
  logger.debug("primaryId to load", primaryId);
746
817
 
747
- // Fetch the item since transactWrite doesn't return values
748
- let savedItem = await this.find(primaryId, { batchDelay: 0 });
749
-
750
- // if the item doesn't exist, sleep for 200ms and try again
751
- if (!savedItem.exists()) {
752
- await new Promise((resolve) => setTimeout(resolve, 200));
753
- savedItem = await this.find(primaryId, { batchDelay: 0 });
818
+ // transactWrite doesn't return values. A new item is exactly its key
819
+ // plus what we wrote (REMOVEd nulls aside), so build it locally. An
820
+ // update must be read back, bypassing the loader cache, which still
821
+ // holds the pre-update row.
822
+ let savedItem;
823
+ if (isNew) {
824
+ const storedItem = { ...dyKey };
825
+ for (const [key, value] of Object.entries(dyUpdatesToSave)) {
826
+ if (value !== undefined && value !== null) {
827
+ storedItem[key] = value;
828
+ }
829
+ }
830
+ savedItem = this._createFromDyItem(storedItem);
831
+ } else {
832
+ const readOptions = { batchDelay: 0, bypassCache: true };
833
+ savedItem = await this.find(primaryId, readOptions);
834
+
835
+ // if the item doesn't exist, sleep for 200ms and try again
836
+ if (!savedItem.exists()) {
837
+ await new Promise((resolve) => setTimeout(resolve, 200));
838
+ savedItem = await this.find(primaryId, readOptions);
839
+ }
754
840
  }
755
841
 
756
842
  logger.debug("savedItem", savedItem);
@@ -766,8 +852,11 @@ const MutationMethods = {
766
852
  "write",
767
853
  false,
768
854
  );
769
- savedItem._addConsumedCapacity(consumedCapacity, "read", false);
855
+ // The loaded row's capacity was counted in the request total when
856
+ // it was consumed, so don't count it again.
857
+ savedItem._addConsumedCapacity(consumedCapacity, "read", false, true);
770
858
 
859
+ this._primeLoaderContext(primaryId, savedItem);
771
860
  return savedItem;
772
861
  } else {
773
862
  // Use simple update if no unique constraints are changing
@@ -795,12 +884,15 @@ const MutationMethods = {
795
884
  "write",
796
885
  false,
797
886
  );
798
- savedItem._addConsumedCapacity(consumedCapacity, "read", false);
887
+ // The loaded row's capacity was counted in the request total when
888
+ // it was consumed, so don't count it again.
889
+ savedItem._addConsumedCapacity(consumedCapacity, "read", false, true);
799
890
 
800
891
  if (!savedItem.exists()) {
801
892
  throw new ConditionalError("Failed to fetch saved item", "update");
802
893
  }
803
894
 
895
+ this._primeLoaderContext(primaryId, savedItem);
804
896
  return savedItem;
805
897
  }
806
898
  } catch (error) {
@@ -810,6 +902,13 @@ const MutationMethods = {
810
902
  }
811
903
 
812
904
  if (error.name === "TransactionCanceledException") {
905
+ // A taken unique value cancels the transaction; this read throws a
906
+ // ConditionalError naming the field if that's the cause.
907
+ await this._validateUniqueConstraints(
908
+ jsUpdates,
909
+ isNew ? null : primaryId,
910
+ );
911
+
813
912
  // Check if it's due to conditional check failure
814
913
  if (
815
914
  error.CancellationReasons?.some(
@@ -822,12 +921,6 @@ const MutationMethods = {
822
921
  error,
823
922
  );
824
923
  }
825
- // For other transaction cancellation reasons, try to validate unique constraints
826
- // which will throw the appropriate ConditionalError if that's the issue
827
- await this._validateUniqueConstraints(
828
- jsUpdates,
829
- isNew ? null : primaryId,
830
- );
831
924
  }
832
925
  throw error;
833
926
  }
package/src/model.js CHANGED
@@ -1119,6 +1119,17 @@ class BaoModel {
1119
1119
  return this.constructor.getPrimaryId(this._dyData);
1120
1120
  }
1121
1121
 
1122
+ /**
1123
+ * The string form of a primary id given as a string or an object (either
1124
+ * `{ pk, sk }` or the key field values), as {@link BaoModel#getPrimaryId}
1125
+ * returns it.
1126
+ * @private
1127
+ */
1128
+ static _canonicalPrimaryId(primaryId) {
1129
+ const pkSk = this._parsePrimaryId(primaryId);
1130
+ return this.makePrimaryId(pkSk.pk, pkSk.sk);
1131
+ }
1132
+
1122
1133
  static _parsePrimaryId(primaryId) {
1123
1134
  if (typeof primaryId === "object" && primaryId !== null) {
1124
1135
  if (primaryId.pk !== undefined) {