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
package/src/model.js
CHANGED
|
@@ -28,8 +28,6 @@ const {
|
|
|
28
28
|
UniqueConstraintConfig: UniqueConstraintConfigClass,
|
|
29
29
|
} = require("./model-config");
|
|
30
30
|
|
|
31
|
-
const GID_SEPARATOR = "##__SK__##";
|
|
32
|
-
|
|
33
31
|
// Passed to the constructor by _createFromDyItem: the instance is about to
|
|
34
32
|
// take its data from a stored row, so skip computing initial field values
|
|
35
33
|
// (which for auto-assigned ULID and version fields means generating ids
|
|
@@ -40,6 +38,16 @@ const HYDRATE = Symbol("dynamo-bao.hydrate");
|
|
|
40
38
|
// prototype; holds the `fields` object they were built from.
|
|
41
39
|
const FIELD_ACCESSORS_FOR = Symbol("dynamo-bao.fieldAccessorsFor");
|
|
42
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
|
+
|
|
43
51
|
// System attributes (_pk, _sk, GSI keys, ...) are plain strings with no
|
|
44
52
|
// per-model options, so one shared field definition serves them all.
|
|
45
53
|
const SYSTEM_STRING_FIELD = StringField();
|
|
@@ -51,9 +59,11 @@ const {
|
|
|
51
59
|
ITERATION_PK_FIELD,
|
|
52
60
|
ITERATION_SK_FIELD,
|
|
53
61
|
SEARCH_TEXT_FIELD,
|
|
62
|
+
GID_SEPARATOR,
|
|
54
63
|
} = require("./constants");
|
|
55
64
|
const {
|
|
56
65
|
ConfigurationError,
|
|
66
|
+
DetachedInstanceError,
|
|
57
67
|
ValidationError,
|
|
58
68
|
QueryError,
|
|
59
69
|
DataFormatError,
|
|
@@ -115,7 +125,17 @@ class BaoModel {
|
|
|
115
125
|
static get manager() {
|
|
116
126
|
const { TenantContext } = require("./tenant-context");
|
|
117
127
|
const tenantId = TenantContext.getCurrentTenant();
|
|
118
|
-
|
|
128
|
+
if (tenantId) {
|
|
129
|
+
return ModelManager.forTenant(tenantId);
|
|
130
|
+
}
|
|
131
|
+
// Fail closed: never fall back to the tenant that was current at init.
|
|
132
|
+
if (this._config?.tenancy?.enabled) {
|
|
133
|
+
throw new ConfigurationError(
|
|
134
|
+
`No tenant in context for ${this.name}. Wrap the operation in ` +
|
|
135
|
+
"TenantContext.runWithTenant(tenantId, fn) or register a resolver.",
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
return ModelManager.getInstance(this._tenantId);
|
|
119
139
|
}
|
|
120
140
|
|
|
121
141
|
static _getField(fieldName) {
|
|
@@ -352,6 +372,8 @@ class BaoModel {
|
|
|
352
372
|
* and so the upper bound on each yielded batch.
|
|
353
373
|
* @param {Object} [options.filter] - Filter on attributes projected onto
|
|
354
374
|
* the iteration index.
|
|
375
|
+
* @param {string[]} [options.allowedFilterFields] - Fields `filter` may
|
|
376
|
+
* reference. Set this when the filter comes from user input.
|
|
355
377
|
* @param {number} [options.concurrency=1] - Buckets to read concurrently.
|
|
356
378
|
* @yields {BaoModel[]} One batch of loaded instances at a time.
|
|
357
379
|
*/
|
|
@@ -360,20 +382,33 @@ class BaoModel {
|
|
|
360
382
|
throw new Error(`Model ${this.name} is not configured as iterable`);
|
|
361
383
|
}
|
|
362
384
|
|
|
363
|
-
const {
|
|
385
|
+
const {
|
|
386
|
+
batchSize = 100,
|
|
387
|
+
filter = null,
|
|
388
|
+
allowedFilterFields,
|
|
389
|
+
concurrency = 1,
|
|
390
|
+
} = options;
|
|
364
391
|
if (!Number.isInteger(concurrency) || concurrency < 1) {
|
|
365
392
|
throw new Error("concurrency must be a positive integer");
|
|
366
393
|
}
|
|
367
394
|
|
|
368
395
|
if (this.iterationBuckets === 1) {
|
|
369
|
-
yield* this._iterateSingleBucket(null, {
|
|
396
|
+
yield* this._iterateSingleBucket(null, {
|
|
397
|
+
batchSize,
|
|
398
|
+
filter,
|
|
399
|
+
allowedFilterFields,
|
|
400
|
+
});
|
|
370
401
|
return;
|
|
371
402
|
}
|
|
372
403
|
|
|
373
404
|
const buckets = Array.from({ length: this.iterationBuckets }, (_, b) => b);
|
|
374
405
|
if (concurrency === 1) {
|
|
375
406
|
for (const bucket of buckets) {
|
|
376
|
-
yield* this._iterateSingleBucket(bucket, {
|
|
407
|
+
yield* this._iterateSingleBucket(bucket, {
|
|
408
|
+
batchSize,
|
|
409
|
+
filter,
|
|
410
|
+
allowedFilterFields,
|
|
411
|
+
});
|
|
377
412
|
}
|
|
378
413
|
return;
|
|
379
414
|
}
|
|
@@ -381,7 +416,11 @@ class BaoModel {
|
|
|
381
416
|
yield* this._interleaveGenerators(
|
|
382
417
|
buckets.map(
|
|
383
418
|
(bucket) => () =>
|
|
384
|
-
this._iterateSingleBucket(bucket, {
|
|
419
|
+
this._iterateSingleBucket(bucket, {
|
|
420
|
+
batchSize,
|
|
421
|
+
filter,
|
|
422
|
+
allowedFilterFields,
|
|
423
|
+
}),
|
|
385
424
|
),
|
|
386
425
|
concurrency,
|
|
387
426
|
);
|
|
@@ -515,6 +554,8 @@ class BaoModel {
|
|
|
515
554
|
* @param {Object} [options.filter] - Additional filter combined via AND
|
|
516
555
|
* with the search predicate. Must reference only attributes projected
|
|
517
556
|
* on `iter_search_index` (i.e., `_searchText` and the index/base keys).
|
|
557
|
+
* @param {string[]} [options.allowedFilterFields] - Fields `filter` may
|
|
558
|
+
* reference. Set this when the filter comes from user input.
|
|
518
559
|
* @returns {Promise<{items: BaoModel[], cursor: string|null}>} `items` is
|
|
519
560
|
* never longer than `limit`. `cursor` is `null` when the search is
|
|
520
561
|
* fully exhausted; otherwise pass it back to get the next page.
|
|
@@ -597,6 +638,7 @@ class BaoModel {
|
|
|
597
638
|
operator = "$and",
|
|
598
639
|
batchSize = 100,
|
|
599
640
|
filter = null,
|
|
641
|
+
allowedFilterFields,
|
|
600
642
|
limit = 100,
|
|
601
643
|
maxQueriesPerBucket = 50,
|
|
602
644
|
parallel = true,
|
|
@@ -693,6 +735,7 @@ class BaoModel {
|
|
|
693
735
|
const page = await this._searchSingleBucketPage(bucketArg(bucketIdx), {
|
|
694
736
|
batchSize,
|
|
695
737
|
filter,
|
|
738
|
+
allowedFilterFields,
|
|
696
739
|
searchPredicate,
|
|
697
740
|
exclusiveStartKey: lek || null,
|
|
698
741
|
});
|
|
@@ -908,6 +951,7 @@ class BaoModel {
|
|
|
908
951
|
const {
|
|
909
952
|
batchSize = 100,
|
|
910
953
|
filter = null,
|
|
954
|
+
allowedFilterFields,
|
|
911
955
|
searchPredicate = null,
|
|
912
956
|
exclusiveStartKey = null,
|
|
913
957
|
} = options;
|
|
@@ -929,7 +973,9 @@ class BaoModel {
|
|
|
929
973
|
if (filter) {
|
|
930
974
|
const { FilterExpressionBuilder } = require("./filter-expression");
|
|
931
975
|
const filterBuilder = new FilterExpressionBuilder();
|
|
932
|
-
const filterExpression = filterBuilder.build(filter, this
|
|
976
|
+
const filterExpression = filterBuilder.build(filter, this, {
|
|
977
|
+
allowedFields: allowedFilterFields,
|
|
978
|
+
});
|
|
933
979
|
if (filterExpression) {
|
|
934
980
|
this._assertFilterFitsIterIndex(
|
|
935
981
|
indexName,
|
|
@@ -973,7 +1019,12 @@ class BaoModel {
|
|
|
973
1019
|
}
|
|
974
1020
|
|
|
975
1021
|
static async *_iterateSingleBucket(bucketNum, options = {}) {
|
|
976
|
-
const {
|
|
1022
|
+
const {
|
|
1023
|
+
batchSize = 100,
|
|
1024
|
+
filter = null,
|
|
1025
|
+
allowedFilterFields,
|
|
1026
|
+
searchPredicate = null,
|
|
1027
|
+
} = options;
|
|
977
1028
|
const iterPk = this._getIterationPk(bucketNum);
|
|
978
1029
|
const indexName = this.manager.getIterationIndexName();
|
|
979
1030
|
|
|
@@ -993,7 +1044,9 @@ class BaoModel {
|
|
|
993
1044
|
if (filter) {
|
|
994
1045
|
const { FilterExpressionBuilder } = require("./filter-expression");
|
|
995
1046
|
const filterBuilder = new FilterExpressionBuilder();
|
|
996
|
-
const filterExpression = filterBuilder.build(filter, this
|
|
1047
|
+
const filterExpression = filterBuilder.build(filter, this, {
|
|
1048
|
+
allowedFields: allowedFilterFields,
|
|
1049
|
+
});
|
|
997
1050
|
if (filterExpression) {
|
|
998
1051
|
// Preflight: filter attributes must be in the GSI's projection.
|
|
999
1052
|
// Otherwise DynamoDB returns an opaque "does not project one or
|
|
@@ -1157,6 +1210,42 @@ class BaoModel {
|
|
|
1157
1210
|
return newObj;
|
|
1158
1211
|
}
|
|
1159
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
|
+
|
|
1160
1249
|
/**
|
|
1161
1250
|
* @description
|
|
1162
1251
|
* Clear the related cache for a given field.
|
|
@@ -1274,7 +1363,11 @@ class BaoModel {
|
|
|
1274
1363
|
}
|
|
1275
1364
|
|
|
1276
1365
|
if (primaryId.indexOf(GID_SEPARATOR) !== -1) {
|
|
1277
|
-
const
|
|
1366
|
+
const parts = primaryId.split(GID_SEPARATOR);
|
|
1367
|
+
if (parts.length !== 2) {
|
|
1368
|
+
throw new ValidationError(`Invalid primary id: ${primaryId}`);
|
|
1369
|
+
}
|
|
1370
|
+
const [pk, sk] = parts;
|
|
1278
1371
|
return { pk, sk };
|
|
1279
1372
|
} else {
|
|
1280
1373
|
if (this.primaryKey.pk === "modelPrefix") {
|
|
@@ -1355,6 +1448,7 @@ class BaoModel {
|
|
|
1355
1448
|
* @returns {Promise<Object>} Returns a promise that resolves to the updated item.
|
|
1356
1449
|
*/
|
|
1357
1450
|
async save(options = {}) {
|
|
1451
|
+
assertAttached(this, "save");
|
|
1358
1452
|
const { forceReindex = false, ...otherOptions } = options;
|
|
1359
1453
|
|
|
1360
1454
|
if (!forceReindex && !this.hasChanges() && this.isLoaded()) {
|
|
@@ -1401,6 +1495,7 @@ class BaoModel {
|
|
|
1401
1495
|
* @returns {Promise<Object>} Returns a promise that resolves to the loaded item.
|
|
1402
1496
|
*/
|
|
1403
1497
|
async getOrLoadRelatedField(fieldName) {
|
|
1498
|
+
assertAttached(this, "getOrLoadRelatedField");
|
|
1404
1499
|
if (this._relatedObjects[fieldName]) {
|
|
1405
1500
|
return this._relatedObjects[fieldName];
|
|
1406
1501
|
}
|
|
@@ -1428,6 +1523,7 @@ class BaoModel {
|
|
|
1428
1523
|
* @returns {Promise<Object>} Returns a promise that resolves to the loaded items and their consumed capacity
|
|
1429
1524
|
*/
|
|
1430
1525
|
async loadRelatedData(fieldNames = null) {
|
|
1526
|
+
assertAttached(this, "loadRelatedData");
|
|
1431
1527
|
const promises = [];
|
|
1432
1528
|
|
|
1433
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 };
|