dynamo-bao 0.6.1 → 0.7.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/package.json +4 -4
- package/src/dynamodb-client.js +35 -2
- package/src/index.js +8 -0
- package/src/mixins/batch-loading-mixin.js +123 -11
- package/src/mixins/mutation-mixin.js +170 -6
- package/src/mixins/query-mixin.js +3 -5
- package/src/mixins/validation-mixin.js +27 -0
- package/src/model.js +121 -31
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dynamo-bao",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
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
|
-
"
|
|
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",
|
package/src/dynamodb-client.js
CHANGED
|
@@ -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/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
|
|
@@ -244,6 +257,31 @@ const BatchLoadingMethods = {
|
|
|
244
257
|
}
|
|
245
258
|
}
|
|
246
259
|
|
|
260
|
+
// Migration read fallback (pk === "modelPrefix", "migrating" mode only):
|
|
261
|
+
// ids not found at the canonical tenant-scoped key may still live at a
|
|
262
|
+
// legacy key shape. Resolve those individually — the miss set is small and
|
|
263
|
+
// only present mid-migration.
|
|
264
|
+
if (
|
|
265
|
+
this.primaryKey.pk === "modelPrefix" &&
|
|
266
|
+
this._modelPrefixPkMode() === "migrating"
|
|
267
|
+
) {
|
|
268
|
+
for (const id of idsToLoad) {
|
|
269
|
+
if (results[id]) continue;
|
|
270
|
+
const fb = await this._getRawItemWithLegacyFallback(
|
|
271
|
+
this._parsePrimaryId(id),
|
|
272
|
+
);
|
|
273
|
+
if (fb.consumedUnits) {
|
|
274
|
+
consumedCapacity.push({ CapacityUnits: fb.consumedUnits });
|
|
275
|
+
_accumulateCapacityToContext(fb.consumedUnits, "read");
|
|
276
|
+
}
|
|
277
|
+
if (fb.item) {
|
|
278
|
+
const instance = this._createFromDyItem(fb.item);
|
|
279
|
+
results[instance.getPrimaryId()] = instance;
|
|
280
|
+
if (loaderContext) loaderContext.set(id, instance);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
247
285
|
return {
|
|
248
286
|
items: results,
|
|
249
287
|
ConsumedCapacity: consumedCapacity,
|
|
@@ -322,17 +360,34 @@ const BatchLoadingMethods = {
|
|
|
322
360
|
}),
|
|
323
361
|
);
|
|
324
362
|
|
|
363
|
+
let item = result.Item;
|
|
364
|
+
let fallbackUnits = 0;
|
|
365
|
+
if (!item) {
|
|
366
|
+
const fb = await this._getRawItemWithLegacyFallback(pkSk);
|
|
367
|
+
item = fb.item;
|
|
368
|
+
fallbackUnits = fb.consumedUnits;
|
|
369
|
+
}
|
|
370
|
+
|
|
325
371
|
let instance;
|
|
326
|
-
if (!
|
|
327
|
-
instance = new ObjectNotFound(
|
|
372
|
+
if (!item) {
|
|
373
|
+
instance = new ObjectNotFound(
|
|
374
|
+
_withExtraCapacityUnits(result.ConsumedCapacity, fallbackUnits),
|
|
375
|
+
);
|
|
328
376
|
// Accumulate capacity for ObjectNotFound since _addConsumedCapacity isn't called
|
|
329
377
|
_accumulateCapacityToContext(
|
|
330
|
-
result.ConsumedCapacity?.CapacityUnits || 0,
|
|
378
|
+
(result.ConsumedCapacity?.CapacityUnits || 0) + fallbackUnits,
|
|
331
379
|
"read",
|
|
332
380
|
);
|
|
333
381
|
} else {
|
|
334
|
-
instance = this._createFromDyItem(
|
|
382
|
+
instance = this._createFromDyItem(item);
|
|
335
383
|
instance._addConsumedCapacity(result.ConsumedCapacity, "read", false);
|
|
384
|
+
if (fallbackUnits) {
|
|
385
|
+
instance._addConsumedCapacity(
|
|
386
|
+
{ CapacityUnits: fallbackUnits },
|
|
387
|
+
"read",
|
|
388
|
+
false,
|
|
389
|
+
);
|
|
390
|
+
}
|
|
336
391
|
}
|
|
337
392
|
|
|
338
393
|
// Add to loader context if provided (unless bypassing cache)
|
|
@@ -381,18 +436,29 @@ const BatchLoadingMethods = {
|
|
|
381
436
|
0,
|
|
382
437
|
);
|
|
383
438
|
|
|
384
|
-
// Resolve all promises, including multiple callbacks for the same ID
|
|
439
|
+
// Resolve all promises, including multiple callbacks for the same ID.
|
|
440
|
+
// Sum ALL ConsumedCapacity entries (multiple BatchGet pages and any
|
|
441
|
+
// legacy-fallback GetItems in migrating mode), not just the first,
|
|
442
|
+
// so the per-operation capacity isn't under-reported.
|
|
443
|
+
const totalUnits = (ConsumedCapacity || []).reduce(
|
|
444
|
+
(sum, c) => sum + (c?.CapacityUnits || 0),
|
|
445
|
+
0,
|
|
446
|
+
);
|
|
385
447
|
const consumedCapacity = {
|
|
386
448
|
TableName: this.table,
|
|
387
|
-
CapacityUnits:
|
|
388
|
-
ConsumedCapacity[0]?.CapacityUnits / totalCallbacks,
|
|
449
|
+
CapacityUnits: totalCallbacks ? totalUnits / totalCallbacks : 0,
|
|
389
450
|
};
|
|
390
451
|
|
|
391
452
|
currentBatch.items.forEach((batchItem) => {
|
|
392
453
|
let item = items[batchItem.id];
|
|
393
454
|
if (item) {
|
|
394
455
|
// Skip context accumulation since batchFind already accumulated the total
|
|
395
|
-
item._addConsumedCapacity(
|
|
456
|
+
item._addConsumedCapacity(
|
|
457
|
+
consumedCapacity,
|
|
458
|
+
"read",
|
|
459
|
+
false,
|
|
460
|
+
true,
|
|
461
|
+
);
|
|
396
462
|
} else {
|
|
397
463
|
item = new ObjectNotFound(consumedCapacity);
|
|
398
464
|
}
|
|
@@ -456,6 +522,35 @@ const BatchLoadingMethods = {
|
|
|
456
522
|
});
|
|
457
523
|
},
|
|
458
524
|
|
|
525
|
+
/**
|
|
526
|
+
* Read fallback for the `pk === "modelPrefix"` migration. When a record is
|
|
527
|
+
* not found at the canonical (tenant-scoped) key while in "migrating" mode,
|
|
528
|
+
* try the legacy key shapes so pre-migration rows remain resolvable.
|
|
529
|
+
*
|
|
530
|
+
* Returns the raw DynamoDB item (with its actual stored `_pk`/`_sk`) or null,
|
|
531
|
+
* plus the total capacity consumed across the fallback GetItem(s). The CALLER
|
|
532
|
+
* is responsible for accounting that capacity (so it is reflected in the
|
|
533
|
+
* returned per-operation ConsumedCapacity, not just the batch context).
|
|
534
|
+
* @param {Object} pkSk - Parsed primary key values
|
|
535
|
+
* @returns {Promise<{ item: Object|null, consumedUnits: number }>}
|
|
536
|
+
*/
|
|
537
|
+
async _getRawItemWithLegacyFallback(pkSk) {
|
|
538
|
+
const legacyKeys = this._legacyDyKeysForPkSk(pkSk);
|
|
539
|
+
let consumedUnits = 0;
|
|
540
|
+
for (const Key of legacyKeys) {
|
|
541
|
+
const result = await this.documentClient.send(
|
|
542
|
+
new GetCommand({
|
|
543
|
+
TableName: this.table,
|
|
544
|
+
Key,
|
|
545
|
+
ReturnConsumedCapacity: "TOTAL",
|
|
546
|
+
}),
|
|
547
|
+
);
|
|
548
|
+
consumedUnits += result.ConsumedCapacity?.CapacityUnits || 0;
|
|
549
|
+
if (result.Item) return { item: result.Item, consumedUnits };
|
|
550
|
+
}
|
|
551
|
+
return { item: null, consumedUnits };
|
|
552
|
+
},
|
|
553
|
+
|
|
459
554
|
/**
|
|
460
555
|
* Execute find operation directly without batching or caching
|
|
461
556
|
* @param {string} primaryId - The primary ID to find
|
|
@@ -472,11 +567,28 @@ const BatchLoadingMethods = {
|
|
|
472
567
|
}),
|
|
473
568
|
);
|
|
474
569
|
|
|
475
|
-
|
|
476
|
-
|
|
570
|
+
let item = result.Item;
|
|
571
|
+
let fallbackUnits = 0;
|
|
572
|
+
if (!item) {
|
|
573
|
+
const fb = await this._getRawItemWithLegacyFallback(pkSk);
|
|
574
|
+
item = fb.item;
|
|
575
|
+
fallbackUnits = fb.consumedUnits;
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
if (!item) {
|
|
579
|
+
return new ObjectNotFound(
|
|
580
|
+
_withExtraCapacityUnits(result.ConsumedCapacity, fallbackUnits),
|
|
581
|
+
);
|
|
477
582
|
} else {
|
|
478
|
-
const instance = this._createFromDyItem(
|
|
583
|
+
const instance = this._createFromDyItem(item);
|
|
479
584
|
instance._addConsumedCapacity(result.ConsumedCapacity, "read", false);
|
|
585
|
+
if (fallbackUnits) {
|
|
586
|
+
instance._addConsumedCapacity(
|
|
587
|
+
{ CapacityUnits: fallbackUnits },
|
|
588
|
+
"read",
|
|
589
|
+
false,
|
|
590
|
+
);
|
|
591
|
+
}
|
|
480
592
|
return instance;
|
|
481
593
|
}
|
|
482
594
|
},
|
|
@@ -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");
|
|
@@ -258,6 +260,129 @@ const MutationMethods = {
|
|
|
258
260
|
}
|
|
259
261
|
},
|
|
260
262
|
|
|
263
|
+
/**
|
|
264
|
+
* @memberof BaoModel
|
|
265
|
+
* @description
|
|
266
|
+
* Relocate a single record's base-table row from a legacy `pk === "modelPrefix"`
|
|
267
|
+
* key to the current canonical key. This is the per-record primitive used to
|
|
268
|
+
* back-fill the `keyMigration.modelPrefixPkMode` migration.
|
|
269
|
+
*
|
|
270
|
+
* Must be called in "migrating" mode and under the row's tenant context (so
|
|
271
|
+
* `getTenantId()` resolves the tenant the canonical `[tenant]#prefix` key is
|
|
272
|
+
* built from). The row's full item is copied verbatim to the canonical key
|
|
273
|
+
* (a conditional Put that won't clobber an existing canonical row), then the
|
|
274
|
+
* legacy row is deleted. GSI entries and unique-constraint pointers are
|
|
275
|
+
* unaffected (their keys never change; the pointer's relatedId is the
|
|
276
|
+
* unchanged logical id), so only the base row moves.
|
|
277
|
+
*
|
|
278
|
+
* Idempotent and safe to re-run: a row already at the canonical key is left
|
|
279
|
+
* alone; a stale legacy row left behind by an interrupted run is cleaned up.
|
|
280
|
+
*
|
|
281
|
+
* @param {string} primaryId - The record's logical primary id.
|
|
282
|
+
* @param {Object} [options]
|
|
283
|
+
* @param {boolean} [options.dryRun=false] - Inspect only; perform no writes.
|
|
284
|
+
* @returns {Promise<{relocated: boolean, from: ?string, to: string, reason?: string}>}
|
|
285
|
+
*/
|
|
286
|
+
async relocateToCanonicalKey(primaryId, options = {}) {
|
|
287
|
+
const { dryRun = false } = options;
|
|
288
|
+
|
|
289
|
+
if (this.primaryKey.pk !== "modelPrefix") {
|
|
290
|
+
throw new Error(
|
|
291
|
+
`relocateToCanonicalKey is only valid for models whose primaryKey.pk is "modelPrefix" (got "${this.primaryKey.pk}" for ${this.name})`,
|
|
292
|
+
);
|
|
293
|
+
}
|
|
294
|
+
if (this._modelPrefixPkMode() !== "migrating") {
|
|
295
|
+
throw new Error(
|
|
296
|
+
`relocateToCanonicalKey must be called in "migrating" mode (modelPrefixPkMode is "${this._modelPrefixPkMode()}")`,
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
const pkSk = this._parsePrimaryId(primaryId);
|
|
301
|
+
const canonicalKey = this._getDyKeyForPkSk(pkSk);
|
|
302
|
+
const legacyKeys = this._legacyDyKeysForPkSk(pkSk);
|
|
303
|
+
|
|
304
|
+
const get = (Key) =>
|
|
305
|
+
this.documentClient
|
|
306
|
+
.send(new GetCommand({ TableName: this.table, Key }))
|
|
307
|
+
.then((r) => r.Item || null);
|
|
308
|
+
|
|
309
|
+
// Already at the canonical key? Clean up any stale legacy duplicate, done.
|
|
310
|
+
const canonicalItem = await get(canonicalKey);
|
|
311
|
+
if (canonicalItem) {
|
|
312
|
+
for (const legacyKey of legacyKeys) {
|
|
313
|
+
const stale = await get(legacyKey);
|
|
314
|
+
if (stale && !dryRun) {
|
|
315
|
+
await this.documentClient.send(
|
|
316
|
+
new DeleteCommand({ TableName: this.table, Key: legacyKey }),
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
return {
|
|
321
|
+
relocated: false,
|
|
322
|
+
from: null,
|
|
323
|
+
to: canonicalKey._pk,
|
|
324
|
+
reason: "already-canonical",
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// Find the row at a legacy key.
|
|
329
|
+
let sourceItem = null;
|
|
330
|
+
let sourceKey = null;
|
|
331
|
+
for (const legacyKey of legacyKeys) {
|
|
332
|
+
const item = await get(legacyKey);
|
|
333
|
+
if (item) {
|
|
334
|
+
sourceItem = item;
|
|
335
|
+
sourceKey = legacyKey;
|
|
336
|
+
break;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
if (!sourceItem) {
|
|
341
|
+
return {
|
|
342
|
+
relocated: false,
|
|
343
|
+
from: null,
|
|
344
|
+
to: canonicalKey._pk,
|
|
345
|
+
reason: "not-found",
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
if (dryRun) {
|
|
349
|
+
return {
|
|
350
|
+
relocated: true,
|
|
351
|
+
from: sourceKey._pk,
|
|
352
|
+
to: canonicalKey._pk,
|
|
353
|
+
reason: "dry-run",
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
// Put the full item at the canonical key (don't clobber a concurrently
|
|
358
|
+
// created canonical row), then delete the legacy row. Put-before-delete so
|
|
359
|
+
// the record is never absent.
|
|
360
|
+
const newItem = {
|
|
361
|
+
...sourceItem,
|
|
362
|
+
_pk: canonicalKey._pk,
|
|
363
|
+
_sk: canonicalKey._sk,
|
|
364
|
+
};
|
|
365
|
+
try {
|
|
366
|
+
await this.documentClient.send(
|
|
367
|
+
new PutCommand({
|
|
368
|
+
TableName: this.table,
|
|
369
|
+
Item: newItem,
|
|
370
|
+
ConditionExpression: "attribute_not_exists(#pk)",
|
|
371
|
+
ExpressionAttributeNames: { "#pk": "_pk" },
|
|
372
|
+
}),
|
|
373
|
+
);
|
|
374
|
+
} catch (error) {
|
|
375
|
+
// A canonical row appeared concurrently — treat as already migrated and
|
|
376
|
+
// fall through to delete the now-redundant legacy row.
|
|
377
|
+
if (error.name !== "ConditionalCheckFailedException") throw error;
|
|
378
|
+
}
|
|
379
|
+
await this.documentClient.send(
|
|
380
|
+
new DeleteCommand({ TableName: this.table, Key: sourceKey }),
|
|
381
|
+
);
|
|
382
|
+
|
|
383
|
+
return { relocated: true, from: sourceKey._pk, to: canonicalKey._pk };
|
|
384
|
+
},
|
|
385
|
+
|
|
261
386
|
_createNewPrimaryId(jsUpdates) {
|
|
262
387
|
// Now calculate primary key values using the processed data
|
|
263
388
|
const pkValue = this._getPkValue(jsUpdates);
|
|
@@ -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:
|
|
655
|
+
Key: writeKey,
|
|
510
656
|
UpdateExpression: updateExpression,
|
|
511
657
|
ReturnValues: "ALL_NEW",
|
|
512
658
|
};
|
|
@@ -552,7 +698,27 @@ const MutationMethods = {
|
|
|
552
698
|
};
|
|
553
699
|
}
|
|
554
700
|
|
|
555
|
-
|
|
701
|
+
if (inPlaceMigratingUpdate) {
|
|
702
|
+
// Updating the row in place at its current (legacy) key. Guard with
|
|
703
|
+
// attribute_exists so a concurrent backfill that relocated/deleted the
|
|
704
|
+
// legacy row can't make this UpdateItem upsert a partial row — it fails
|
|
705
|
+
// loudly (ConditionalError) instead, and the caller can retry, which
|
|
706
|
+
// will then find and update the relocated canonical row. ANDed with any
|
|
707
|
+
// caller-supplied condition.
|
|
708
|
+
//
|
|
709
|
+
// Use a dedicated placeholder (not "#pk") so we never clobber a user
|
|
710
|
+
// field literally named `pk`, which _buildUpdateExpression maps to
|
|
711
|
+
// "#pk".
|
|
712
|
+
updateParams.ExpressionAttributeNames = {
|
|
713
|
+
...updateParams.ExpressionAttributeNames,
|
|
714
|
+
"#migExistsPk": "_pk",
|
|
715
|
+
};
|
|
716
|
+
updateParams.ConditionExpression = updateParams.ConditionExpression
|
|
717
|
+
? `(${updateParams.ConditionExpression}) AND attribute_exists(#migExistsPk)`
|
|
718
|
+
: "attribute_exists(#migExistsPk)";
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
const dyKey = writeKey;
|
|
556
722
|
logger.debug("dyKey", dyKey);
|
|
557
723
|
|
|
558
724
|
try {
|
|
@@ -792,10 +958,8 @@ const MutationMethods = {
|
|
|
792
958
|
|
|
793
959
|
// Detect partial GSI key updates that would cause index staleness
|
|
794
960
|
if (isUpdate && index.indexId !== undefined) {
|
|
795
|
-
const pkProvided =
|
|
796
|
-
|
|
797
|
-
const skProvided =
|
|
798
|
-
index.sk === "modelPrefix" || skValue !== undefined;
|
|
961
|
+
const pkProvided = index.pk === "modelPrefix" || pkValue !== undefined;
|
|
962
|
+
const skProvided = index.sk === "modelPrefix" || skValue !== undefined;
|
|
799
963
|
if (pkProvided && !skProvided) {
|
|
800
964
|
throw new Error(
|
|
801
965
|
`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.
|
|
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.
|
|
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
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
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
|
-
|
|
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
|
|
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(
|
|
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 (
|
|
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
|
}
|