dynamo-bao 0.7.3 → 0.8.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/README.md +7 -1
- package/package.json +1 -1
- package/src/dynamodb-client.js +17 -17
- package/src/fields.js +0 -6
- package/src/index.js +1 -1
- package/src/mixins/batch-loading-mixin.js +89 -39
- package/src/mixins/mutation-mixin.js +623 -453
- package/src/mixins/query-mixin.js +15 -25
- package/src/model.js +229 -103
- package/src/utils/logger.js +18 -3
package/README.md
CHANGED
|
@@ -409,7 +409,13 @@ try {
|
|
|
409
409
|
|
|
410
410
|
This convenience comes at a cost: every `create`, `update`, or `delete` operation on an iterable model requires a second write to the database to maintain the iteration index. This doubles the write cost for every item.
|
|
411
411
|
|
|
412
|
-
To prevent "hot partitions" on large models, the iteration index is automatically split into 10 "buckets" or partitions. The `iterateAll()` method handles fetching from all buckets seamlessly.
|
|
412
|
+
To prevent "hot partitions" on large models, the iteration index is automatically split into 10 "buckets" or partitions. The `iterateAll()` method handles fetching from all buckets seamlessly. Within a bucket it fetches the next page of keys while the current page is being loaded. Buckets are read one at a time by default; pass `concurrency` to read several at once for bulk jobs (batches from different buckets are then interleaved):
|
|
413
|
+
|
|
414
|
+
```javascript
|
|
415
|
+
for await (const batch of User.iterateAll({ batchSize: 100, concurrency: 4 })) {
|
|
416
|
+
// ...
|
|
417
|
+
}
|
|
418
|
+
```
|
|
413
419
|
|
|
414
420
|
**Default**
|
|
415
421
|
|
package/package.json
CHANGED
package/src/dynamodb-client.js
CHANGED
|
@@ -3,6 +3,22 @@ const fs = require('fs');
|
|
|
3
3
|
const path = require('path');
|
|
4
4
|
const os = require('os');
|
|
5
5
|
|
|
6
|
+
const OPERATION_NAMES = {
|
|
7
|
+
'GetCommand': 'GetItem',
|
|
8
|
+
'QueryCommand': 'Query',
|
|
9
|
+
'PutCommand': 'PutItem',
|
|
10
|
+
'UpdateCommand': 'UpdateItem',
|
|
11
|
+
'DeleteCommand': 'DeleteItem',
|
|
12
|
+
'BatchGetCommand': 'BatchGetItem',
|
|
13
|
+
'TransactWriteCommand': 'TransactWriteItems',
|
|
14
|
+
'CreateTableCommand': 'CreateTable',
|
|
15
|
+
'ListTablesCommand': 'ListTables',
|
|
16
|
+
'DescribeTableCommand': 'DescribeTable',
|
|
17
|
+
'UpdateTimeToLiveCommand': 'UpdateTimeToLive',
|
|
18
|
+
'DescribeTimeToLiveCommand': 'DescribeTimeToLive',
|
|
19
|
+
'UpdateTableCommand': 'UpdateTable'
|
|
20
|
+
};
|
|
21
|
+
|
|
6
22
|
class DynamoDBClient {
|
|
7
23
|
constructor(config = {}) {
|
|
8
24
|
this.region = config.region || this._resolveRegion();
|
|
@@ -187,23 +203,7 @@ class DynamoDBClient {
|
|
|
187
203
|
}
|
|
188
204
|
|
|
189
205
|
_getOperationName(commandName) {
|
|
190
|
-
|
|
191
|
-
'GetCommand': 'GetItem',
|
|
192
|
-
'QueryCommand': 'Query',
|
|
193
|
-
'PutCommand': 'PutItem',
|
|
194
|
-
'UpdateCommand': 'UpdateItem',
|
|
195
|
-
'DeleteCommand': 'DeleteItem',
|
|
196
|
-
'BatchGetCommand': 'BatchGetItem',
|
|
197
|
-
'TransactWriteCommand': 'TransactWriteItems',
|
|
198
|
-
'CreateTableCommand': 'CreateTable',
|
|
199
|
-
'ListTablesCommand': 'ListTables',
|
|
200
|
-
'DescribeTableCommand': 'DescribeTable',
|
|
201
|
-
'UpdateTimeToLiveCommand': 'UpdateTimeToLive',
|
|
202
|
-
'DescribeTimeToLiveCommand': 'DescribeTimeToLive',
|
|
203
|
-
'UpdateTableCommand': 'UpdateTable'
|
|
204
|
-
};
|
|
205
|
-
|
|
206
|
-
return operationMap[commandName] || commandName.replace('Command', '');
|
|
206
|
+
return OPERATION_NAMES[commandName] || commandName.replace('Command', '');
|
|
207
207
|
}
|
|
208
208
|
|
|
209
209
|
async send(command) {
|
package/src/fields.js
CHANGED
|
@@ -4,7 +4,6 @@
|
|
|
4
4
|
* This module contains the built-in fields for Bao.
|
|
5
5
|
*/
|
|
6
6
|
const { ulid, decodeTime } = require("ulid");
|
|
7
|
-
const { defaultLogger: logger } = require("./utils/logger");
|
|
8
7
|
const { ValidationError } = require("./exceptions");
|
|
9
8
|
|
|
10
9
|
/**
|
|
@@ -236,7 +235,6 @@ class DateTimeField extends BaoBaseField {
|
|
|
236
235
|
const timestamp = this.toDy(value);
|
|
237
236
|
if (!timestamp) return "0";
|
|
238
237
|
const result = timestamp.toString().padStart(20, "0");
|
|
239
|
-
// logger.log('Converting to GSI:', { value, timestamp, result });
|
|
240
238
|
return result;
|
|
241
239
|
} catch (error) {
|
|
242
240
|
console.warn("Error converting date for GSI:", error);
|
|
@@ -544,8 +542,6 @@ class CounterField extends BaoBaseField {
|
|
|
544
542
|
fieldValue: value,
|
|
545
543
|
};
|
|
546
544
|
|
|
547
|
-
logger.log("CounterField - getUpdateExpression", fieldName, value);
|
|
548
|
-
|
|
549
545
|
if (value === null) {
|
|
550
546
|
expObj = {
|
|
551
547
|
...expObj,
|
|
@@ -746,7 +742,6 @@ class TtlField extends DateTimeField {
|
|
|
746
742
|
}
|
|
747
743
|
|
|
748
744
|
toDy(value) {
|
|
749
|
-
logger.log("TTL toDy", value);
|
|
750
745
|
if (value === undefined) return undefined; // Skip field
|
|
751
746
|
if (value === null) return null; // Remove field
|
|
752
747
|
|
|
@@ -770,7 +765,6 @@ class TtlField extends DateTimeField {
|
|
|
770
765
|
}
|
|
771
766
|
|
|
772
767
|
fromDy(value) {
|
|
773
|
-
logger.log("TTL fromDy", value);
|
|
774
768
|
if (value === undefined || value === null) {
|
|
775
769
|
return null; // Convert both undefined and null to null
|
|
776
770
|
}
|
package/src/index.js
CHANGED
|
@@ -200,7 +200,7 @@ function initModels(userConfig = {}) {
|
|
|
200
200
|
// Initialize the manager & 2nd model registration pass
|
|
201
201
|
manager.init(finalConfig);
|
|
202
202
|
|
|
203
|
-
logger.
|
|
203
|
+
logger.debug("Models initialized:", {
|
|
204
204
|
testId: finalConfig.testId,
|
|
205
205
|
tenantId: manager.getTenantId(),
|
|
206
206
|
managerTestId: manager.getTestId(),
|
|
@@ -16,8 +16,53 @@ try {
|
|
|
16
16
|
// Request-scoped batch context
|
|
17
17
|
const batchContext = AsyncLocalStorage ? new AsyncLocalStorage() : null;
|
|
18
18
|
|
|
19
|
-
const DEFAULT_BATCH_DELAY_MS = 5;
|
|
20
19
|
const BATCH_REQUEST_TIMEOUT = 10000; // 10 seconds max lifetime for a batch
|
|
20
|
+
const BATCH_GET_SIZE = 100; // BatchGetItem's per-request key limit
|
|
21
|
+
const BATCH_GET_CONCURRENCY = 5; // BatchGetItem requests in flight per batchFind
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Run `fn` over `items` with at most `limit` calls in flight. Rejects with
|
|
25
|
+
* the first error once it occurs; in-flight calls are left to settle.
|
|
26
|
+
* @private
|
|
27
|
+
*/
|
|
28
|
+
async function mapConcurrent(items, limit, fn) {
|
|
29
|
+
const results = new Array(items.length);
|
|
30
|
+
let next = 0;
|
|
31
|
+
const worker = async () => {
|
|
32
|
+
while (next < items.length) {
|
|
33
|
+
const i = next++;
|
|
34
|
+
results[i] = await fn(items[i], i);
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
const workers = [];
|
|
38
|
+
for (let w = 0; w < Math.min(limit, items.length); w++) {
|
|
39
|
+
workers.push(worker());
|
|
40
|
+
}
|
|
41
|
+
await Promise.all(workers);
|
|
42
|
+
return results;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Schedule a batch flush. With no delay the batch is sent on the next
|
|
47
|
+
* macrotask (setImmediate), after every pending microtask has run, so each
|
|
48
|
+
* find() issued in the current tick (a Promise.all fan-out, loadRelatedData
|
|
49
|
+
* over a query page) joins one BatchGetItem without a wall-clock wait. A
|
|
50
|
+
* positive delay opts into a timer-based window instead. Returns a cancel
|
|
51
|
+
* function.
|
|
52
|
+
* @private
|
|
53
|
+
*/
|
|
54
|
+
function scheduleBatchFlush(fn, delay) {
|
|
55
|
+
if (delay > 0) {
|
|
56
|
+
const timer = setTimeout(fn, delay);
|
|
57
|
+
return () => clearTimeout(timer);
|
|
58
|
+
}
|
|
59
|
+
if (typeof setImmediate === "function") {
|
|
60
|
+
const handle = setImmediate(fn);
|
|
61
|
+
return () => clearImmediate(handle);
|
|
62
|
+
}
|
|
63
|
+
const timer = setTimeout(fn, 0);
|
|
64
|
+
return () => clearTimeout(timer);
|
|
65
|
+
}
|
|
21
66
|
|
|
22
67
|
/**
|
|
23
68
|
* Accumulate capacity units to the current batch context.
|
|
@@ -122,11 +167,8 @@ const BatchLoadingMethods = {
|
|
|
122
167
|
* @private
|
|
123
168
|
*/
|
|
124
169
|
_loaderKey(primaryId) {
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
this.manager.getTenantId() ?? null,
|
|
128
|
-
this._canonicalPrimaryId(primaryId),
|
|
129
|
-
]);
|
|
170
|
+
// Joined on NUL, which can't appear in a model name, tenant id or key.
|
|
171
|
+
return `${this.name}\0${this.manager.getTenantId() ?? ""}\0${this._canonicalPrimaryId(primaryId)}`;
|
|
130
172
|
},
|
|
131
173
|
|
|
132
174
|
/**
|
|
@@ -210,10 +252,8 @@ const BatchLoadingMethods = {
|
|
|
210
252
|
primaryIds.forEach((id) => {
|
|
211
253
|
const loaderKey = this._loaderKey(id);
|
|
212
254
|
if (loaderContext.has(loaderKey)) {
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
);
|
|
216
|
-
results[id] = instance;
|
|
255
|
+
// Same instance find() would return for this id.
|
|
256
|
+
results[id] = loaderContext.get(loaderKey);
|
|
217
257
|
} else {
|
|
218
258
|
idsToLoad.push(id);
|
|
219
259
|
}
|
|
@@ -232,9 +272,14 @@ const BatchLoadingMethods = {
|
|
|
232
272
|
// remove duplicates from idsToLoad
|
|
233
273
|
idsToLoad = [...new Set(idsToLoad)];
|
|
234
274
|
|
|
235
|
-
//
|
|
236
|
-
|
|
237
|
-
|
|
275
|
+
// Load in chunks of BATCH_GET_SIZE keys, several chunks in flight at
|
|
276
|
+
// once. Results are keyed by id, so completion order doesn't matter.
|
|
277
|
+
const chunks = [];
|
|
278
|
+
for (let i = 0; i < idsToLoad.length; i += BATCH_GET_SIZE) {
|
|
279
|
+
chunks.push(idsToLoad.slice(i, i + BATCH_GET_SIZE));
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
const loadChunk = async (batchIds) => {
|
|
238
283
|
const Keys = batchIds.map((id) => {
|
|
239
284
|
const pkSk = this._parsePrimaryId(id);
|
|
240
285
|
return this._getDyKeyForPkSk(pkSk);
|
|
@@ -301,7 +346,9 @@ const BatchLoadingMethods = {
|
|
|
301
346
|
`Failed to process ${unprocessedKeys.length} items after ${maxRetries} retries`,
|
|
302
347
|
);
|
|
303
348
|
}
|
|
304
|
-
}
|
|
349
|
+
};
|
|
350
|
+
|
|
351
|
+
await mapConcurrent(chunks, BATCH_GET_CONCURRENCY, loadChunk);
|
|
305
352
|
|
|
306
353
|
// Migration read fallback (pk === "modelPrefix", "migrating" mode only):
|
|
307
354
|
// ids not found at the canonical tenant-scoped key may still live at a
|
|
@@ -344,16 +391,22 @@ const BatchLoadingMethods = {
|
|
|
344
391
|
* preferred over {@link BaoModel.batchFind}. Find uses batchFind internally, unless batchDelay
|
|
345
392
|
* is set to 0.
|
|
346
393
|
*
|
|
394
|
+
* By default, every find() issued in the same tick (for example a
|
|
395
|
+
* Promise.all fan-out, or loadRelatedData over a page of query results) is
|
|
396
|
+
* sent as one BatchGetItem on the next macrotask, with no added delay.
|
|
397
|
+
*
|
|
347
398
|
* @param {string} primaryId - The primary ID of the item to find
|
|
348
399
|
* @param {Object} [options={}] - Optional configuration for the find operation
|
|
349
|
-
* @param {number} [options.batchDelay
|
|
350
|
-
*
|
|
400
|
+
* @param {number} [options.batchDelay] - Omit to flush the batch on the next tick.
|
|
401
|
+
* Pass a positive number of milliseconds to hold the
|
|
402
|
+
* batch open for that long so later calls can join it.
|
|
403
|
+
* Set to 0 for an immediate individual GetItem.
|
|
351
404
|
* @param {boolean} [options.bypassCache=false] - If true, bypasses both batching and caching entirely
|
|
352
405
|
* @returns {Promise<Object>} Returns a promise that resolves to the found item instance or ObjectNotFound
|
|
353
406
|
* @throws {Error} If the batch request times out or other errors occur during the operation
|
|
354
407
|
*/
|
|
355
408
|
async find(primaryId, options = {}) {
|
|
356
|
-
const batchDelay = options.batchDelay
|
|
409
|
+
const batchDelay = options.batchDelay;
|
|
357
410
|
const bypassCache = options.bypassCache ?? false;
|
|
358
411
|
|
|
359
412
|
// Ensure we're within a batch context (unless bypassing everything for AsyncLocalStorage availability check)
|
|
@@ -452,14 +505,16 @@ const BatchLoadingMethods = {
|
|
|
452
505
|
// One batch per model, tenant and delay: the batch builds its keys in
|
|
453
506
|
// the first caller's async context, so it must not mix tenants.
|
|
454
507
|
const tenantId = this.manager.getTenantId() ?? "";
|
|
455
|
-
const batchKey = `${this.name}-${tenantId}-${batchDelay}`;
|
|
508
|
+
const batchKey = `${this.name}-${tenantId}-${batchDelay ?? "tick"}`;
|
|
456
509
|
const batchRequests = this._getBatchRequests();
|
|
457
510
|
let batchRequest = batchRequests.get(batchKey);
|
|
458
511
|
|
|
459
512
|
if (!batchRequest) {
|
|
460
513
|
batchRequest = {
|
|
461
514
|
model: this,
|
|
462
|
-
|
|
515
|
+
// canonical string id -> { id, callbacks }. Keyed by the canonical
|
|
516
|
+
// form so a string id and its object form share one entry.
|
|
517
|
+
items: new Map(),
|
|
463
518
|
timer: null,
|
|
464
519
|
timeoutTimer: null,
|
|
465
520
|
delay: batchDelay,
|
|
@@ -468,25 +523,22 @@ const BatchLoadingMethods = {
|
|
|
468
523
|
};
|
|
469
524
|
batchRequests.set(batchKey, batchRequest);
|
|
470
525
|
|
|
471
|
-
//
|
|
472
|
-
batchRequest.timer =
|
|
526
|
+
// Schedule the flush. `timer` is a cancel function (see scheduleBatchFlush).
|
|
527
|
+
batchRequest.timer = scheduleBatchFlush(async () => {
|
|
473
528
|
try {
|
|
474
529
|
const currentBatch = batchRequests.get(batchKey);
|
|
475
530
|
if (!currentBatch) return;
|
|
476
531
|
|
|
477
|
-
const batchIds = currentBatch.items.
|
|
532
|
+
const batchIds = Array.from(currentBatch.items.keys());
|
|
478
533
|
|
|
479
534
|
// Execute bulk find
|
|
480
|
-
const { items, ConsumedCapacity } = await this.batchFind(
|
|
481
|
-
batchIds,
|
|
482
|
-
loaderContext,
|
|
483
|
-
);
|
|
535
|
+
const { items, ConsumedCapacity } = await this.batchFind(batchIds);
|
|
484
536
|
|
|
485
537
|
// total callbacks
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
538
|
+
let totalCallbacks = 0;
|
|
539
|
+
for (const item of currentBatch.items.values()) {
|
|
540
|
+
totalCallbacks += item.callbacks.length;
|
|
541
|
+
}
|
|
490
542
|
|
|
491
543
|
// Resolve all promises, including multiple callbacks for the same ID.
|
|
492
544
|
// Sum ALL ConsumedCapacity entries (multiple BatchGet pages and any
|
|
@@ -522,7 +574,7 @@ const BatchLoadingMethods = {
|
|
|
522
574
|
clearTimeout(currentBatch.timeoutTimer);
|
|
523
575
|
}
|
|
524
576
|
if (currentBatch.timer) {
|
|
525
|
-
|
|
577
|
+
currentBatch.timer();
|
|
526
578
|
}
|
|
527
579
|
batchRequests.delete(batchKey);
|
|
528
580
|
} catch (error) {
|
|
@@ -535,7 +587,7 @@ const BatchLoadingMethods = {
|
|
|
535
587
|
clearTimeout(currentBatch.timeoutTimer);
|
|
536
588
|
}
|
|
537
589
|
if (currentBatch.timer) {
|
|
538
|
-
|
|
590
|
+
currentBatch.timer();
|
|
539
591
|
}
|
|
540
592
|
batchRequests.delete(batchKey);
|
|
541
593
|
}
|
|
@@ -547,7 +599,7 @@ const BatchLoadingMethods = {
|
|
|
547
599
|
const currentBatch = batchRequests.get(batchKey);
|
|
548
600
|
if (currentBatch === batchRequest) {
|
|
549
601
|
if (currentBatch.timer) {
|
|
550
|
-
|
|
602
|
+
currentBatch.timer();
|
|
551
603
|
}
|
|
552
604
|
batchRequests.delete(batchKey);
|
|
553
605
|
currentBatch.items.forEach((batchItem) => {
|
|
@@ -560,14 +612,13 @@ const BatchLoadingMethods = {
|
|
|
560
612
|
}
|
|
561
613
|
|
|
562
614
|
// Add this request to the batch
|
|
563
|
-
const
|
|
564
|
-
|
|
565
|
-
);
|
|
615
|
+
const canonicalId = this._canonicalPrimaryId(primaryId);
|
|
616
|
+
const existingItem = batchRequest.items.get(canonicalId);
|
|
566
617
|
if (existingItem) {
|
|
567
618
|
existingItem.callbacks.push({ resolve, reject });
|
|
568
619
|
} else {
|
|
569
|
-
batchRequest.items.
|
|
570
|
-
id:
|
|
620
|
+
batchRequest.items.set(canonicalId, {
|
|
621
|
+
id: canonicalId,
|
|
571
622
|
callbacks: [{ resolve, reject }],
|
|
572
623
|
});
|
|
573
624
|
}
|
|
@@ -675,6 +726,5 @@ module.exports = {
|
|
|
675
726
|
runWithBatchContext,
|
|
676
727
|
getBatchContextCapacity,
|
|
677
728
|
_accumulateCapacityToContext,
|
|
678
|
-
DEFAULT_BATCH_DELAY_MS,
|
|
679
729
|
BATCH_REQUEST_TIMEOUT,
|
|
680
730
|
};
|