dynamo-bao 0.3.8 → 0.4.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 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
@@ -94,7 +95,7 @@ models:
94
95
  content: {type: StringField, required: true}
95
96
  primaryKey: {partitionKey: postId}
96
97
  indexes:
97
- # Add up to 3 indexes; make sure each index has a unique id: gsi1, gsi2, gsi3
98
+ # Add up to 5 indexes; make sure each index has a unique id: gsi1, gsi2, gsi3, gsi4, gsi5
98
99
  # Enables user.queryPosts() to query posts for a user
99
100
  postsForUser: {partitionKey: userId, sortKey: postId, indexId: gsi2}
100
101
  ```
@@ -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.
@@ -4,6 +4,8 @@ const {
4
4
  DynamoDBClient,
5
5
  CreateTableCommand,
6
6
  ListTablesCommand,
7
+ DescribeTableCommand,
8
+ UpdateTimeToLiveCommand,
7
9
  } = require("../src/dynamodb-client.js");
8
10
  const readline = require("readline");
9
11
  const fs = require("fs");
@@ -86,6 +88,23 @@ module.exports = config;
86
88
  console.log(`Config file written to: ${configPath}`);
87
89
  }
88
90
 
91
+ async function waitForTableActive(tableName, maxAttempts = 30) {
92
+ for (let i = 0; i < maxAttempts; i++) {
93
+ const response = await client.send(
94
+ new DescribeTableCommand({ TableName: tableName }),
95
+ );
96
+ const status = response.Table.TableStatus;
97
+ if (status === "ACTIVE") {
98
+ return;
99
+ }
100
+ // Wait 2 seconds between checks
101
+ await new Promise((resolve) => setTimeout(resolve, 2000));
102
+ }
103
+ throw new Error(
104
+ `Table ${tableName} did not become active within ${maxAttempts * 2} seconds`,
105
+ );
106
+ }
107
+
89
108
  async function createTable() {
90
109
  // Prompt user for table name
91
110
  const defaultTableName = "dynamo-bao-dev";
@@ -106,6 +125,10 @@ async function createTable() {
106
125
  { AttributeName: "_gsi2_sk", AttributeType: "S" },
107
126
  { AttributeName: "_gsi3_pk", AttributeType: "S" },
108
127
  { AttributeName: "_gsi3_sk", AttributeType: "S" },
128
+ { AttributeName: "_gsi4_pk", AttributeType: "S" },
129
+ { AttributeName: "_gsi4_sk", AttributeType: "S" },
130
+ { AttributeName: "_gsi5_pk", AttributeType: "S" },
131
+ { AttributeName: "_gsi5_sk", AttributeType: "S" },
109
132
  { AttributeName: "_iter_pk", AttributeType: "S" },
110
133
  { AttributeName: "_iter_sk", AttributeType: "S" },
111
134
  ],
@@ -138,6 +161,22 @@ async function createTable() {
138
161
  ],
139
162
  Projection: { ProjectionType: "ALL" },
140
163
  },
164
+ {
165
+ IndexName: "gsi4",
166
+ KeySchema: [
167
+ { AttributeName: "_gsi4_pk", KeyType: "HASH" },
168
+ { AttributeName: "_gsi4_sk", KeyType: "RANGE" },
169
+ ],
170
+ Projection: { ProjectionType: "ALL" },
171
+ },
172
+ {
173
+ IndexName: "gsi5",
174
+ KeySchema: [
175
+ { AttributeName: "_gsi5_pk", KeyType: "HASH" },
176
+ { AttributeName: "_gsi5_sk", KeyType: "RANGE" },
177
+ ],
178
+ Projection: { ProjectionType: "ALL" },
179
+ },
141
180
  {
142
181
  IndexName: "iter_index",
143
182
  KeySchema: [
@@ -147,10 +186,6 @@ async function createTable() {
147
186
  Projection: { ProjectionType: "KEYS_ONLY" },
148
187
  },
149
188
  ],
150
- TimeToLiveSpecification: {
151
- AttributeName: "ttl",
152
- Enabled: true,
153
- },
154
189
  };
155
190
 
156
191
  try {
@@ -162,7 +197,23 @@ async function createTable() {
162
197
  response.TableDescription.TableName,
163
198
  );
164
199
 
165
- // Add this line to write the config file after table creation
200
+ // Wait for table to become active before enabling TTL
201
+ console.log("Waiting for table to become active...");
202
+ await waitForTableActive(tableName);
203
+
204
+ // Enable TTL (must be done after table creation via UpdateTimeToLive)
205
+ await client.send(
206
+ new UpdateTimeToLiveCommand({
207
+ TableName: tableName,
208
+ TimeToLiveSpecification: {
209
+ AttributeName: "ttl",
210
+ Enabled: true,
211
+ },
212
+ }),
213
+ );
214
+ console.log("TTL enabled on attribute 'ttl'");
215
+
216
+ // Write the config file after table creation
166
217
  await writeConfigFile(tableName);
167
218
  } catch (error) {
168
219
  console.error("Error creating table:", error);
@@ -0,0 +1,237 @@
1
+ #!/usr/bin/env node
2
+
3
+ const {
4
+ DynamoDBClient,
5
+ DescribeTableCommand,
6
+ UpdateTableCommand,
7
+ DescribeTimeToLiveCommand,
8
+ UpdateTimeToLiveCommand,
9
+ } = require("../src/dynamodb-client.js");
10
+ const { initConfig } = require("../src/config.js");
11
+
12
+ // Expected GSI definitions - the full set that should exist on the table
13
+ const EXPECTED_GSIS = [
14
+ {
15
+ IndexName: "gsi1",
16
+ KeySchema: [
17
+ { AttributeName: "_gsi1_pk", KeyType: "HASH" },
18
+ { AttributeName: "_gsi1_sk", KeyType: "RANGE" },
19
+ ],
20
+ Projection: { ProjectionType: "ALL" },
21
+ },
22
+ {
23
+ IndexName: "gsi2",
24
+ KeySchema: [
25
+ { AttributeName: "_gsi2_pk", KeyType: "HASH" },
26
+ { AttributeName: "_gsi2_sk", KeyType: "RANGE" },
27
+ ],
28
+ Projection: { ProjectionType: "ALL" },
29
+ },
30
+ {
31
+ IndexName: "gsi3",
32
+ KeySchema: [
33
+ { AttributeName: "_gsi3_pk", KeyType: "HASH" },
34
+ { AttributeName: "_gsi3_sk", KeyType: "RANGE" },
35
+ ],
36
+ Projection: { ProjectionType: "ALL" },
37
+ },
38
+ {
39
+ IndexName: "gsi4",
40
+ KeySchema: [
41
+ { AttributeName: "_gsi4_pk", KeyType: "HASH" },
42
+ { AttributeName: "_gsi4_sk", KeyType: "RANGE" },
43
+ ],
44
+ Projection: { ProjectionType: "ALL" },
45
+ },
46
+ {
47
+ IndexName: "gsi5",
48
+ KeySchema: [
49
+ { AttributeName: "_gsi5_pk", KeyType: "HASH" },
50
+ { AttributeName: "_gsi5_sk", KeyType: "RANGE" },
51
+ ],
52
+ Projection: { ProjectionType: "ALL" },
53
+ },
54
+ {
55
+ IndexName: "iter_index",
56
+ KeySchema: [
57
+ { AttributeName: "_iter_pk", KeyType: "HASH" },
58
+ { AttributeName: "_iter_sk", KeyType: "RANGE" },
59
+ ],
60
+ Projection: { ProjectionType: "KEYS_ONLY" },
61
+ },
62
+ ];
63
+
64
+ // All attribute definitions that GSIs may reference
65
+ const ALL_ATTRIBUTE_DEFINITIONS = [
66
+ { AttributeName: "_gsi1_pk", AttributeType: "S" },
67
+ { AttributeName: "_gsi1_sk", AttributeType: "S" },
68
+ { AttributeName: "_gsi2_pk", AttributeType: "S" },
69
+ { AttributeName: "_gsi2_sk", AttributeType: "S" },
70
+ { AttributeName: "_gsi3_pk", AttributeType: "S" },
71
+ { AttributeName: "_gsi3_sk", AttributeType: "S" },
72
+ { AttributeName: "_gsi4_pk", AttributeType: "S" },
73
+ { AttributeName: "_gsi4_sk", AttributeType: "S" },
74
+ { AttributeName: "_gsi5_pk", AttributeType: "S" },
75
+ { AttributeName: "_gsi5_sk", AttributeType: "S" },
76
+ { AttributeName: "_iter_pk", AttributeType: "S" },
77
+ { AttributeName: "_iter_sk", AttributeType: "S" },
78
+ ];
79
+
80
+ let client;
81
+
82
+ async function waitForTableActive(tableName, maxAttempts = 60) {
83
+ for (let i = 0; i < maxAttempts; i++) {
84
+ const response = await client.send(
85
+ new DescribeTableCommand({ TableName: tableName }),
86
+ );
87
+ const status = response.Table.TableStatus;
88
+ if (status === "ACTIVE") {
89
+ return;
90
+ }
91
+ console.log(` Table status: ${status}, waiting...`);
92
+ await new Promise((resolve) => setTimeout(resolve, 5000));
93
+ }
94
+ throw new Error(
95
+ `Table ${tableName} did not become active within ${maxAttempts * 5} seconds`,
96
+ );
97
+ }
98
+
99
+ async function checkAndAddMissingGSIs(tableName) {
100
+ const response = await client.send(
101
+ new DescribeTableCommand({ TableName: tableName }),
102
+ );
103
+
104
+ const existingIndexNames = (response.Table.GlobalSecondaryIndexes || []).map(
105
+ (gsi) => gsi.IndexName,
106
+ );
107
+
108
+ const missingGSIs = EXPECTED_GSIS.filter(
109
+ (gsi) => !existingIndexNames.includes(gsi.IndexName),
110
+ );
111
+
112
+ if (missingGSIs.length === 0) {
113
+ console.log("All GSIs are present.");
114
+ return;
115
+ }
116
+
117
+ console.log(
118
+ `Missing GSIs: ${missingGSIs.map((g) => g.IndexName).join(", ")}`,
119
+ );
120
+
121
+ // DynamoDB only allows adding one GSI per UpdateTable call
122
+ for (const gsi of missingGSIs) {
123
+ console.log(`\nAdding GSI: ${gsi.IndexName}...`);
124
+
125
+ // Collect attribute definitions needed for this GSI
126
+ const neededAttrs = gsi.KeySchema.map((ks) => ks.AttributeName);
127
+ const attrDefs = ALL_ATTRIBUTE_DEFINITIONS.filter((ad) =>
128
+ neededAttrs.includes(ad.AttributeName),
129
+ );
130
+
131
+ await client.send(
132
+ new UpdateTableCommand({
133
+ TableName: tableName,
134
+ AttributeDefinitions: attrDefs,
135
+ GlobalSecondaryIndexUpdates: [
136
+ {
137
+ Create: {
138
+ IndexName: gsi.IndexName,
139
+ KeySchema: gsi.KeySchema,
140
+ Projection: gsi.Projection,
141
+ },
142
+ },
143
+ ],
144
+ }),
145
+ );
146
+
147
+ console.log(
148
+ ` GSI ${gsi.IndexName} creation initiated. Waiting for table to become active...`,
149
+ );
150
+ await waitForTableActive(tableName);
151
+ console.log(` GSI ${gsi.IndexName} is ready.`);
152
+ }
153
+ }
154
+
155
+ async function checkAndEnableTTL(tableName) {
156
+ const response = await client.send(
157
+ new DescribeTimeToLiveCommand({ TableName: tableName }),
158
+ );
159
+
160
+ const ttlStatus = response.TimeToLiveDescription?.TimeToLiveStatus;
161
+ const ttlAttr = response.TimeToLiveDescription?.AttributeName;
162
+
163
+ if (ttlStatus === "ENABLED" && ttlAttr === "ttl") {
164
+ console.log("TTL is already enabled on attribute 'ttl'.");
165
+ return;
166
+ }
167
+
168
+ if (ttlStatus === "ENABLING") {
169
+ console.log("TTL is currently being enabled. Please wait and try again.");
170
+ return;
171
+ }
172
+
173
+ if (ttlStatus === "DISABLING") {
174
+ console.log(
175
+ "TTL is currently being disabled. Please wait for it to finish, then run this script again.",
176
+ );
177
+ return;
178
+ }
179
+
180
+ console.log("Enabling TTL on attribute 'ttl'...");
181
+ await client.send(
182
+ new UpdateTimeToLiveCommand({
183
+ TableName: tableName,
184
+ TimeToLiveSpecification: {
185
+ AttributeName: "ttl",
186
+ Enabled: true,
187
+ },
188
+ }),
189
+ );
190
+ console.log("TTL enabled successfully.");
191
+ }
192
+
193
+ async function main() {
194
+ const config = await initConfig();
195
+ const tableName = config.db.tableName;
196
+
197
+ if (!tableName) {
198
+ console.error(
199
+ "No table name found in config. Please run bao-init first or set TABLE_NAME.",
200
+ );
201
+ process.exit(1);
202
+ }
203
+
204
+ client = new DynamoDBClient({
205
+ region: config.aws?.region,
206
+ });
207
+
208
+ console.log(`Updating table: ${tableName}\n`);
209
+
210
+ // Verify the table exists
211
+ try {
212
+ await client.send(new DescribeTableCommand({ TableName: tableName }));
213
+ } catch (error) {
214
+ if (error.name === "ResourceNotFoundException") {
215
+ console.error(
216
+ `Table '${tableName}' not found. Please run bao-init to create it first.`,
217
+ );
218
+ process.exit(1);
219
+ }
220
+ throw error;
221
+ }
222
+
223
+ // Check and add missing GSIs
224
+ console.log("Checking GSIs...");
225
+ await checkAndAddMissingGSIs(tableName);
226
+
227
+ // Check and enable TTL
228
+ console.log("\nChecking TTL...");
229
+ await checkAndEnableTTL(tableName);
230
+
231
+ console.log("\nTable update complete.");
232
+ }
233
+
234
+ main().catch((error) => {
235
+ console.error("Error:", error);
236
+ process.exit(1);
237
+ });
@@ -100,7 +100,11 @@ function generateModelClass(
100
100
  // Update logging
101
101
  logger.debug(`Generating index ${indexName}:`, indexConfig);
102
102
 
103
- const indexId = `GSI_INDEX_ID${indexConfig.indexId.slice(-1)}`;
103
+ const indexNum = indexConfig.indexId.match(/(\d+)$/);
104
+ if (!indexNum) {
105
+ throw new Error(`Invalid indexId format: ${indexConfig.indexId}. Expected format: gsi1, gsi2, etc.`);
106
+ }
107
+ const indexId = `GSI_INDEX_ID${indexNum[1]}`;
104
108
  constantImports.add(indexId);
105
109
  return ` ${indexName}: IndexConfig('${indexConfig.partitionKey}', '${indexConfig.sortKey}', ${indexId}),`;
106
110
  })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dynamo-bao",
3
- "version": "0.3.8",
3
+ "version": "0.4.0",
4
4
  "description": "Simple powerful data modeling primitives for DynamoDB in JavaScript.",
5
5
  "main": "src/index.js",
6
6
  "exports": {
@@ -55,6 +55,7 @@
55
55
  "bao-init": "bin/dynamo-bao-create-table.js",
56
56
  "bao-codegen": "./bin/codegen.js",
57
57
  "bao-watch": "./bin/watch.js",
58
+ "bao-update-table": "bin/dynamo-bao-update-table.js",
58
59
  "bao-delete": "bin/dynamo-bao-delete-table.js"
59
60
  }
60
61
  }
package/src/constants.js CHANGED
@@ -2,6 +2,8 @@
2
2
  const GSI_INDEX_ID1 = "gsi1";
3
3
  const GSI_INDEX_ID2 = "gsi2";
4
4
  const GSI_INDEX_ID3 = "gsi3";
5
+ const GSI_INDEX_ID4 = "gsi4";
6
+ const GSI_INDEX_ID5 = "gsi5";
5
7
 
6
8
  // Constants for iteration index
7
9
  const ITERATION_INDEX_NAME = "iter_index";
@@ -23,6 +25,10 @@ const SYSTEM_FIELDS = [
23
25
  "_gsi2_sk",
24
26
  "_gsi3_pk",
25
27
  "_gsi3_sk",
28
+ "_gsi4_pk",
29
+ "_gsi4_sk",
30
+ "_gsi5_pk",
31
+ "_gsi5_sk",
26
32
  "_iter_pk",
27
33
  "_iter_sk",
28
34
  ];
@@ -33,6 +39,8 @@ module.exports = {
33
39
  GSI_INDEX_ID1,
34
40
  GSI_INDEX_ID2,
35
41
  GSI_INDEX_ID3,
42
+ GSI_INDEX_ID4,
43
+ GSI_INDEX_ID5,
36
44
  ITERATION_INDEX_NAME,
37
45
  ITERATION_PK_FIELD,
38
46
  ITERATION_SK_FIELD,
@@ -196,7 +196,10 @@ class DynamoDBClient {
196
196
  'TransactWriteCommand': 'TransactWriteItems',
197
197
  'CreateTableCommand': 'CreateTable',
198
198
  'ListTablesCommand': 'ListTables',
199
- 'DescribeTableCommand': 'DescribeTable'
199
+ 'DescribeTableCommand': 'DescribeTable',
200
+ 'UpdateTimeToLiveCommand': 'UpdateTimeToLive',
201
+ 'DescribeTimeToLiveCommand': 'DescribeTimeToLive',
202
+ 'UpdateTableCommand': 'UpdateTable'
200
203
  };
201
204
 
202
205
  return operationMap[commandName] || commandName.replace('Command', '');
@@ -628,6 +631,24 @@ class DescribeTableCommand {
628
631
  }
629
632
  }
630
633
 
634
+ class UpdateTimeToLiveCommand {
635
+ constructor(input) {
636
+ this.input = input;
637
+ }
638
+ }
639
+
640
+ class DescribeTimeToLiveCommand {
641
+ constructor(input) {
642
+ this.input = input;
643
+ }
644
+ }
645
+
646
+ class UpdateTableCommand {
647
+ constructor(input) {
648
+ this.input = input;
649
+ }
650
+ }
651
+
631
652
  module.exports = {
632
653
  DynamoDBClient,
633
654
  DynamoDBDocumentClient,
@@ -640,6 +661,9 @@ module.exports = {
640
661
  CreateTableCommand,
641
662
  ListTablesCommand,
642
663
  DescribeTableCommand,
664
+ UpdateTimeToLiveCommand,
665
+ DescribeTimeToLiveCommand,
666
+ UpdateTableCommand,
643
667
  marshall,
644
668
  unmarshall
645
- };
669
+ };
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
  };
@@ -348,13 +348,46 @@ const MutationMethods = {
348
348
  }
349
349
  }
350
350
 
351
- if (forceReindex && currentItem) {
352
- Object.keys(this.fields).forEach((fieldName) => {
353
- const currentValue = currentItem._dyData[fieldName];
354
- if (currentValue !== undefined) {
355
- indexComputationData[fieldName] = currentValue;
356
- }
357
- });
351
+ // Backfill from currentItem for GSI consistency
352
+ if (!isNew && currentItem) {
353
+ if (forceReindex) {
354
+ // forceReindex: backfill all fields from current item
355
+ Object.keys(this.fields).forEach((fieldName) => {
356
+ const currentValue = currentItem._dyData[fieldName];
357
+ if (
358
+ currentValue !== undefined &&
359
+ indexComputationData[fieldName] === undefined
360
+ ) {
361
+ indexComputationData[fieldName] = currentValue;
362
+ }
363
+ });
364
+ } else {
365
+ // Regular update: backfill GSI counterpart fields so indexes
366
+ // stay consistent when only one field of a key pair is updated
367
+ Object.entries(this.indexes).forEach(([, index]) => {
368
+ const pkField = index.pk;
369
+ const skField = index.sk;
370
+ const pkInUpdate =
371
+ pkField === "modelPrefix" ||
372
+ indexComputationData[pkField] !== undefined;
373
+ const skInUpdate =
374
+ skField === "modelPrefix" ||
375
+ indexComputationData[skField] !== undefined;
376
+
377
+ if (pkInUpdate && !skInUpdate && skField !== "modelPrefix") {
378
+ const currentValue = currentItem._dyData[skField];
379
+ if (currentValue !== undefined) {
380
+ indexComputationData[skField] = currentValue;
381
+ }
382
+ }
383
+ if (skInUpdate && !pkInUpdate && pkField !== "modelPrefix") {
384
+ const currentValue = currentItem._dyData[pkField];
385
+ if (currentValue !== undefined) {
386
+ indexComputationData[pkField] = currentValue;
387
+ }
388
+ }
389
+ });
390
+ }
358
391
  }
359
392
 
360
393
  if (isNew) {
@@ -428,12 +461,13 @@ const MutationMethods = {
428
461
  }
429
462
 
430
463
  // Add GSI keys
431
- const indexSourceData =
432
- forceReindex && Object.keys(indexComputationData).length
433
- ? indexComputationData
434
- : dyUpdatesToSave;
464
+ const indexSourceData = Object.keys(indexComputationData).length
465
+ ? indexComputationData
466
+ : dyUpdatesToSave;
435
467
 
436
- const indexKeys = this._getIndexKeys(indexSourceData);
468
+ const indexKeys = this._getIndexKeys(indexSourceData, {
469
+ isUpdate: !isNew,
470
+ });
437
471
  logger.debug("indexKeys", indexKeys);
438
472
  Object.assign(dyUpdatesToSave, indexKeys);
439
473
 
@@ -711,7 +745,7 @@ const MutationMethods = {
711
745
  };
712
746
  },
713
747
 
714
- _getIndexKeys(data) {
748
+ _getIndexKeys(data, { isUpdate = false } = {}) {
715
749
  const indexKeys = {};
716
750
 
717
751
  Object.entries(this.indexes).forEach(([indexName, index]) => {
@@ -739,6 +773,26 @@ const MutationMethods = {
739
773
  }
740
774
  }
741
775
 
776
+ // Detect partial GSI key updates that would cause index staleness
777
+ if (isUpdate && index.indexId !== undefined) {
778
+ const pkProvided =
779
+ index.pk === "modelPrefix" || pkValue !== undefined;
780
+ const skProvided =
781
+ index.sk === "modelPrefix" || skValue !== undefined;
782
+ if (pkProvided && !skProvided) {
783
+ throw new Error(
784
+ `Update includes GSI partition key "${index.pk}" for index "${indexName}" ` +
785
+ `but is missing sort key "${index.sk}". Include both fields or use forceReindex.`,
786
+ );
787
+ }
788
+ if (skProvided && !pkProvided) {
789
+ throw new Error(
790
+ `Update includes GSI sort key "${index.sk}" for index "${indexName}" ` +
791
+ `but is missing partition key "${index.pk}". Include both fields or use forceReindex.`,
792
+ );
793
+ }
794
+ }
795
+
742
796
  if (
743
797
  pkValue !== undefined &&
744
798
  skValue !== undefined &&
@@ -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,
@@ -6,6 +6,8 @@ const {
6
6
  GSI_INDEX_ID1,
7
7
  GSI_INDEX_ID2,
8
8
  GSI_INDEX_ID3,
9
+ GSI_INDEX_ID4,
10
+ GSI_INDEX_ID5,
9
11
  UNIQUE_CONSTRAINT_ID1,
10
12
  UNIQUE_CONSTRAINT_ID2,
11
13
  UNIQUE_CONSTRAINT_ID3,
@@ -98,6 +100,8 @@ const ValidationMethods = {
98
100
  GSI_INDEX_ID1,
99
101
  GSI_INDEX_ID2,
100
102
  GSI_INDEX_ID3,
103
+ GSI_INDEX_ID4,
104
+ GSI_INDEX_ID5,
101
105
  undefined,
102
106
  ]; // undefined for PK-based indexes
103
107
 
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
  }