dynamo-bao 0.2.10 → 0.2.12
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 +32 -0
- package/bin/dynamo-bao-create-table.js +6 -6
- package/package.json +1 -1
- package/src/index.js +10 -10
- package/src/mixins/batch-loading-mixin.js +65 -7
package/README.md
CHANGED
|
@@ -153,6 +153,38 @@ 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`**: Batching is automatically disabled for safety to prevent cross-request interference, with a warning logged. While this ensures request isolation, you'll lose batching efficiency benefits.
|
|
185
|
+
|
|
186
|
+
For production Cloudflare Workers deployments, always use `runWithBatchContext` to get both safety and performance.
|
|
187
|
+
|
|
156
188
|
### Iterating over all items
|
|
157
189
|
|
|
158
190
|
DynamoBao makes it easy to iterate over all items in a model, which is useful for tasks like data migration, backfills, or reporting.
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
const {
|
|
4
4
|
DynamoDBClient,
|
|
5
5
|
CreateTableCommand,
|
|
6
6
|
ListTablesCommand,
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
7
|
+
} = require("../src/dynamodb-client.js");
|
|
8
|
+
const readline = require("readline");
|
|
9
|
+
const fs = require("fs");
|
|
10
|
+
const path = require("path");
|
|
11
11
|
|
|
12
12
|
// Create DynamoDB client at the top level
|
|
13
13
|
const client = new DynamoDBClient();
|
|
@@ -51,7 +51,7 @@ const prompt = (query) => {
|
|
|
51
51
|
};
|
|
52
52
|
|
|
53
53
|
async function writeConfigFile(tableName) {
|
|
54
|
-
const region = client.region || process.env.AWS_REGION ||
|
|
54
|
+
const region = client.region || process.env.AWS_REGION || "us-east-1";
|
|
55
55
|
const configContent = `const path = require("path");
|
|
56
56
|
|
|
57
57
|
const config = {
|
package/package.json
CHANGED
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.",
|
|
@@ -212,6 +209,9 @@ const firstExport = {
|
|
|
212
209
|
// Tenant management
|
|
213
210
|
TenantContext,
|
|
214
211
|
|
|
212
|
+
// Batch context for Cloudflare Workers
|
|
213
|
+
runWithBatchContext,
|
|
214
|
+
|
|
215
215
|
// Configurations
|
|
216
216
|
PrimaryKeyConfig,
|
|
217
217
|
IndexConfig,
|
|
@@ -3,18 +3,53 @@ const { ObjectNotFound } = require("../object-not-found");
|
|
|
3
3
|
const { pluginManager } = require("../plugin-manager");
|
|
4
4
|
const { BatchGetCommand, GetCommand } = require("../dynamodb-client");
|
|
5
5
|
|
|
6
|
-
//
|
|
7
|
-
|
|
6
|
+
// Import AsyncLocalStorage for request-scoped batching
|
|
7
|
+
let AsyncLocalStorage;
|
|
8
|
+
try {
|
|
9
|
+
AsyncLocalStorage = require("node:async_hooks").AsyncLocalStorage;
|
|
10
|
+
} catch (e) {
|
|
11
|
+
// Fallback for environments without AsyncLocalStorage
|
|
12
|
+
AsyncLocalStorage = null;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// Request-scoped batch context
|
|
16
|
+
const batchContext = AsyncLocalStorage ? new AsyncLocalStorage() : null;
|
|
17
|
+
|
|
18
|
+
// Fallback global state for environments without AsyncLocalStorage (primarily for testing)
|
|
19
|
+
const FALLBACK_BATCH_REQUESTS = new Map(); // testId -> { modelName-delay -> batch }
|
|
20
|
+
|
|
8
21
|
const DEFAULT_BATCH_DELAY_MS = 5;
|
|
9
22
|
const BATCH_REQUEST_TIMEOUT = 10000; // 10 seconds max lifetime for a batch
|
|
10
23
|
|
|
11
24
|
const BatchLoadingMethods = {
|
|
12
25
|
_getBatchRequests() {
|
|
13
|
-
|
|
14
|
-
if (
|
|
15
|
-
|
|
26
|
+
// Try AsyncLocalStorage first, but only if context is already set
|
|
27
|
+
if (batchContext) {
|
|
28
|
+
const context = batchContext.getStore();
|
|
29
|
+
if (context && context.batchRequests) {
|
|
30
|
+
return context.batchRequests;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Fallback to testId-based isolation
|
|
35
|
+
const tenantId = this._tenantId;
|
|
36
|
+
if (tenantId) {
|
|
37
|
+
// Test environment: use tenantId for isolation
|
|
38
|
+
if (!FALLBACK_BATCH_REQUESTS.has(tenantId)) {
|
|
39
|
+
FALLBACK_BATCH_REQUESTS.set(tenantId, new Map());
|
|
40
|
+
}
|
|
41
|
+
return FALLBACK_BATCH_REQUESTS.get(tenantId);
|
|
16
42
|
}
|
|
17
|
-
|
|
43
|
+
|
|
44
|
+
// Production without proper context: disable batching for safety
|
|
45
|
+
// This prevents cross-request interference at the cost of batching efficiency
|
|
46
|
+
logger.warn(
|
|
47
|
+
"No batch context found. Batching is disabled for safety. " +
|
|
48
|
+
"Use runWithBatchContext() in Cloudflare Workers for optimal performance.",
|
|
49
|
+
);
|
|
50
|
+
|
|
51
|
+
// Return a new Map for each call - no batching, but safe
|
|
52
|
+
return new Map();
|
|
18
53
|
},
|
|
19
54
|
|
|
20
55
|
/**
|
|
@@ -328,9 +363,32 @@ const BatchLoadingMethods = {
|
|
|
328
363
|
},
|
|
329
364
|
};
|
|
330
365
|
|
|
366
|
+
/**
|
|
367
|
+
* Initialize batch context for request-scoped batching.
|
|
368
|
+
* This should be called at the beginning of each request in Cloudflare Workers.
|
|
369
|
+
* @param {Function} fn - Function to run within the batch context
|
|
370
|
+
* @returns {*} Result of the function
|
|
371
|
+
*/
|
|
372
|
+
function runWithBatchContext(fn) {
|
|
373
|
+
if (!batchContext) {
|
|
374
|
+
// No AsyncLocalStorage available, just run the function
|
|
375
|
+
return fn();
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
const context = {
|
|
379
|
+
requestId: Date.now().toString(36) + Math.random().toString(36).substr(2),
|
|
380
|
+
batchRequests: new Map(),
|
|
381
|
+
timers: new Set(),
|
|
382
|
+
startTime: Date.now(),
|
|
383
|
+
};
|
|
384
|
+
|
|
385
|
+
return batchContext.run(context, fn);
|
|
386
|
+
}
|
|
387
|
+
|
|
331
388
|
module.exports = {
|
|
332
389
|
BatchLoadingMethods,
|
|
333
|
-
|
|
390
|
+
runWithBatchContext,
|
|
391
|
+
FALLBACK_BATCH_REQUESTS,
|
|
334
392
|
DEFAULT_BATCH_DELAY_MS,
|
|
335
393
|
BATCH_REQUEST_TIMEOUT,
|
|
336
394
|
};
|