dynamo-bao 0.6.1 → 0.7.1

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.6.1",
3
+ "version": "0.7.1",
4
4
  "description": "Simple powerful data modeling primitives for DynamoDB in JavaScript.",
5
5
  "main": "src/index.js",
6
6
  "exports": {
@@ -45,12 +45,12 @@
45
45
  "clean-jsdoc-theme": "^4.3.0",
46
46
  "cross-env": "^7.0.3",
47
47
  "docdash": "^2.0.2",
48
- "formidable": ">=2.1.3",
48
+ "eslint-plugin-promise": "^6.1.1",
49
+ "formidable": "^3.5.4",
49
50
  "gh-pages": "^6.2.0",
50
51
  "jest": "^29.7.0",
51
52
  "jsdoc": "^4.0.4",
52
- "prettier": "3.4.2",
53
- "eslint-plugin-promise": "^6.1.1"
53
+ "prettier": "3.4.2"
54
54
  },
55
55
  "bin": {
56
56
  "bao-init": "./bin/dynamo-bao-create-table.js",
@@ -190,6 +190,7 @@ class DynamoDBClient {
190
190
  const operationMap = {
191
191
  'GetCommand': 'GetItem',
192
192
  'QueryCommand': 'Query',
193
+ 'PutCommand': 'PutItem',
193
194
  'UpdateCommand': 'UpdateItem',
194
195
  'DeleteCommand': 'DeleteItem',
195
196
  'BatchGetCommand': 'BatchGetItem',
@@ -294,6 +295,21 @@ class DynamoDBDocumentClient {
294
295
  }
295
296
  break;
296
297
 
298
+ case 'PutCommand':
299
+ const putItem = {};
300
+ Object.keys(input.Item).forEach(key => {
301
+ putItem[key] = marshall(input.Item[key]);
302
+ });
303
+ input.Item = putItem;
304
+ if (input.ExpressionAttributeValues) {
305
+ const marshalledValues = {};
306
+ Object.keys(input.ExpressionAttributeValues).forEach(key => {
307
+ marshalledValues[key] = marshall(input.ExpressionAttributeValues[key]);
308
+ });
309
+ input.ExpressionAttributeValues = marshalledValues;
310
+ }
311
+ break;
312
+
297
313
  case 'UpdateCommand':
298
314
  const updateKey = {};
299
315
  Object.keys(input.Key).forEach(key => {
@@ -308,7 +324,7 @@ class DynamoDBDocumentClient {
308
324
  input.ExpressionAttributeValues = marshalledValues;
309
325
  }
310
326
  break;
311
-
327
+
312
328
  case 'DeleteCommand':
313
329
  const deleteKey = {};
314
330
  Object.keys(input.Key).forEach(key => {
@@ -442,6 +458,16 @@ class DynamoDBDocumentClient {
442
458
  }
443
459
  break;
444
460
 
461
+ case 'PutCommand':
462
+ if (result.Attributes) {
463
+ const unmarshalledAttributes = {};
464
+ Object.keys(result.Attributes).forEach(key => {
465
+ unmarshalledAttributes[key] = unmarshall(result.Attributes[key]);
466
+ });
467
+ result.Attributes = unmarshalledAttributes;
468
+ }
469
+ break;
470
+
445
471
  case 'UpdateCommand':
446
472
  if (result.Attributes) {
447
473
  const unmarshalledAttributes = {};
@@ -451,7 +477,7 @@ class DynamoDBDocumentClient {
451
477
  result.Attributes = unmarshalledAttributes;
452
478
  }
453
479
  break;
454
-
480
+
455
481
  case 'DeleteCommand':
456
482
  if (result.Attributes) {
457
483
  const unmarshalledAttributes = {};
@@ -589,6 +615,12 @@ class QueryCommand {
589
615
  }
590
616
  }
591
617
 
618
+ class PutCommand {
619
+ constructor(input) {
620
+ this.input = input;
621
+ }
622
+ }
623
+
592
624
  class UpdateCommand {
593
625
  constructor(input) {
594
626
  this.input = input;
@@ -654,6 +686,7 @@ module.exports = {
654
686
  DynamoDBDocumentClient,
655
687
  GetCommand,
656
688
  QueryCommand,
689
+ PutCommand,
657
690
  UpdateCommand,
658
691
  DeleteCommand,
659
692
  BatchGetCommand,
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"
package/src/index.js CHANGED
@@ -172,6 +172,14 @@ function initModels(userConfig = {}) {
172
172
  ...config.batchContext,
173
173
  ...(userConfig.batchContext || {}),
174
174
  },
175
+ // Key-migration controls (e.g. modelPrefixPkMode) for safely transitioning
176
+ // the on-disk key format of `pk === "modelPrefix"` models. Unset mode still
177
+ // resolves to legacy behavior, but tenant-enabled models with this key shape
178
+ // must choose a mode explicitly during validation.
179
+ keyMigration: {
180
+ ...config.keyMigration,
181
+ ...(userConfig.keyMigration || {}),
182
+ },
175
183
  models: userConfig.models || config.models || null,
176
184
  };
177
185
 
@@ -33,6 +33,19 @@ function _accumulateCapacityToContext(capacityUnits, type) {
33
33
  }
34
34
  }
35
35
 
36
+ /**
37
+ * Return a ConsumedCapacity object with `extraUnits` added to its CapacityUnits.
38
+ * Used so the legacy-fallback reads (migrating mode) are reflected in the
39
+ * capacity carried by the returned item/ObjectNotFound, not just the context.
40
+ */
41
+ function _withExtraCapacityUnits(consumedCapacity, extraUnits) {
42
+ if (!extraUnits) return consumedCapacity;
43
+ return {
44
+ ...consumedCapacity,
45
+ CapacityUnits: (consumedCapacity?.CapacityUnits || 0) + extraUnits,
46
+ };
47
+ }
48
+
36
49
  /**
37
50
  * Get the total consumed capacity for the current batch context.
38
51
  * Returns the accumulated RCUs and WCUs for all operations within the current
@@ -102,6 +115,52 @@ const BatchLoadingMethods = {
102
115
  return !!(context && context.batchRequests);
103
116
  },
104
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
+ const pkSk = this._parsePrimaryId(primaryId);
126
+ return JSON.stringify([
127
+ this.name,
128
+ this.manager.getTenantId() ?? null,
129
+ this.makePrimaryId(pkSk.pk, pkSk.sk),
130
+ ]);
131
+ },
132
+
133
+ /**
134
+ * Store a just-written instance in the request-scoped loader cache so a
135
+ * later find() in the same request returns the written row instead of a
136
+ * stale one. Caches a copy with no consumed capacity, so later operations
137
+ * that load it don't report this write's capacity as their own. No-op
138
+ * outside runWithBatchContext().
139
+ * @private
140
+ */
141
+ _primeLoaderContext(primaryId, instance) {
142
+ const loaderContext = batchContext?.getStore()?.loaderContext;
143
+ if (loaderContext) {
144
+ loaderContext.set(
145
+ this._loaderKey(primaryId),
146
+ this._createFromDyItem({ ...instance._dyData }),
147
+ );
148
+ }
149
+ },
150
+
151
+ /**
152
+ * Drop a just-deleted item from the request-scoped loader cache so a later
153
+ * find() in the same request doesn't return the deleted row. No-op outside
154
+ * runWithBatchContext().
155
+ * @private
156
+ */
157
+ _evictFromLoaderContext(primaryId) {
158
+ const loaderContext = batchContext?.getStore()?.loaderContext;
159
+ if (loaderContext) {
160
+ loaderContext.delete(this._loaderKey(primaryId));
161
+ }
162
+ },
163
+
105
164
  /**
106
165
  * @memberof BaoModel
107
166
  * @description
@@ -150,9 +209,10 @@ const BatchLoadingMethods = {
150
209
  // First check loaderContext for existing items
151
210
  if (loaderContext) {
152
211
  primaryIds.forEach((id) => {
153
- if (loaderContext.has(id)) {
212
+ const loaderKey = this._loaderKey(id);
213
+ if (loaderContext.has(loaderKey)) {
154
214
  const instance = this._createFromDyItem(
155
- loaderContext.get(id)._dyData,
215
+ loaderContext.get(loaderKey)._dyData,
156
216
  );
157
217
  results[id] = instance;
158
218
  } else {
@@ -209,7 +269,7 @@ const BatchLoadingMethods = {
209
269
 
210
270
  // Add to loader context if provided
211
271
  if (loaderContext) {
212
- loaderContext.set(primaryId, instance);
272
+ loaderContext.set(this._loaderKey(primaryId), instance);
213
273
  }
214
274
  });
215
275
  }
@@ -244,6 +304,31 @@ const BatchLoadingMethods = {
244
304
  }
245
305
  }
246
306
 
307
+ // Migration read fallback (pk === "modelPrefix", "migrating" mode only):
308
+ // ids not found at the canonical tenant-scoped key may still live at a
309
+ // legacy key shape. Resolve those individually — the miss set is small and
310
+ // only present mid-migration.
311
+ if (
312
+ this.primaryKey.pk === "modelPrefix" &&
313
+ this._modelPrefixPkMode() === "migrating"
314
+ ) {
315
+ for (const id of idsToLoad) {
316
+ if (results[id]) continue;
317
+ const fb = await this._getRawItemWithLegacyFallback(
318
+ this._parsePrimaryId(id),
319
+ );
320
+ if (fb.consumedUnits) {
321
+ consumedCapacity.push({ CapacityUnits: fb.consumedUnits });
322
+ _accumulateCapacityToContext(fb.consumedUnits, "read");
323
+ }
324
+ if (fb.item) {
325
+ const instance = this._createFromDyItem(fb.item);
326
+ results[instance.getPrimaryId()] = instance;
327
+ if (loaderContext) loaderContext.set(this._loaderKey(id), instance);
328
+ }
329
+ }
330
+ }
331
+
247
332
  return {
248
333
  items: results,
249
334
  ConsumedCapacity: consumedCapacity,
@@ -304,13 +389,16 @@ const BatchLoadingMethods = {
304
389
  }
305
390
 
306
391
  // Check loader context first (unless bypassing cache)
307
- if (!bypassCache && loaderContext && loaderContext.has(primaryId)) {
308
- const cachedItem = loaderContext.get(primaryId);
392
+ const loaderKey = loaderContext ? this._loaderKey(primaryId) : null;
393
+ if (!bypassCache && loaderContext && loaderContext.has(loaderKey)) {
394
+ const cachedItem = loaderContext.get(loaderKey);
309
395
  // Return the exact same cached object instance for true caching
310
396
  return cachedItem;
311
397
  }
312
398
 
313
- if (batchDelay === 0) {
399
+ // bypassCache skips batching too: a batch resolves through batchFind,
400
+ // which reads the loader cache.
401
+ if (batchDelay === 0 || bypassCache) {
314
402
  // Direct DynamoDB request logic
315
403
  const pkSk = this._parsePrimaryId(primaryId);
316
404
  const dyKey = this._getDyKeyForPkSk(pkSk);
@@ -322,22 +410,39 @@ const BatchLoadingMethods = {
322
410
  }),
323
411
  );
324
412
 
413
+ let item = result.Item;
414
+ let fallbackUnits = 0;
415
+ if (!item) {
416
+ const fb = await this._getRawItemWithLegacyFallback(pkSk);
417
+ item = fb.item;
418
+ fallbackUnits = fb.consumedUnits;
419
+ }
420
+
325
421
  let instance;
326
- if (!result.Item) {
327
- instance = new ObjectNotFound(result.ConsumedCapacity);
422
+ if (!item) {
423
+ instance = new ObjectNotFound(
424
+ _withExtraCapacityUnits(result.ConsumedCapacity, fallbackUnits),
425
+ );
328
426
  // Accumulate capacity for ObjectNotFound since _addConsumedCapacity isn't called
329
427
  _accumulateCapacityToContext(
330
- result.ConsumedCapacity?.CapacityUnits || 0,
428
+ (result.ConsumedCapacity?.CapacityUnits || 0) + fallbackUnits,
331
429
  "read",
332
430
  );
333
431
  } else {
334
- instance = this._createFromDyItem(result.Item);
432
+ instance = this._createFromDyItem(item);
335
433
  instance._addConsumedCapacity(result.ConsumedCapacity, "read", false);
434
+ if (fallbackUnits) {
435
+ instance._addConsumedCapacity(
436
+ { CapacityUnits: fallbackUnits },
437
+ "read",
438
+ false,
439
+ );
440
+ }
336
441
  }
337
442
 
338
443
  // Add to loader context if provided (unless bypassing cache)
339
444
  if (!bypassCache && loaderContext) {
340
- loaderContext.set(primaryId, instance);
445
+ loaderContext.set(loaderKey, instance);
341
446
  }
342
447
 
343
448
  return instance;
@@ -345,7 +450,10 @@ const BatchLoadingMethods = {
345
450
 
346
451
  // Batch request logic
347
452
  return new Promise((resolve, reject) => {
348
- const batchKey = `${this.name}-${batchDelay}`;
453
+ // One batch per model, tenant and delay: the batch builds its keys in
454
+ // the first caller's async context, so it must not mix tenants.
455
+ const tenantId = this.manager.getTenantId() ?? "";
456
+ const batchKey = `${this.name}-${tenantId}-${batchDelay}`;
349
457
  const batchRequests = this._getBatchRequests();
350
458
  let batchRequest = batchRequests.get(batchKey);
351
459
 
@@ -381,18 +489,29 @@ const BatchLoadingMethods = {
381
489
  0,
382
490
  );
383
491
 
384
- // Resolve all promises, including multiple callbacks for the same ID
492
+ // Resolve all promises, including multiple callbacks for the same ID.
493
+ // Sum ALL ConsumedCapacity entries (multiple BatchGet pages and any
494
+ // legacy-fallback GetItems in migrating mode), not just the first,
495
+ // so the per-operation capacity isn't under-reported.
496
+ const totalUnits = (ConsumedCapacity || []).reduce(
497
+ (sum, c) => sum + (c?.CapacityUnits || 0),
498
+ 0,
499
+ );
385
500
  const consumedCapacity = {
386
501
  TableName: this.table,
387
- CapacityUnits:
388
- ConsumedCapacity[0]?.CapacityUnits / totalCallbacks,
502
+ CapacityUnits: totalCallbacks ? totalUnits / totalCallbacks : 0,
389
503
  };
390
504
 
391
505
  currentBatch.items.forEach((batchItem) => {
392
506
  let item = items[batchItem.id];
393
507
  if (item) {
394
508
  // Skip context accumulation since batchFind already accumulated the total
395
- item._addConsumedCapacity(consumedCapacity, "read", false, true);
509
+ item._addConsumedCapacity(
510
+ consumedCapacity,
511
+ "read",
512
+ false,
513
+ true,
514
+ );
396
515
  } else {
397
516
  item = new ObjectNotFound(consumedCapacity);
398
517
  }
@@ -456,6 +575,35 @@ const BatchLoadingMethods = {
456
575
  });
457
576
  },
458
577
 
578
+ /**
579
+ * Read fallback for the `pk === "modelPrefix"` migration. When a record is
580
+ * not found at the canonical (tenant-scoped) key while in "migrating" mode,
581
+ * try the legacy key shapes so pre-migration rows remain resolvable.
582
+ *
583
+ * Returns the raw DynamoDB item (with its actual stored `_pk`/`_sk`) or null,
584
+ * plus the total capacity consumed across the fallback GetItem(s). The CALLER
585
+ * is responsible for accounting that capacity (so it is reflected in the
586
+ * returned per-operation ConsumedCapacity, not just the batch context).
587
+ * @param {Object} pkSk - Parsed primary key values
588
+ * @returns {Promise<{ item: Object|null, consumedUnits: number }>}
589
+ */
590
+ async _getRawItemWithLegacyFallback(pkSk) {
591
+ const legacyKeys = this._legacyDyKeysForPkSk(pkSk);
592
+ let consumedUnits = 0;
593
+ for (const Key of legacyKeys) {
594
+ const result = await this.documentClient.send(
595
+ new GetCommand({
596
+ TableName: this.table,
597
+ Key,
598
+ ReturnConsumedCapacity: "TOTAL",
599
+ }),
600
+ );
601
+ consumedUnits += result.ConsumedCapacity?.CapacityUnits || 0;
602
+ if (result.Item) return { item: result.Item, consumedUnits };
603
+ }
604
+ return { item: null, consumedUnits };
605
+ },
606
+
459
607
  /**
460
608
  * Execute find operation directly without batching or caching
461
609
  * @param {string} primaryId - The primary ID to find
@@ -472,11 +620,28 @@ const BatchLoadingMethods = {
472
620
  }),
473
621
  );
474
622
 
475
- if (!result.Item) {
476
- return new ObjectNotFound(result.ConsumedCapacity);
623
+ let item = result.Item;
624
+ let fallbackUnits = 0;
625
+ if (!item) {
626
+ const fb = await this._getRawItemWithLegacyFallback(pkSk);
627
+ item = fb.item;
628
+ fallbackUnits = fb.consumedUnits;
629
+ }
630
+
631
+ if (!item) {
632
+ return new ObjectNotFound(
633
+ _withExtraCapacityUnits(result.ConsumedCapacity, fallbackUnits),
634
+ );
477
635
  } else {
478
- const instance = this._createFromDyItem(result.Item);
636
+ const instance = this._createFromDyItem(item);
479
637
  instance._addConsumedCapacity(result.ConsumedCapacity, "read", false);
638
+ if (fallbackUnits) {
639
+ instance._addConsumedCapacity(
640
+ { CapacityUnits: fallbackUnits },
641
+ "read",
642
+ false,
643
+ );
644
+ }
480
645
  return instance;
481
646
  }
482
647
  },
@@ -2,6 +2,8 @@ const {
2
2
  TransactWriteCommand,
3
3
  UpdateCommand,
4
4
  DeleteCommand,
5
+ GetCommand,
6
+ PutCommand,
5
7
  } = require("../dynamodb-client");
6
8
  const { defaultLogger: logger } = require("../utils/logger");
7
9
  const { pluginManager } = require("../plugin-manager");
@@ -223,6 +225,8 @@ const MutationMethods = {
223
225
  );
224
226
  }
225
227
 
228
+ this._evictFromLoaderContext(primaryId);
229
+
226
230
  await pluginManager.executeHooks(
227
231
  this.name,
228
232
  "afterDelete",
@@ -258,6 +262,129 @@ const MutationMethods = {
258
262
  }
259
263
  },
260
264
 
265
+ /**
266
+ * @memberof BaoModel
267
+ * @description
268
+ * Relocate a single record's base-table row from a legacy `pk === "modelPrefix"`
269
+ * key to the current canonical key. This is the per-record primitive used to
270
+ * back-fill the `keyMigration.modelPrefixPkMode` migration.
271
+ *
272
+ * Must be called in "migrating" mode and under the row's tenant context (so
273
+ * `getTenantId()` resolves the tenant the canonical `[tenant]#prefix` key is
274
+ * built from). The row's full item is copied verbatim to the canonical key
275
+ * (a conditional Put that won't clobber an existing canonical row), then the
276
+ * legacy row is deleted. GSI entries and unique-constraint pointers are
277
+ * unaffected (their keys never change; the pointer's relatedId is the
278
+ * unchanged logical id), so only the base row moves.
279
+ *
280
+ * Idempotent and safe to re-run: a row already at the canonical key is left
281
+ * alone; a stale legacy row left behind by an interrupted run is cleaned up.
282
+ *
283
+ * @param {string} primaryId - The record's logical primary id.
284
+ * @param {Object} [options]
285
+ * @param {boolean} [options.dryRun=false] - Inspect only; perform no writes.
286
+ * @returns {Promise<{relocated: boolean, from: ?string, to: string, reason?: string}>}
287
+ */
288
+ async relocateToCanonicalKey(primaryId, options = {}) {
289
+ const { dryRun = false } = options;
290
+
291
+ if (this.primaryKey.pk !== "modelPrefix") {
292
+ throw new Error(
293
+ `relocateToCanonicalKey is only valid for models whose primaryKey.pk is "modelPrefix" (got "${this.primaryKey.pk}" for ${this.name})`,
294
+ );
295
+ }
296
+ if (this._modelPrefixPkMode() !== "migrating") {
297
+ throw new Error(
298
+ `relocateToCanonicalKey must be called in "migrating" mode (modelPrefixPkMode is "${this._modelPrefixPkMode()}")`,
299
+ );
300
+ }
301
+
302
+ const pkSk = this._parsePrimaryId(primaryId);
303
+ const canonicalKey = this._getDyKeyForPkSk(pkSk);
304
+ const legacyKeys = this._legacyDyKeysForPkSk(pkSk);
305
+
306
+ const get = (Key) =>
307
+ this.documentClient
308
+ .send(new GetCommand({ TableName: this.table, Key }))
309
+ .then((r) => r.Item || null);
310
+
311
+ // Already at the canonical key? Clean up any stale legacy duplicate, done.
312
+ const canonicalItem = await get(canonicalKey);
313
+ if (canonicalItem) {
314
+ for (const legacyKey of legacyKeys) {
315
+ const stale = await get(legacyKey);
316
+ if (stale && !dryRun) {
317
+ await this.documentClient.send(
318
+ new DeleteCommand({ TableName: this.table, Key: legacyKey }),
319
+ );
320
+ }
321
+ }
322
+ return {
323
+ relocated: false,
324
+ from: null,
325
+ to: canonicalKey._pk,
326
+ reason: "already-canonical",
327
+ };
328
+ }
329
+
330
+ // Find the row at a legacy key.
331
+ let sourceItem = null;
332
+ let sourceKey = null;
333
+ for (const legacyKey of legacyKeys) {
334
+ const item = await get(legacyKey);
335
+ if (item) {
336
+ sourceItem = item;
337
+ sourceKey = legacyKey;
338
+ break;
339
+ }
340
+ }
341
+
342
+ if (!sourceItem) {
343
+ return {
344
+ relocated: false,
345
+ from: null,
346
+ to: canonicalKey._pk,
347
+ reason: "not-found",
348
+ };
349
+ }
350
+ if (dryRun) {
351
+ return {
352
+ relocated: true,
353
+ from: sourceKey._pk,
354
+ to: canonicalKey._pk,
355
+ reason: "dry-run",
356
+ };
357
+ }
358
+
359
+ // Put the full item at the canonical key (don't clobber a concurrently
360
+ // created canonical row), then delete the legacy row. Put-before-delete so
361
+ // the record is never absent.
362
+ const newItem = {
363
+ ...sourceItem,
364
+ _pk: canonicalKey._pk,
365
+ _sk: canonicalKey._sk,
366
+ };
367
+ try {
368
+ await this.documentClient.send(
369
+ new PutCommand({
370
+ TableName: this.table,
371
+ Item: newItem,
372
+ ConditionExpression: "attribute_not_exists(#pk)",
373
+ ExpressionAttributeNames: { "#pk": "_pk" },
374
+ }),
375
+ );
376
+ } catch (error) {
377
+ // A canonical row appeared concurrently — treat as already migrated and
378
+ // fall through to delete the now-redundant legacy row.
379
+ if (error.name !== "ConditionalCheckFailedException") throw error;
380
+ }
381
+ await this.documentClient.send(
382
+ new DeleteCommand({ TableName: this.table, Key: sourceKey }),
383
+ );
384
+
385
+ return { relocated: true, from: sourceKey._pk, to: canonicalKey._pk };
386
+ },
387
+
261
388
  _createNewPrimaryId(jsUpdates) {
262
389
  // Now calculate primary key values using the processed data
263
390
  const pkValue = this._getPkValue(jsUpdates);
@@ -418,11 +545,9 @@ const MutationMethods = {
418
545
  }
419
546
  });
420
547
 
421
- // Validate unique constraints before attempting save
422
- await this._validateUniqueConstraints(
423
- jsUpdates,
424
- isNew ? null : primaryId,
425
- );
548
+ // No pre-save uniqueness read: each constraint Put in the transaction
549
+ // carries attribute_not_exists, and the catch block below runs
550
+ // _validateUniqueConstraints to name the colliding field.
426
551
 
427
552
  // Handle unique constraints
428
553
  for (const constraint of Object.values(this.uniqueConstraints || {})) {
@@ -503,10 +628,31 @@ const MutationMethods = {
503
628
  currentItem,
504
629
  );
505
630
 
631
+ // Key to write to. Normally the canonical key. But for an EXISTING
632
+ // `pk === "modelPrefix"` row in "migrating" mode, write in place at the
633
+ // row's current (possibly legacy) key so we update the full row rather
634
+ // than create a partial duplicate at the canonical key. The backfill is
635
+ // what relocates rows to the canonical key; deletes already target the
636
+ // loaded key. New items always use the canonical key.
637
+ let writeKey = this._getDyKeyForPkSk(this._parsePrimaryId(primaryId));
638
+ let inPlaceMigratingUpdate = false;
639
+ if (
640
+ !isNew &&
641
+ this.primaryKey.pk === "modelPrefix" &&
642
+ this._modelPrefixPkMode() === "migrating" &&
643
+ currentItem?._dyData?._pk
644
+ ) {
645
+ writeKey = {
646
+ _pk: currentItem._dyData._pk,
647
+ _sk: currentItem._dyData._sk,
648
+ };
649
+ inPlaceMigratingUpdate = true;
650
+ }
651
+
506
652
  // Create the base update params
507
653
  const updateParams = {
508
654
  TableName: this.table,
509
- Key: this._getDyKeyForPkSk(this._parsePrimaryId(primaryId)),
655
+ Key: writeKey,
510
656
  UpdateExpression: updateExpression,
511
657
  ReturnValues: "ALL_NEW",
512
658
  };
@@ -543,16 +689,43 @@ const MutationMethods = {
543
689
  ...filterExpression.ExpressionAttributeValues,
544
690
  };
545
691
  }
546
- } else if (isNew) {
547
- // For new items, ensure they don't already exist
548
- updateParams.ConditionExpression = "attribute_not_exists(#pk)";
692
+ }
693
+
694
+ if (isNew) {
695
+ // For new items, ensure they don't already exist, ANDed with any
696
+ // caller-supplied condition. _buildUpdateExpression maps each field
697
+ // to "#<fieldName>"; user field names can't start with "_" and no
698
+ // system field starts with "__", so a "#__" placeholder can't clobber
699
+ // one.
700
+ updateParams.ConditionExpression = updateParams.ConditionExpression
701
+ ? `(${updateParams.ConditionExpression}) AND attribute_not_exists(#__newItemPk)`
702
+ : "attribute_not_exists(#__newItemPk)";
703
+ updateParams.ExpressionAttributeNames = {
704
+ ...updateParams.ExpressionAttributeNames,
705
+ "#__newItemPk": "_pk",
706
+ };
707
+ }
708
+
709
+ if (inPlaceMigratingUpdate) {
710
+ // Updating the row in place at its current (legacy) key. Guard with
711
+ // attribute_exists so a concurrent backfill that relocated/deleted the
712
+ // legacy row can't make this UpdateItem upsert a partial row — it fails
713
+ // loudly (ConditionalError) instead, and the caller can retry, which
714
+ // will then find and update the relocated canonical row. ANDed with any
715
+ // caller-supplied condition.
716
+ //
717
+ // Use a "#__" placeholder so we never clobber a field placeholder
718
+ // (see the new-item guard above).
549
719
  updateParams.ExpressionAttributeNames = {
550
720
  ...updateParams.ExpressionAttributeNames,
551
- "#pk": "_pk",
721
+ "#__migExistsPk": "_pk",
552
722
  };
723
+ updateParams.ConditionExpression = updateParams.ConditionExpression
724
+ ? `(${updateParams.ConditionExpression}) AND attribute_exists(#__migExistsPk)`
725
+ : "attribute_exists(#__migExistsPk)";
553
726
  }
554
727
 
555
- const dyKey = this._getDyKeyForPkSk(this._parsePrimaryId(primaryId));
728
+ const dyKey = writeKey;
556
729
  logger.debug("dyKey", dyKey);
557
730
 
558
731
  try {
@@ -578,13 +751,39 @@ const MutationMethods = {
578
751
  logger.debug("transactItems response", response);
579
752
  logger.debug("primaryId to load", primaryId);
580
753
 
581
- // Fetch the item since transactWrite doesn't return values
582
- let savedItem = await this.find(primaryId, { batchDelay: 0 });
583
-
584
- // if the item doesn't exist, sleep for 200ms and try again
585
- if (!savedItem.exists()) {
586
- await new Promise((resolve) => setTimeout(resolve, 200));
587
- savedItem = await this.find(primaryId, { batchDelay: 0 });
754
+ // transactWrite doesn't return values. A new item is exactly its key
755
+ // plus what we wrote (REMOVEd nulls aside), so build it locally. An
756
+ // update must be read back, bypassing the loader cache, which still
757
+ // holds the pre-update row.
758
+ let savedItem;
759
+ if (isNew) {
760
+ const storedItem = { ...dyKey };
761
+ for (const [key, value] of Object.entries(dyUpdatesToSave)) {
762
+ if (value !== undefined && value !== null) {
763
+ storedItem[key] = value;
764
+ }
765
+ }
766
+ // A relative counter ("+3") is written with ADD, which on a new
767
+ // item stores the number itself.
768
+ const { CounterFieldClass } = require("../fields");
769
+ for (const [key, field] of Object.entries(this.fields)) {
770
+ if (
771
+ field instanceof CounterFieldClass &&
772
+ typeof storedItem[key] === "string"
773
+ ) {
774
+ storedItem[key] = parseInt(storedItem[key], 10);
775
+ }
776
+ }
777
+ savedItem = this._createFromDyItem(storedItem);
778
+ } else {
779
+ const readOptions = { batchDelay: 0, bypassCache: true };
780
+ savedItem = await this.find(primaryId, readOptions);
781
+
782
+ // if the item doesn't exist, sleep for 200ms and try again
783
+ if (!savedItem.exists()) {
784
+ await new Promise((resolve) => setTimeout(resolve, 200));
785
+ savedItem = await this.find(primaryId, readOptions);
786
+ }
588
787
  }
589
788
 
590
789
  logger.debug("savedItem", savedItem);
@@ -600,8 +799,11 @@ const MutationMethods = {
600
799
  "write",
601
800
  false,
602
801
  );
603
- savedItem._addConsumedCapacity(consumedCapacity, "read", false);
802
+ // The loaded row's capacity was counted in the request total when
803
+ // it was consumed, so don't count it again.
804
+ savedItem._addConsumedCapacity(consumedCapacity, "read", false, true);
604
805
 
806
+ this._primeLoaderContext(primaryId, savedItem);
605
807
  return savedItem;
606
808
  } else {
607
809
  // Use simple update if no unique constraints are changing
@@ -629,12 +831,15 @@ const MutationMethods = {
629
831
  "write",
630
832
  false,
631
833
  );
632
- savedItem._addConsumedCapacity(consumedCapacity, "read", false);
834
+ // The loaded row's capacity was counted in the request total when
835
+ // it was consumed, so don't count it again.
836
+ savedItem._addConsumedCapacity(consumedCapacity, "read", false, true);
633
837
 
634
838
  if (!savedItem.exists()) {
635
839
  throw new ConditionalError("Failed to fetch saved item", "update");
636
840
  }
637
841
 
842
+ this._primeLoaderContext(primaryId, savedItem);
638
843
  return savedItem;
639
844
  }
640
845
  } catch (error) {
@@ -644,6 +849,13 @@ const MutationMethods = {
644
849
  }
645
850
 
646
851
  if (error.name === "TransactionCanceledException") {
852
+ // A taken unique value cancels the transaction; this read throws a
853
+ // ConditionalError naming the field if that's the cause.
854
+ await this._validateUniqueConstraints(
855
+ jsUpdates,
856
+ isNew ? null : primaryId,
857
+ );
858
+
647
859
  // Check if it's due to conditional check failure
648
860
  if (
649
861
  error.CancellationReasons?.some(
@@ -656,12 +868,6 @@ const MutationMethods = {
656
868
  error,
657
869
  );
658
870
  }
659
- // For other transaction cancellation reasons, try to validate unique constraints
660
- // which will throw the appropriate ConditionalError if that's the issue
661
- await this._validateUniqueConstraints(
662
- jsUpdates,
663
- isNew ? null : primaryId,
664
- );
665
871
  }
666
872
  throw error;
667
873
  }
@@ -792,10 +998,8 @@ const MutationMethods = {
792
998
 
793
999
  // Detect partial GSI key updates that would cause index staleness
794
1000
  if (isUpdate && index.indexId !== undefined) {
795
- const pkProvided =
796
- index.pk === "modelPrefix" || pkValue !== undefined;
797
- const skProvided =
798
- index.sk === "modelPrefix" || skValue !== undefined;
1001
+ const pkProvided = index.pk === "modelPrefix" || pkValue !== undefined;
1002
+ const skProvided = index.sk === "modelPrefix" || skValue !== undefined;
799
1003
  if (pkProvided && !skProvided) {
800
1004
  throw new Error(
801
1005
  `Update includes GSI partition key "${index.pk}" for index "${indexName}" ` +
@@ -7,9 +7,7 @@ const assert = require("assert");
7
7
  const { retryOperation } = require("../utils/retry-helper");
8
8
  const { QueryCommand } = require("../dynamodb-client");
9
9
  const { QueryError } = require("../exceptions");
10
- const {
11
- _accumulateCapacityToContext,
12
- } = require("./batch-loading-mixin");
10
+ const { _accumulateCapacityToContext } = require("./batch-loading-mixin");
13
11
 
14
12
  const QueryMethods = {
15
13
  /**
@@ -37,7 +35,7 @@ const QueryMethods = {
37
35
  async queryByPrimaryKey(pkValue, skCondition = null, options = {}) {
38
36
  const params = this._getBaseQueryParams(
39
37
  "_pk",
40
- this._formatPrimaryKey(this.modelPrefix, pkValue),
38
+ this._formatPrimaryPartition(pkValue),
41
39
  skCondition,
42
40
  options,
43
41
  );
@@ -164,7 +162,7 @@ const QueryMethods = {
164
162
  // Format the partition key using the field's toGsi method
165
163
  let formattedPk;
166
164
  if (index instanceof PrimaryKeyConfig) {
167
- formattedPk = this._formatPrimaryKey(this.modelPrefix, pkValue);
165
+ formattedPk = this._formatPrimaryPartition(pkValue);
168
166
  } else {
169
167
  const pkField = this._getField(index.pk);
170
168
  const gsiValue = pkField.toGsi(pkValue);
@@ -13,6 +13,12 @@ const {
13
13
  UNIQUE_CONSTRAINT_ID3,
14
14
  } = require("../constants");
15
15
 
16
+ const VALID_MODEL_PREFIX_PK_MODES = new Set([
17
+ "legacy",
18
+ "migrating",
19
+ "tenant-scoped",
20
+ ]);
21
+
16
22
  const ValidationMethods = {
17
23
  /**
18
24
  *
@@ -59,6 +65,27 @@ const ValidationMethods = {
59
65
  );
60
66
  }
61
67
 
68
+ if (this.primaryKey.pk === "modelPrefix") {
69
+ const configuredMode = this._config?.keyMigration?.modelPrefixPkMode;
70
+
71
+ if (configuredMode !== undefined) {
72
+ if (!VALID_MODEL_PREFIX_PK_MODES.has(configuredMode)) {
73
+ throw new ConfigurationError(
74
+ `${this.name} has invalid keyMigration.modelPrefixPkMode "${configuredMode}". ` +
75
+ `Expected one of: "legacy", "migrating", or "tenant-scoped".`,
76
+ this.name,
77
+ );
78
+ }
79
+ } else if (this._config?.tenancy?.enabled) {
80
+ throw new ConfigurationError(
81
+ `${this.name} uses modelPrefix as its primary partition key with tenancy enabled. ` +
82
+ `Set keyMigration.modelPrefixPkMode to "legacy", "migrating", or "tenant-scoped". ` +
83
+ `Use "tenant-scoped" for new apps.`,
84
+ this.name,
85
+ );
86
+ }
87
+ }
88
+
62
89
  // Update to use TtlFieldClass instead of TtlField
63
90
  Object.entries(this.fields).forEach(([fieldName, field]) => {
64
91
  if (field instanceof TtlFieldClass && fieldName !== "ttl") {
package/src/model.js CHANGED
@@ -178,23 +178,111 @@ class BaoModel {
178
178
  return tenantId ? `[${tenantId}]#${baseKey}` : baseKey;
179
179
  }
180
180
 
181
+ /**
182
+ * Migration mode for models whose primary key partition is `modelPrefix`
183
+ * (i.e. `PrimaryKeyConfig("modelPrefix", <idField>)`). For these models the
184
+ * base-table partition key historically was the bare model prefix (e.g.
185
+ * `"apin"`), which is GLOBAL — every tenant's rows share one partition and a
186
+ * by-id `find()` is not tenant-isolated. Tenant-scoping it (`[tenant]#apin`)
187
+ * closes that hole, but flipping the on-disk key atomically strands every
188
+ * existing row. This flag drives a safe expand/migrate/contract rollout:
189
+ *
190
+ * "legacy" - bare `modelPrefix` pk. Identical to historical behavior.
191
+ * "migrating" - writes/reads use the tenant-scoped pk, but reads fall
192
+ * back to legacy key shapes so nothing is stranded while a
193
+ * backfill relocates rows. Updates write in place at the
194
+ * row's current key; deletes already target the loaded key.
195
+ * "tenant-scoped" - tenant-scoped pk only; fallback off (post-migration).
196
+ *
197
+ * The tenant-scoped key is the clean `[tenant]#modelPrefix` (e.g.
198
+ * `[tenant]#apin`). Both the write path (`_getDyKeyForPkSk`) and the query
199
+ * path (`queryByPrimaryKey` / primary-key `queryByIndex`) derive it from the
200
+ * same `_formatPrimaryPartition` helper, so writes/finds/queries stay
201
+ * consistent.
202
+ *
203
+ * Set via initModels config: `{ keyMigration: { modelPrefixPkMode: "..." } }`.
204
+ * Only affects models with `primaryKey.pk === "modelPrefix"`. When tenancy is
205
+ * enabled, those models must set the mode explicitly so new apps choose the
206
+ * isolated key format intentionally and existing apps opt into legacy behavior
207
+ * deliberately.
208
+ *
209
+ * Known limitations during the "migrating" window (both resolve once the
210
+ * backfill completes and you switch to "tenant-scoped"):
211
+ * - Primary-key PARTITION queries (`queryByPrimaryKey` / a primary-key
212
+ * `queryByIndex`) read only the canonical partition, so rows not yet
213
+ * relocated by the backfill are not returned. By-id `find()` is unaffected
214
+ * (it falls back), and GSI queries are unaffected (GSI keys never change).
215
+ * - `create()` with an EXPLICIT primary id that already exists at a legacy
216
+ * key is not detected as a duplicate (the `attribute_not_exists` guard
217
+ * only checks the canonical key). Models with auto-assigned ids (the
218
+ * default) cannot hit this.
219
+ *
220
+ * @returns {"legacy"|"migrating"|"tenant-scoped"}
221
+ */
222
+ static _modelPrefixPkMode() {
223
+ return this._config?.keyMigration?.modelPrefixPkMode || "legacy";
224
+ }
225
+
226
+ /**
227
+ * Base-table partition `_pk` for the `pk === "modelPrefix"` shape, honoring
228
+ * the migration mode:
229
+ * legacy: `modelPrefix` (bare, global)
230
+ * migrating/tenant-scoped: `[tenant]#modelPrefix` (clean, tenant-scoped)
231
+ * Falls back to the bare prefix when tenancy is disabled (no [tenant] segment,
232
+ * so no isolation is possible or needed).
233
+ */
234
+ static _modelPrefixPartitionPk() {
235
+ if (this._modelPrefixPkMode() === "legacy") {
236
+ return this.modelPrefix;
237
+ }
238
+ const tenantId = this.manager.getTenantId();
239
+ return tenantId ? `[${tenantId}]#${this.modelPrefix}` : this.modelPrefix;
240
+ }
241
+
242
+ /**
243
+ * Base-table partition `_pk` for a given partition value. Used by BOTH the
244
+ * write path and the primary-key query paths so the two never diverge. For
245
+ * the `pk === "modelPrefix"` shape the value is the model prefix itself and
246
+ * the key is mode-aware (see `_modelPrefixPartitionPk`); for every other
247
+ * shape it is the standard `_formatPrimaryKey(modelPrefix, value)`.
248
+ */
249
+ static _formatPrimaryPartition(pkValue) {
250
+ if (this.primaryKey.pk === "modelPrefix") {
251
+ return this._modelPrefixPartitionPk();
252
+ }
253
+ return this._formatPrimaryKey(this.modelPrefix, pkValue);
254
+ }
255
+
181
256
  static _getDyKeyForPkSk(pkSk) {
182
- if (this.primaryKey.sk === "modelPrefix") {
183
- return {
184
- _pk: this._formatPrimaryKey(this.modelPrefix, pkSk.pk),
185
- _sk: this.modelPrefix,
186
- };
187
- } else if (this.primaryKey.pk === "modelPrefix") {
188
- return {
189
- _pk: this._formatPrimaryKey(this.modelPrefix, pkSk.pk),
190
- _sk: pkSk.sk,
191
- };
192
- } else {
193
- return {
194
- _pk: this._formatPrimaryKey(this.modelPrefix, pkSk.pk),
195
- _sk: pkSk.sk,
196
- };
257
+ const _pk = this._formatPrimaryPartition(pkSk.pk);
258
+ const _sk =
259
+ this.primaryKey.sk === "modelPrefix" ? this.modelPrefix : pkSk.sk;
260
+ return { _pk, _sk };
261
+ }
262
+
263
+ /**
264
+ * Candidate legacy `{_pk,_sk}` keys to try as a read fallback for a given
265
+ * pkSk, in "migrating" mode only. Empty unless the model uses the
266
+ * `pk === "modelPrefix"` shape and is mid-migration. Pre-migration rows may
267
+ * live at either historical shape:
268
+ * - `modelPrefix` (<= 0.6.0: bare, global)
269
+ * - `[tenant]#modelPrefix#modelPrefix` (0.6.1: doubled, tenant-scoped)
270
+ */
271
+ static _legacyDyKeysForPkSk(pkSk) {
272
+ if (
273
+ this.primaryKey.pk !== "modelPrefix" ||
274
+ this._modelPrefixPkMode() !== "migrating"
275
+ ) {
276
+ return [];
197
277
  }
278
+ const canonical = this._modelPrefixPartitionPk();
279
+ const candidates = [
280
+ this.modelPrefix,
281
+ this._formatPrimaryKey(this.modelPrefix, this.modelPrefix),
282
+ ];
283
+ return [...new Set(candidates)]
284
+ .filter((pk) => pk !== canonical)
285
+ .map((pk) => ({ _pk: pk, _sk: pkSk.sk }));
198
286
  }
199
287
 
200
288
  static _getIterationKeys(objectId, dyData) {
@@ -428,13 +516,8 @@ class BaoModel {
428
516
  } = options;
429
517
 
430
518
  validateLimit(limit);
431
- if (
432
- !Number.isInteger(maxQueriesPerBucket) ||
433
- maxQueriesPerBucket < 1
434
- ) {
435
- throw new Error(
436
- "maxQueriesPerBucket must be a positive integer.",
437
- );
519
+ if (!Number.isInteger(maxQueriesPerBucket) || maxQueriesPerBucket < 1) {
520
+ throw new Error("maxQueriesPerBucket must be a positive integer.");
438
521
  }
439
522
 
440
523
  const searchPredicate = buildSearchPredicate(terms, this.searchConfig, {
@@ -567,9 +650,7 @@ class BaoModel {
567
650
  let overflowKeys = [];
568
651
  if (items.length > limit) {
569
652
  kept = items.slice(0, limit);
570
- overflowKeys = items
571
- .slice(limit)
572
- .map((m) => m.getPrimaryId());
653
+ overflowKeys = items.slice(limit).map((m) => m.getPrimaryId());
573
654
  }
574
655
 
575
656
  const bucketsRemaining = Object.keys(bucketCursors).length > 0;
@@ -789,9 +870,7 @@ class BaoModel {
789
870
  );
790
871
  }
791
872
  if (filterParts.length > 0) {
792
- params.FilterExpression = filterParts
793
- .map((p) => `(${p})`)
794
- .join(" AND ");
873
+ params.FilterExpression = filterParts.map((p) => `(${p})`).join(" AND ");
795
874
  }
796
875
 
797
876
  const response = await this._runIterationQuery(params, indexName);
@@ -864,7 +943,9 @@ class BaoModel {
864
943
  );
865
944
  }
866
945
  if (filterParts.length > 0) {
867
- params.FilterExpression = filterParts.map((p) => `(${p})`).join(" AND ");
946
+ params.FilterExpression = filterParts
947
+ .map((p) => `(${p})`)
948
+ .join(" AND ");
868
949
  }
869
950
 
870
951
  const response = await this._runIterationQuery(params, indexName);
@@ -1352,7 +1433,12 @@ class BaoModel {
1352
1433
 
1353
1434
  if (Array.isArray(consumedCapacity)) {
1354
1435
  consumedCapacity.forEach((item) =>
1355
- this._addConsumedCapacity(item, type, isRelated, skipContextAccumulation),
1436
+ this._addConsumedCapacity(
1437
+ item,
1438
+ type,
1439
+ isRelated,
1440
+ skipContextAccumulation,
1441
+ ),
1356
1442
  );
1357
1443
  } else {
1358
1444
  if (consumedCapacity.consumedCapacity) {
@@ -1362,7 +1448,11 @@ class BaoModel {
1362
1448
  type: consumedCapacity.type || type,
1363
1449
  });
1364
1450
  // Accumulate to batch context (only for non-related to avoid double counting)
1365
- if (!isRelated && !consumedCapacity.fromContext && !skipContextAccumulation) {
1451
+ if (
1452
+ !isRelated &&
1453
+ !consumedCapacity.fromContext &&
1454
+ !skipContextAccumulation
1455
+ ) {
1366
1456
  const units = consumedCapacity.consumedCapacity?.CapacityUnits || 0;
1367
1457
  _accumulateCapacityToContext(units, consumedCapacity.type || type);
1368
1458
  }