dynamo-bao 0.2.11 → 0.3.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 +132 -0
- package/package.json +1 -1
- package/src/config.js +23 -11
- package/src/index.js +14 -10
- package/src/mixins/batch-loading-mixin.js +151 -28
- package/src/model-manager.js +8 -2
- package/src/model.js +13 -25
package/README.md
CHANGED
|
@@ -153,6 +153,138 @@ async function testUserModel() {
|
|
|
153
153
|
testUserModel();
|
|
154
154
|
```
|
|
155
155
|
|
|
156
|
+
### Cloudflare Workers Support
|
|
157
|
+
|
|
158
|
+
DynamoBao supports Cloudflare Workers with request-scoped batching to ensure proper isolation between concurrent requests. To use DynamoBao in Cloudflare Workers, you'll need to enable Node.js compatibility and wrap your request handlers with the batch context:
|
|
159
|
+
|
|
160
|
+
```javascript
|
|
161
|
+
// wrangler.toml
|
|
162
|
+
compatibility_flags = ["nodejs_compat"];
|
|
163
|
+
compatibility_date = "2024-09-23";
|
|
164
|
+
|
|
165
|
+
// worker.js
|
|
166
|
+
import { runWithBatchContext } from "dynamo-bao";
|
|
167
|
+
import { User } from "./models/user.js";
|
|
168
|
+
|
|
169
|
+
export default {
|
|
170
|
+
async fetch(request, env, ctx) {
|
|
171
|
+
return runWithBatchContext(async () => {
|
|
172
|
+
// All batching operations are now request-scoped
|
|
173
|
+
const user = await User.find(userId);
|
|
174
|
+
// Additional database operations...
|
|
175
|
+
return new Response(JSON.stringify(user));
|
|
176
|
+
});
|
|
177
|
+
},
|
|
178
|
+
};
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
**Request Isolation**:
|
|
182
|
+
|
|
183
|
+
- **With `runWithBatchContext`**: Each request gets its own isolated batch context with optimal batching performance
|
|
184
|
+
- **Without `runWithBatchContext`**: Operations automatically fall back to direct execution (no batching/caching) to ensure request isolation
|
|
185
|
+
|
|
186
|
+
For production Cloudflare Workers deployments, always use `runWithBatchContext` to get both safety and optimal performance.
|
|
187
|
+
|
|
188
|
+
### Batch Context Configuration
|
|
189
|
+
|
|
190
|
+
DynamoBao provides flexible batch context behavior that can be configured based on your application's needs:
|
|
191
|
+
|
|
192
|
+
#### Configuration Options
|
|
193
|
+
|
|
194
|
+
Add the `batchContext` configuration to your config file:
|
|
195
|
+
|
|
196
|
+
```javascript
|
|
197
|
+
// config.js or dynamo-bao.config.js
|
|
198
|
+
module.exports = {
|
|
199
|
+
aws: {
|
|
200
|
+
region: "us-west-2",
|
|
201
|
+
},
|
|
202
|
+
db: {
|
|
203
|
+
tableName: "your-table-name",
|
|
204
|
+
},
|
|
205
|
+
batchContext: {
|
|
206
|
+
requireBatchContext: false, // Default: allow fallback behavior
|
|
207
|
+
},
|
|
208
|
+
// ... other config
|
|
209
|
+
};
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
#### Behavior Modes
|
|
213
|
+
|
|
214
|
+
**Default Mode (`requireBatchContext: false`)**:
|
|
215
|
+
|
|
216
|
+
- Operations inside `runWithBatchContext`: Full batching and caching enabled
|
|
217
|
+
- Operations outside `runWithBatchContext`: Direct execution without batching or caching
|
|
218
|
+
- Provides maximum flexibility and backward compatibility
|
|
219
|
+
|
|
220
|
+
```javascript
|
|
221
|
+
// Works with direct execution (no batching/caching)
|
|
222
|
+
const user = await User.find("user123");
|
|
223
|
+
|
|
224
|
+
// Also works with batching + caching
|
|
225
|
+
await runWithBatchContext(async () => {
|
|
226
|
+
const user = await User.find("user123");
|
|
227
|
+
});
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
**Strict Mode (`requireBatchContext: true`)**:
|
|
231
|
+
|
|
232
|
+
- Operations inside `runWithBatchContext`: Full batching and caching enabled
|
|
233
|
+
- Operations outside `runWithBatchContext`: Throws an error
|
|
234
|
+
- Ensures all database operations use proper batch context
|
|
235
|
+
|
|
236
|
+
```javascript
|
|
237
|
+
// Configure strict mode
|
|
238
|
+
const manager = initModels({
|
|
239
|
+
batchContext: { requireBatchContext: true },
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
// This throws an error
|
|
243
|
+
await User.find("user123"); // Error: Batch operations must be executed within runWithBatchContext()
|
|
244
|
+
|
|
245
|
+
// This works
|
|
246
|
+
await runWithBatchContext(async () => {
|
|
247
|
+
const user = await User.find("user123"); // ✅
|
|
248
|
+
});
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
#### Context Detection API
|
|
252
|
+
|
|
253
|
+
You can check if code is currently running within a batch context:
|
|
254
|
+
|
|
255
|
+
```javascript
|
|
256
|
+
const { User } = require("./models/user");
|
|
257
|
+
|
|
258
|
+
// Check if inside batch context
|
|
259
|
+
const isInBatchContext = User.isInsideBatchContext();
|
|
260
|
+
|
|
261
|
+
if (isInBatchContext) {
|
|
262
|
+
// Full batching and caching available
|
|
263
|
+
console.log("Running with batching enabled");
|
|
264
|
+
} else {
|
|
265
|
+
// Direct execution mode
|
|
266
|
+
console.log("Running in direct execution mode");
|
|
267
|
+
}
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
#### Environment Variable Support
|
|
271
|
+
|
|
272
|
+
You can also configure batch context behavior via environment variables:
|
|
273
|
+
|
|
274
|
+
```bash
|
|
275
|
+
# Enable strict mode globally
|
|
276
|
+
export DYNAMO_BAO_REQUIRE_BATCH_CONTEXT=true
|
|
277
|
+
|
|
278
|
+
# Your application will now require runWithBatchContext for all operations
|
|
279
|
+
node your-app.js
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
This is particularly useful for:
|
|
283
|
+
|
|
284
|
+
- **Development/Testing**: Use strict mode to catch missing batch contexts early
|
|
285
|
+
- **Production**: Use default mode for maximum flexibility
|
|
286
|
+
- **Migration**: Gradually migrate from direct calls to batch context usage
|
|
287
|
+
|
|
156
288
|
### Iterating over all items
|
|
157
289
|
|
|
158
290
|
DynamoBao makes it easy to iterate over all items in a model, which is useful for tasks like data migration, backfills, or reporting.
|
package/package.json
CHANGED
package/src/config.js
CHANGED
|
@@ -52,7 +52,7 @@ async function findConfig() {
|
|
|
52
52
|
tableName: process.env.TABLE_NAME || "dynamo-bao-dev",
|
|
53
53
|
},
|
|
54
54
|
codegen: {
|
|
55
|
-
moduleSystem:
|
|
55
|
+
moduleSystem: "commonjs",
|
|
56
56
|
},
|
|
57
57
|
logging: {
|
|
58
58
|
level: process.env.LOG_LEVEL || "ERROR",
|
|
@@ -65,16 +65,20 @@ async function findConfig() {
|
|
|
65
65
|
tenancy: {
|
|
66
66
|
enabled: process.env.DYNAMO_BAO_TENANCY_ENABLED === "true" || false,
|
|
67
67
|
},
|
|
68
|
+
batchContext: {
|
|
69
|
+
requireBatchContext:
|
|
70
|
+
process.env.DYNAMO_BAO_REQUIRE_BATCH_CONTEXT === "true" || false,
|
|
71
|
+
},
|
|
68
72
|
};
|
|
69
73
|
}
|
|
70
74
|
|
|
71
75
|
async function loadConfigFile(configPath) {
|
|
72
|
-
if (configPath.endsWith(
|
|
76
|
+
if (configPath.endsWith(".cjs")) {
|
|
73
77
|
// Use require for CommonJS files
|
|
74
78
|
return require(configPath);
|
|
75
|
-
} else if (configPath.endsWith(
|
|
79
|
+
} else if (configPath.endsWith(".mjs") || configPath.endsWith(".js")) {
|
|
76
80
|
// Use dynamic import for ESM files
|
|
77
|
-
const fileUrl =
|
|
81
|
+
const fileUrl = "file://" + configPath;
|
|
78
82
|
const module = await import(fileUrl);
|
|
79
83
|
return module.default || module;
|
|
80
84
|
} else {
|
|
@@ -83,13 +87,12 @@ async function loadConfigFile(configPath) {
|
|
|
83
87
|
}
|
|
84
88
|
}
|
|
85
89
|
|
|
86
|
-
|
|
87
90
|
function normalizeConfig(rawConfig, configDir) {
|
|
88
91
|
return {
|
|
89
92
|
...rawConfig,
|
|
90
93
|
models: rawConfig.models || null,
|
|
91
94
|
codegen: {
|
|
92
|
-
moduleSystem:
|
|
95
|
+
moduleSystem: "commonjs",
|
|
93
96
|
...(rawConfig.codegen || {}),
|
|
94
97
|
},
|
|
95
98
|
paths: {
|
|
@@ -116,6 +119,10 @@ function normalizeConfig(rawConfig, configDir) {
|
|
|
116
119
|
enabled: false,
|
|
117
120
|
...rawConfig.tenancy,
|
|
118
121
|
},
|
|
122
|
+
batchContext: {
|
|
123
|
+
requireBatchContext: false,
|
|
124
|
+
...rawConfig.batchContext,
|
|
125
|
+
},
|
|
119
126
|
};
|
|
120
127
|
}
|
|
121
128
|
|
|
@@ -124,7 +131,7 @@ let config = null;
|
|
|
124
131
|
|
|
125
132
|
function getConfig() {
|
|
126
133
|
if (!config) {
|
|
127
|
-
throw new Error(
|
|
134
|
+
throw new Error("Config not initialized. Call initConfig() first.");
|
|
128
135
|
}
|
|
129
136
|
return config;
|
|
130
137
|
}
|
|
@@ -146,7 +153,7 @@ try {
|
|
|
146
153
|
tableName: process.env.TABLE_NAME || "dynamo-bao-dev",
|
|
147
154
|
},
|
|
148
155
|
codegen: {
|
|
149
|
-
moduleSystem:
|
|
156
|
+
moduleSystem: "commonjs",
|
|
150
157
|
},
|
|
151
158
|
logging: {
|
|
152
159
|
level: process.env.LOG_LEVEL || "ERROR",
|
|
@@ -159,18 +166,23 @@ try {
|
|
|
159
166
|
tenancy: {
|
|
160
167
|
enabled: process.env.DYNAMO_BAO_TENANCY_ENABLED === "true" || false,
|
|
161
168
|
},
|
|
169
|
+
batchContext: {
|
|
170
|
+
requireBatchContext:
|
|
171
|
+
process.env.DYNAMO_BAO_REQUIRE_BATCH_CONTEXT === "true" || false,
|
|
172
|
+
},
|
|
162
173
|
};
|
|
163
174
|
} catch (err) {
|
|
164
|
-
console.error(
|
|
175
|
+
console.error("Error loading config:", err);
|
|
165
176
|
}
|
|
166
177
|
|
|
167
178
|
module.exports = config || {
|
|
168
179
|
aws: { region: "us-west-2" },
|
|
169
180
|
db: { tableName: "dynamo-bao-dev" },
|
|
170
|
-
codegen: { moduleSystem:
|
|
181
|
+
codegen: { moduleSystem: "commonjs" },
|
|
171
182
|
logging: { level: "ERROR" },
|
|
172
183
|
paths: { modelsDir: null },
|
|
173
|
-
tenancy: { enabled: false }
|
|
184
|
+
tenancy: { enabled: false },
|
|
185
|
+
batchContext: { requireBatchContext: false },
|
|
174
186
|
};
|
|
175
187
|
|
|
176
188
|
module.exports.initConfig = initConfig;
|
package/src/index.js
CHANGED
|
@@ -17,6 +17,7 @@ const {
|
|
|
17
17
|
} = require("./model");
|
|
18
18
|
|
|
19
19
|
const { TenantContext } = require("./tenant-context");
|
|
20
|
+
const { runWithBatchContext } = require("./mixins/batch-loading-mixin");
|
|
20
21
|
|
|
21
22
|
function findModelFiles(dir) {
|
|
22
23
|
let results = [];
|
|
@@ -64,9 +65,7 @@ function _registerModelsFromDirectory(manager, modelsDir) {
|
|
|
64
65
|
);
|
|
65
66
|
}
|
|
66
67
|
if (!fs.existsSync(modelsDir)) {
|
|
67
|
-
throw new ConfigurationError(
|
|
68
|
-
`modelsDir does not exist: ${modelsDir}`,
|
|
69
|
-
);
|
|
68
|
+
throw new ConfigurationError(`modelsDir does not exist: ${modelsDir}`);
|
|
70
69
|
}
|
|
71
70
|
const modelFiles = findModelFiles(modelsDir);
|
|
72
71
|
const models = {};
|
|
@@ -83,7 +82,7 @@ function _registerModelsFromDirectory(manager, modelsDir) {
|
|
|
83
82
|
}
|
|
84
83
|
|
|
85
84
|
function _registerModelsFromDirectImports(manager, modelsObject) {
|
|
86
|
-
if (!modelsObject || typeof modelsObject !==
|
|
85
|
+
if (!modelsObject || typeof modelsObject !== "object") {
|
|
87
86
|
throw new ConfigurationError(
|
|
88
87
|
"models must be an object containing model classes",
|
|
89
88
|
);
|
|
@@ -91,15 +90,13 @@ function _registerModelsFromDirectImports(manager, modelsObject) {
|
|
|
91
90
|
|
|
92
91
|
const models = {};
|
|
93
92
|
Object.entries(modelsObject).forEach(([name, ModelClass]) => {
|
|
94
|
-
if (!ModelClass || typeof ModelClass !==
|
|
93
|
+
if (!ModelClass || typeof ModelClass !== "function") {
|
|
95
94
|
throw new ConfigurationError(
|
|
96
95
|
`Invalid model "${name}": must be a constructor function`,
|
|
97
96
|
);
|
|
98
97
|
}
|
|
99
98
|
if (!(ModelClass.prototype instanceof BaoModel)) {
|
|
100
|
-
throw new ConfigurationError(
|
|
101
|
-
`Model "${name}" must extend BaoModel`,
|
|
102
|
-
);
|
|
99
|
+
throw new ConfigurationError(`Model "${name}" must extend BaoModel`);
|
|
103
100
|
}
|
|
104
101
|
manager.registerModel(ModelClass);
|
|
105
102
|
models[name] = ModelClass;
|
|
@@ -114,8 +111,8 @@ function _registerModels(manager, config) {
|
|
|
114
111
|
}
|
|
115
112
|
|
|
116
113
|
// Check if filesystem is available
|
|
117
|
-
const fsAvailable = typeof fs !==
|
|
118
|
-
|
|
114
|
+
const fsAvailable = typeof fs !== "undefined" && fs.existsSync;
|
|
115
|
+
|
|
119
116
|
if (!fsAvailable) {
|
|
120
117
|
throw new ConfigurationError(
|
|
121
118
|
"Filesystem not available. Please provide models directly using the 'models' config option.",
|
|
@@ -168,6 +165,10 @@ function initModels(userConfig = {}) {
|
|
|
168
165
|
...config.tenancy,
|
|
169
166
|
...(userConfig.tenancy || {}),
|
|
170
167
|
},
|
|
168
|
+
batchContext: {
|
|
169
|
+
...config.batchContext,
|
|
170
|
+
...(userConfig.batchContext || {}),
|
|
171
|
+
},
|
|
171
172
|
models: userConfig.models || config.models || null,
|
|
172
173
|
};
|
|
173
174
|
|
|
@@ -212,6 +213,9 @@ const firstExport = {
|
|
|
212
213
|
// Tenant management
|
|
213
214
|
TenantContext,
|
|
214
215
|
|
|
216
|
+
// Batch context for Cloudflare Workers
|
|
217
|
+
runWithBatchContext,
|
|
218
|
+
|
|
215
219
|
// Configurations
|
|
216
220
|
PrimaryKeyConfig,
|
|
217
221
|
IndexConfig,
|
|
@@ -2,19 +2,61 @@ const { defaultLogger: logger } = require("../utils/logger");
|
|
|
2
2
|
const { ObjectNotFound } = require("../object-not-found");
|
|
3
3
|
const { pluginManager } = require("../plugin-manager");
|
|
4
4
|
const { BatchGetCommand, GetCommand } = require("../dynamodb-client");
|
|
5
|
+
const defaultConfig = require("../config");
|
|
6
|
+
|
|
7
|
+
// Import AsyncLocalStorage for request-scoped batching
|
|
8
|
+
let AsyncLocalStorage;
|
|
9
|
+
try {
|
|
10
|
+
AsyncLocalStorage = require("node:async_hooks").AsyncLocalStorage;
|
|
11
|
+
} catch (e) {
|
|
12
|
+
// Fallback for environments without AsyncLocalStorage
|
|
13
|
+
AsyncLocalStorage = null;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// Request-scoped batch context
|
|
17
|
+
const batchContext = AsyncLocalStorage ? new AsyncLocalStorage() : null;
|
|
5
18
|
|
|
6
|
-
// Move these constants from model.js to here
|
|
7
|
-
const BATCH_REQUESTS = new Map(); // testId -> { modelName-delay -> batch }
|
|
8
19
|
const DEFAULT_BATCH_DELAY_MS = 5;
|
|
9
20
|
const BATCH_REQUEST_TIMEOUT = 10000; // 10 seconds max lifetime for a batch
|
|
10
21
|
|
|
11
22
|
const BatchLoadingMethods = {
|
|
12
23
|
_getBatchRequests() {
|
|
13
|
-
|
|
14
|
-
if (
|
|
15
|
-
|
|
24
|
+
// AsyncLocalStorage is required - check for context
|
|
25
|
+
if (batchContext) {
|
|
26
|
+
const context = batchContext.getStore();
|
|
27
|
+
if (context && context.batchRequests) {
|
|
28
|
+
return context.batchRequests;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Check if we should require batch context
|
|
33
|
+
const modelConfig = this._config || {};
|
|
34
|
+
const batchContextConfig = modelConfig.batchContext || {
|
|
35
|
+
requireBatchContext: false,
|
|
36
|
+
};
|
|
37
|
+
if (batchContextConfig.requireBatchContext) {
|
|
38
|
+
// No batch context found - operations must be within runWithBatchContext
|
|
39
|
+
throw new Error(
|
|
40
|
+
"Batch operations must be executed within runWithBatchContext(). " +
|
|
41
|
+
"Wrap your database operations in runWithBatchContext() to enable batching and caching.",
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Fallback: Return null to indicate no batch context available
|
|
46
|
+
return null;
|
|
47
|
+
},
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Check if currently executing within a batch context
|
|
51
|
+
* @returns {boolean} True if inside a batch context, false otherwise
|
|
52
|
+
*/
|
|
53
|
+
isInsideBatchContext() {
|
|
54
|
+
if (!batchContext) {
|
|
55
|
+
return false;
|
|
16
56
|
}
|
|
17
|
-
|
|
57
|
+
|
|
58
|
+
const context = batchContext.getStore();
|
|
59
|
+
return !!(context && context.batchRequests);
|
|
18
60
|
},
|
|
19
61
|
|
|
20
62
|
/**
|
|
@@ -24,12 +66,16 @@ const BatchLoadingMethods = {
|
|
|
24
66
|
* This function should only be used when {@link BaoModel.find} or {@link BaoModel#loadRelatedData} is not sufficient.
|
|
25
67
|
*
|
|
26
68
|
* @param {string[]} primaryIds - The primary IDs of the items to load
|
|
27
|
-
* @param {Object} [loaderContext] - Cache context for storing and retrieving items across requests.
|
|
28
69
|
* @returns {Promise<Object>} Returns a promise that resolves to the loaded items and their consumed capacity
|
|
29
70
|
*/
|
|
30
|
-
async batchFind(primaryIds
|
|
71
|
+
async batchFind(primaryIds) {
|
|
31
72
|
if (!primaryIds?.length) return { items: {}, ConsumedCapacity: [] };
|
|
32
73
|
|
|
74
|
+
// Get batch context and loader context - will be null if not in batch context
|
|
75
|
+
const batchRequests = this._getBatchRequests();
|
|
76
|
+
const context = batchContext?.getStore();
|
|
77
|
+
const loaderContext = context?.loaderContext;
|
|
78
|
+
|
|
33
79
|
// Add retry wrapper function
|
|
34
80
|
const retryOperation = async (operation, maxRetries = 3) => {
|
|
35
81
|
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
|
@@ -61,8 +107,10 @@ const BatchLoadingMethods = {
|
|
|
61
107
|
// First check loaderContext for existing items
|
|
62
108
|
if (loaderContext) {
|
|
63
109
|
primaryIds.forEach((id) => {
|
|
64
|
-
if (loaderContext
|
|
65
|
-
const instance = this._createFromDyItem(
|
|
110
|
+
if (loaderContext.has(id)) {
|
|
111
|
+
const instance = this._createFromDyItem(
|
|
112
|
+
loaderContext.get(id)._dyData,
|
|
113
|
+
);
|
|
66
114
|
results[id] = instance;
|
|
67
115
|
} else {
|
|
68
116
|
idsToLoad.push(id);
|
|
@@ -118,7 +166,7 @@ const BatchLoadingMethods = {
|
|
|
118
166
|
|
|
119
167
|
// Add to loader context if provided
|
|
120
168
|
if (loaderContext) {
|
|
121
|
-
loaderContext
|
|
169
|
+
loaderContext.set(primaryId, instance);
|
|
122
170
|
}
|
|
123
171
|
});
|
|
124
172
|
}
|
|
@@ -168,23 +216,50 @@ const BatchLoadingMethods = {
|
|
|
168
216
|
* @param {Object} [options={}] - Optional configuration for the find operation
|
|
169
217
|
* @param {number} [options.batchDelay=5] - Delay in milliseconds before executing batch request.
|
|
170
218
|
* Set to 0 for immediate individual requests
|
|
171
|
-
* @param {
|
|
172
|
-
* If provided, results will be stored in and retrieved from this context
|
|
219
|
+
* @param {boolean} [options.bypassCache=false] - If true, bypasses both batching and caching entirely
|
|
173
220
|
* @returns {Promise<Object>} Returns a promise that resolves to the found item instance or ObjectNotFound
|
|
174
221
|
* @throws {Error} If the batch request times out or other errors occur during the operation
|
|
175
222
|
*/
|
|
176
223
|
async find(primaryId, options = {}) {
|
|
177
224
|
const batchDelay = options.batchDelay ?? DEFAULT_BATCH_DELAY_MS;
|
|
178
|
-
const
|
|
179
|
-
|
|
180
|
-
//
|
|
181
|
-
if (
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
225
|
+
const bypassCache = options.bypassCache ?? false;
|
|
226
|
+
|
|
227
|
+
// Ensure we're within a batch context (unless bypassing everything for AsyncLocalStorage availability check)
|
|
228
|
+
if (!batchContext) {
|
|
229
|
+
throw new Error(
|
|
230
|
+
"AsyncLocalStorage is not available. Dynamo-bao requires Node.js with AsyncLocalStorage support.",
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const context = batchContext.getStore();
|
|
235
|
+
if (!context) {
|
|
236
|
+
// Check if we should require batch context
|
|
237
|
+
const modelConfig = this._config || {};
|
|
238
|
+
const batchContextConfig = modelConfig.batchContext || {
|
|
239
|
+
requireBatchContext: false,
|
|
240
|
+
};
|
|
241
|
+
if (batchContextConfig.requireBatchContext) {
|
|
242
|
+
throw new Error(
|
|
243
|
+
"Batch operations must be executed within runWithBatchContext(). " +
|
|
244
|
+
"Wrap your database operations in runWithBatchContext() to enable batching and caching.",
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// Fallback behavior: direct execution without batching or caching
|
|
249
|
+
return this._executeFindDirect(primaryId);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// Get automatic loaderContext from batch context
|
|
253
|
+
let loaderContext = null;
|
|
254
|
+
if (!bypassCache && context?.loaderContext) {
|
|
255
|
+
loaderContext = context.loaderContext;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// Check loader context first (unless bypassing cache)
|
|
259
|
+
if (!bypassCache && loaderContext && loaderContext.has(primaryId)) {
|
|
260
|
+
const cachedItem = loaderContext.get(primaryId);
|
|
261
|
+
// Return the exact same cached object instance for true caching
|
|
262
|
+
return cachedItem;
|
|
188
263
|
}
|
|
189
264
|
|
|
190
265
|
if (batchDelay === 0) {
|
|
@@ -207,9 +282,9 @@ const BatchLoadingMethods = {
|
|
|
207
282
|
instance._addConsumedCapacity(result.ConsumedCapacity, "read", false);
|
|
208
283
|
}
|
|
209
284
|
|
|
210
|
-
// Add to loader context if provided
|
|
211
|
-
if (loaderContext) {
|
|
212
|
-
loaderContext
|
|
285
|
+
// Add to loader context if provided (unless bypassing cache)
|
|
286
|
+
if (!bypassCache && loaderContext) {
|
|
287
|
+
loaderContext.set(primaryId, instance);
|
|
213
288
|
}
|
|
214
289
|
|
|
215
290
|
return instance;
|
|
@@ -229,7 +304,7 @@ const BatchLoadingMethods = {
|
|
|
229
304
|
timeoutTimer: null,
|
|
230
305
|
delay: batchDelay,
|
|
231
306
|
createdAt: Date.now(),
|
|
232
|
-
loaderContext,
|
|
307
|
+
loaderContext: bypassCache ? null : loaderContext,
|
|
233
308
|
};
|
|
234
309
|
batchRequests.set(batchKey, batchRequest);
|
|
235
310
|
|
|
@@ -326,11 +401,59 @@ const BatchLoadingMethods = {
|
|
|
326
401
|
}
|
|
327
402
|
});
|
|
328
403
|
},
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* Execute find operation directly without batching or caching
|
|
407
|
+
* @param {string} primaryId - The primary ID to find
|
|
408
|
+
* @returns {Promise<Object>} The found item or ObjectNotFound
|
|
409
|
+
*/
|
|
410
|
+
async _executeFindDirect(primaryId) {
|
|
411
|
+
const pkSk = this._parsePrimaryId(primaryId);
|
|
412
|
+
const dyKey = this._getDyKeyForPkSk(pkSk);
|
|
413
|
+
const result = await this.documentClient.send(
|
|
414
|
+
new GetCommand({
|
|
415
|
+
TableName: this.table,
|
|
416
|
+
Key: dyKey,
|
|
417
|
+
ReturnConsumedCapacity: "TOTAL",
|
|
418
|
+
}),
|
|
419
|
+
);
|
|
420
|
+
|
|
421
|
+
if (!result.Item) {
|
|
422
|
+
return new ObjectNotFound(result.ConsumedCapacity);
|
|
423
|
+
} else {
|
|
424
|
+
const instance = this._createFromDyItem(result.Item);
|
|
425
|
+
instance._addConsumedCapacity(result.ConsumedCapacity, "read", false);
|
|
426
|
+
return instance;
|
|
427
|
+
}
|
|
428
|
+
},
|
|
329
429
|
};
|
|
330
430
|
|
|
431
|
+
/**
|
|
432
|
+
* Initialize batch context for request-scoped batching.
|
|
433
|
+
* This should be called at the beginning of each request in Cloudflare Workers.
|
|
434
|
+
* @param {Function} fn - Function to run within the batch context
|
|
435
|
+
* @returns {*} Result of the function
|
|
436
|
+
*/
|
|
437
|
+
function runWithBatchContext(fn) {
|
|
438
|
+
if (!batchContext) {
|
|
439
|
+
// No AsyncLocalStorage available, just run the function
|
|
440
|
+
return fn();
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
const context = {
|
|
444
|
+
requestId: Date.now().toString(36) + Math.random().toString(36).substr(2),
|
|
445
|
+
batchRequests: new Map(),
|
|
446
|
+
loaderContext: new Map(), // Add automatic loaderContext
|
|
447
|
+
timers: new Set(),
|
|
448
|
+
startTime: Date.now(),
|
|
449
|
+
};
|
|
450
|
+
|
|
451
|
+
return batchContext.run(context, fn);
|
|
452
|
+
}
|
|
453
|
+
|
|
331
454
|
module.exports = {
|
|
332
455
|
BatchLoadingMethods,
|
|
333
|
-
|
|
456
|
+
runWithBatchContext,
|
|
334
457
|
DEFAULT_BATCH_DELAY_MS,
|
|
335
458
|
BATCH_REQUEST_TIMEOUT,
|
|
336
459
|
};
|
package/src/model-manager.js
CHANGED
|
@@ -13,6 +13,7 @@ class ModelManager {
|
|
|
13
13
|
this._tenantId = null; // Changed from _testId
|
|
14
14
|
this._tenancyEnabled = false;
|
|
15
15
|
this._models = new Map();
|
|
16
|
+
this._config = null; // Store config for models to access
|
|
16
17
|
}
|
|
17
18
|
|
|
18
19
|
static getInstance(tenantId = null) {
|
|
@@ -27,16 +28,19 @@ class ModelManager {
|
|
|
27
28
|
|
|
28
29
|
async init(config = {}) {
|
|
29
30
|
// Validate tenant requirement
|
|
30
|
-
const { TenantContext } = require(
|
|
31
|
+
const { TenantContext } = require("./tenant-context");
|
|
31
32
|
TenantContext.validateTenantRequired(config);
|
|
32
33
|
|
|
34
|
+
// Store config for models to access
|
|
35
|
+
this._config = config;
|
|
36
|
+
|
|
33
37
|
const client = new DynamoDBClient({
|
|
34
38
|
region: config.aws.region,
|
|
35
39
|
});
|
|
36
40
|
this._docClient = DynamoDBDocumentClient.from(client);
|
|
37
41
|
this._tableName = config.db.tableName;
|
|
38
42
|
this._tenancyEnabled = config.tenancy?.enabled || false;
|
|
39
|
-
|
|
43
|
+
|
|
40
44
|
// Support both tenantId and testId for backward compatibility
|
|
41
45
|
this._tenantId = config.tenantId || config.testId || this._tenantId;
|
|
42
46
|
|
|
@@ -46,6 +50,7 @@ class ModelManager {
|
|
|
46
50
|
ModelClass._testId = this._tenantId; // Backward compatibility
|
|
47
51
|
ModelClass.documentClient = this._docClient;
|
|
48
52
|
ModelClass.table = this._tableName;
|
|
53
|
+
ModelClass._config = config; // Pass config to models
|
|
49
54
|
ModelClass._validateConfiguration();
|
|
50
55
|
}
|
|
51
56
|
|
|
@@ -88,6 +93,7 @@ class ModelManager {
|
|
|
88
93
|
if (this._initialized) {
|
|
89
94
|
ModelClass.documentClient = this._docClient;
|
|
90
95
|
ModelClass.table = this._tableName;
|
|
96
|
+
ModelClass._config = this._config; // Pass config to newly registered models
|
|
91
97
|
ModelClass._validateConfiguration();
|
|
92
98
|
}
|
|
93
99
|
|
package/src/model.js
CHANGED
|
@@ -233,20 +233,18 @@ class BaoModel {
|
|
|
233
233
|
throw new Error(`Model ${this.name} is not configured as iterable`);
|
|
234
234
|
}
|
|
235
235
|
|
|
236
|
-
const { batchSize = 100, filter = null
|
|
236
|
+
const { batchSize = 100, filter = null } = options;
|
|
237
237
|
|
|
238
238
|
if (this.iterationBuckets === 1) {
|
|
239
239
|
yield* this._iterateSingleBucket(null, {
|
|
240
240
|
batchSize,
|
|
241
241
|
filter,
|
|
242
|
-
loaderContext,
|
|
243
242
|
});
|
|
244
243
|
} else {
|
|
245
244
|
for (let bucket = 0; bucket < this.iterationBuckets; bucket++) {
|
|
246
245
|
yield* this._iterateSingleBucket(bucket, {
|
|
247
246
|
batchSize,
|
|
248
247
|
filter,
|
|
249
|
-
loaderContext,
|
|
250
248
|
});
|
|
251
249
|
}
|
|
252
250
|
}
|
|
@@ -267,7 +265,7 @@ class BaoModel {
|
|
|
267
265
|
}
|
|
268
266
|
|
|
269
267
|
static async *_iterateSingleBucket(bucketNum, options = {}) {
|
|
270
|
-
const { batchSize = 100, filter = null
|
|
268
|
+
const { batchSize = 100, filter = null } = options;
|
|
271
269
|
const tenantId = this.manager.getTenantId();
|
|
272
270
|
|
|
273
271
|
let iterPk;
|
|
@@ -324,7 +322,7 @@ class BaoModel {
|
|
|
324
322
|
(item) => item[ITERATION_SK_FIELD],
|
|
325
323
|
);
|
|
326
324
|
|
|
327
|
-
const { items } = await this.batchFind(objectIds
|
|
325
|
+
const { items } = await this.batchFind(objectIds);
|
|
328
326
|
const batch = Object.values(items);
|
|
329
327
|
|
|
330
328
|
if (batch.length > 0) {
|
|
@@ -619,7 +617,7 @@ class BaoModel {
|
|
|
619
617
|
* @param {Object} [loaderContext] - Cache context for storing and retrieving items across requests.
|
|
620
618
|
* @returns {Promise<Object>} Returns a promise that resolves to the loaded item.
|
|
621
619
|
*/
|
|
622
|
-
async getOrLoadRelatedField(fieldName
|
|
620
|
+
async getOrLoadRelatedField(fieldName) {
|
|
623
621
|
if (this._relatedObjects[fieldName]) {
|
|
624
622
|
return this._relatedObjects[fieldName];
|
|
625
623
|
}
|
|
@@ -636,9 +634,7 @@ class BaoModel {
|
|
|
636
634
|
if (!value) return null;
|
|
637
635
|
|
|
638
636
|
const ModelClass = this.constructor.manager.getModel(field.modelName);
|
|
639
|
-
this._relatedObjects[fieldName] = await ModelClass.find(value
|
|
640
|
-
loaderContext,
|
|
641
|
-
});
|
|
637
|
+
this._relatedObjects[fieldName] = await ModelClass.find(value);
|
|
642
638
|
return this._relatedObjects[fieldName];
|
|
643
639
|
}
|
|
644
640
|
|
|
@@ -646,10 +642,9 @@ class BaoModel {
|
|
|
646
642
|
* @description
|
|
647
643
|
* Load objects for RelatedField's on the current model instance.
|
|
648
644
|
* @param {string[]} [fieldNames] - The names of the fields to load. If not provided, all related fields will be loaded.
|
|
649
|
-
* @param {Object} [loaderContext] - Cache context for storing and retrieving items across requests.
|
|
650
645
|
* @returns {Promise<Object>} Returns a promise that resolves to the loaded items and their consumed capacity
|
|
651
646
|
*/
|
|
652
|
-
async loadRelatedData(fieldNames = null
|
|
647
|
+
async loadRelatedData(fieldNames = null) {
|
|
653
648
|
const promises = [];
|
|
654
649
|
|
|
655
650
|
for (const [fieldName, field] of Object.entries(this.constructor.fields)) {
|
|
@@ -659,11 +654,9 @@ class BaoModel {
|
|
|
659
654
|
|
|
660
655
|
if (field instanceof RelatedFieldClass && this[fieldName]) {
|
|
661
656
|
promises.push(
|
|
662
|
-
this._loadRelatedField(fieldName, field
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
},
|
|
666
|
-
),
|
|
657
|
+
this._loadRelatedField(fieldName, field).then((instance) => {
|
|
658
|
+
this._relatedObjects[fieldName] = instance;
|
|
659
|
+
}),
|
|
667
660
|
);
|
|
668
661
|
}
|
|
669
662
|
}
|
|
@@ -672,7 +665,7 @@ class BaoModel {
|
|
|
672
665
|
return this;
|
|
673
666
|
}
|
|
674
667
|
|
|
675
|
-
async _loadRelatedField(fieldName, field
|
|
668
|
+
async _loadRelatedField(fieldName, field) {
|
|
676
669
|
const value = this[fieldName];
|
|
677
670
|
if (!value) return null;
|
|
678
671
|
|
|
@@ -683,7 +676,7 @@ class BaoModel {
|
|
|
683
676
|
}
|
|
684
677
|
|
|
685
678
|
// Load the instance and track its capacity
|
|
686
|
-
const relatedInstance = await ModelClass.find(value
|
|
679
|
+
const relatedInstance = await ModelClass.find(value);
|
|
687
680
|
|
|
688
681
|
return relatedInstance;
|
|
689
682
|
}
|
|
@@ -711,14 +704,9 @@ class BaoModel {
|
|
|
711
704
|
* to find an object.
|
|
712
705
|
* @param {string} constraintName - The name of the unique constraint to use.
|
|
713
706
|
* @param {string} value - The value of the unique constraint.
|
|
714
|
-
* @param {Object} [loaderContext] - Cache context for storing and retrieving items across requests.
|
|
715
707
|
* @returns {Promise<Object>} Returns a promise that resolves to the found item.
|
|
716
708
|
*/
|
|
717
|
-
static async findByUniqueConstraint(
|
|
718
|
-
constraintName,
|
|
719
|
-
value,
|
|
720
|
-
loaderContext = null,
|
|
721
|
-
) {
|
|
709
|
+
static async findByUniqueConstraint(constraintName, value) {
|
|
722
710
|
const constraint = this.uniqueConstraints[constraintName];
|
|
723
711
|
if (!constraint) {
|
|
724
712
|
throw new ConfigurationError(
|
|
@@ -757,7 +745,7 @@ class BaoModel {
|
|
|
757
745
|
return new ObjectNotFound(result.ConsumedCapacity);
|
|
758
746
|
}
|
|
759
747
|
|
|
760
|
-
const item = await this.find(result.Item.relatedId
|
|
748
|
+
const item = await this.find(result.Item.relatedId);
|
|
761
749
|
|
|
762
750
|
if (item.exists()) {
|
|
763
751
|
item._addConsumedCapacity(result.ConsumedCapacity, "read");
|