dynamo-bao 0.9.0 → 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 +88 -1
- package/README.md +29 -0
- package/bin/bao-create-table.js +0 -0
- package/package.json +16 -3
- package/src/exceptions.js +17 -0
- package/src/model.js +50 -0
- 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/CHANGELOG.md
CHANGED
|
@@ -9,6 +9,92 @@ Each version heading links to the tag that was published to npm. Entries before
|
|
|
9
9
|
|
|
10
10
|
## [Unreleased]
|
|
11
11
|
|
|
12
|
+
## [0.10.0] - 2026-11-07
|
|
13
|
+
|
|
14
|
+
Semver minor (0.10.0). Adds the `dynamo-bao/remote` entry point; nothing
|
|
15
|
+
existing changes behavior.
|
|
16
|
+
|
|
17
|
+
**Key format: no key code changed.** Primary keys, GSI keys, unique
|
|
18
|
+
constraint keys, iteration keys and tenant prefixes are built exactly as in
|
|
19
|
+
0.9.0. Outside `src/remote/`, the only source changes are additions to
|
|
20
|
+
`src/model.js` (`fromRemote`, `isDetached`, and a guard at the top of
|
|
21
|
+
`save`, `loadRelatedData` and `getOrLoadRelatedField` that only fires on
|
|
22
|
+
instances `fromRemote` created) and one new exception class. The root
|
|
23
|
+
`dynamo-bao` entry exports the same names as before.
|
|
24
|
+
|
|
25
|
+
### Added
|
|
26
|
+
|
|
27
|
+
- **`dynamo-bao/remote`**, a new entry point (`require("dynamo-bao/remote")`
|
|
28
|
+
or `import ... from "dynamo-bao/remote"`) for running named, versioned
|
|
29
|
+
procedures next to DynamoDB and calling them from far away in one round
|
|
30
|
+
trip. See `tutorials/11-remote-procedures.md`, which freezes
|
|
31
|
+
`ProcedureContext`, `Actor`, the outcome tags (`ok` / `error` /
|
|
32
|
+
`unknown`) and the replay classes (`idempotent` / `conditional` /
|
|
33
|
+
`needs-ledger`). Exports:
|
|
34
|
+
- `defineProcedure`, `ProcedureRegistry` (with `get`, `has`, `versions`,
|
|
35
|
+
`latest`, `manifest`), `REPLAY_CLASSES`, `SCOPES`: registration by name,
|
|
36
|
+
version, scope and replay class. A procedure without a replay class or
|
|
37
|
+
scope is refused, and so is a version gap. Previous-version serving is
|
|
38
|
+
the application's obligation: the registry serves `@1` beside `@2` while
|
|
39
|
+
both descriptors are registered.
|
|
40
|
+
- `createContext`, `fresh`, `bindModelsToTenant`: the procedure context
|
|
41
|
+
(models, admin models bound to the resolver's admin partition, which is
|
|
42
|
+
required for `admin` and `both` scopes, tenant as
|
|
43
|
+
a value, actor passed through, request and operation ids, a logger bound
|
|
44
|
+
to request id and tenant, `now()`, `fresh` with capacity merge and
|
|
45
|
+
outer-cache priming, `waitUntil` with a 30 s cap, frozen config).
|
|
46
|
+
- `encodeValue`, `decodeRow`, `CodecError`: the wire codec, covering every
|
|
47
|
+
field type in `fields.js`. Dates and TTLs travel as epoch milliseconds,
|
|
48
|
+
`BinaryField` as `{ $binary }`, `StringSetField` as an array; any
|
|
49
|
+
non-JSON value is refused with its path.
|
|
50
|
+
- `createExecutor({ procedures, context, ingress, budget, region,
|
|
51
|
+
plainReturns })`: the fetch handler. Envelope validation, unknown
|
|
52
|
+
procedure and scope refusal, the actor check (the actor's `appId` must
|
|
53
|
+
equal the call tenant; no other actor field is read), concurrent and
|
|
54
|
+
isolated calls, tagged outcomes with capacity and duration, placement
|
|
55
|
+
echo, budget and ingress refusal, `drain()`. An error raised after `run`
|
|
56
|
+
returned (encoding its result, or `ResponseTooLarge`) carries
|
|
57
|
+
`executed: true`; an executor refusal carries `refused: true`.
|
|
58
|
+
- `remote(transport, { actor, retries, headers })` with `call` and
|
|
59
|
+
`batch`, and `inProcess(executor, { env, headers, ctx })`: `unknown` on
|
|
60
|
+
transport failure, no automatic resend of `needs-ledger` calls, reported
|
|
61
|
+
capacity added to the caller's batch context, and the executor's
|
|
62
|
+
`placement` (`{ colo, region }`) on each `ok` and `error` outcome.
|
|
63
|
+
- `DetachedInstanceError` (also in `exceptions`).
|
|
64
|
+
- **`Model.fromRemote(row)`** hydrates a detached, read-only instance from an
|
|
65
|
+
encoded row, and **`instance.isDetached()`** reports it. On a detached
|
|
66
|
+
instance `save`, `update`, `delete`, `loadRelatedData` and
|
|
67
|
+
`getOrLoadRelatedField` throw `DetachedInstanceError`.
|
|
68
|
+
- **TypeScript declarations** for the entry point in `src/remote/index.d.ts`
|
|
69
|
+
(`ProcedureContext`, `ContextResolver`, `Actor`, the descriptor, outcome
|
|
70
|
+
and replay types, and every export). A caller's `ok` is typed as it
|
|
71
|
+
arrives (`WireResult<Result>`: model instances as `EncodedRow`), and
|
|
72
|
+
`defineProcedure` is a type error when its result can hold a `Date`,
|
|
73
|
+
`Map`, `Set`, function or other non-JSON value. Resolvable with `moduleResolution`
|
|
74
|
+
`node`, `node16` and `bundler`. The package `exports` map gains
|
|
75
|
+
`./remote`, and `typesVersions` maps it for `moduleResolution: node`.
|
|
76
|
+
- **`examples/cloudflare-remote-executor/`**: a data worker with the
|
|
77
|
+
placement line, the `DATA` self-binding and the ingress secret, tested in
|
|
78
|
+
workerd with `@cloudflare/vitest-pool-workers` (`npm run test:workerd`).
|
|
79
|
+
- `tutorials/11-remote-procedures.md`.
|
|
80
|
+
|
|
81
|
+
### Codec refusals
|
|
82
|
+
|
|
83
|
+
The codec refuses one model shape: a **custom field whose stored value is
|
|
84
|
+
not JSON** (for example a custom field whose `toDy` returns a `Map`). Such a
|
|
85
|
+
row throws `CodecError` naming the model and field. Every built-in field
|
|
86
|
+
type encodes. A `Date` anywhere in a procedure result is refused; return
|
|
87
|
+
epoch milliseconds.
|
|
88
|
+
|
|
89
|
+
### For consumers adopting the executor
|
|
90
|
+
|
|
91
|
+
The Spike 6 audit's consumer-facing lists (the callers that cross the
|
|
92
|
+
boundary with a `Date` or a model instance, the memberships-cache
|
|
93
|
+
invalidation sites, and the activity-gate helpers) were handed over on
|
|
94
|
+
issue #18 on 2026-11-07:
|
|
95
|
+
https://github.com/aag1024/dynamo-bao/issues/18#issuecomment-6703195120
|
|
96
|
+
|
|
97
|
+
|
|
12
98
|
## [0.9.0] - 2026-10-28
|
|
13
99
|
|
|
14
100
|
### Security
|
|
@@ -567,7 +653,8 @@ Initial release: single-table models with fields, GSIs, unique constraints,
|
|
|
567
653
|
related fields, counters, TTL, filters, pagination, batch loading, hooks,
|
|
568
654
|
YAML codegen and a table creation tool.
|
|
569
655
|
|
|
570
|
-
[Unreleased]: https://github.com/aag1024/dynamo-bao/compare/v0.
|
|
656
|
+
[Unreleased]: https://github.com/aag1024/dynamo-bao/compare/v0.10.0...HEAD
|
|
657
|
+
[0.10.0]: https://github.com/aag1024/dynamo-bao/compare/v0.9.0...v0.10.0
|
|
571
658
|
[0.9.0]: https://github.com/aag1024/dynamo-bao/compare/v0.8.2...v0.9.0
|
|
572
659
|
[0.8.2]: https://github.com/aag1024/dynamo-bao/compare/v0.8.1...v0.8.2
|
|
573
660
|
[0.8.1]: https://github.com/aag1024/dynamo-bao/compare/v0.8.0...v0.8.1
|
package/README.md
CHANGED
|
@@ -190,6 +190,35 @@ export default {
|
|
|
190
190
|
|
|
191
191
|
For production Cloudflare Workers deployments, always use `runWithBatchContext` to get both safety and optimal performance.
|
|
192
192
|
|
|
193
|
+
### Remote Procedures (`dynamo-bao/remote`)
|
|
194
|
+
|
|
195
|
+
When code runs far from the table (Durable Objects near users, Workflows), each DynamoDB call pays a cross-region round trip. `dynamo-bao/remote` lets you register named, versioned procedures on a Worker placed next to DynamoDB and call them in one trip:
|
|
196
|
+
|
|
197
|
+
```javascript
|
|
198
|
+
const { defineProcedure, ProcedureRegistry, createExecutor, remote } = require("dynamo-bao/remote");
|
|
199
|
+
|
|
200
|
+
const getUser = defineProcedure({
|
|
201
|
+
name: "user.get", version: 1, scope: "app", replay: "idempotent",
|
|
202
|
+
async run(ctx, { userId }) {
|
|
203
|
+
const user = await ctx.models.User.find(userId);
|
|
204
|
+
return user.exists() ? { name: user.name } : null;
|
|
205
|
+
},
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
// Data worker, next to DynamoDB:
|
|
209
|
+
const executor = createExecutor({
|
|
210
|
+
procedures: new ProcedureRegistry([getUser]),
|
|
211
|
+
context: (call, env) => ({ models: getModels(env) }),
|
|
212
|
+
ingress: (request, env) => request.headers.get("x-data-binding") === env.DATA_BINDING_SECRET,
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
// Caller, anywhere:
|
|
216
|
+
const r = await remote(env.DATA, { actor, headers }).call(getUser, { userId }, { tenant: appId });
|
|
217
|
+
if ("ok" in r) console.log(r.ok.name);
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
See [tutorial 11](tutorials/11-remote-procedures.md) for the contract (context, actor, outcomes, replay classes) and [`examples/cloudflare-remote-executor/`](examples/cloudflare-remote-executor/) for a complete Worker. TypeScript declarations ship with the entry point.
|
|
221
|
+
|
|
193
222
|
### Batch Context Configuration
|
|
194
223
|
|
|
195
224
|
DynamoBao provides flexible batch context behavior that can be configured based on your application's needs:
|
package/bin/bao-create-table.js
CHANGED
|
File without changes
|
package/package.json
CHANGED
|
@@ -1,19 +1,31 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dynamo-bao",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"description": "Simple powerful data modeling primitives for DynamoDB in JavaScript.",
|
|
5
5
|
"main": "src/index.js",
|
|
6
6
|
"exports": {
|
|
7
7
|
".": "./src/index.js",
|
|
8
|
+
"./remote": {
|
|
9
|
+
"types": "./src/remote/index.d.ts",
|
|
10
|
+
"default": "./src/remote/index.js"
|
|
11
|
+
},
|
|
8
12
|
"./src/*": "./src/*",
|
|
9
13
|
"./package.json": "./package.json"
|
|
10
14
|
},
|
|
15
|
+
"typesVersions": {
|
|
16
|
+
"*": {
|
|
17
|
+
"remote": [
|
|
18
|
+
"src/remote/index.d.ts"
|
|
19
|
+
]
|
|
20
|
+
}
|
|
21
|
+
},
|
|
11
22
|
"scripts": {
|
|
12
23
|
"test": "LOG_LEVEL=OFF jest",
|
|
13
24
|
"test:debug": "LOG_LEVEL=DEBUG jest",
|
|
14
25
|
"create-table": "node bin/dynamo-bao-create-table.js",
|
|
15
26
|
"watch": "node bin/watch.js",
|
|
16
|
-
"docs": "jsdoc -c jsdoc.json --verbose"
|
|
27
|
+
"docs": "jsdoc -c jsdoc.json --verbose",
|
|
28
|
+
"test:workerd": "npm --prefix examples/cloudflare-remote-executor install --no-audit --no-fund && npm --prefix examples/cloudflare-remote-executor test"
|
|
17
29
|
},
|
|
18
30
|
"files": [
|
|
19
31
|
"bin/",
|
|
@@ -51,7 +63,8 @@
|
|
|
51
63
|
"gh-pages": "^6.2.0",
|
|
52
64
|
"jest": "^29.7.0",
|
|
53
65
|
"jsdoc": "^4.0.4",
|
|
54
|
-
"prettier": "3.4.2"
|
|
66
|
+
"prettier": "3.4.2",
|
|
67
|
+
"typescript": "^5.9.3"
|
|
55
68
|
},
|
|
56
69
|
"bin": {
|
|
57
70
|
"bao-init": "bin/dynamo-bao-create-table.js",
|
package/src/exceptions.js
CHANGED
|
@@ -86,6 +86,22 @@ class DataFormatError extends BaoError {
|
|
|
86
86
|
}
|
|
87
87
|
}
|
|
88
88
|
|
|
89
|
+
/**
|
|
90
|
+
* Thrown by a persistence method called on an instance hydrated with
|
|
91
|
+
* `Model.fromRemote()`. Such an instance is a read-only view of a row a
|
|
92
|
+
* remote procedure returned; writes and related loads belong in a procedure.
|
|
93
|
+
*/
|
|
94
|
+
class DetachedInstanceError extends BaoError {
|
|
95
|
+
constructor(modelName, method) {
|
|
96
|
+
super(
|
|
97
|
+
`${modelName}.${method}() was called on a detached instance (hydrated with fromRemote). ` +
|
|
98
|
+
"Detached rows are read-only; do the write or load in a procedure and call it with remote(...).call().",
|
|
99
|
+
);
|
|
100
|
+
this.modelName = modelName;
|
|
101
|
+
this.method = method;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
89
105
|
module.exports = {
|
|
90
106
|
BaoError,
|
|
91
107
|
ConfigurationError,
|
|
@@ -94,4 +110,5 @@ module.exports = {
|
|
|
94
110
|
ItemNotFoundError,
|
|
95
111
|
ConditionalError,
|
|
96
112
|
DataFormatError,
|
|
113
|
+
DetachedInstanceError,
|
|
97
114
|
};
|
package/src/model.js
CHANGED
|
@@ -38,6 +38,16 @@ const HYDRATE = Symbol("dynamo-bao.hydrate");
|
|
|
38
38
|
// prototype; holds the `fields` object they were built from.
|
|
39
39
|
const FIELD_ACCESSORS_FOR = Symbol("dynamo-bao.fieldAccessorsFor");
|
|
40
40
|
|
|
41
|
+
// Set on instances hydrated by fromRemote(): read-only views of a row a remote
|
|
42
|
+
// procedure returned. Persistence methods refuse to run on them.
|
|
43
|
+
const DETACHED = Symbol("dynamo-bao.detached");
|
|
44
|
+
|
|
45
|
+
function assertAttached(instance, method) {
|
|
46
|
+
if (instance[DETACHED]) {
|
|
47
|
+
throw new DetachedInstanceError(instance.constructor.name, method);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
41
51
|
// System attributes (_pk, _sk, GSI keys, ...) are plain strings with no
|
|
42
52
|
// per-model options, so one shared field definition serves them all.
|
|
43
53
|
const SYSTEM_STRING_FIELD = StringField();
|
|
@@ -53,6 +63,7 @@ const {
|
|
|
53
63
|
} = require("./constants");
|
|
54
64
|
const {
|
|
55
65
|
ConfigurationError,
|
|
66
|
+
DetachedInstanceError,
|
|
56
67
|
ValidationError,
|
|
57
68
|
QueryError,
|
|
58
69
|
DataFormatError,
|
|
@@ -1199,6 +1210,42 @@ class BaoModel {
|
|
|
1199
1210
|
return newObj;
|
|
1200
1211
|
}
|
|
1201
1212
|
|
|
1213
|
+
/**
|
|
1214
|
+
* @description
|
|
1215
|
+
* Hydrate a detached, read-only instance from a row a remote procedure
|
|
1216
|
+
* returned (`{ $model, data }`, as produced by `encodeValue` in
|
|
1217
|
+
* `dynamo-bao/remote`). Field getters work as on a loaded instance;
|
|
1218
|
+
* `save`, `update`, `delete`, `loadRelatedData` and `getOrLoadRelatedField`
|
|
1219
|
+
* throw `DetachedInstanceError`. Static model methods are not guarded.
|
|
1220
|
+
* @param {{ $model: string, data: Object }} encoded - The encoded row.
|
|
1221
|
+
* @returns {BaoModel} A detached instance of this model.
|
|
1222
|
+
*/
|
|
1223
|
+
static fromRemote(encoded) {
|
|
1224
|
+
const { decodeRow } = require("./remote/codec");
|
|
1225
|
+
const instance = this._createFromDyItem(decodeRow(this, encoded));
|
|
1226
|
+
Object.defineProperty(instance, DETACHED, { value: true });
|
|
1227
|
+
// Instances have no update/delete methods (those are static), but a
|
|
1228
|
+
// detached row is the place a caller is most likely to try them.
|
|
1229
|
+
for (const method of ["update", "delete"]) {
|
|
1230
|
+
if (!Object.prototype.hasOwnProperty.call(this.fields, method)) {
|
|
1231
|
+
Object.defineProperty(instance, method, {
|
|
1232
|
+
value: async () => assertAttached(instance, method),
|
|
1233
|
+
enumerable: false,
|
|
1234
|
+
});
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
return instance;
|
|
1238
|
+
}
|
|
1239
|
+
|
|
1240
|
+
/**
|
|
1241
|
+
* @description
|
|
1242
|
+
* Returns true for an instance hydrated with {@link BaoModel.fromRemote}.
|
|
1243
|
+
* @returns {boolean}
|
|
1244
|
+
*/
|
|
1245
|
+
isDetached() {
|
|
1246
|
+
return this[DETACHED] === true;
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1202
1249
|
/**
|
|
1203
1250
|
* @description
|
|
1204
1251
|
* Clear the related cache for a given field.
|
|
@@ -1401,6 +1448,7 @@ class BaoModel {
|
|
|
1401
1448
|
* @returns {Promise<Object>} Returns a promise that resolves to the updated item.
|
|
1402
1449
|
*/
|
|
1403
1450
|
async save(options = {}) {
|
|
1451
|
+
assertAttached(this, "save");
|
|
1404
1452
|
const { forceReindex = false, ...otherOptions } = options;
|
|
1405
1453
|
|
|
1406
1454
|
if (!forceReindex && !this.hasChanges() && this.isLoaded()) {
|
|
@@ -1447,6 +1495,7 @@ class BaoModel {
|
|
|
1447
1495
|
* @returns {Promise<Object>} Returns a promise that resolves to the loaded item.
|
|
1448
1496
|
*/
|
|
1449
1497
|
async getOrLoadRelatedField(fieldName) {
|
|
1498
|
+
assertAttached(this, "getOrLoadRelatedField");
|
|
1450
1499
|
if (this._relatedObjects[fieldName]) {
|
|
1451
1500
|
return this._relatedObjects[fieldName];
|
|
1452
1501
|
}
|
|
@@ -1474,6 +1523,7 @@ class BaoModel {
|
|
|
1474
1523
|
* @returns {Promise<Object>} Returns a promise that resolves to the loaded items and their consumed capacity
|
|
1475
1524
|
*/
|
|
1476
1525
|
async loadRelatedData(fieldNames = null) {
|
|
1526
|
+
assertAttached(this, "loadRelatedData");
|
|
1477
1527
|
const promises = [];
|
|
1478
1528
|
|
|
1479
1529
|
for (const [fieldName, field] of Object.entries(this.constructor.fields)) {
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The caller side: post envelopes to an executor and get tagged outcomes.
|
|
3
|
+
* @module remote/client
|
|
4
|
+
*/
|
|
5
|
+
const { ulid } = require("ulid");
|
|
6
|
+
const { encodeValue } = require("./codec");
|
|
7
|
+
const { isPlainObject } = require("./json");
|
|
8
|
+
const { REPLAY_CLASSES, SCOPES } = require("./procedures");
|
|
9
|
+
const { _accumulateCapacityToContext } = require("../mixins/batch-loading-mixin");
|
|
10
|
+
|
|
11
|
+
const DEFAULT_URL = "https://dynamo-bao.executor/_data/call";
|
|
12
|
+
|
|
13
|
+
function assertDescriptor(procedure) {
|
|
14
|
+
if (
|
|
15
|
+
!procedure ||
|
|
16
|
+
typeof procedure.id !== "string" ||
|
|
17
|
+
!REPLAY_CLASSES.includes(procedure.replay) ||
|
|
18
|
+
!SCOPES.includes(procedure.scope)
|
|
19
|
+
) {
|
|
20
|
+
throw new TypeError(
|
|
21
|
+
"remote: the first argument must be a procedure descriptor from defineProcedure",
|
|
22
|
+
);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function addCapacity(capacity) {
|
|
27
|
+
if (!capacity) return;
|
|
28
|
+
if (typeof capacity.read === "number") _accumulateCapacityToContext(capacity.read, "read");
|
|
29
|
+
if (typeof capacity.write === "number") _accumulateCapacityToContext(capacity.write, "write");
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Wrap a transport as a client.
|
|
34
|
+
* @param {{fetch: function(Request): Promise<Response>}} transport - A
|
|
35
|
+
* service binding (`env.DATA`), `inProcess(executor)`, or anything with a
|
|
36
|
+
* compatible `fetch`.
|
|
37
|
+
* @param {Object} [options]
|
|
38
|
+
* @param {Object} [options.actor] - Default actor for every call.
|
|
39
|
+
* @param {number} [options.retries=0] - Resends after a transport failure,
|
|
40
|
+
* for envelopes whose calls are all `idempotent` or `conditional`. A
|
|
41
|
+
* `needs-ledger` call is never resent; its caller gets `unknown`.
|
|
42
|
+
* @param {string} [options.url] - Request URL; only the path matters to a
|
|
43
|
+
* service binding. Defaults to a URL ending in `/_data/call`.
|
|
44
|
+
* @param {Object<string,string>} [options.headers] - Extra request headers,
|
|
45
|
+
* e.g. the binding secret the executor's ingress check expects.
|
|
46
|
+
*/
|
|
47
|
+
function remote(transport, options = {}) {
|
|
48
|
+
if (!transport || typeof transport.fetch !== "function") {
|
|
49
|
+
throw new TypeError("remote: the transport must have a fetch(request) method");
|
|
50
|
+
}
|
|
51
|
+
const { actor: defaultActor, retries = 0, url = DEFAULT_URL, headers = {} } = options;
|
|
52
|
+
|
|
53
|
+
async function send(entries, { operationId = ulid(), requestId } = {}) {
|
|
54
|
+
const calls = entries.map((e) => {
|
|
55
|
+
const call = {
|
|
56
|
+
id: e.id,
|
|
57
|
+
proc: e.procedure.id,
|
|
58
|
+
tenant: e.tenant,
|
|
59
|
+
scope: e.procedure.scope,
|
|
60
|
+
args: encodeValue(e.args === undefined ? null : e.args),
|
|
61
|
+
};
|
|
62
|
+
if (e.actor !== undefined) call.actor = e.actor;
|
|
63
|
+
return call;
|
|
64
|
+
});
|
|
65
|
+
const envelope = { v: 1, operationId };
|
|
66
|
+
if (requestId !== undefined) envelope.requestId = requestId;
|
|
67
|
+
if (defaultActor !== undefined) envelope.actor = defaultActor;
|
|
68
|
+
envelope.calls = calls;
|
|
69
|
+
const body = JSON.stringify(envelope);
|
|
70
|
+
const resendable = entries.every((e) => e.procedure.replay !== "needs-ledger");
|
|
71
|
+
|
|
72
|
+
const unknownAll = (reason) =>
|
|
73
|
+
Object.fromEntries(entries.map((e) => [e.id, { unknown: true, reason }]));
|
|
74
|
+
|
|
75
|
+
let attempt = 0;
|
|
76
|
+
for (;;) {
|
|
77
|
+
const result = await attemptOnce(body);
|
|
78
|
+
if (result.transportFailure && resendable && attempt < retries) {
|
|
79
|
+
attempt += 1;
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
if (result.transportFailure) return unknownAll(result.reason);
|
|
83
|
+
if (result.envelopeError) {
|
|
84
|
+
const error = { ...result.envelopeError, refused: true };
|
|
85
|
+
return Object.fromEntries(entries.map((e) => [e.id, { error }]));
|
|
86
|
+
}
|
|
87
|
+
// fromEntries defines own properties, so an id such as "__proto__" keeps its outcome
|
|
88
|
+
return Object.fromEntries(
|
|
89
|
+
entries.map((e) => {
|
|
90
|
+
const outcome = Object.hasOwn(result.calls, e.id) ? result.calls[e.id] : undefined;
|
|
91
|
+
if (!outcome || !("ok" in outcome || "error" in outcome)) {
|
|
92
|
+
return [e.id, { unknown: true, reason: "the response has no outcome for this call" }];
|
|
93
|
+
}
|
|
94
|
+
addCapacity(outcome.capacity);
|
|
95
|
+
return [e.id, result.placement ? { ...outcome, placement: result.placement } : outcome];
|
|
96
|
+
}),
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async function attemptOnce(body) {
|
|
102
|
+
let response;
|
|
103
|
+
try {
|
|
104
|
+
response = await transport.fetch(
|
|
105
|
+
new Request(url, {
|
|
106
|
+
method: "POST",
|
|
107
|
+
headers: { ...headers, "content-type": "application/json" },
|
|
108
|
+
body,
|
|
109
|
+
}),
|
|
110
|
+
);
|
|
111
|
+
} catch (error) {
|
|
112
|
+
return { transportFailure: true, reason: `transport failed: ${error?.message || error}` };
|
|
113
|
+
}
|
|
114
|
+
let parsed;
|
|
115
|
+
try {
|
|
116
|
+
parsed = await response.json();
|
|
117
|
+
} catch {
|
|
118
|
+
return {
|
|
119
|
+
transportFailure: true,
|
|
120
|
+
reason: `HTTP ${response.status} without an executor envelope`,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
if (!isPlainObject(parsed) || parsed.v !== 1) {
|
|
124
|
+
return { transportFailure: true, reason: `HTTP ${response.status} without an executor envelope` };
|
|
125
|
+
}
|
|
126
|
+
if (response.status !== 200) {
|
|
127
|
+
if (isPlainObject(parsed.error) && typeof parsed.error.name === "string") {
|
|
128
|
+
return { envelopeError: parsed.error };
|
|
129
|
+
}
|
|
130
|
+
return { transportFailure: true, reason: `HTTP ${response.status}` };
|
|
131
|
+
}
|
|
132
|
+
if (!isPlainObject(parsed.calls)) {
|
|
133
|
+
return { transportFailure: true, reason: "the response has no calls" };
|
|
134
|
+
}
|
|
135
|
+
const placement = isPlainObject(parsed.placement)
|
|
136
|
+
? { colo: parsed.placement.colo ?? null, region: parsed.placement.region ?? null }
|
|
137
|
+
: undefined;
|
|
138
|
+
return { calls: parsed.calls, placement };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function prepare(entry, i) {
|
|
142
|
+
assertDescriptor(entry.procedure);
|
|
143
|
+
if (typeof entry.tenant !== "string" || entry.tenant === "") {
|
|
144
|
+
throw new TypeError(`remote: call ${entry.procedure.id} needs a tenant`);
|
|
145
|
+
}
|
|
146
|
+
if (entry.actor === undefined && defaultActor === undefined) {
|
|
147
|
+
throw new TypeError(`remote: call ${entry.procedure.id} needs an actor (per call or on remote())`);
|
|
148
|
+
}
|
|
149
|
+
return { ...entry, id: entry.id ?? `c${i}` };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
return Object.freeze({
|
|
153
|
+
/**
|
|
154
|
+
* Call one procedure.
|
|
155
|
+
* @param {Object} procedure - A descriptor from defineProcedure.
|
|
156
|
+
* @param {any} args - JSON arguments; model instances are encoded.
|
|
157
|
+
* @param {{tenant: string, actor: (Object|undefined), operationId: (string|undefined), requestId: (string|undefined)}} options
|
|
158
|
+
* @returns {Promise<Object>} One outcome: `{ok, capacity, ms, placement}`,
|
|
159
|
+
* `{error, capacity?, ms?, placement?}` or `{unknown: true, reason}`.
|
|
160
|
+
* `placement` is the executor's `{colo, region}`.
|
|
161
|
+
*/
|
|
162
|
+
async call(procedure, args, { tenant, actor, operationId, requestId } = {}) {
|
|
163
|
+
const entry = prepare({ id: "c0", procedure, args, tenant, actor }, 0);
|
|
164
|
+
const out = await send([entry], { operationId, requestId });
|
|
165
|
+
return out.c0;
|
|
166
|
+
},
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Call several procedures in one envelope. They run concurrently and in
|
|
170
|
+
* isolation on the executor.
|
|
171
|
+
* @param {Array<Object>} calls - Each `{id?, procedure, args?, tenant, actor?}`.
|
|
172
|
+
* @param {{operationId: (string|undefined), requestId: (string|undefined)}} [options]
|
|
173
|
+
* @returns {Promise<Object<string, Object>>} Outcomes by call id.
|
|
174
|
+
*/
|
|
175
|
+
async batch(calls, options) {
|
|
176
|
+
if (!Array.isArray(calls) || calls.length === 0) {
|
|
177
|
+
throw new TypeError("remote: batch needs a non-empty array of calls");
|
|
178
|
+
}
|
|
179
|
+
const entries = calls.map(prepare);
|
|
180
|
+
const ids = new Set();
|
|
181
|
+
for (const e of entries) {
|
|
182
|
+
if (ids.has(e.id)) throw new TypeError(`remote: duplicate call id "${e.id}"`);
|
|
183
|
+
ids.add(e.id);
|
|
184
|
+
}
|
|
185
|
+
return send(entries, options);
|
|
186
|
+
},
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* A transport that runs the executor in this isolate with no network: for
|
|
192
|
+
* tests and `wrangler dev`. The request still goes through the executor's
|
|
193
|
+
* ingress check, so pass the headers it expects.
|
|
194
|
+
* @param {{fetch: Function}} executor - From createExecutor.
|
|
195
|
+
* @param {Object} [options]
|
|
196
|
+
* @param {any} [options.env] - Passed to the executor as `env`.
|
|
197
|
+
* @param {Object<string,string>} [options.headers] - Added to every request.
|
|
198
|
+
* @param {{waitUntil: function(Promise<*>)}} [options.ctx] - Passed as the
|
|
199
|
+
* execution context; without it deferred work is awaited by executor.drain().
|
|
200
|
+
*/
|
|
201
|
+
function inProcess(executor, { env, headers = {}, ctx } = {}) {
|
|
202
|
+
if (!executor || typeof executor.fetch !== "function" || typeof executor.drain !== "function") {
|
|
203
|
+
throw new TypeError("inProcess needs an executor from createExecutor");
|
|
204
|
+
}
|
|
205
|
+
return Object.freeze({
|
|
206
|
+
async fetch(request) {
|
|
207
|
+
const extra = Object.entries(headers);
|
|
208
|
+
let req = request;
|
|
209
|
+
if (extra.length > 0) {
|
|
210
|
+
const merged = new Headers(request.headers);
|
|
211
|
+
for (const [k, v] of extra) merged.set(k, v);
|
|
212
|
+
req = new Request(request, { headers: merged });
|
|
213
|
+
}
|
|
214
|
+
return executor.fetch(req, env, ctx);
|
|
215
|
+
},
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
module.exports = { remote, inProcess };
|