dynamo-bao 0.3.8 → 0.3.9

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 CHANGED
@@ -22,6 +22,7 @@ DynamoBao is the tool I wish I had when I started.
22
22
  - Enforce unique constraints and use them for lookups
23
23
  - Built-in multi-tenancy support with complete data isolation and concurrency safety
24
24
  - Return total read/write consumed capacity (even when multiple operations were performed)
25
+ - Request-scoped capacity aggregation for usage metering and billing
25
26
  - Easily iterate over all items in a model for batch processing or migrations
26
27
  - ESM (ECMAScript Modules) support for modern JavaScript projects
27
28
  - StringSetField for storing sets of strings with efficient diffing on save
@@ -286,6 +287,34 @@ This is particularly useful for:
286
287
  - **Production**: Use default mode for maximum flexibility
287
288
  - **Migration**: Gradually migrate from direct calls to batch context usage
288
289
 
290
+ ### Request-Scoped Capacity Tracking
291
+
292
+ DynamoBao provides `getBatchContextCapacity()` to retrieve the total DynamoDB consumed capacity (RCUs/WCUs) for all operations within the current `runWithBatchContext` scope. This is useful for usage metering and billing in multi-tenant applications.
293
+
294
+ ```javascript
295
+ import { runWithBatchContext, getBatchContextCapacity } from "dynamo-bao";
296
+
297
+ app.use(async (req, res, next) => {
298
+ await runWithBatchContext(async () => {
299
+ await next();
300
+
301
+ // Get total capacity consumed during this request
302
+ const capacity = getBatchContextCapacity();
303
+ // Returns: { read: 2.5, write: 1.0 }
304
+
305
+ // Record for billing/metering
306
+ usageTracker.record(req.tenantId, capacity);
307
+ });
308
+ });
309
+ ```
310
+
311
+ **Key features:**
312
+
313
+ - Tracks all operations: `find`, `batchFind`, `query`, `create`, `update`, `delete`
314
+ - Automatically accumulates capacity across multiple models
315
+ - Returns `{ read: 0, write: 0 }` when called outside a batch context
316
+ - Each batch context has isolated capacity tracking
317
+
289
318
  ### Iterating over all items
290
319
 
291
320
  DynamoBao makes it easy to iterate over all items in a model, which is useful for tasks like data migration, backfills, or reporting.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dynamo-bao",
3
- "version": "0.3.8",
3
+ "version": "0.3.9",
4
4
  "description": "Simple powerful data modeling primitives for DynamoDB in JavaScript.",
5
5
  "main": "src/index.js",
6
6
  "exports": {
package/src/index.js CHANGED
@@ -17,7 +17,10 @@ const {
17
17
  } = require("./model");
18
18
 
19
19
  const { TenantContext } = require("./tenant-context");
20
- const { runWithBatchContext } = require("./mixins/batch-loading-mixin");
20
+ const {
21
+ runWithBatchContext,
22
+ getBatchContextCapacity,
23
+ } = require("./mixins/batch-loading-mixin");
21
24
 
22
25
  function findModelFiles(dir) {
23
26
  let results = [];
@@ -215,6 +218,7 @@ const firstExport = {
215
218
 
216
219
  // Batch context for Cloudflare Workers
217
220
  runWithBatchContext,
221
+ getBatchContextCapacity,
218
222
 
219
223
  // Configurations
220
224
  PrimaryKeyConfig,
@@ -19,6 +19,49 @@ const batchContext = AsyncLocalStorage ? new AsyncLocalStorage() : null;
19
19
  const DEFAULT_BATCH_DELAY_MS = 5;
20
20
  const BATCH_REQUEST_TIMEOUT = 10000; // 10 seconds max lifetime for a batch
21
21
 
22
+ /**
23
+ * Accumulate capacity units to the current batch context.
24
+ * This is called internally by model operations to track total capacity consumed.
25
+ * @param {number} capacityUnits - The capacity units to accumulate
26
+ * @param {string} type - Either "read" or "write"
27
+ */
28
+ function _accumulateCapacityToContext(capacityUnits, type) {
29
+ if (!batchContext) return;
30
+ const context = batchContext.getStore();
31
+ if (context?.capacityAccumulator && typeof capacityUnits === "number") {
32
+ context.capacityAccumulator[type] += capacityUnits;
33
+ }
34
+ }
35
+
36
+ /**
37
+ * Get the total consumed capacity for the current batch context.
38
+ * Returns the accumulated RCUs and WCUs for all operations within the current
39
+ * runWithBatchContext scope.
40
+ *
41
+ * @returns {{ read: number, write: number }} The accumulated capacity, or { read: 0, write: 0 } if not in a batch context
42
+ *
43
+ * @example
44
+ * import { runWithBatchContext, getBatchContextCapacity } from "dynamo-bao";
45
+ *
46
+ * await runWithBatchContext(async () => {
47
+ * await User.find(userId);
48
+ * await Post.queryByIndex('byUser', userId);
49
+ *
50
+ * const capacity = getBatchContextCapacity();
51
+ * console.log(`Read: ${capacity.read} RCUs, Write: ${capacity.write} WCUs`);
52
+ * });
53
+ */
54
+ function getBatchContextCapacity() {
55
+ if (!batchContext) {
56
+ return { read: 0, write: 0 };
57
+ }
58
+ const context = batchContext.getStore();
59
+ if (!context?.capacityAccumulator) {
60
+ return { read: 0, write: 0 };
61
+ }
62
+ return { ...context.capacityAccumulator };
63
+ }
64
+
22
65
  const BatchLoadingMethods = {
23
66
  _getBatchRequests() {
24
67
  // AsyncLocalStorage is required - check for context
@@ -174,6 +217,11 @@ const BatchLoadingMethods = {
174
217
  // Track consumed capacity
175
218
  if (batchResult.ConsumedCapacity) {
176
219
  consumedCapacity.push(...[].concat(batchResult.ConsumedCapacity));
220
+ // Accumulate to batch context
221
+ const capacityArray = [].concat(batchResult.ConsumedCapacity);
222
+ for (const cap of capacityArray) {
223
+ _accumulateCapacityToContext(cap?.CapacityUnits || 0, "read");
224
+ }
177
225
  }
178
226
 
179
227
  // Handle unprocessed keys
@@ -277,6 +325,11 @@ const BatchLoadingMethods = {
277
325
  let instance;
278
326
  if (!result.Item) {
279
327
  instance = new ObjectNotFound(result.ConsumedCapacity);
328
+ // Accumulate capacity for ObjectNotFound since _addConsumedCapacity isn't called
329
+ _accumulateCapacityToContext(
330
+ result.ConsumedCapacity?.CapacityUnits || 0,
331
+ "read",
332
+ );
280
333
  } else {
281
334
  instance = this._createFromDyItem(result.Item);
282
335
  instance._addConsumedCapacity(result.ConsumedCapacity, "read", false);
@@ -338,7 +391,8 @@ const BatchLoadingMethods = {
338
391
  currentBatch.items.forEach((batchItem) => {
339
392
  let item = items[batchItem.id];
340
393
  if (item) {
341
- item._addConsumedCapacity(consumedCapacity, "read", false);
394
+ // Skip context accumulation since batchFind already accumulated the total
395
+ item._addConsumedCapacity(consumedCapacity, "read", false, true);
342
396
  } else {
343
397
  item = new ObjectNotFound(consumedCapacity);
344
398
  }
@@ -446,6 +500,7 @@ function runWithBatchContext(fn) {
446
500
  loaderContext: new Map(), // Add automatic loaderContext
447
501
  timers: new Set(),
448
502
  startTime: Date.now(),
503
+ capacityAccumulator: { read: 0, write: 0 }, // Track total capacity consumed
449
504
  };
450
505
 
451
506
  return batchContext.run(context, fn);
@@ -454,6 +509,8 @@ function runWithBatchContext(fn) {
454
509
  module.exports = {
455
510
  BatchLoadingMethods,
456
511
  runWithBatchContext,
512
+ getBatchContextCapacity,
513
+ _accumulateCapacityToContext,
457
514
  DEFAULT_BATCH_DELAY_MS,
458
515
  BATCH_REQUEST_TIMEOUT,
459
516
  };
@@ -7,6 +7,9 @@ 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
13
 
11
14
  const QueryMethods = {
12
15
  /**
@@ -296,6 +299,10 @@ const QueryMethods = {
296
299
  },
297
300
 
298
301
  async _processQueryResponse(response, options = {}) {
302
+ // Accumulate query capacity to batch context
303
+ const capacityUnits = response.ConsumedCapacity?.CapacityUnits || 0;
304
+ _accumulateCapacityToContext(capacityUnits, "read");
305
+
299
306
  if (options.countOnly) {
300
307
  return {
301
308
  count: response.Count,
package/src/model.js CHANGED
@@ -19,6 +19,7 @@ const {
19
19
  BatchLoadingMethods,
20
20
  BATCH_REQUESTS,
21
21
  BATCH_REQUEST_TIMEOUT,
22
+ _accumulateCapacityToContext,
22
23
  } = require("./mixins/batch-loading-mixin");
23
24
 
24
25
  const {
@@ -788,7 +789,12 @@ class BaoModel {
788
789
  this._addConsumedCapacity(capacity, type, fromContext);
789
790
  }
790
791
 
791
- _addConsumedCapacity(consumedCapacity, type, isRelated = false) {
792
+ _addConsumedCapacity(
793
+ consumedCapacity,
794
+ type,
795
+ isRelated = false,
796
+ skipContextAccumulation = false,
797
+ ) {
792
798
  if (!["read", "write"].includes(type)) {
793
799
  throw new ValidationError(`Invalid consumed capacity type: ${type}`);
794
800
  }
@@ -799,7 +805,7 @@ class BaoModel {
799
805
 
800
806
  if (Array.isArray(consumedCapacity)) {
801
807
  consumedCapacity.forEach((item) =>
802
- this._addConsumedCapacity(item, type, isRelated),
808
+ this._addConsumedCapacity(item, type, isRelated, skipContextAccumulation),
803
809
  );
804
810
  } else {
805
811
  if (consumedCapacity.consumedCapacity) {
@@ -808,12 +814,22 @@ class BaoModel {
808
814
  fromContext: consumedCapacity.fromContext || isRelated,
809
815
  type: consumedCapacity.type || type,
810
816
  });
817
+ // Accumulate to batch context (only for non-related to avoid double counting)
818
+ if (!isRelated && !consumedCapacity.fromContext && !skipContextAccumulation) {
819
+ const units = consumedCapacity.consumedCapacity?.CapacityUnits || 0;
820
+ _accumulateCapacityToContext(units, consumedCapacity.type || type);
821
+ }
811
822
  } else {
812
823
  this._consumedCapacity.push({
813
824
  consumedCapacity: consumedCapacity,
814
825
  fromContext: isRelated,
815
826
  type: type,
816
827
  });
828
+ // Accumulate to batch context (only for non-related to avoid double counting)
829
+ if (!isRelated && !skipContextAccumulation) {
830
+ const units = consumedCapacity?.CapacityUnits || 0;
831
+ _accumulateCapacityToContext(units, type);
832
+ }
817
833
  }
818
834
  }
819
835
  }