dynamo-bao 0.1.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.
@@ -0,0 +1,336 @@
1
+ const { defaultLogger: logger } = require("../utils/logger");
2
+ const { ObjectNotFound } = require("../object-not-found");
3
+ const { pluginManager } = require("../plugin-manager");
4
+ const { BatchGetCommand, GetCommand } = require("@aws-sdk/lib-dynamodb");
5
+
6
+ // Move these constants from model.js to here
7
+ const BATCH_REQUESTS = new Map(); // testId -> { modelName-delay -> batch }
8
+ const DEFAULT_BATCH_DELAY_MS = 5;
9
+ const BATCH_REQUEST_TIMEOUT = 10000; // 10 seconds max lifetime for a batch
10
+
11
+ const BatchLoadingMethods = {
12
+ _getBatchRequests() {
13
+ const testId = this._testId || "default";
14
+ if (!BATCH_REQUESTS.has(testId)) {
15
+ BATCH_REQUESTS.set(testId, new Map());
16
+ }
17
+ return BATCH_REQUESTS.get(testId);
18
+ },
19
+
20
+ /**
21
+ * @memberof BaoModel
22
+ * @description
23
+ * This is the primary way to load multiple objects given an array of ids.
24
+ * This function should only be used when {@link BaoModel.find} or {@link BaoModel#loadRelatedData} is not sufficient.
25
+ *
26
+ * @param {string[]} primaryIds - The primary IDs of the items to load
27
+ * @param {Object} [loaderContext] - Cache context for storing and retrieving items across requests.
28
+ * @returns {Promise<Object>} Returns a promise that resolves to the loaded items and their consumed capacity
29
+ */
30
+ async batchFind(primaryIds, loaderContext = null) {
31
+ if (!primaryIds?.length) return { items: {}, ConsumedCapacity: [] };
32
+
33
+ // Add retry wrapper function
34
+ const retryOperation = async (operation, maxRetries = 3) => {
35
+ for (let attempt = 0; attempt < maxRetries; attempt++) {
36
+ try {
37
+ return await operation();
38
+ } catch (error) {
39
+ if (attempt === maxRetries - 1) throw error;
40
+
41
+ // Check if it's a network-related error
42
+ if (
43
+ error.name === "TimeoutError" ||
44
+ error.code === "NetworkingError" ||
45
+ error.message.includes("getaddrinfo ENOTFOUND")
46
+ ) {
47
+ const delay = Math.pow(2, attempt) * 100; // exponential backoff
48
+ await new Promise((resolve) => setTimeout(resolve, delay));
49
+ continue;
50
+ }
51
+
52
+ throw error; // rethrow non-network errors immediately
53
+ }
54
+ }
55
+ };
56
+
57
+ // Initialize results object
58
+ const results = {};
59
+ let idsToLoad = [];
60
+
61
+ // First check loaderContext for existing items
62
+ if (loaderContext) {
63
+ primaryIds.forEach((id) => {
64
+ if (loaderContext[id]) {
65
+ const instance = this._createFromDyItem(loaderContext[id]._dyData);
66
+ results[id] = instance;
67
+ } else {
68
+ idsToLoad.push(id);
69
+ }
70
+ });
71
+ } else {
72
+ idsToLoad.push(...primaryIds);
73
+ }
74
+
75
+ // If all items were in context, return early
76
+ if (!idsToLoad.length) {
77
+ return { items: results, ConsumedCapacity: [] };
78
+ }
79
+
80
+ const consumedCapacity = [];
81
+
82
+ // remove duplicates from idsToLoad
83
+ idsToLoad = [...new Set(idsToLoad)];
84
+
85
+ // Process items in batches of 100
86
+ for (let i = 0; i < idsToLoad.length; i += 100) {
87
+ const batchIds = idsToLoad.slice(i, i + 100);
88
+ const Keys = batchIds.map((id) => {
89
+ const pkSk = this._parsePrimaryId(id);
90
+ return this._getDyKeyForPkSk(pkSk);
91
+ });
92
+
93
+ let unprocessedKeys = Keys;
94
+ const maxRetries = 3;
95
+ let retryCount = 0;
96
+
97
+ while (unprocessedKeys.length > 0 && retryCount < maxRetries) {
98
+ // Wrap the batchGet call with our retry function
99
+ const batchResult = await retryOperation(() =>
100
+ this.documentClient.send(
101
+ new BatchGetCommand({
102
+ RequestItems: {
103
+ [this.table]: {
104
+ Keys: unprocessedKeys,
105
+ },
106
+ },
107
+ ReturnConsumedCapacity: "TOTAL",
108
+ }),
109
+ ),
110
+ );
111
+
112
+ // Process successful items
113
+ if (batchResult.Responses?.[this.table]) {
114
+ batchResult.Responses[this.table].forEach((item) => {
115
+ const instance = this._createFromDyItem(item);
116
+ const primaryId = instance.getPrimaryId();
117
+ results[primaryId] = instance;
118
+
119
+ // Add to loader context if provided
120
+ if (loaderContext) {
121
+ loaderContext[primaryId] = instance;
122
+ }
123
+ });
124
+ }
125
+
126
+ // Track consumed capacity
127
+ if (batchResult.ConsumedCapacity) {
128
+ consumedCapacity.push(...[].concat(batchResult.ConsumedCapacity));
129
+ }
130
+
131
+ // Handle unprocessed keys
132
+ unprocessedKeys = batchResult.UnprocessedKeys?.[this.table]?.Keys || [];
133
+
134
+ if (unprocessedKeys.length > 0) {
135
+ retryCount++;
136
+ // Add exponential backoff if needed
137
+ await new Promise((resolve) =>
138
+ setTimeout(resolve, Math.pow(2, retryCount) * 100),
139
+ );
140
+ }
141
+ }
142
+
143
+ // If we still have unprocessed keys after retries, log a warning
144
+ if (unprocessedKeys.length > 0) {
145
+ console.warn(
146
+ `Failed to process ${unprocessedKeys.length} items after ${maxRetries} retries`,
147
+ );
148
+ }
149
+ }
150
+
151
+ return {
152
+ items: results,
153
+ ConsumedCapacity: consumedCapacity,
154
+ };
155
+ },
156
+
157
+ /**
158
+ *@memberof BaoModel
159
+ *
160
+ * @description
161
+ * Find is the primary way to look up an object given its id. It will return the object
162
+ * if it exists, or an {@link ObjectNotFound} instance if it does not. Find supports
163
+ * efficient batch loading and caching. In general, this function should be
164
+ * preferred over {@link BaoModel.batchFind}. Find uses batchFind internally, unless batchDelay
165
+ * is set to 0.
166
+ *
167
+ * @param {string} primaryId - The primary ID of the item to find
168
+ * @param {Object} [options={}] - Optional configuration for the find operation
169
+ * @param {number} [options.batchDelay=5] - Delay in milliseconds before executing batch request.
170
+ * Set to 0 for immediate individual requests
171
+ * @param {Object} [options.loaderContext] - Cache context for storing and retrieving items across requests.
172
+ * If provided, results will be stored in and retrieved from this context
173
+ * @returns {Promise<Object>} Returns a promise that resolves to the found item instance or ObjectNotFound
174
+ * @throws {Error} If the batch request times out or other errors occur during the operation
175
+ */
176
+ async find(primaryId, options = {}) {
177
+ const batchDelay = options.batchDelay ?? DEFAULT_BATCH_DELAY_MS;
178
+ const loaderContext = options.loaderContext;
179
+
180
+ // Check loader context first
181
+ if (loaderContext && loaderContext[primaryId]) {
182
+ const cachedItem = loaderContext[primaryId];
183
+ const instance = this._createFromDyItem(cachedItem._dyData);
184
+ const consumedCapacity =
185
+ cachedItem.getConsumedCapacity().consumedCapacity;
186
+ instance._addConsumedCapacity(consumedCapacity, "read", true);
187
+ return instance;
188
+ }
189
+
190
+ if (batchDelay === 0) {
191
+ // Direct DynamoDB request logic
192
+ const pkSk = this._parsePrimaryId(primaryId);
193
+ const dyKey = this._getDyKeyForPkSk(pkSk);
194
+ const result = await this.documentClient.send(
195
+ new GetCommand({
196
+ TableName: this.table,
197
+ Key: dyKey,
198
+ ReturnConsumedCapacity: "TOTAL",
199
+ }),
200
+ );
201
+
202
+ let instance;
203
+ if (!result.Item) {
204
+ instance = new ObjectNotFound(result.ConsumedCapacity);
205
+ } else {
206
+ instance = this._createFromDyItem(result.Item);
207
+ instance._addConsumedCapacity(result.ConsumedCapacity, "read", false);
208
+ }
209
+
210
+ // Add to loader context if provided
211
+ if (loaderContext) {
212
+ loaderContext[primaryId] = instance;
213
+ }
214
+
215
+ return instance;
216
+ }
217
+
218
+ // Batch request logic
219
+ return new Promise((resolve, reject) => {
220
+ const batchKey = `${this.name}-${batchDelay}`;
221
+ const batchRequests = this._getBatchRequests();
222
+ let batchRequest = batchRequests.get(batchKey);
223
+
224
+ if (!batchRequest) {
225
+ batchRequest = {
226
+ model: this,
227
+ items: [],
228
+ timer: null,
229
+ timeoutTimer: null,
230
+ delay: batchDelay,
231
+ createdAt: Date.now(),
232
+ loaderContext,
233
+ };
234
+ batchRequests.set(batchKey, batchRequest);
235
+
236
+ // Set batch execution timer
237
+ batchRequest.timer = setTimeout(async () => {
238
+ try {
239
+ const currentBatch = batchRequests.get(batchKey);
240
+ if (!currentBatch) return;
241
+
242
+ const batchIds = currentBatch.items.map((item) => item.id);
243
+
244
+ // Execute bulk find
245
+ const { items, ConsumedCapacity } = await this.batchFind(
246
+ batchIds,
247
+ loaderContext,
248
+ );
249
+
250
+ // total callbacks
251
+ const totalCallbacks = currentBatch.items.reduce(
252
+ (sum, item) => sum + item.callbacks.length,
253
+ 0,
254
+ );
255
+
256
+ // Resolve all promises, including multiple callbacks for the same ID
257
+ const consumedCapacity = {
258
+ TableName: this.table,
259
+ CapacityUnits:
260
+ ConsumedCapacity[0]?.CapacityUnits / totalCallbacks,
261
+ };
262
+
263
+ currentBatch.items.forEach((batchItem) => {
264
+ let item = items[batchItem.id];
265
+ if (item) {
266
+ item._addConsumedCapacity(consumedCapacity, "read", false);
267
+ } else {
268
+ item = new ObjectNotFound(consumedCapacity);
269
+ }
270
+ batchItem.callbacks.forEach((cb) => cb.resolve(item));
271
+ });
272
+
273
+ // Clean up the batch and BOTH timers
274
+ if (currentBatch.timeoutTimer) {
275
+ clearTimeout(currentBatch.timeoutTimer);
276
+ }
277
+ if (currentBatch.timer) {
278
+ clearTimeout(currentBatch.timer);
279
+ }
280
+ batchRequests.delete(batchKey);
281
+ } catch (error) {
282
+ const currentBatch = batchRequests.get(batchKey);
283
+ if (currentBatch) {
284
+ currentBatch.items.forEach((batchItem) => {
285
+ batchItem.callbacks.forEach((cb) => cb.reject(error));
286
+ });
287
+ if (currentBatch.timeoutTimer) {
288
+ clearTimeout(currentBatch.timeoutTimer);
289
+ }
290
+ if (currentBatch.timer) {
291
+ clearTimeout(currentBatch.timer);
292
+ }
293
+ batchRequests.delete(batchKey);
294
+ }
295
+ }
296
+ }, batchDelay);
297
+
298
+ // Set timeout timer
299
+ batchRequest.timeoutTimer = setTimeout(() => {
300
+ const currentBatch = batchRequests.get(batchKey);
301
+ if (currentBatch === batchRequest) {
302
+ if (currentBatch.timer) {
303
+ clearTimeout(currentBatch.timer);
304
+ }
305
+ batchRequests.delete(batchKey);
306
+ currentBatch.items.forEach((batchItem) => {
307
+ batchItem.callbacks.forEach((cb) =>
308
+ cb.reject(new Error("Batch request timed out")),
309
+ );
310
+ });
311
+ }
312
+ }, BATCH_REQUEST_TIMEOUT);
313
+ }
314
+
315
+ // Add this request to the batch
316
+ const existingItem = batchRequest.items.find(
317
+ (item) => item.id === primaryId,
318
+ );
319
+ if (existingItem) {
320
+ existingItem.callbacks.push({ resolve, reject });
321
+ } else {
322
+ batchRequest.items.push({
323
+ id: primaryId,
324
+ callbacks: [{ resolve, reject }],
325
+ });
326
+ }
327
+ });
328
+ },
329
+ };
330
+
331
+ module.exports = {
332
+ BatchLoadingMethods,
333
+ BATCH_REQUESTS,
334
+ DEFAULT_BATCH_DELAY_MS,
335
+ BATCH_REQUEST_TIMEOUT,
336
+ };