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/CHANGELOG.md +169 -1
- package/README.md +32 -3
- package/bin/bao-create-table.js +0 -0
- package/bin/bao-rebuild-search-text.js +40 -14
- package/bin/dynamo-bao-update-table.js +20 -3
- package/bin/generators/manifest.js +1 -1
- package/bin/generators/model.js +7 -8
- package/bin/lib/confirm.js +24 -0
- package/bin/lib/process-models.js +73 -2
- package/package.json +17 -3
- package/src/config.js +21 -11
- package/src/constants.js +4 -0
- package/src/exceptions.js +17 -0
- package/src/fields.js +55 -1
- package/src/filter-expression.js +46 -17
- package/src/index.js +4 -3
- package/src/key-condition.js +2 -2
- package/src/mixins/batch-loading-mixin.js +8 -0
- package/src/mixins/mutation-mixin.js +80 -10
- package/src/mixins/query-mixin.js +4 -1
- package/src/mixins/unique-constraint-mixin.js +1 -1
- package/src/model-manager.js +33 -4
- package/src/model.js +107 -11
- package/src/remote/client.js +219 -0
- package/src/remote/codec.js +234 -0
- package/src/remote/context.js +299 -0
- package/src/remote/executor.js +400 -0
- package/src/remote/index.d.ts +413 -0
- package/src/remote/index.js +36 -0
- package/src/remote/json.js +104 -0
- package/src/remote/procedures.js +195 -0
- package/src/tenant-context.js +52 -26
- package/src/utils/search-text.js +1 -1
- package/bin/chokidar-test.js +0 -60
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Named, versioned procedures and the registry the executor serves them from.
|
|
3
|
+
* @module remote/procedures
|
|
4
|
+
*/
|
|
5
|
+
const { findNonJson, deepFreeze, jsonClone } = require("./json");
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* What a resend after an `unknown` outcome does. Frozen vocabulary: see
|
|
9
|
+
* tutorials/11-remote-procedures.md.
|
|
10
|
+
* - `idempotent`: no writes, or writes whose repeat has no further effect.
|
|
11
|
+
* - `conditional`: every write is a guarded state transition, so a repeat
|
|
12
|
+
* fails its condition and the procedure reports that.
|
|
13
|
+
* - `needs-ledger`: an unguarded write or a counter; the procedure keeps its
|
|
14
|
+
* own marker keyed by `ctx.operationId`. The client never resends it.
|
|
15
|
+
*/
|
|
16
|
+
const REPLAY_CLASSES = Object.freeze(["idempotent", "conditional", "needs-ledger"]);
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Which model sets a procedure receives. `app`: `ctx.models` only. `admin` and
|
|
20
|
+
* `both`: also `ctx.adminModels`, bound to the admin partition the context
|
|
21
|
+
* resolver names.
|
|
22
|
+
*/
|
|
23
|
+
const SCOPES = Object.freeze(["app", "admin", "both"]);
|
|
24
|
+
|
|
25
|
+
const NAME = /^[A-Za-z][A-Za-z0-9_.-]*$/;
|
|
26
|
+
const ID = /^([A-Za-z][A-Za-z0-9_.-]*)@([1-9][0-9]*)$/;
|
|
27
|
+
const DESCRIPTOR_KEYS = new Set(["name", "version", "scope", "replay", "args", "run"]);
|
|
28
|
+
const DESCRIPTORS = new WeakSet();
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Define a procedure. The returned descriptor is what the registry serves and
|
|
32
|
+
* what a caller passes to `remote(...).call`.
|
|
33
|
+
* @param {Object} spec
|
|
34
|
+
* @param {string} spec.name - Dotted name, e.g. "rateLimit.reserve". No "@".
|
|
35
|
+
* @param {number} spec.version - Positive integer. Bump it when args or the
|
|
36
|
+
* result shape change; keep the previous descriptor registered for one
|
|
37
|
+
* deploy so callers built against it keep working.
|
|
38
|
+
* @param {"app"|"admin"|"both"} spec.scope
|
|
39
|
+
* @param {"idempotent"|"conditional"|"needs-ledger"} spec.replay
|
|
40
|
+
* @param {Object} [spec.args] - JSON description of the arguments (for
|
|
41
|
+
* example a JSON Schema). Not interpreted; published by `manifest()`.
|
|
42
|
+
* @param {function(Object, *): Promise<*>} spec.run
|
|
43
|
+
* @returns {Readonly<Object>} The descriptor.
|
|
44
|
+
*/
|
|
45
|
+
function defineProcedure(spec) {
|
|
46
|
+
if (!spec || typeof spec !== "object") {
|
|
47
|
+
throw new TypeError("defineProcedure needs a descriptor object");
|
|
48
|
+
}
|
|
49
|
+
for (const key of Object.keys(spec)) {
|
|
50
|
+
if (!DESCRIPTOR_KEYS.has(key)) {
|
|
51
|
+
throw new TypeError(
|
|
52
|
+
`defineProcedure: unknown key "${key}"; expected ${[...DESCRIPTOR_KEYS].join(", ")}`,
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
const { name, version, scope, replay, args = null, run } = spec;
|
|
57
|
+
if (typeof name !== "string" || !NAME.test(name)) {
|
|
58
|
+
throw new TypeError(
|
|
59
|
+
`defineProcedure: name ${JSON.stringify(name)} must start with a letter and contain only letters, digits, ".", "_" or "-"`,
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
if (!Number.isInteger(version) || version < 1) {
|
|
63
|
+
throw new TypeError(`defineProcedure ${name}: version must be a positive integer`);
|
|
64
|
+
}
|
|
65
|
+
if (!SCOPES.includes(scope)) {
|
|
66
|
+
throw new TypeError(
|
|
67
|
+
`defineProcedure ${name}@${version}: scope must be one of ${SCOPES.join(", ")}`,
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
if (!REPLAY_CLASSES.includes(replay)) {
|
|
71
|
+
throw new TypeError(
|
|
72
|
+
`defineProcedure ${name}@${version}: replay class must be one of ${REPLAY_CLASSES.join(", ")}`,
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
if (typeof run !== "function") {
|
|
76
|
+
throw new TypeError(`defineProcedure ${name}@${version}: run must be a function`);
|
|
77
|
+
}
|
|
78
|
+
const bad = args === null ? null : findNonJson(args);
|
|
79
|
+
if (bad || (args !== null && typeof args !== "object")) {
|
|
80
|
+
throw new TypeError(
|
|
81
|
+
`defineProcedure ${name}@${version}: args must be a plain JSON description${bad ? ` (found ${bad.found} at ${bad.path})` : ""}`,
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
const descriptor = Object.freeze({
|
|
85
|
+
id: `${name}@${version}`,
|
|
86
|
+
name,
|
|
87
|
+
version,
|
|
88
|
+
scope,
|
|
89
|
+
replay,
|
|
90
|
+
args: args === null ? null : deepFreeze(jsonClone(args)),
|
|
91
|
+
run,
|
|
92
|
+
});
|
|
93
|
+
DESCRIPTORS.add(descriptor);
|
|
94
|
+
return descriptor;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function isDescriptor(value) {
|
|
98
|
+
return DESCRIPTORS.has(value);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* The set of procedures one deployment serves.
|
|
103
|
+
*
|
|
104
|
+
* Previous-version serving is the application's obligation: the registry
|
|
105
|
+
* serves `name@1` beside `name@2` only while both descriptors are passed in.
|
|
106
|
+
* Keep the previous version registered for one deploy of the callers, then
|
|
107
|
+
* drop it. Versions of one name must be contiguous; a gap is refused so a
|
|
108
|
+
* dropped middle version can't go unnoticed.
|
|
109
|
+
*/
|
|
110
|
+
class ProcedureRegistry {
|
|
111
|
+
/** @param {Object[]} descriptors - Results of defineProcedure. */
|
|
112
|
+
constructor(descriptors) {
|
|
113
|
+
if (!Array.isArray(descriptors)) {
|
|
114
|
+
throw new TypeError("ProcedureRegistry needs an array of descriptors");
|
|
115
|
+
}
|
|
116
|
+
const byId = new Map();
|
|
117
|
+
const byName = new Map();
|
|
118
|
+
for (const d of descriptors) {
|
|
119
|
+
if (!isDescriptor(d)) {
|
|
120
|
+
throw new TypeError(
|
|
121
|
+
"ProcedureRegistry: every entry must come from defineProcedure",
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
if (byId.has(d.id)) {
|
|
125
|
+
throw new Error(`ProcedureRegistry: ${d.id} is registered twice`);
|
|
126
|
+
}
|
|
127
|
+
byId.set(d.id, d);
|
|
128
|
+
if (!byName.has(d.name)) byName.set(d.name, []);
|
|
129
|
+
byName.get(d.name).push(d.version);
|
|
130
|
+
}
|
|
131
|
+
for (const [name, versions] of byName) {
|
|
132
|
+
versions.sort((a, b) => a - b);
|
|
133
|
+
for (let i = 1; i < versions.length; i++) {
|
|
134
|
+
if (versions[i] !== versions[i - 1] + 1) {
|
|
135
|
+
throw new Error(
|
|
136
|
+
`ProcedureRegistry: version gap for ${name}: has ${versions.join(", ")}, missing ${versions[i - 1] + 1}`,
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
Object.freeze(versions);
|
|
141
|
+
}
|
|
142
|
+
this._byId = byId;
|
|
143
|
+
this._byName = byName;
|
|
144
|
+
Object.freeze(this);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** @returns {Object|undefined} The descriptor for "name@version". */
|
|
148
|
+
get(id) {
|
|
149
|
+
if (typeof id !== "string" || !ID.test(id)) return undefined;
|
|
150
|
+
return this._byId.get(id);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
has(id) {
|
|
154
|
+
return this.get(id) !== undefined;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** @returns {number[]} Registered versions of `name`, ascending. */
|
|
158
|
+
versions(name) {
|
|
159
|
+
return [...(this._byName.get(name) || [])];
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** @returns {Object|undefined} The highest registered version of `name`. */
|
|
163
|
+
latest(name) {
|
|
164
|
+
const versions = this._byName.get(name);
|
|
165
|
+
return versions ? this._byId.get(`${name}@${versions[versions.length - 1]}`) : undefined;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Plain-JSON listing of every registered procedure, sorted by id, for a
|
|
170
|
+
* build step that publishes argument schemas across bundles.
|
|
171
|
+
* @returns {Array<{id: string, name: string, version: number, scope: string, replay: string, args: ?Object}>}
|
|
172
|
+
*/
|
|
173
|
+
manifest() {
|
|
174
|
+
return [...this._byId.values()]
|
|
175
|
+
.sort((a, b) =>
|
|
176
|
+
a.name === b.name ? a.version - b.version : a.name < b.name ? -1 : 1,
|
|
177
|
+
)
|
|
178
|
+
.map(({ id, name, version, scope, replay, args }) => ({
|
|
179
|
+
id,
|
|
180
|
+
name,
|
|
181
|
+
version,
|
|
182
|
+
scope,
|
|
183
|
+
replay,
|
|
184
|
+
args: args === null ? null : jsonClone(args),
|
|
185
|
+
}));
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
module.exports = {
|
|
190
|
+
defineProcedure,
|
|
191
|
+
ProcedureRegistry,
|
|
192
|
+
REPLAY_CLASSES,
|
|
193
|
+
SCOPES,
|
|
194
|
+
isDescriptor,
|
|
195
|
+
};
|
package/src/tenant-context.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
*
|
|
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
|
-
*
|
|
45
|
-
*
|
|
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
|
-
|
|
56
|
-
if (
|
|
57
|
-
return
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
125
|
-
*
|
|
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
|
-
|
|
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
|
|
package/src/utils/search-text.js
CHANGED
|
@@ -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 (`:
|
|
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 = [];
|
package/bin/chokidar-test.js
DELETED
|
@@ -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
|
-
});
|