dynamo-bao 0.8.1 → 0.9.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.
@@ -25,6 +25,16 @@ const SYSTEM_FILTERABLE_FIELDS = {
25
25
  },
26
26
  };
27
27
 
28
+ // Deep nesting is never needed in practice and would otherwise let a
29
+ // forwarded filter overflow the stack.
30
+ const MAX_FILTER_DEPTH = 16;
31
+
32
+ // Filter keys are often user input, so look fields up as own properties only;
33
+ // keys like "constructor" or "__proto__" must not resolve through prototypes.
34
+ function lookupOwn(obj, key) {
35
+ return Object.prototype.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
36
+ }
37
+
28
38
  /**
29
39
  * Supporting class for building DynamoDB filter expressions.
30
40
  * @class
@@ -42,27 +52,28 @@ class FilterExpressionBuilder {
42
52
  this.valueCount = 0;
43
53
  }
44
54
 
45
- // Generate unique name placeholder
55
+ // Placeholders use a "__" prefix: user field names can't start with "_",
56
+ // so these never collide with the "#field"/":field" update placeholders
57
+ // they get merged with in conditional writes.
46
58
  generateName(fieldName) {
47
- const key = `#n${++this.nameCount}`;
59
+ const key = `#__f${++this.nameCount}`;
48
60
  this.names[key] = fieldName;
49
61
  return key;
50
62
  }
51
63
 
52
- // Generate unique value placeholder
53
64
  generateValue(value) {
54
- const key = `:v${++this.valueCount}`;
65
+ const key = `:__f${++this.valueCount}`;
55
66
  this.values[key] = value;
56
67
  return key;
57
68
  }
58
69
 
59
70
  // Simplified value conversion - let the field handle it
60
71
  convertValue(value, model, fieldName) {
61
- const systemField = SYSTEM_FILTERABLE_FIELDS[fieldName];
72
+ const systemField = lookupOwn(SYSTEM_FILTERABLE_FIELDS, fieldName);
62
73
  if (systemField) {
63
74
  return systemField.convertValue(value, model);
64
75
  }
65
- const field = model.fields[fieldName];
76
+ const field = lookupOwn(model.fields, fieldName);
66
77
  return field.toDy(value);
67
78
  }
68
79
 
@@ -214,7 +225,7 @@ class FilterExpressionBuilder {
214
225
  expressions.push(this.buildLogicalExpression(key, value, model));
215
226
  } else if (key === "$not") {
216
227
  const innerExpr = this.buildFilterExpression(value, model);
217
- expressions.push(`NOT ${innerExpr}`);
228
+ expressions.push(`NOT (${innerExpr})`);
218
229
  } else {
219
230
  expressions.push(this.buildFieldExpression(key, value, model));
220
231
  }
@@ -235,6 +246,10 @@ class FilterExpressionBuilder {
235
246
  * - $or: [{condition1}, {condition2}] - At least one condition must match
236
247
  * - $not: {condition} - Condition must not match
237
248
  * @param {BaoModel} model - The model to build the expression for. Used to validate field names.
249
+ * @param {Object} [options]
250
+ * @param {string[]} [options.allowedFields] - When set, the filter may only reference
251
+ * these fields. Pass this whenever the filter comes from user input, so callers
252
+ * can't probe fields they shouldn't see.
238
253
  * @example
239
254
  * filterExp1 = {
240
255
  * status: 'active', // Exact match
@@ -264,9 +279,9 @@ class FilterExpressionBuilder {
264
279
  * - ExpressionAttributeNames: Map of attribute name placeholders
265
280
  * - ExpressionAttributeValues: Map of attribute value placeholders
266
281
  */
267
- build(filter, model) {
282
+ build(filter, model, options = {}) {
268
283
  // Validate field names against model
269
- this.validateFields(filter, model);
284
+ this.validateFields(filter, model, options);
270
285
 
271
286
  const filterExpression = this.buildFilterExpression(filter, model);
272
287
 
@@ -282,27 +297,41 @@ class FilterExpressionBuilder {
282
297
  }
283
298
 
284
299
  // Validate fields against model definition
285
- validateFields(filter, model) {
286
- const validateObject = (obj) => {
300
+ validateFields(filter, model, { allowedFields } = {}) {
301
+ const validateObject = (obj, depth) => {
302
+ if (depth > MAX_FILTER_DEPTH) {
303
+ throw new QueryError(
304
+ `Filter is nested more than ${MAX_FILTER_DEPTH} levels deep`,
305
+ );
306
+ }
307
+ if (!obj || typeof obj !== "object" || Array.isArray(obj)) {
308
+ throw new QueryError("Filter conditions must be objects");
309
+ }
287
310
  for (const [key, value] of Object.entries(obj)) {
288
311
  // Skip logical operators
289
312
  if (["$and", "$or", "$not"].includes(key)) {
290
- if (Array.isArray(value)) {
291
- value.forEach(validateObject);
313
+ if (key === "$not") {
314
+ validateObject(value, depth + 1);
315
+ } else if (Array.isArray(value)) {
316
+ value.forEach((condition) => validateObject(condition, depth + 1));
292
317
  } else {
293
- validateObject(value);
318
+ throw new QueryError(`${key} requires an array of conditions`);
294
319
  }
295
320
  continue;
296
321
  }
297
322
 
323
+ if (allowedFields && !allowedFields.includes(key)) {
324
+ throw new QueryError(`Field not allowed in filter: ${key}`);
325
+ }
326
+
298
327
  // Allow whitelisted system fields (e.g., _searchText) without
299
328
  // requiring a matching entry in model.fields. Operator validation
300
329
  // below still runs so bad operators are rejected the same way.
301
- const isSystemField = !!SYSTEM_FILTERABLE_FIELDS[key];
330
+ const isSystemField = !!lookupOwn(SYSTEM_FILTERABLE_FIELDS, key);
302
331
 
303
332
  if (!isSystemField) {
304
333
  // Validate field exists in model
305
- const field = model.fields[key];
334
+ const field = lookupOwn(model.fields, key);
306
335
  if (!field) {
307
336
  throw new QueryError(`Unknown field in filter: ${key}`);
308
337
  }
@@ -338,7 +367,7 @@ class FilterExpressionBuilder {
338
367
  }
339
368
  };
340
369
 
341
- validateObject(filter);
370
+ validateObject(filter, 0);
342
371
  }
343
372
  }
344
373
 
package/src/index.js CHANGED
@@ -183,9 +183,10 @@ function initModels(userConfig = {}) {
183
183
  models: userConfig.models || config.models || null,
184
184
  };
185
185
 
186
- // Validate tenant context if tenancy enabled
187
- if (finalConfig.tenancy?.enabled) {
188
- TenantContext.validateTenantRequired(finalConfig);
186
+ // The logger is created at import, before this config exists. The
187
+ // environment variable still wins, as it does at import.
188
+ if (finalConfig.logging?.level && !process.env.DYNAMO_BAO_LOG_LEVEL) {
189
+ logger.currentLevel = finalConfig.logging.level.toUpperCase();
189
190
  }
190
191
 
191
192
  const modelsDir = finalConfig.paths.modelsDir;
@@ -18,13 +18,13 @@ class KeyConditionBuilder {
18
18
  }
19
19
 
20
20
  generateName(fieldName) {
21
- const key = `#n${++this.nameCount}`;
21
+ const key = `#__k${++this.nameCount}`;
22
22
  this.names[key] = fieldName;
23
23
  return key;
24
24
  }
25
25
 
26
26
  generateValue(value) {
27
- const key = `:v${++this.valueCount}`;
27
+ const key = `:__k${++this.valueCount}`;
28
28
  this.values[key] = value;
29
29
  return key;
30
30
  }
@@ -716,14 +716,22 @@ function runWithBatchContext(fn) {
716
716
  timers: new Set(),
717
717
  startTime: Date.now(),
718
718
  capacityAccumulator: { read: 0, write: 0 }, // Track total capacity consumed
719
+ // A tenant set with setCurrentTenant() inside a batch context lives here,
720
+ // scoped to the request. Nested contexts inherit it.
721
+ tenantId: batchContext.getStore()?.tenantId ?? null,
719
722
  };
720
723
 
721
724
  return batchContext.run(context, fn);
722
725
  }
723
726
 
727
+ function getBatchContextStore() {
728
+ return batchContext?.getStore() ?? null;
729
+ }
730
+
724
731
  module.exports = {
725
732
  BatchLoadingMethods,
726
733
  runWithBatchContext,
734
+ getBatchContextStore,
727
735
  getBatchContextCapacity,
728
736
  _accumulateCapacityToContext,
729
737
  BATCH_REQUEST_TIMEOUT,
@@ -8,6 +8,7 @@ const {
8
8
  const { defaultLogger: logger } = require("../utils/logger");
9
9
  const { pluginManager } = require("../plugin-manager");
10
10
  const { retryOperation } = require("../utils/retry-helper");
11
+ const { ulid } = require("ulid");
11
12
  const assert = require("assert");
12
13
  const { FilterExpressionBuilder } = require("../filter-expression");
13
14
  const {
@@ -16,7 +17,7 @@ const {
16
17
  ValidationError,
17
18
  } = require("../exceptions");
18
19
  const { computeSearchTextUpdate } = require("../utils/search-text");
19
- const { SEARCH_TEXT_FIELD } = require("../constants");
20
+ const { SEARCH_TEXT_FIELD, GID_SEPARATOR } = require("../constants");
20
21
 
21
22
  /**
22
23
  * AND a guard onto an optional ConditionExpression. The existing expression
@@ -222,10 +223,14 @@ const MutationMethods = {
222
223
  }
223
224
  }
224
225
 
226
+ // The token makes a retry after a lost response a no-op instead of
227
+ // applying the transaction twice.
228
+ const clientRequestToken = ulid();
225
229
  response = await retryOperation(() =>
226
230
  this.documentClient.send(
227
231
  new TransactWriteCommand({
228
232
  TransactItems: transactItems,
233
+ ClientRequestToken: clientRequestToken,
229
234
  ReturnConsumedCapacity: "TOTAL",
230
235
  }),
231
236
  ),
@@ -294,7 +299,7 @@ const MutationMethods = {
294
299
  ) {
295
300
  if (
296
301
  !item &&
297
- !(await this._existsAfterGuardFailure(primaryId, options))
302
+ !(await this._existsAfterGuardFailure(primaryId, options, error))
298
303
  ) {
299
304
  throw new ItemNotFoundError("Item not found", primaryId);
300
305
  }
@@ -324,7 +329,7 @@ const MutationMethods = {
324
329
  /**
325
330
  * AND an `attribute_exists(_pk)` guard into a write's ConditionExpression.
326
331
  * Uses a "#__" placeholder so it can't clobber a field placeholder (user
327
- * field names can't start with "_"; filter placeholders are "#nN").
332
+ * field names can't start with "_"; filter placeholders are "#__fN").
328
333
  * @private
329
334
  */
330
335
  _addExistsGuard(params) {
@@ -336,18 +341,26 @@ const MutationMethods = {
336
341
  params.ConditionExpression,
337
342
  "attribute_exists(#__existsPk)",
338
343
  );
344
+ // Ask DynamoDB to return the row the condition was evaluated against,
345
+ // so a failed check can be attributed without a follow-up read (see
346
+ // _existsAfterGuardFailure).
347
+ params.ReturnValuesOnConditionCheckFailure = "ALL_OLD";
339
348
  },
340
349
 
341
350
  /**
342
351
  * After a guarded write fails its condition check, decide whether the row
343
- * exists. With no caller condition the guard is the only thing that could
344
- * have failed, so no read is needed; otherwise one GetItem (cache
345
- * bypassed) tells a missing row apart from an unmet condition. Only the
346
- * failure path pays for this read.
352
+ * existed when the condition was evaluated. With no caller condition the
353
+ * guard is the only thing that could have failed, so the row was missing.
354
+ * Otherwise the error's `Item` (from ReturnValuesOnConditionCheckFailure)
355
+ * is exact: present means the caller's condition failed, null means the
356
+ * row did not exist. A read after the fact is only a fallback for clients
357
+ * that do not surface `Item`; it can be wrong when another writer creates
358
+ * the row between the failed write and the read.
347
359
  * @private
348
360
  */
349
- async _existsAfterGuardFailure(primaryId, options) {
361
+ async _existsAfterGuardFailure(primaryId, options, error) {
350
362
  if (!options.condition) return false;
363
+ if (error && error.Item !== undefined) return error.Item !== null;
351
364
  const existing = await this.find(primaryId, {
352
365
  batchDelay: 0,
353
366
  bypassCache: true,
@@ -478,11 +491,48 @@ const MutationMethods = {
478
491
  return { relocated: true, from: sourceKey._pk, to: canonicalKey._pk };
479
492
  },
480
493
 
494
+ /**
495
+ * An update can't move a row to a different key, so reject a change to any
496
+ * field the primary key is built from. Re-sending the current value is fine.
497
+ * @private
498
+ */
499
+ _assertPrimaryKeyUnchanged(primaryId, jsUpdates) {
500
+ const current = this._parsePrimaryId(primaryId);
501
+ for (const [part, fieldName] of [
502
+ ["pk", this.primaryKey.pk],
503
+ ["sk", this.primaryKey.sk],
504
+ ]) {
505
+ if (
506
+ !fieldName ||
507
+ fieldName === "modelPrefix" ||
508
+ jsUpdates[fieldName] === undefined
509
+ ) {
510
+ continue;
511
+ }
512
+ const field = this._getField(fieldName);
513
+ if (String(field.toGsi(jsUpdates[fieldName])) !== String(current[part])) {
514
+ throw new ValidationError(
515
+ `Cannot change primary key field ${fieldName} on update`,
516
+ );
517
+ }
518
+ }
519
+ },
520
+
481
521
  _createNewPrimaryId(jsUpdates) {
482
522
  // Now calculate primary key values using the processed data
483
523
  const pkValue = this._getPkValue(jsUpdates);
484
524
  const skValue = this._getSkValue(jsUpdates);
485
525
 
526
+ // The primary id joins pk and sk with GID_SEPARATOR, so a key value that
527
+ // contains it would parse back to a different record's key.
528
+ for (const value of [pkValue, skValue]) {
529
+ if (typeof value === "string" && value.includes(GID_SEPARATOR)) {
530
+ throw new ValidationError(
531
+ `Primary key values cannot contain "${GID_SEPARATOR}"`,
532
+ );
533
+ }
534
+ }
535
+
486
536
  // Format the primary key
487
537
  const pk = this._formatPrimaryKey(this.modelPrefix, pkValue);
488
538
  const primaryId = this.getPrimaryId({
@@ -527,8 +577,16 @@ const MutationMethods = {
527
577
 
528
578
  logger.debug("jsUpdates", jsUpdates);
529
579
 
580
+ if (!isNew) {
581
+ this._assertPrimaryKeyUnchanged(primaryId, jsUpdates);
582
+ }
583
+
530
584
  // Generate Dynamo Updates to save
531
585
  for (const [key, field] of Object.entries(this.fields)) {
586
+ if (field.serverGenerated || (!isNew && field.immutable)) {
587
+ delete jsUpdates[key];
588
+ }
589
+
532
590
  if (isNew && jsUpdates[key] === undefined) {
533
591
  // Only set initial values during creation
534
592
  const initialValue = field.getInitialValue();
@@ -581,7 +639,10 @@ const MutationMethods = {
581
639
  // the loaded value plus the delta, guarded on the loaded value, so a
582
640
  // concurrent change fails the update (ConditionalError) instead of
583
641
  // leaving the index key stale. Other counters keep the atomic ADD.
584
- const counterGuards = [];
642
+ // Fields whose stored value must still equal the loaded value for the
643
+ // write to apply. Filled for index-key counters here and for unchanged
644
+ // unique values below.
645
+ const loadedValueGuards = [];
585
646
  const { CounterFieldClass } = require("../fields");
586
647
  for (const [key, field] of Object.entries(this.fields)) {
587
648
  const dyValue = dyUpdatesToSave[key];
@@ -604,7 +665,7 @@ const MutationMethods = {
604
665
  ) {
605
666
  const loadedValue = currentItem._loadedDyData[key];
606
667
  value = Number(loadedValue ?? 0) + delta;
607
- counterGuards.push({ fieldName: key, loadedValue });
668
+ loadedValueGuards.push({ fieldName: key, loadedValue });
608
669
  } else {
609
670
  continue;
610
671
  }
@@ -720,6 +781,15 @@ const MutationMethods = {
720
781
  ),
721
782
  );
722
783
  }
784
+ } else if (dyNewValue !== undefined && currentItem) {
785
+ // Re-sending the unchanged value writes no constraint rows, so guard
786
+ // the update on the stored value: if a concurrent update moved this
787
+ // record off the value (releasing its constraint), this write must
788
+ // not set it back without owning the constraint.
789
+ loadedValueGuards.push({
790
+ fieldName,
791
+ loadedValue: dyCurrentValue,
792
+ });
723
793
  }
724
794
  }
725
795
 
@@ -862,9 +932,9 @@ const MutationMethods = {
862
932
  );
863
933
  }
864
934
 
865
- for (const { fieldName, loadedValue } of counterGuards) {
866
- const name = `#__counterGuard_${fieldName}`;
867
- const value = `:__counterGuard_${fieldName}`;
935
+ for (const { fieldName, loadedValue } of loadedValueGuards) {
936
+ const name = `#__loadedGuard_${fieldName}`;
937
+ const value = `:__loadedGuard_${fieldName}`;
868
938
  updateParams.ExpressionAttributeNames = {
869
939
  ...updateParams.ExpressionAttributeNames,
870
940
  [name]: fieldName,
@@ -899,10 +969,14 @@ const MutationMethods = {
899
969
  logger.debug("transactItems", JSON.stringify(transactItems, null, 2));
900
970
  }
901
971
 
972
+ // The token makes a retry after a lost response a no-op instead of
973
+ // applying the transaction twice.
974
+ const clientRequestToken = ulid();
902
975
  response = await retryOperation(() =>
903
976
  this.documentClient.send(
904
977
  new TransactWriteCommand({
905
978
  TransactItems: transactItems,
979
+ ClientRequestToken: clientRequestToken,
906
980
  ReturnConsumedCapacity: "TOTAL",
907
981
  }),
908
982
  ),
@@ -972,14 +1046,18 @@ const MutationMethods = {
972
1046
  logger.debug("updateParams", JSON.stringify(updateParams, null, 2));
973
1047
  }
974
1048
 
975
- response = await retryOperation(() =>
1049
+ // ADD isn't idempotent: if a request times out after DynamoDB applied
1050
+ // it, a retry would apply it again. Only retry pure SET/REMOVE writes.
1051
+ const sendUpdate = () =>
976
1052
  this.documentClient.send(
977
1053
  new UpdateCommand({
978
1054
  ...updateParams,
979
1055
  ReturnConsumedCapacity: "TOTAL",
980
1056
  }),
981
- ),
982
- );
1057
+ );
1058
+ response = hasAtomicOps
1059
+ ? await sendUpdate()
1060
+ : await retryOperation(sendUpdate);
983
1061
 
984
1062
  const savedItem = this._createFromDyItem(response.Attributes);
985
1063
  logger.debug("savedItem", savedItem);
@@ -1020,7 +1098,7 @@ const MutationMethods = {
1020
1098
  if (error.name === "ConditionalCheckFailedException") {
1021
1099
  if (
1022
1100
  existsGuard &&
1023
- !(await this._existsAfterGuardFailure(primaryId, options))
1101
+ !(await this._existsAfterGuardFailure(primaryId, options, error))
1024
1102
  ) {
1025
1103
  throw new ItemNotFoundError("Item not found", primaryId);
1026
1104
  }
@@ -102,6 +102,7 @@ const QueryMethods = {
102
102
  * @param {Object} options.startKey - Exclusive start key for pagination
103
103
  * @param {boolean} options.countOnly - If true, returns only the count of matching items
104
104
  * @param {Object} options.filter - Additional filter conditions for the query. For full filter syntax, see {@link FilterExpressionBuilder#build}
105
+ * @param {string[]} options.allowedFilterFields - Fields `filter` may reference. Set this when the filter comes from user input.
105
106
  * @param {boolean} options.returnWrapped - If false, returns raw DynamoDB items instead of model instances
106
107
  * @param {boolean} options.loadRelated - If true, loads related models for RelatedFields
107
108
  * @param {string[]} options.relatedFields - Array of field names to load related data for (used with loadRelated)
@@ -268,7 +269,9 @@ const QueryMethods = {
268
269
  // Add filter expression if provided
269
270
  if (options.filter) {
270
271
  const filterBuilder = new FilterExpressionBuilder();
271
- const filterExpression = filterBuilder.build(options.filter, this);
272
+ const filterExpression = filterBuilder.build(options.filter, this, {
273
+ allowedFields: options.allowedFilterFields,
274
+ });
272
275
 
273
276
  if (filterExpression) {
274
277
  params.FilterExpression = filterExpression.FilterExpression;
@@ -63,7 +63,7 @@ const UniqueConstraintMethods = {
63
63
  if (innerError instanceof ConditionalError) {
64
64
  throw innerError;
65
65
  }
66
- console.error("Error checking unique constraint:", innerError);
66
+ logger.error("Error checking unique constraint:", innerError);
67
67
  throw new ConditionalError(
68
68
  `Failed to validate ${constraint.field} uniqueness`,
69
69
  "unique_constraint",
@@ -5,6 +5,9 @@ const { ConfigurationError } = require("./exceptions");
5
5
 
6
6
  class ModelManager {
7
7
  static _instances = new Map();
8
+ // The most recently initialized manager. Runtime tenants borrow its models,
9
+ // client and config through forTenant().
10
+ static _primary = null;
8
11
 
9
12
  constructor(config = {}) {
10
13
  this._initialized = false;
@@ -26,11 +29,36 @@ class ModelManager {
26
29
  return ModelManager._instances.get(key);
27
30
  }
28
31
 
29
- async init(config = {}) {
30
- // Validate tenant requirement
31
- const { TenantContext } = require("./tenant-context");
32
- TenantContext.validateTenantRequired(config);
32
+ /**
33
+ * Returns the manager to use for a tenant at request time. A manager that
34
+ * was explicitly initialized for this tenant wins; otherwise this returns a
35
+ * lightweight view of the primary manager with the tenant id swapped in.
36
+ * Views are not cached, so arbitrary tenant ids don't grow memory.
37
+ */
38
+ static forTenant(tenantId) {
39
+ // Keys are built as "[tenant]#prefix#value", so a tenant id containing
40
+ // "]" or "#" could produce another tenant's keys.
41
+ if (
42
+ tenantId != null &&
43
+ (typeof tenantId !== "string" || /[\]#]/.test(tenantId))
44
+ ) {
45
+ throw new ConfigurationError(
46
+ `Invalid tenant id ${JSON.stringify(tenantId)}: must be a string without "]" or "#"`,
47
+ );
48
+ }
49
+ const existing = ModelManager._instances.get(tenantId || "default");
50
+ if (existing) {
51
+ return existing;
52
+ }
53
+ if (!ModelManager._primary) {
54
+ return ModelManager.getInstance(tenantId);
55
+ }
56
+ const view = Object.create(ModelManager._primary);
57
+ view._tenantId = tenantId;
58
+ return view;
59
+ }
33
60
 
61
+ async init(config = {}) {
34
62
  // Store config for models to access
35
63
  this._config = config;
36
64
 
@@ -55,6 +83,7 @@ class ModelManager {
55
83
  }
56
84
 
57
85
  this._initialized = true;
86
+ ModelManager._primary = this;
58
87
  return this;
59
88
  }
60
89