dynamo-bao 0.2.1 → 0.2.2

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
@@ -20,8 +20,14 @@ DynamoBao is the tool I wish I had when I started.
20
20
  - Efficiently load data: load related objects in parallel, cache data using loading contexts
21
21
  - Minimize race conditions: save diffs, version checks on save, atomic counters
22
22
  - Enforce unique constraints and use them for lookups
23
+ - Built-in multi-tenancy support with complete data isolation and concurrency safety
23
24
  - Return total read/write consumed capacity (even when multiple operations were performed)
24
25
 
26
+ ## Requirements
27
+
28
+ - **Node.js 12.17.0+** (for AsyncLocalStorage support in multi-tenant features)
29
+ - AWS credentials configured for DynamoDB access
30
+
25
31
  ## Example 1: Simple model
26
32
 
27
33
  Step 1 is to define your models in a yaml file. Here's a simple example.
@@ -73,6 +73,9 @@ const config = {
73
73
  modelsDefinitionPath: path.resolve(__dirname, "./models.yaml"),
74
74
  fieldsDir: path.resolve(__dirname, "./fields"), // optional for custom fields
75
75
  },
76
+ tenancy: {
77
+ enabled: false, // Set to true to enable multi-tenancy
78
+ },
76
79
  };
77
80
 
78
81
  module.exports = config;
@@ -103,7 +106,8 @@ async function createTable() {
103
106
  { AttributeName: "_gsi2_sk", AttributeType: "S" },
104
107
  { AttributeName: "_gsi3_pk", AttributeType: "S" },
105
108
  { AttributeName: "_gsi3_sk", AttributeType: "S" },
106
- { AttributeName: "_gsi_test_id", AttributeType: "S" },
109
+ { AttributeName: "_iter_pk", AttributeType: "S" },
110
+ { AttributeName: "_iter_sk", AttributeType: "S" },
107
111
  ],
108
112
  KeySchema: [
109
113
  { AttributeName: "_pk", KeyType: "HASH" },
@@ -135,9 +139,12 @@ async function createTable() {
135
139
  Projection: { ProjectionType: "ALL" },
136
140
  },
137
141
  {
138
- IndexName: "gsi_test",
139
- KeySchema: [{ AttributeName: "_gsi_test_id", KeyType: "HASH" }],
140
- Projection: { ProjectionType: "ALL" },
142
+ IndexName: "iter_index",
143
+ KeySchema: [
144
+ { AttributeName: "_iter_pk", KeyType: "HASH" },
145
+ { AttributeName: "_iter_sk", KeyType: "RANGE" },
146
+ ],
147
+ Projection: { ProjectionType: "KEYS_ONLY" },
141
148
  },
142
149
  ],
143
150
  TimeToLiveSpecification: {
@@ -110,6 +110,10 @@ function generateModelClass(
110
110
  .join("\n")
111
111
  : "";
112
112
 
113
+ // Handle iteration configuration
114
+ const iterable = modelConfig.iterable === true;
115
+ const iterationBuckets = modelConfig.iterationBuckets || 100;
116
+
113
117
  // Always need these
114
118
  baseImports.add("PrimaryKeyConfig");
115
119
  if (indexes) baseImports.add("IndexConfig");
@@ -186,6 +190,8 @@ ${Array.from(relatedModels)
186
190
 
187
191
  class ${modelName} extends BaoModel {
188
192
  static modelPrefix = '${modelConfig.modelPrefix}';
193
+ static iterable = ${iterable};
194
+ static iterationBuckets = ${iterationBuckets};
189
195
 
190
196
  static fields = {
191
197
  ${fields}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dynamo-bao",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "description": "Simple powerful data modeling primitives for DynamoDB in JavaScript.",
5
5
  "main": "src/index.js",
6
6
  "scripts": {
package/src/config.js CHANGED
@@ -54,6 +54,9 @@ function findConfig() {
54
54
  ? path.resolve(process.cwd(), process.env.MODELS_DIR)
55
55
  : null,
56
56
  },
57
+ tenancy: {
58
+ enabled: process.env.DYNAMO_BAO_TENANCY_ENABLED === "true" || false,
59
+ },
57
60
  };
58
61
  }
59
62
 
@@ -72,6 +75,15 @@ function normalizeConfig(rawConfig, configDir) {
72
75
  ? path.resolve(configDir, rawConfig.paths.fieldsDir)
73
76
  : null,
74
77
  },
78
+ logging: {
79
+ ...rawConfig.logging,
80
+ // Allow environment variable to override config file
81
+ level: process.env.LOG_LEVEL || rawConfig.logging?.level || "ERROR",
82
+ },
83
+ tenancy: {
84
+ enabled: false,
85
+ ...rawConfig.tenancy,
86
+ },
75
87
  };
76
88
  }
77
89
 
package/src/constants.js CHANGED
@@ -3,6 +3,11 @@ const GSI_INDEX_ID1 = "gsi1";
3
3
  const GSI_INDEX_ID2 = "gsi2";
4
4
  const GSI_INDEX_ID3 = "gsi3";
5
5
 
6
+ // Constants for iteration index
7
+ const ITERATION_INDEX_NAME = "iter_index";
8
+ const ITERATION_PK_FIELD = "_iter_pk";
9
+ const ITERATION_SK_FIELD = "_iter_sk";
10
+
6
11
  // Constants for unique constraints
7
12
  const UNIQUE_CONSTRAINT_ID1 = "_uc1";
8
13
  const UNIQUE_CONSTRAINT_ID2 = "_uc2";
@@ -18,7 +23,8 @@ const SYSTEM_FIELDS = [
18
23
  "_gsi2_sk",
19
24
  "_gsi3_pk",
20
25
  "_gsi3_sk",
21
- "_gsi_test_id",
26
+ "_iter_pk",
27
+ "_iter_sk",
22
28
  ];
23
29
 
24
30
  const UNIQUE_CONSTRAINT_KEY = "_raft_uc";
@@ -27,6 +33,9 @@ module.exports = {
27
33
  GSI_INDEX_ID1,
28
34
  GSI_INDEX_ID2,
29
35
  GSI_INDEX_ID3,
36
+ ITERATION_INDEX_NAME,
37
+ ITERATION_PK_FIELD,
38
+ ITERATION_SK_FIELD,
30
39
  UNIQUE_CONSTRAINT_ID1,
31
40
  UNIQUE_CONSTRAINT_ID2,
32
41
  UNIQUE_CONSTRAINT_ID3,
package/src/index.js CHANGED
@@ -76,12 +76,24 @@ function initModels(userConfig = {}) {
76
76
  ...config.paths,
77
77
  ...(userConfig.paths || {}),
78
78
  },
79
+ tenancy: {
80
+ ...config.tenancy,
81
+ ...(userConfig.tenancy || {}),
82
+ },
79
83
  };
80
84
 
85
+ // Validate tenant context if tenancy enabled
86
+ if (finalConfig.tenancy?.enabled) {
87
+ const { TenantContext } = require('./tenant-context');
88
+ TenantContext.validateTenantRequired(finalConfig);
89
+ }
90
+
81
91
  const modelsDir = finalConfig.paths.modelsDir;
82
92
 
83
- // Get/create manager instance with testId
84
- const manager = ModelManager.getInstance(finalConfig.testId);
93
+ // Get/create manager instance with tenantId
94
+ const { TenantContext } = require('./tenant-context');
95
+ const tenantId = TenantContext.getCurrentTenant() || finalConfig.testId;
96
+ const manager = ModelManager.getInstance(tenantId);
85
97
 
86
98
  // First pass to register models
87
99
  const registeredModels = _registerModels(manager, modelsDir);
@@ -91,6 +103,7 @@ function initModels(userConfig = {}) {
91
103
 
92
104
  logger.log("Models initialized:", {
93
105
  testId: finalConfig.testId,
106
+ tenantId: manager.getTenantId(),
94
107
  managerTestId: manager.getTestId(),
95
108
  registeredModels: Array.from(manager._models.keys()),
96
109
  });
@@ -100,6 +113,8 @@ function initModels(userConfig = {}) {
100
113
  return manager;
101
114
  }
102
115
 
116
+ const { TenantContext } = require('./tenant-context');
117
+
103
118
  const firstExport = {
104
119
  // Initialize function
105
120
  initModels,
@@ -109,6 +124,9 @@ const firstExport = {
109
124
  ModelManager,
110
125
  fields,
111
126
 
127
+ // Tenant management
128
+ TenantContext,
129
+
112
130
  // Configurations
113
131
  PrimaryKeyConfig,
114
132
  IndexConfig,
@@ -406,20 +406,17 @@ const MutationMethods = {
406
406
  }
407
407
  }
408
408
 
409
- // Add testId if we're in test mode
410
- const testId = this.manager.getTestId();
411
- if (testId) {
412
- logger.debug("savedTestId", testId, currentItem);
413
- if (testId !== currentItem?._loadedDyData._gsi_test_id) {
414
- dyUpdatesToSave._gsi_test_id = testId;
415
- }
416
- }
417
-
418
409
  // Add GSI keys
419
410
  const indexKeys = this._getIndexKeys(dyUpdatesToSave);
420
411
  logger.debug("indexKeys", indexKeys);
421
412
  Object.assign(dyUpdatesToSave, indexKeys);
422
413
 
414
+ // Add iteration keys if model is iterable
415
+ if (this.iterable) {
416
+ const iterationKeys = this._getIterationKeys(primaryId, dyUpdatesToSave);
417
+ Object.assign(dyUpdatesToSave, iterationKeys);
418
+ }
419
+
423
420
  // Build the update expression first
424
421
  const { updateExpression, names, values } =
425
422
  this._buildUpdateExpression(dyUpdatesToSave);
@@ -143,6 +143,33 @@ const ValidationMethods = {
143
143
  const idxSkField = this._getField(index.sk);
144
144
  });
145
145
 
146
+ // Validate iteration configuration
147
+ if (this.hasOwnProperty('iterable')) {
148
+ if (typeof this.iterable !== 'boolean') {
149
+ throw new ConfigurationError(
150
+ `iterable must be a boolean in ${this.name}`,
151
+ this.name
152
+ );
153
+ }
154
+
155
+ if (this.iterable) {
156
+ if (!this.hasOwnProperty('iterationBuckets')) {
157
+ this.iterationBuckets = 100; // Set default
158
+ } else {
159
+ if (!Number.isInteger(this.iterationBuckets) ||
160
+ this.iterationBuckets < 1 ||
161
+ this.iterationBuckets > 1000) {
162
+ throw new ConfigurationError(
163
+ `iterationBuckets must be an integer between 1 and 1000 in ${this.name}`,
164
+ this.name
165
+ );
166
+ }
167
+ }
168
+ }
169
+ } else {
170
+ this.iterable = false;
171
+ }
172
+
146
173
  // Validate unique constraints
147
174
  const validConstraintIds = [
148
175
  UNIQUE_CONSTRAINT_ID1,
@@ -10,31 +10,40 @@ class ModelManager {
10
10
  this._initialized = false;
11
11
  this._docClient = null;
12
12
  this._tableName = null;
13
- this._testId = null;
13
+ this._tenantId = null; // Changed from _testId
14
+ this._tenancyEnabled = false;
14
15
  this._models = new Map();
15
16
  }
16
17
 
17
- static getInstance(testId = null) {
18
- const key = testId || "default";
18
+ static getInstance(tenantId = null) {
19
+ const key = tenantId || "default";
19
20
  if (!ModelManager._instances.has(key)) {
20
21
  const instance = new ModelManager();
21
- instance._testId = testId;
22
+ instance._tenantId = tenantId;
22
23
  ModelManager._instances.set(key, instance);
23
24
  }
24
25
  return ModelManager._instances.get(key);
25
26
  }
26
27
 
27
28
  init(config = {}) {
29
+ // Validate tenant requirement
30
+ const { TenantContext } = require('./tenant-context');
31
+ TenantContext.validateTenantRequired(config);
32
+
28
33
  const client = new DynamoDBClient({
29
34
  region: config.aws.region,
30
35
  });
31
36
  this._docClient = DynamoDBDocumentClient.from(client);
32
37
  this._tableName = config.db.tableName;
33
- this._testId = config.testId || this._testId;
38
+ this._tenancyEnabled = config.tenancy?.enabled || false;
39
+
40
+ // Support both tenantId and testId for backward compatibility
41
+ this._tenantId = config.tenantId || config.testId || this._tenantId;
34
42
 
35
43
  // Initialize all registered models
36
44
  for (const [_, ModelClass] of this._models) {
37
- ModelClass._testId = this._testId;
45
+ ModelClass._tenantId = this._tenantId;
46
+ ModelClass._testId = this._tenantId; // Backward compatibility
38
47
  ModelClass.documentClient = this._docClient;
39
48
  ModelClass.table = this._tableName;
40
49
  ModelClass._validateConfiguration();
@@ -74,7 +83,8 @@ class ModelManager {
74
83
  };
75
84
 
76
85
  // Initialize as before
77
- ModelClass._testId = this._testId;
86
+ ModelClass._tenantId = this._tenantId;
87
+ ModelClass._testId = this._tenantId; // Backward compatibility
78
88
  if (this._initialized) {
79
89
  ModelClass.documentClient = this._docClient;
80
90
  ModelClass.table = this._tableName;
@@ -93,8 +103,17 @@ class ModelManager {
93
103
  return this._tableName;
94
104
  }
95
105
 
106
+ getTenantId() {
107
+ return this._tenantId;
108
+ }
109
+
110
+ // Backward compatibility
96
111
  getTestId() {
97
- return this._testId;
112
+ return this._tenantId;
113
+ }
114
+
115
+ isTenancyEnabled() {
116
+ return this._tenancyEnabled;
98
117
  }
99
118
 
100
119
  // Helper method for debugging
package/src/model.js CHANGED
@@ -24,7 +24,13 @@ const {
24
24
  } = require("./model-config");
25
25
 
26
26
  const GID_SEPARATOR = "##__SK__##";
27
- const { UNIQUE_CONSTRAINT_KEY, SYSTEM_FIELDS } = require("./constants");
27
+ const {
28
+ UNIQUE_CONSTRAINT_KEY,
29
+ SYSTEM_FIELDS,
30
+ ITERATION_INDEX_NAME,
31
+ ITERATION_PK_FIELD,
32
+ ITERATION_SK_FIELD,
33
+ } = require("./constants");
28
34
  const {
29
35
  ConfigurationError,
30
36
  ValidationError,
@@ -39,7 +45,8 @@ const {
39
45
  * by the code generator.
40
46
  */
41
47
  class BaoModel {
42
- static _testId = null;
48
+ static _tenantId = null;
49
+ static _testId = null; // Backward compatibility
43
50
  static table = null;
44
51
  static documentClient = null;
45
52
 
@@ -49,6 +56,8 @@ class BaoModel {
49
56
  static primaryKey = null;
50
57
  static indexes = {};
51
58
  static uniqueConstraints = {};
59
+ static iterable = false;
60
+ static iterationBuckets = 100;
52
61
 
53
62
  static defaultQueryLimit = 100;
54
63
 
@@ -67,17 +76,23 @@ class BaoModel {
67
76
  * prevent data from being shared between tests/tests to run in parallel.
68
77
  * However, it should not be used outside of this context. For examples,
69
78
  * showing how to use this, see the tests.
79
+ *
80
+ * @deprecated Use TenantContext.setCurrentTenant() with the new multi-tenancy
81
+ * system for both testing and production tenant isolation. See tutorial 08-multi-tenancy.
70
82
  * @param {string} testId - The ID of the test.
71
83
  */
72
84
  static setTestId(testId) {
73
- this._testId = testId;
85
+ this._tenantId = testId;
86
+ this._testId = testId; // Backward compatibility
74
87
  const manager = ModelManager.getInstance(testId);
75
88
  this.documentClient = manager.documentClient;
76
89
  this.table = manager.tableName;
77
90
  }
78
91
 
79
92
  static get manager() {
80
- return ModelManager.getInstance(this._testId);
93
+ const { TenantContext } = require('./tenant-context');
94
+ const tenantId = TenantContext.getCurrentTenant();
95
+ return ModelManager.getInstance(tenantId || this._tenantId);
81
96
  }
82
97
 
83
98
  static _getField(fieldName) {
@@ -137,21 +152,21 @@ class BaoModel {
137
152
  }
138
153
 
139
154
  static _formatGsiKey(modelPrefix, indexId, value) {
140
- const testId = this.manager.getTestId();
155
+ const tenantId = this.manager.getTenantId();
141
156
  const baseKey = `${modelPrefix}#${indexId}#${value}`;
142
- return testId ? `[${testId}]#${baseKey}` : baseKey;
157
+ return tenantId ? `[${tenantId}]#${baseKey}` : baseKey;
143
158
  }
144
159
 
145
160
  static _formatPrimaryKey(modelPrefix, value) {
146
- const testId = this.manager.getTestId();
161
+ const tenantId = this.manager.getTenantId();
147
162
  const baseKey = `${modelPrefix}#${value}`;
148
- return testId ? `[${testId}]#${baseKey}` : baseKey;
163
+ return tenantId ? `[${tenantId}]#${baseKey}` : baseKey;
149
164
  }
150
165
 
151
166
  static _formatUniqueConstraintKey(constraintId, modelPrefix, field, value) {
152
- const testId = this.manager.getTestId();
167
+ const tenantId = this.manager.getTenantId();
153
168
  const baseKey = `${UNIQUE_CONSTRAINT_KEY}#${constraintId}#${modelPrefix}#${field}:${value}`;
154
- return testId ? `[${testId}]#${baseKey}` : baseKey;
169
+ return tenantId ? `[${tenantId}]#${baseKey}` : baseKey;
155
170
  }
156
171
 
157
172
  static _getDyKeyForPkSk(pkSk) {
@@ -173,6 +188,136 @@ class BaoModel {
173
188
  }
174
189
  }
175
190
 
191
+ static _getIterationKeys(objectId, dyData) {
192
+ if (!this.iterable) {
193
+ return {};
194
+ }
195
+
196
+ const tenantId = this.manager.getTenantId();
197
+ let iterPk;
198
+
199
+ if (this.iterationBuckets === 1) {
200
+ iterPk = tenantId ?
201
+ `[${tenantId}]#${this.modelPrefix}#iter` :
202
+ `${this.modelPrefix}#iter`;
203
+ } else {
204
+ const bucketNum = this._hashObjectId(objectId) % this.iterationBuckets;
205
+ const bucket = bucketNum.toString().padStart(3, '0');
206
+ iterPk = tenantId ?
207
+ `[${tenantId}]#${this.modelPrefix}#iter#${bucket}` :
208
+ `${this.modelPrefix}#iter#${bucket}`;
209
+ }
210
+
211
+ return {
212
+ [ITERATION_PK_FIELD]: iterPk,
213
+ [ITERATION_SK_FIELD]: objectId
214
+ };
215
+ }
216
+
217
+ static _hashObjectId(objectId) {
218
+ let hash = 0;
219
+ for (let i = 0; i < objectId.length; i++) {
220
+ const char = objectId.charCodeAt(i);
221
+ hash = ((hash << 5) - hash) + char;
222
+ hash = hash & hash;
223
+ }
224
+ return Math.abs(hash);
225
+ }
226
+
227
+ static getIterationBuckets() {
228
+ return this.iterable ? this.iterationBuckets : 1;
229
+ }
230
+
231
+ static async* iterateAll(options = {}) {
232
+ if (!this.iterable) {
233
+ throw new Error(`Model ${this.name} is not configured as iterable`);
234
+ }
235
+
236
+ const { batchSize = 100, filter = null, loaderContext = null } = options;
237
+
238
+ if (this.iterationBuckets === 1) {
239
+ yield* this._iterateSingleBucket(null, { batchSize, filter, loaderContext });
240
+ } else {
241
+ for (let bucket = 0; bucket < this.iterationBuckets; bucket++) {
242
+ yield* this._iterateSingleBucket(bucket, { batchSize, filter, loaderContext });
243
+ }
244
+ }
245
+ }
246
+
247
+ static async* iterateBucket(bucketNum, options = {}) {
248
+ if (!this.iterable) {
249
+ throw new Error(`Model ${this.name} is not configured as iterable`);
250
+ }
251
+
252
+ if (bucketNum < 0 || bucketNum >= this.iterationBuckets) {
253
+ throw new Error(`Invalid bucket number ${bucketNum}. Must be 0-${this.iterationBuckets - 1}`);
254
+ }
255
+
256
+ yield* this._iterateSingleBucket(bucketNum, options);
257
+ }
258
+
259
+ static async* _iterateSingleBucket(bucketNum, options = {}) {
260
+ const { batchSize = 100, filter = null, loaderContext = null } = options;
261
+ const tenantId = this.manager.getTenantId();
262
+
263
+ let iterPk;
264
+ if (this.iterationBuckets === 1) {
265
+ iterPk = tenantId ?
266
+ `[${tenantId}]#${this.modelPrefix}#iter` :
267
+ `${this.modelPrefix}#iter`;
268
+ } else {
269
+ const bucket = bucketNum.toString().padStart(3, '0');
270
+ iterPk = tenantId ?
271
+ `[${tenantId}]#${this.modelPrefix}#iter#${bucket}` :
272
+ `${this.modelPrefix}#iter#${bucket}`;
273
+ }
274
+
275
+ let lastEvaluatedKey = null;
276
+
277
+ do {
278
+ const { QueryCommand } = require("./dynamodb-client");
279
+ const params = {
280
+ TableName: this.table,
281
+ IndexName: ITERATION_INDEX_NAME,
282
+ KeyConditionExpression: '#pk = :pk',
283
+ ExpressionAttributeNames: { '#pk': ITERATION_PK_FIELD },
284
+ ExpressionAttributeValues: { ':pk': iterPk },
285
+ Limit: batchSize,
286
+ ReturnConsumedCapacity: 'TOTAL'
287
+ };
288
+
289
+ if (lastEvaluatedKey) {
290
+ params.ExclusiveStartKey = lastEvaluatedKey;
291
+ }
292
+
293
+ if (filter) {
294
+ const { FilterExpressionBuilder } = require("./filter-expression");
295
+ const filterBuilder = new FilterExpressionBuilder();
296
+ const filterExpression = filterBuilder.build(filter, this);
297
+ if (filterExpression) {
298
+ params.FilterExpression = filterExpression.FilterExpression;
299
+ Object.assign(params.ExpressionAttributeNames, filterExpression.ExpressionAttributeNames);
300
+ Object.assign(params.ExpressionAttributeValues, filterExpression.ExpressionAttributeValues);
301
+ }
302
+ }
303
+
304
+ const response = await this.documentClient.send(new QueryCommand(params));
305
+
306
+ if (response.Items && response.Items.length > 0) {
307
+ const objectIds = response.Items.map(item => item[ITERATION_SK_FIELD]);
308
+
309
+ const { items } = await this.batchFind(objectIds, loaderContext);
310
+ const batch = Object.values(items);
311
+
312
+ if (batch.length > 0) {
313
+ yield batch;
314
+ }
315
+ }
316
+
317
+ lastEvaluatedKey = response.LastEvaluatedKey;
318
+ } while (lastEvaluatedKey);
319
+ }
320
+
176
321
  /**
177
322
  * @description
178
323
  * Create a new model instance.
@@ -0,0 +1,164 @@
1
+ const { AsyncLocalStorage } = require('async_hooks');
2
+
3
+ /**
4
+ * @class TenantContext
5
+ * @description Manages tenant context for multi-tenant applications using DynamoBao.
6
+ * Provides runtime tenant resolution and instance management with concurrency safety.
7
+ */
8
+ class TenantContext {
9
+ static _asyncStorage = new AsyncLocalStorage();
10
+ static _instances = new Map(); // tenantId -> ModelManager
11
+ static _resolvers = [];
12
+ static _fallbackTenant = null; // For backward compatibility when not in async context
13
+
14
+ /**
15
+ * Sets the current tenant ID and returns the associated ModelManager instance.
16
+ * For backward compatibility and simple use cases (like tests).
17
+ * @param {string} tenantId - The tenant identifier
18
+ * @returns {ModelManager} The ModelManager instance for the tenant
19
+ */
20
+ static setCurrentTenant(tenantId) {
21
+ const store = this._asyncStorage.getStore();
22
+ if (store) {
23
+ // We're inside an async context, set the tenant there
24
+ store.tenantId = tenantId;
25
+ } else {
26
+ // We're not in an async context, use fallback
27
+ this._fallbackTenant = tenantId;
28
+ }
29
+ return this.getInstance(tenantId);
30
+ }
31
+
32
+ /**
33
+ * Gets the current tenant ID using async context or resolver chain.
34
+ * Concurrency-safe using AsyncLocalStorage.
35
+ * @returns {string|null} The current tenant ID or null if not found
36
+ */
37
+ static getCurrentTenant() {
38
+ // 1. Check async context first (for concurrent request safety)
39
+ const store = this._asyncStorage.getStore();
40
+ if (store?.tenantId) {
41
+ return store.tenantId;
42
+ }
43
+
44
+ // 2. Check fallback tenant (for backward compatibility)
45
+ if (this._fallbackTenant) {
46
+ return this._fallbackTenant;
47
+ }
48
+
49
+ // 3. Try resolvers in order (for request-scoped resolution)
50
+ for (const resolver of this._resolvers) {
51
+ const tenantId = resolver();
52
+ if (tenantId) {
53
+ return tenantId;
54
+ }
55
+ }
56
+
57
+ return null;
58
+ }
59
+
60
+ /**
61
+ * Adds a resolver function to determine tenant context.
62
+ * Resolvers are tried in the order they were added.
63
+ * @param {Function} resolver - Function that returns a tenant ID or null
64
+ */
65
+ static addResolver(resolver) {
66
+ if (typeof resolver !== 'function') {
67
+ throw new Error('Resolver must be a function');
68
+ }
69
+ this._resolvers.push(resolver);
70
+ }
71
+
72
+ /**
73
+ * Runs a callback function with a specific tenant context.
74
+ * Ensures concurrency safety by using AsyncLocalStorage.
75
+ * @param {string} tenantId - The tenant identifier
76
+ * @param {Function} callback - The function to run with tenant context
77
+ * @returns {Promise} The result of the callback
78
+ */
79
+ static runWithTenant(tenantId, callback) {
80
+ return this._asyncStorage.run({ tenantId }, callback);
81
+ }
82
+
83
+ /**
84
+ * Explicit tenant override for cross-tenant operations.
85
+ * Alias for runWithTenant for better readability in cross-tenant scenarios.
86
+ * @param {string} tenantId - The tenant identifier
87
+ * @param {Function} operation - The operation to run with tenant context
88
+ * @returns {Promise} The result of the operation
89
+ */
90
+ static withTenant(tenantId, operation) {
91
+ return this.runWithTenant(tenantId, operation);
92
+ }
93
+
94
+ /**
95
+ * Gets or creates a ModelManager instance for the specified tenant.
96
+ * @param {string|null} tenantId - The tenant identifier or null for default
97
+ * @returns {ModelManager} The ModelManager instance
98
+ */
99
+ static getInstance(tenantId = null) {
100
+ const { ModelManager } = require('./model-manager');
101
+ const effectiveTenantId = tenantId || this.getCurrentTenant();
102
+ const key = effectiveTenantId || "default";
103
+
104
+ if (!this._instances.has(key)) {
105
+ const manager = ModelManager.getInstance(effectiveTenantId);
106
+ this._instances.set(key, manager);
107
+ }
108
+
109
+ return this._instances.get(key);
110
+ }
111
+
112
+ /**
113
+ * Clears the current tenant context.
114
+ * For test cleanup and simple use cases.
115
+ */
116
+ static clearTenant() {
117
+ const store = this._asyncStorage.getStore();
118
+ if (store) {
119
+ delete store.tenantId;
120
+ }
121
+ this._fallbackTenant = null;
122
+ }
123
+
124
+ /**
125
+ * Clears all resolver functions.
126
+ */
127
+ static clearResolvers() {
128
+ this._resolvers = [];
129
+ }
130
+
131
+ /**
132
+ * Validates that tenant context is available when required by configuration.
133
+ * @param {Object} config - The configuration object
134
+ * @throws {Error} If tenancy is enabled but no tenant context is found
135
+ */
136
+ static validateTenantRequired(config) {
137
+ if (config.tenancy?.enabled && !this.getCurrentTenant()) {
138
+ throw new Error(
139
+ 'Tenant context is required when tenancy is enabled. ' +
140
+ 'Use TenantContext.runWithTenant(tenantId, callback) or add tenant resolvers.'
141
+ );
142
+ }
143
+ }
144
+
145
+ /**
146
+ * Resets all tenant context state (for testing).
147
+ */
148
+ static reset() {
149
+ this._instances.clear();
150
+ this._resolvers = [];
151
+ this._fallbackTenant = null;
152
+
153
+ // Clear any async storage context
154
+ this.clearTenant();
155
+
156
+ // Also clear ModelManager instances to ensure clean state
157
+ const { ModelManager } = require('./model-manager');
158
+ if (ModelManager._instances) {
159
+ ModelManager._instances.clear();
160
+ }
161
+ }
162
+ }
163
+
164
+ module.exports = { TenantContext };