dynamo-bao 0.9.0 → 0.11.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 +135 -1
- package/README.md +60 -0
- package/bin/bao-create-table.js +0 -0
- package/package.json +16 -3
- package/src/dynamodb-client.js +23 -1
- package/src/exceptions.js +38 -0
- package/src/index.js +4 -0
- package/src/mixins/mutation-mixin.js +496 -132
- package/src/model.js +50 -0
- package/src/plugin-manager.js +5 -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/src/tenant-context.js +16 -0
- package/src/transact.js +367 -0
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)) {
|
package/src/plugin-manager.js
CHANGED
|
@@ -19,6 +19,11 @@ class PluginManager {
|
|
|
19
19
|
}
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
+
hasHook(modelName, hookName) {
|
|
23
|
+
const plugins = this.plugins.get(modelName) || [];
|
|
24
|
+
return plugins.some((plugin) => typeof plugin[hookName] === "function");
|
|
25
|
+
}
|
|
26
|
+
|
|
22
27
|
async executeHooks(modelName, hookName, ...args) {
|
|
23
28
|
const plugins = this.plugins.get(modelName) || [];
|
|
24
29
|
for (const plugin of plugins) {
|
|
@@ -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 };
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wire codec for procedure arguments and results.
|
|
3
|
+
*
|
|
4
|
+
* Everything that crosses the executor boundary is plain JSON. Model rows
|
|
5
|
+
* travel as `{ $model: "<ModelName>", data: { <field>: <value> } }` holding
|
|
6
|
+
* only the model's declared fields, with:
|
|
7
|
+
* - DateTimeField, CreateDateField, ModifiedDateField, TtlField: epoch
|
|
8
|
+
* milliseconds (TtlField is stored in seconds and converted).
|
|
9
|
+
* - BinaryField: `{ $binary: "<base64>" }`.
|
|
10
|
+
* - StringSetField: an array of strings.
|
|
11
|
+
* - Every other built-in field: its stored value, which is already JSON.
|
|
12
|
+
* - A custom field: its stored value if that is plain JSON; otherwise the
|
|
13
|
+
* row is refused with a CodecError naming the model and field.
|
|
14
|
+
*
|
|
15
|
+
* Any other non-JSON value (Date, Map, Set, Buffer, class instance, function,
|
|
16
|
+
* NaN, ...) is refused rather than letting JSON.stringify change it silently.
|
|
17
|
+
* @module remote/codec
|
|
18
|
+
*/
|
|
19
|
+
const fields = require("../fields");
|
|
20
|
+
const { findNonJson, isPlainObject } = require("./json");
|
|
21
|
+
const { ObjectNotFound } = require("../object-not-found");
|
|
22
|
+
|
|
23
|
+
class CodecError extends Error {
|
|
24
|
+
constructor(message) {
|
|
25
|
+
super(message);
|
|
26
|
+
this.name = "CodecError";
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const DATE_FIELDS = [
|
|
31
|
+
fields.DateTimeFieldClass, // CreateDate, ModifiedDate and Ttl extend it
|
|
32
|
+
];
|
|
33
|
+
|
|
34
|
+
function isDateField(field) {
|
|
35
|
+
return DATE_FIELDS.some((C) => field instanceof C);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function isModelInstance(value) {
|
|
39
|
+
// Lazy: model.js requires this module for fromRemote.
|
|
40
|
+
const { BaoModel } = require("../model");
|
|
41
|
+
return value instanceof BaoModel;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function isBinary(value) {
|
|
45
|
+
return value instanceof Uint8Array; // Buffer is a Uint8Array
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function toBase64(bytes) {
|
|
49
|
+
if (typeof Buffer !== "undefined") return Buffer.from(bytes).toString("base64");
|
|
50
|
+
let s = "";
|
|
51
|
+
for (const b of bytes) s += String.fromCharCode(b);
|
|
52
|
+
return btoa(s);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function fromBase64(text) {
|
|
56
|
+
if (typeof Buffer !== "undefined") return Buffer.from(text, "base64");
|
|
57
|
+
return Uint8Array.from(atob(text), (c) => c.charCodeAt(0));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function encodeField(modelName, fieldName, field, dy) {
|
|
61
|
+
if (dy === undefined) return undefined;
|
|
62
|
+
if (dy === null) return null;
|
|
63
|
+
const where = `${modelName}.${fieldName}`;
|
|
64
|
+
if (field instanceof fields.TtlFieldClass) {
|
|
65
|
+
if (typeof dy !== "number") throw new CodecError(`${where}: stored TTL is not a number`);
|
|
66
|
+
return dy * 1000;
|
|
67
|
+
}
|
|
68
|
+
if (isDateField(field)) {
|
|
69
|
+
if (typeof dy !== "number") throw new CodecError(`${where}: stored date is not a number`);
|
|
70
|
+
return dy;
|
|
71
|
+
}
|
|
72
|
+
if (field instanceof fields.BinaryFieldClass) {
|
|
73
|
+
if (!isBinary(dy)) throw new CodecError(`${where}: stored binary is not bytes`);
|
|
74
|
+
return { $binary: toBase64(dy) };
|
|
75
|
+
}
|
|
76
|
+
if (field instanceof fields.StringSetFieldClass) {
|
|
77
|
+
const list = dy instanceof Set ? [...dy] : dy;
|
|
78
|
+
if (!Array.isArray(list) || list.some((s) => typeof s !== "string")) {
|
|
79
|
+
throw new CodecError(`${where}: stored string set is not an array of strings`);
|
|
80
|
+
}
|
|
81
|
+
return [...list];
|
|
82
|
+
}
|
|
83
|
+
const bad = findNonJson(dy);
|
|
84
|
+
if (bad) {
|
|
85
|
+
throw new CodecError(
|
|
86
|
+
`${where}: the stored value is not JSON (found ${bad.found}); the remote codec can't ship this field`,
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
return dy;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function decodeField(modelName, fieldName, field, wire) {
|
|
93
|
+
if (wire === undefined) return undefined;
|
|
94
|
+
if (wire === null) return null;
|
|
95
|
+
const where = `${modelName}.${fieldName}`;
|
|
96
|
+
if (field instanceof fields.TtlFieldClass) {
|
|
97
|
+
if (typeof wire !== "number" || !Number.isFinite(wire)) {
|
|
98
|
+
throw new CodecError(`${where}: expected epoch milliseconds`);
|
|
99
|
+
}
|
|
100
|
+
return Math.floor(wire / 1000);
|
|
101
|
+
}
|
|
102
|
+
if (isDateField(field)) {
|
|
103
|
+
if (typeof wire !== "number" || !Number.isFinite(wire)) {
|
|
104
|
+
throw new CodecError(`${where}: expected epoch milliseconds`);
|
|
105
|
+
}
|
|
106
|
+
return wire;
|
|
107
|
+
}
|
|
108
|
+
if (field instanceof fields.BinaryFieldClass) {
|
|
109
|
+
if (!isPlainObject(wire) || typeof wire.$binary !== "string") {
|
|
110
|
+
throw new CodecError(`${where}: expected { $binary: "<base64>" }`);
|
|
111
|
+
}
|
|
112
|
+
return fromBase64(wire.$binary);
|
|
113
|
+
}
|
|
114
|
+
if (field instanceof fields.StringSetFieldClass) {
|
|
115
|
+
if (!Array.isArray(wire) || wire.some((s) => typeof s !== "string")) {
|
|
116
|
+
throw new CodecError(`${where}: expected an array of strings`);
|
|
117
|
+
}
|
|
118
|
+
return [...wire];
|
|
119
|
+
}
|
|
120
|
+
const bad = findNonJson(wire);
|
|
121
|
+
if (bad) throw new CodecError(`${where}: expected JSON, found ${bad.found}`);
|
|
122
|
+
return wire;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Encode one model instance as `{ $model, data }`.
|
|
127
|
+
* @private
|
|
128
|
+
*/
|
|
129
|
+
function encodeRow(instance) {
|
|
130
|
+
const Model = instance.constructor;
|
|
131
|
+
const data = {};
|
|
132
|
+
for (const [fieldName, field] of Object.entries(Model.fields)) {
|
|
133
|
+
const value = encodeField(Model.name, fieldName, field, instance._dyData[fieldName]);
|
|
134
|
+
if (value !== undefined) data[fieldName] = value;
|
|
135
|
+
}
|
|
136
|
+
return { $model: Model.name, data };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Encode a procedure argument or result as plain JSON.
|
|
141
|
+
* @param {any} value
|
|
142
|
+
* @param {Object} [options]
|
|
143
|
+
* @param {"encode"|"refuse"} [options.models="encode"] - What to do with a
|
|
144
|
+
* model instance found in `value`: encode it as `{ $model, data }`, or
|
|
145
|
+
* refuse it (the plain-view rule: a procedure must encode rows itself,
|
|
146
|
+
* with `encodeValue(row)`, so none crosses by accident).
|
|
147
|
+
* @returns {any} A plain-JSON copy. An `ObjectNotFound` becomes null; a
|
|
148
|
+
* top-level undefined becomes null.
|
|
149
|
+
* @throws {CodecError} Naming the path of the first value that is not JSON.
|
|
150
|
+
*/
|
|
151
|
+
function encodeValue(value, { models = "encode" } = {}) {
|
|
152
|
+
return encodeAt(value, "$", models, new Set());
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function encodeAt(value, path, models, seen) {
|
|
156
|
+
if (value === undefined) return null;
|
|
157
|
+
if (value === null || typeof value !== "object") {
|
|
158
|
+
const bad = findNonJson(value, path);
|
|
159
|
+
if (bad) throw nonJson(bad);
|
|
160
|
+
return value;
|
|
161
|
+
}
|
|
162
|
+
if (value instanceof ObjectNotFound) return null;
|
|
163
|
+
if (isModelInstance(value)) {
|
|
164
|
+
if (models === "refuse") {
|
|
165
|
+
throw new CodecError(
|
|
166
|
+
`${path}: a ${value.constructor.name} instance crossed the boundary; return encodeValue(row) or a plain view`,
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
return encodeRow(value);
|
|
170
|
+
}
|
|
171
|
+
if (seen.has(value)) throw new CodecError(`${path}: a circular reference is not JSON`);
|
|
172
|
+
seen.add(value);
|
|
173
|
+
try {
|
|
174
|
+
if (Array.isArray(value)) {
|
|
175
|
+
const out = new Array(value.length);
|
|
176
|
+
for (let i = 0; i < value.length; i++) {
|
|
177
|
+
if (!(i in value) || value[i] === undefined) {
|
|
178
|
+
throw nonJson({ path: `${path}[${i}]`, found: "undefined" });
|
|
179
|
+
}
|
|
180
|
+
out[i] = encodeAt(value[i], `${path}[${i}]`, models, seen);
|
|
181
|
+
}
|
|
182
|
+
return out;
|
|
183
|
+
}
|
|
184
|
+
if (!isPlainObject(value) || Object.getOwnPropertySymbols(value).length > 0) {
|
|
185
|
+
throw nonJson(findNonJson(value, path));
|
|
186
|
+
}
|
|
187
|
+
const out = {};
|
|
188
|
+
for (const key of Object.keys(value)) {
|
|
189
|
+
if (value[key] === undefined) continue;
|
|
190
|
+
out[key] = encodeAt(value[key], `${path}.${key}`, models, seen);
|
|
191
|
+
}
|
|
192
|
+
return out;
|
|
193
|
+
} finally {
|
|
194
|
+
seen.delete(value);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function nonJson({ path, found }) {
|
|
199
|
+
const hint = found === "a Date" ? "; send epoch milliseconds" : "";
|
|
200
|
+
return new CodecError(`${path}: ${found} is not JSON${hint}`);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Decode an encoded row into the model's stored representation (the shape
|
|
205
|
+
* of `instance._dyData`: dates as epoch ms, TTL in seconds, binary as bytes,
|
|
206
|
+
* string sets as arrays). `Model.fromRemote` builds on this.
|
|
207
|
+
* Fields the receiving model does not declare are dropped, so a row from a
|
|
208
|
+
* newer bundle still hydrates.
|
|
209
|
+
* @param {Function} ModelClass - A BaoModel subclass.
|
|
210
|
+
* @param {{$model: string, data: Object}} encoded
|
|
211
|
+
* @returns {Object}
|
|
212
|
+
* @throws {CodecError}
|
|
213
|
+
*/
|
|
214
|
+
function decodeRow(ModelClass, encoded) {
|
|
215
|
+
if (!isPlainObject(encoded) || typeof encoded.$model !== "string") {
|
|
216
|
+
throw new CodecError(`decodeRow: expected { $model, data } for ${ModelClass.name}`);
|
|
217
|
+
}
|
|
218
|
+
if (encoded.$model !== ModelClass.name) {
|
|
219
|
+
throw new CodecError(
|
|
220
|
+
`decodeRow: the row is a ${encoded.$model}, not a ${ModelClass.name}`,
|
|
221
|
+
);
|
|
222
|
+
}
|
|
223
|
+
if (!isPlainObject(encoded.data)) {
|
|
224
|
+
throw new CodecError(`decodeRow: ${ModelClass.name} row has no data object`);
|
|
225
|
+
}
|
|
226
|
+
const dy = {};
|
|
227
|
+
for (const [fieldName, field] of Object.entries(ModelClass.fields)) {
|
|
228
|
+
const value = decodeField(ModelClass.name, fieldName, field, encoded.data[fieldName]);
|
|
229
|
+
if (value !== undefined) dy[fieldName] = value;
|
|
230
|
+
}
|
|
231
|
+
return dy;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
module.exports = { encodeValue, decodeRow, CodecError };
|