dynamo-bao 0.8.2 → 0.10.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/src/exceptions.js CHANGED
@@ -86,6 +86,22 @@ class DataFormatError extends BaoError {
86
86
  }
87
87
  }
88
88
 
89
+ /**
90
+ * Thrown by a persistence method called on an instance hydrated with
91
+ * `Model.fromRemote()`. Such an instance is a read-only view of a row a
92
+ * remote procedure returned; writes and related loads belong in a procedure.
93
+ */
94
+ class DetachedInstanceError extends BaoError {
95
+ constructor(modelName, method) {
96
+ super(
97
+ `${modelName}.${method}() was called on a detached instance (hydrated with fromRemote). ` +
98
+ "Detached rows are read-only; do the write or load in a procedure and call it with remote(...).call().",
99
+ );
100
+ this.modelName = modelName;
101
+ this.method = method;
102
+ }
103
+ }
104
+
89
105
  module.exports = {
90
106
  BaoError,
91
107
  ConfigurationError,
@@ -94,4 +110,5 @@ module.exports = {
94
110
  ItemNotFoundError,
95
111
  ConditionalError,
96
112
  DataFormatError,
113
+ DetachedInstanceError,
97
114
  };
package/src/fields.js CHANGED
@@ -155,10 +155,27 @@ class BaoBaseField {
155
155
  * A field that stores a string value.
156
156
  */
157
157
  class StringField extends BaoBaseField {
158
+ constructor(options = {}) {
159
+ super(options);
160
+ this.maxLength = options.maxLength;
161
+ }
162
+
158
163
  validate(value) {
159
164
  if (this.required && !value) {
160
165
  throw new ValidationError("Field is required", null, value);
161
166
  }
167
+ if (
168
+ value !== null &&
169
+ value !== undefined &&
170
+ typeof value !== "string" &&
171
+ typeof value !== "number"
172
+ ) {
173
+ throw new ValidationError(
174
+ "StringField value must be a string",
175
+ null,
176
+ value,
177
+ );
178
+ }
162
179
  if (value && this.maxLength && value.length > this.maxLength) {
163
180
  throw new ValidationError(
164
181
  `Value exceeds maximum length of ${this.maxLength}`,
@@ -195,6 +212,9 @@ class DateTimeField extends BaoBaseField {
195
212
  value,
196
213
  );
197
214
  }
215
+ if (value !== undefined && value !== null && isNaN(this.toDy(value))) {
216
+ throw new ValidationError("Invalid date value", null, value);
217
+ }
198
218
  }
199
219
 
200
220
  toDy(value) {
@@ -250,6 +270,21 @@ class DateTimeField extends BaoBaseField {
250
270
  * A field that stores an integer value.
251
271
  */
252
272
  class IntegerField extends BaoBaseField {
273
+ validate(value) {
274
+ super.validate(value);
275
+ if (value !== undefined && value !== null) {
276
+ const num = Number(value);
277
+ if (typeof value === "boolean" || !Number.isInteger(num)) {
278
+ throw new ValidationError(
279
+ "IntegerField value must be an integer",
280
+ null,
281
+ value,
282
+ );
283
+ }
284
+ }
285
+ return true;
286
+ }
287
+
253
288
  getInitialValue() {
254
289
  return this.options.defaultValue !== undefined
255
290
  ? this.options.defaultValue
@@ -283,6 +318,20 @@ class IntegerField extends BaoBaseField {
283
318
  * A field that stores a floating point number value.
284
319
  */
285
320
  class FloatField extends BaoBaseField {
321
+ validate(value) {
322
+ super.validate(value);
323
+ if (value !== undefined && value !== null) {
324
+ if (typeof value === "boolean" || !Number.isFinite(Number(value))) {
325
+ throw new ValidationError(
326
+ "FloatField value must be a number",
327
+ null,
328
+ value,
329
+ );
330
+ }
331
+ }
332
+ return true;
333
+ }
334
+
286
335
  getInitialValue() {
287
336
  return this.options.defaultValue !== undefined
288
337
  ? this.options.defaultValue
@@ -325,6 +374,8 @@ class CreateDateField extends DateTimeField {
325
374
  ...options,
326
375
  required: true,
327
376
  });
377
+ // Set once on create; updates leave the stored value alone.
378
+ this.immutable = true;
328
379
  }
329
380
 
330
381
  getInitialValue() {
@@ -335,7 +386,7 @@ class CreateDateField extends DateTimeField {
335
386
  if (!value) {
336
387
  return Date.now();
337
388
  }
338
- return value instanceof Date ? value.getTime() : value;
389
+ return super.toDy(value);
339
390
  }
340
391
  }
341
392
 
@@ -643,6 +694,9 @@ class VersionField extends BaoBaseField {
643
694
  required: true,
644
695
  });
645
696
  this.defaultValue = options.defaultValue || ulid;
697
+ // Every save gets a fresh version; a caller-supplied value is ignored,
698
+ // so it can't be rolled back to defeat optimistic locking.
699
+ this.serverGenerated = true;
646
700
  }
647
701
 
648
702
  validate(value) {
@@ -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
  ),
@@ -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) {
@@ -486,11 +491,48 @@ const MutationMethods = {
486
491
  return { relocated: true, from: sourceKey._pk, to: canonicalKey._pk };
487
492
  },
488
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
+
489
521
  _createNewPrimaryId(jsUpdates) {
490
522
  // Now calculate primary key values using the processed data
491
523
  const pkValue = this._getPkValue(jsUpdates);
492
524
  const skValue = this._getSkValue(jsUpdates);
493
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
+
494
536
  // Format the primary key
495
537
  const pk = this._formatPrimaryKey(this.modelPrefix, pkValue);
496
538
  const primaryId = this.getPrimaryId({
@@ -535,8 +577,16 @@ const MutationMethods = {
535
577
 
536
578
  logger.debug("jsUpdates", jsUpdates);
537
579
 
580
+ if (!isNew) {
581
+ this._assertPrimaryKeyUnchanged(primaryId, jsUpdates);
582
+ }
583
+
538
584
  // Generate Dynamo Updates to save
539
585
  for (const [key, field] of Object.entries(this.fields)) {
586
+ if (field.serverGenerated || (!isNew && field.immutable)) {
587
+ delete jsUpdates[key];
588
+ }
589
+
540
590
  if (isNew && jsUpdates[key] === undefined) {
541
591
  // Only set initial values during creation
542
592
  const initialValue = field.getInitialValue();
@@ -589,7 +639,10 @@ const MutationMethods = {
589
639
  // the loaded value plus the delta, guarded on the loaded value, so a
590
640
  // concurrent change fails the update (ConditionalError) instead of
591
641
  // leaving the index key stale. Other counters keep the atomic ADD.
592
- 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 = [];
593
646
  const { CounterFieldClass } = require("../fields");
594
647
  for (const [key, field] of Object.entries(this.fields)) {
595
648
  const dyValue = dyUpdatesToSave[key];
@@ -612,7 +665,7 @@ const MutationMethods = {
612
665
  ) {
613
666
  const loadedValue = currentItem._loadedDyData[key];
614
667
  value = Number(loadedValue ?? 0) + delta;
615
- counterGuards.push({ fieldName: key, loadedValue });
668
+ loadedValueGuards.push({ fieldName: key, loadedValue });
616
669
  } else {
617
670
  continue;
618
671
  }
@@ -728,6 +781,15 @@ const MutationMethods = {
728
781
  ),
729
782
  );
730
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
+ });
731
793
  }
732
794
  }
733
795
 
@@ -870,9 +932,9 @@ const MutationMethods = {
870
932
  );
871
933
  }
872
934
 
873
- for (const { fieldName, loadedValue } of counterGuards) {
874
- const name = `#__counterGuard_${fieldName}`;
875
- const value = `:__counterGuard_${fieldName}`;
935
+ for (const { fieldName, loadedValue } of loadedValueGuards) {
936
+ const name = `#__loadedGuard_${fieldName}`;
937
+ const value = `:__loadedGuard_${fieldName}`;
876
938
  updateParams.ExpressionAttributeNames = {
877
939
  ...updateParams.ExpressionAttributeNames,
878
940
  [name]: fieldName,
@@ -907,10 +969,14 @@ const MutationMethods = {
907
969
  logger.debug("transactItems", JSON.stringify(transactItems, null, 2));
908
970
  }
909
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();
910
975
  response = await retryOperation(() =>
911
976
  this.documentClient.send(
912
977
  new TransactWriteCommand({
913
978
  TransactItems: transactItems,
979
+ ClientRequestToken: clientRequestToken,
914
980
  ReturnConsumedCapacity: "TOTAL",
915
981
  }),
916
982
  ),
@@ -980,14 +1046,18 @@ const MutationMethods = {
980
1046
  logger.debug("updateParams", JSON.stringify(updateParams, null, 2));
981
1047
  }
982
1048
 
983
- 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 = () =>
984
1052
  this.documentClient.send(
985
1053
  new UpdateCommand({
986
1054
  ...updateParams,
987
1055
  ReturnConsumedCapacity: "TOTAL",
988
1056
  }),
989
- ),
990
- );
1057
+ );
1058
+ response = hasAtomicOps
1059
+ ? await sendUpdate()
1060
+ : await retryOperation(sendUpdate);
991
1061
 
992
1062
  const savedItem = this._createFromDyItem(response.Attributes);
993
1063
  logger.debug("savedItem", savedItem);
@@ -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