dynamo-bao 0.8.2 → 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.
@@ -11,6 +11,10 @@ function getModelManager() {
11
11
  return _ModelManager;
12
12
  }
13
13
 
14
+ function getBatchContextStore() {
15
+ return require('./mixins/batch-loading-mixin').getBatchContextStore();
16
+ }
17
+
14
18
  /**
15
19
  * @class TenantContext
16
20
  * @description Manages tenant context for multi-tenant applications using DynamoBao.
@@ -18,46 +22,63 @@ function getModelManager() {
18
22
  */
19
23
  class TenantContext {
20
24
  static _asyncStorage = new AsyncLocalStorage();
21
- static _instances = new Map(); // tenantId -> ModelManager
22
25
  static _resolvers = [];
23
- static _fallbackTenant = null; // For backward compatibility when not in async context
26
+ // Process-wide tenant, set by setCurrentTenant() outside any request
27
+ // context (scripts and tests). Never consulted inside runWithTenant().
28
+ static _fallbackTenant = null;
24
29
 
25
30
  /**
26
31
  * Sets the current tenant ID and returns the associated ModelManager instance.
27
- * For backward compatibility and simple use cases (like tests).
32
+ *
33
+ * Inside runWithTenant() or runWithBatchContext() the tenant is set for that
34
+ * context only. Outside both, it sets a process-wide tenant, which is only
35
+ * appropriate for scripts and tests: concurrent requests that have no tenant
36
+ * of their own would see it.
28
37
  * @param {string} tenantId - The tenant identifier
29
38
  * @returns {ModelManager} The ModelManager instance for the tenant
30
39
  */
31
40
  static setCurrentTenant(tenantId) {
32
41
  const store = this._asyncStorage.getStore();
42
+ const batchStore = getBatchContextStore();
33
43
  if (store) {
34
- // We're inside an async context, set the tenant there
35
44
  store.tenantId = tenantId;
45
+ } else if (batchStore) {
46
+ batchStore.tenantId = tenantId;
36
47
  } else {
37
- // We're not in an async context, use fallback
38
48
  this._fallbackTenant = tenantId;
39
49
  }
40
50
  return this.getInstance(tenantId);
41
51
  }
42
52
 
43
53
  /**
44
- * Gets the current tenant ID using async context or resolver chain.
45
- * Concurrency-safe using AsyncLocalStorage.
54
+ * Sets the process-wide tenant regardless of the current context. Meant for
55
+ * scripts, jobs and tests that handle one tenant at a time; never call it
56
+ * from request handling code.
57
+ * @param {string|null} tenantId - The tenant identifier, or null to clear it
58
+ * @returns {ModelManager} The ModelManager instance for the tenant
59
+ */
60
+ static setDefaultTenant(tenantId) {
61
+ this._fallbackTenant = tenantId || null;
62
+ return this.getInstance(tenantId);
63
+ }
64
+
65
+ /**
66
+ * Gets the current tenant ID. Checked in order: the runWithTenant() context,
67
+ * a tenant set inside the current batch context, resolvers, and finally the
68
+ * process-wide tenant (only outside runWithTenant()).
46
69
  * @returns {string|null} The current tenant ID or null if not found
47
70
  */
48
71
  static getCurrentTenant() {
49
- // 1. Check async context first (for concurrent request safety)
50
72
  const store = this._asyncStorage.getStore();
51
73
  if (store?.tenantId) {
52
74
  return store.tenantId;
53
75
  }
54
76
 
55
- // 2. Check fallback tenant (for backward compatibility)
56
- if (this._fallbackTenant) {
57
- return this._fallbackTenant;
77
+ const batchTenant = getBatchContextStore()?.tenantId;
78
+ if (batchTenant) {
79
+ return batchTenant;
58
80
  }
59
81
 
60
- // 3. Try resolvers in order (for request-scoped resolution)
61
82
  for (const resolver of this._resolvers) {
62
83
  const tenantId = resolver();
63
84
  if (tenantId) {
@@ -65,7 +86,13 @@ class TenantContext {
65
86
  }
66
87
  }
67
88
 
68
- return null;
89
+ // runWithTenant() is an explicit request scope; a process-wide tenant
90
+ // must not leak into it.
91
+ if (store) {
92
+ return null;
93
+ }
94
+
95
+ return this._fallbackTenant || null;
69
96
  }
70
97
 
71
98
  /**
@@ -109,27 +136,26 @@ class TenantContext {
109
136
  */
110
137
  static getInstance(tenantId = null) {
111
138
  const ModelManager = getModelManager();
112
- const effectiveTenantId = tenantId || this.getCurrentTenant();
113
- const key = effectiveTenantId || "default";
114
-
115
- if (!this._instances.has(key)) {
116
- const manager = ModelManager.getInstance(effectiveTenantId);
117
- this._instances.set(key, manager);
118
- }
119
-
120
- return this._instances.get(key);
139
+ return ModelManager.forTenant(tenantId || this.getCurrentTenant());
121
140
  }
122
141
 
123
142
  /**
124
- * Clears the current tenant context.
125
- * For test cleanup and simple use cases.
143
+ * Clears the current tenant. Inside runWithTenant() or runWithBatchContext()
144
+ * this clears only that context's tenant; outside both it clears the
145
+ * process-wide tenant.
126
146
  */
127
147
  static clearTenant() {
128
148
  const store = this._asyncStorage.getStore();
149
+ const batchStore = getBatchContextStore();
129
150
  if (store) {
130
151
  delete store.tenantId;
131
152
  }
132
- this._fallbackTenant = null;
153
+ if (batchStore) {
154
+ batchStore.tenantId = null;
155
+ }
156
+ if (!store && !batchStore) {
157
+ this._fallbackTenant = null;
158
+ }
133
159
  }
134
160
 
135
161
  /**
@@ -157,7 +183,6 @@ class TenantContext {
157
183
  * Resets all tenant context state (for testing).
158
184
  */
159
185
  static reset() {
160
- this._instances.clear();
161
186
  this._resolvers = [];
162
187
  this._fallbackTenant = null;
163
188
 
@@ -169,6 +194,7 @@ class TenantContext {
169
194
  if (ModelManager._instances) {
170
195
  ModelManager._instances.clear();
171
196
  }
197
+ ModelManager._primary = null;
172
198
  }
173
199
  }
174
200
 
@@ -182,7 +182,7 @@ function buildSearchPredicate(terms, searchConfig, options = {}) {
182
182
  }
183
183
 
184
184
  // `:stN` placeholders are deliberately a separate namespace from the
185
- // FilterExpressionBuilder convention (`:vN`, see src/filter-expression.js)
185
+ // FilterExpressionBuilder convention (`:__fN`, see src/filter-expression.js)
186
186
  // so the two can be merged into a single FilterExpression without colliding.
187
187
  const join = operator === "$or" ? " OR " : " AND ";
188
188
  const parts = [];
@@ -1,60 +0,0 @@
1
- import path from "path";
2
- import { promises as fs } from "fs";
3
- import os from "os";
4
- import chokidar from "chokidar";
5
-
6
- async function testChokidar() {
7
- let tempDir = path.join(os.tmpdir(), "chokidar-test-" + Date.now());
8
- await fs.mkdir(tempDir, { recursive: true });
9
-
10
- const testFile = path.join(tempDir, "test-file.js");
11
- await fs.writeFile(testFile, "// Initial content");
12
-
13
- console.log("Watching directory:", tempDir);
14
- console.log("Test file path:", testFile);
15
-
16
- // DON'T DO THIS tempDir = path.join(tempDir, '**/*.js');
17
-
18
- const watcher = chokidar.watch(tempDir, {
19
- // Changed to watch entire directory
20
- persistent: true,
21
- ignoreInitial: false, // Changed to false to see initial add events
22
- usePolling: true,
23
- interval: 100,
24
- awaitWriteFinish: {
25
- stabilityThreshold: 100,
26
- pollInterval: 100,
27
- },
28
- });
29
-
30
- watcher
31
- .on("add", (path) => console.log(`File ${path} has been added`))
32
- .on("change", (filepath) => {
33
- console.log("Change detected:", filepath);
34
- })
35
- .on("error", (error) => console.log(`Watcher error: ${error}`))
36
- .on("ready", () => {
37
- console.log("Watcher is ready");
38
-
39
- setTimeout(async () => {
40
- console.log("Modifying file");
41
- try {
42
- await fs.writeFile(testFile, "// Modified content");
43
- console.log("File modification completed");
44
- } catch (err) {
45
- console.error("Error modifying file:", err);
46
- }
47
- }, 1000);
48
- });
49
-
50
- // Keep process alive longer
51
- setTimeout(() => {
52
- console.log("Closing watcher");
53
- watcher.close();
54
- }, 10000); // Increased timeout to 10 seconds
55
- }
56
-
57
- testChokidar().catch((err) => {
58
- console.error("Test failed:", err);
59
- process.exit(1);
60
- });