@olivia-db/client 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +40 -0
- package/dist/dsl.d.ts +498 -0
- package/dist/dsl.js +957 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +8 -0
- package/dist/native.d.ts +10 -0
- package/dist/native.js +19 -4
- package/package.json +7 -2
- package/src/dsl.ts +1228 -0
- package/src/index.ts +9 -0
- package/src/native.ts +26 -4
package/dist/dsl.js
ADDED
|
@@ -0,0 +1,957 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
/**
|
|
3
|
+
* Typed models and queries: the runtime of the code `oliviadb codegen --lang ts` generates
|
|
4
|
+
* (`sdk-dsl.md` of the specification). Generated code holds the schema's models, keys, paths,
|
|
5
|
+
* patches and new-node types as types, and tables that describe them; every request is made
|
|
6
|
+
* here, over HTTP (OliviaDbClient) or the native protocol (NativeClient of
|
|
7
|
+
* `@olivia-db/client/native`).
|
|
8
|
+
*
|
|
9
|
+
* const db = new Db(new OliviaDbClient({ baseUrl, apiKey }));
|
|
10
|
+
* const c = await db.get(Customer.key("42"), { tree: true });
|
|
11
|
+
* await db.txn((t) => {
|
|
12
|
+
* t.update(Customer.key("42").account("1001"), { add: { balance: amount.neg() } });
|
|
13
|
+
* t.update(Customer.key("42").account("1002"), { add: { balance: amount } });
|
|
14
|
+
* });
|
|
15
|
+
*
|
|
16
|
+
* A read's answer is decoded into the model from the node form the network API documents
|
|
17
|
+
* (`docs/network-api.md`, "Native aggregates"): over HTTP its JSON, over the native protocol
|
|
18
|
+
* the rows given in that form by the row reader (`Rows.toJson`). A node written with another
|
|
19
|
+
* layout of its type than the one the generated code was made for (an older version of the
|
|
20
|
+
* schema) is read by field number from that layout's fields (the connection's descriptors, or
|
|
21
|
+
* `GET /v1/layouts/{id}` over HTTP), fields it lacks with their declared defaults (`adapt`); a
|
|
22
|
+
* field whose type conflicts is a SchemaMismatchError naming it, never decoded by guess. A field the model requires and the answer
|
|
23
|
+
* lacks or shows masked is a DecodeError naming it, never a default.
|
|
24
|
+
*/
|
|
25
|
+
import { OliviaDbClient, OliviaDbError } from "./index.js";
|
|
26
|
+
// ---- errors ----
|
|
27
|
+
/** An answer the generated code cannot read as its model (a field missing or of another type). */
|
|
28
|
+
export class DecodeError extends Error {
|
|
29
|
+
name = "DecodeError";
|
|
30
|
+
}
|
|
31
|
+
/** A node written with a layout that conflicts with the generated code's: another type under the
|
|
32
|
+
* same field number, or a layout the connection cannot describe. */
|
|
33
|
+
export class SchemaMismatchError extends Error {
|
|
34
|
+
name = "SchemaMismatchError";
|
|
35
|
+
}
|
|
36
|
+
// ---- values ----
|
|
37
|
+
/** An exact decimal (`decimal(p,s)`): `unscaled × 10^-scale`. */
|
|
38
|
+
export class Decimal {
|
|
39
|
+
unscaled;
|
|
40
|
+
scale;
|
|
41
|
+
constructor(unscaled, scale) {
|
|
42
|
+
this.unscaled = unscaled;
|
|
43
|
+
this.scale = scale;
|
|
44
|
+
}
|
|
45
|
+
/** `-12.50`, `3`, `+0.5`; anything else throws DecodeError. */
|
|
46
|
+
static parse(s) {
|
|
47
|
+
const m = /^([+-]?)(\d*)(?:\.(\d*))?$/.exec(s);
|
|
48
|
+
if (!m || (m[2] === "" && (m[3] ?? "") === ""))
|
|
49
|
+
throw new DecodeError(`decimal ${JSON.stringify(s)}`);
|
|
50
|
+
const f = m[3] ?? "";
|
|
51
|
+
const u = BigInt(`${m[2]}${f}` || "0");
|
|
52
|
+
return new Decimal(m[1] === "-" ? -u : u, f.length);
|
|
53
|
+
}
|
|
54
|
+
at(scale) {
|
|
55
|
+
return this.unscaled * 10n ** BigInt(scale - this.scale);
|
|
56
|
+
}
|
|
57
|
+
neg() {
|
|
58
|
+
return new Decimal(-this.unscaled, this.scale);
|
|
59
|
+
}
|
|
60
|
+
add(o) {
|
|
61
|
+
const s = Math.max(this.scale, o.scale);
|
|
62
|
+
return new Decimal(this.at(s) + o.at(s), s);
|
|
63
|
+
}
|
|
64
|
+
/** Equal values, whatever their scales (`1.50` equals `1.5`). */
|
|
65
|
+
equals(o) {
|
|
66
|
+
const s = Math.max(this.scale, o.scale);
|
|
67
|
+
return this.at(s) === o.at(s);
|
|
68
|
+
}
|
|
69
|
+
toString() {
|
|
70
|
+
const neg = this.unscaled < 0n;
|
|
71
|
+
let d = (neg ? -this.unscaled : this.unscaled).toString();
|
|
72
|
+
if (this.scale > 0) {
|
|
73
|
+
d = d.padStart(this.scale + 1, "0");
|
|
74
|
+
d = `${d.slice(0, d.length - this.scale)}.${d.slice(d.length - this.scale)}`;
|
|
75
|
+
}
|
|
76
|
+
return neg ? `-${d}` : d;
|
|
77
|
+
}
|
|
78
|
+
toJSON() {
|
|
79
|
+
return this.toString();
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
// Days from a civil date and back (proleptic Gregorian; H. Hinnant, "chrono-Compatible
|
|
83
|
+
// Low-Level Date Algorithms", days_from_civil / civil_from_days).
|
|
84
|
+
function daysFromCivil(y, m, d) {
|
|
85
|
+
y -= m <= 2 ? 1 : 0;
|
|
86
|
+
const era = Math.floor(y / 400);
|
|
87
|
+
const yoe = y - era * 400;
|
|
88
|
+
const doy = Math.floor((153 * ((m + 9) % 12) + 2) / 5) + d - 1;
|
|
89
|
+
const doe = yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy;
|
|
90
|
+
return era * 146097 + doe - 719468;
|
|
91
|
+
}
|
|
92
|
+
function civilFromDays(z) {
|
|
93
|
+
z += 719468;
|
|
94
|
+
const era = Math.floor(z / 146097);
|
|
95
|
+
const doe = z - era * 146097;
|
|
96
|
+
const yoe = Math.floor((doe - Math.floor(doe / 1460) + Math.floor(doe / 36524) - Math.floor(doe / 146096)) / 365);
|
|
97
|
+
const doy = doe - (365 * yoe + Math.floor(yoe / 4) - Math.floor(yoe / 100));
|
|
98
|
+
const mp = Math.floor((5 * doy + 2) / 153);
|
|
99
|
+
const d = doy - Math.floor((153 * mp + 2) / 5) + 1;
|
|
100
|
+
const m = mp < 10 ? mp + 3 : mp - 9;
|
|
101
|
+
return [yoe + era * 400 + (m <= 2 ? 1 : 0), m, d];
|
|
102
|
+
}
|
|
103
|
+
const pad = (n, w) => String(n).padStart(w, "0");
|
|
104
|
+
/** A calendar date (`date`): days since 1970-01-01. */
|
|
105
|
+
export class PlainDate {
|
|
106
|
+
days;
|
|
107
|
+
constructor(days) {
|
|
108
|
+
this.days = days;
|
|
109
|
+
}
|
|
110
|
+
static of(y, m, d) {
|
|
111
|
+
return new PlainDate(daysFromCivil(y, m, d));
|
|
112
|
+
}
|
|
113
|
+
/** `YYYY-MM-DD`. */
|
|
114
|
+
static parse(s) {
|
|
115
|
+
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s);
|
|
116
|
+
if (!m || +m[2] < 1 || +m[2] > 12 || +m[3] < 1 || +m[3] > 31)
|
|
117
|
+
throw new DecodeError(`date ${JSON.stringify(s)}`);
|
|
118
|
+
return PlainDate.of(+m[1], +m[2], +m[3]);
|
|
119
|
+
}
|
|
120
|
+
equals(o) {
|
|
121
|
+
return this.days === o.days;
|
|
122
|
+
}
|
|
123
|
+
toString() {
|
|
124
|
+
const [y, m, d] = civilFromDays(this.days);
|
|
125
|
+
return `${pad(y, 4)}-${pad(m, 2)}-${pad(d, 2)}`;
|
|
126
|
+
}
|
|
127
|
+
toJSON() {
|
|
128
|
+
return this.toString();
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
/** An instant in UTC (`timestamp`): microseconds since 1970-01-01T00:00:00Z. */
|
|
132
|
+
export class Instant {
|
|
133
|
+
micros;
|
|
134
|
+
constructor(micros) {
|
|
135
|
+
this.micros = micros;
|
|
136
|
+
}
|
|
137
|
+
/** `YYYY-MM-DDTHH:MM:SS[.f{1,6}]Z`, the form the network API shows (it writes six digits). */
|
|
138
|
+
static parse(s) {
|
|
139
|
+
const m = /^(\d{4}-\d{2}-\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?Z$/.exec(s);
|
|
140
|
+
if (!m)
|
|
141
|
+
throw new DecodeError(`timestamp ${JSON.stringify(s)}`);
|
|
142
|
+
const day = BigInt(PlainDate.parse(m[1]).days);
|
|
143
|
+
const secs = day * 86400n + BigInt(+m[2] * 3600 + +m[3] * 60 + +m[4]);
|
|
144
|
+
return new Instant(secs * 1000000n + BigInt((m[5] ?? "").padEnd(6, "0")));
|
|
145
|
+
}
|
|
146
|
+
equals(o) {
|
|
147
|
+
return this.micros === o.micros;
|
|
148
|
+
}
|
|
149
|
+
toString() {
|
|
150
|
+
let s = this.micros / 1000000n;
|
|
151
|
+
let us = this.micros % 1000000n;
|
|
152
|
+
if (us < 0n) {
|
|
153
|
+
us += 1000000n;
|
|
154
|
+
s -= 1n;
|
|
155
|
+
}
|
|
156
|
+
let days = s / 86400n;
|
|
157
|
+
let rem = s % 86400n;
|
|
158
|
+
if (rem < 0n) {
|
|
159
|
+
rem += 86400n;
|
|
160
|
+
days -= 1n;
|
|
161
|
+
}
|
|
162
|
+
const r = Number(rem);
|
|
163
|
+
const t = `${pad(Math.floor(r / 3600), 2)}:${pad(Math.floor(r / 60) % 60, 2)}:${pad(r % 60, 2)}`;
|
|
164
|
+
return `${new PlainDate(Number(days)).toString()}T${t}.${us.toString().padStart(6, "0")}Z`;
|
|
165
|
+
}
|
|
166
|
+
toJSON() {
|
|
167
|
+
return this.toString();
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
/** A reference field (`ref T`): the target's levels below where the reference starts, as the
|
|
171
|
+
* network API shows them (`""`: none). */
|
|
172
|
+
export class Ref {
|
|
173
|
+
text;
|
|
174
|
+
constructor(text) {
|
|
175
|
+
this.text = text;
|
|
176
|
+
}
|
|
177
|
+
isNone() {
|
|
178
|
+
return this.text === "";
|
|
179
|
+
}
|
|
180
|
+
toJSON() {
|
|
181
|
+
return this.text;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
function hex(b) {
|
|
185
|
+
return Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
|
|
186
|
+
}
|
|
187
|
+
/** A value as the network API's JSON writes it. */
|
|
188
|
+
export function toJson(v) {
|
|
189
|
+
if (v instanceof Decimal || v instanceof PlainDate || v instanceof Instant)
|
|
190
|
+
return v.toString();
|
|
191
|
+
if (v instanceof Ref)
|
|
192
|
+
return v.text;
|
|
193
|
+
if (v instanceof Uint8Array)
|
|
194
|
+
return hex(v);
|
|
195
|
+
if (typeof v === "bigint")
|
|
196
|
+
return (v < 0n ? -v : v) < 1n << 53n ? Number(v) : v.toString();
|
|
197
|
+
return v;
|
|
198
|
+
}
|
|
199
|
+
/** A key part's text in a path (before percent-encoding). */
|
|
200
|
+
export function keyText(v) {
|
|
201
|
+
const j = toJson(v);
|
|
202
|
+
return typeof j === "string" ? j : JSON.stringify(j);
|
|
203
|
+
}
|
|
204
|
+
const intOf = (v) => {
|
|
205
|
+
if (typeof v === "number" && Number.isInteger(v))
|
|
206
|
+
return BigInt(v);
|
|
207
|
+
if (typeof v === "string" && /^-?\d+$/.test(v))
|
|
208
|
+
return BigInt(v);
|
|
209
|
+
return undefined;
|
|
210
|
+
};
|
|
211
|
+
function tryParse(f) {
|
|
212
|
+
return {
|
|
213
|
+
from: (v) => {
|
|
214
|
+
if (typeof v === "number")
|
|
215
|
+
v = String(v);
|
|
216
|
+
if (typeof v !== "string")
|
|
217
|
+
return undefined;
|
|
218
|
+
try {
|
|
219
|
+
return f(v);
|
|
220
|
+
}
|
|
221
|
+
catch {
|
|
222
|
+
return undefined;
|
|
223
|
+
}
|
|
224
|
+
},
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
/** The conversions generated tables name, one per schema type. */
|
|
228
|
+
export const V = {
|
|
229
|
+
str: { from: (v) => (typeof v === "string" ? v : undefined) },
|
|
230
|
+
/** `int8..int32`, `uint8..uint16`. */
|
|
231
|
+
int: {
|
|
232
|
+
from: (v) => {
|
|
233
|
+
const b = intOf(v);
|
|
234
|
+
return b === undefined ? undefined : Number(b);
|
|
235
|
+
},
|
|
236
|
+
},
|
|
237
|
+
/** `int64`, `uint32`, `uint64`. */
|
|
238
|
+
big: { from: intOf },
|
|
239
|
+
float: { from: (v) => (typeof v === "number" ? v : undefined) },
|
|
240
|
+
bool: { from: (v) => (typeof v === "boolean" ? v : undefined) },
|
|
241
|
+
dec: tryParse((s) => Decimal.parse(s)),
|
|
242
|
+
date: tryParse((s) => PlainDate.parse(s)),
|
|
243
|
+
ts: tryParse((s) => Instant.parse(s)),
|
|
244
|
+
bytes: {
|
|
245
|
+
from: (v) => typeof v === "string" && /^(?:[0-9a-fA-F]{2})*$/.test(v)
|
|
246
|
+
? Uint8Array.from(v.match(/../g) ?? [], (h) => parseInt(h, 16))
|
|
247
|
+
: undefined,
|
|
248
|
+
},
|
|
249
|
+
ref() {
|
|
250
|
+
return { from: (v) => (typeof v === "string" ? new Ref(v) : undefined) };
|
|
251
|
+
},
|
|
252
|
+
oneOf(members) {
|
|
253
|
+
return {
|
|
254
|
+
from: (v) => (typeof v === "string" && members.includes(v) ? v : undefined),
|
|
255
|
+
};
|
|
256
|
+
},
|
|
257
|
+
};
|
|
258
|
+
const typeName = (tpath) => tpath.slice(tpath.lastIndexOf("/") + 1);
|
|
259
|
+
function nodeName(v) {
|
|
260
|
+
return typeof v.type === "string" ? v.type : "?";
|
|
261
|
+
}
|
|
262
|
+
function readField(v, where, def, required) {
|
|
263
|
+
const x = where[def.name];
|
|
264
|
+
if (x === undefined || x === null) {
|
|
265
|
+
if (required)
|
|
266
|
+
throw new DecodeError(`${nodeName(v)}.${def.name}: the answer has no field ${def.name} (a profile that does not show it: generate the code with that profile)`);
|
|
267
|
+
return undefined;
|
|
268
|
+
}
|
|
269
|
+
const out = def.conv.from(x);
|
|
270
|
+
if (out === undefined)
|
|
271
|
+
throw new DecodeError(`${nodeName(v)}.${def.name}: ${JSON.stringify(x)} is not of the field's type (a masked value: generate the code with the caller's profile)`);
|
|
272
|
+
return out;
|
|
273
|
+
}
|
|
274
|
+
function readFields(v, defs, out, all) {
|
|
275
|
+
const fields = (v.fields ?? {});
|
|
276
|
+
for (const [prop, def] of Object.entries(defs)) {
|
|
277
|
+
if (def.cases) {
|
|
278
|
+
const member = readField(v, fields, def, def.required && all);
|
|
279
|
+
if (member === undefined)
|
|
280
|
+
continue;
|
|
281
|
+
const fs = def.cases[member];
|
|
282
|
+
if (!fs)
|
|
283
|
+
throw new DecodeError(`${nodeName(v)}.${def.name}: ${member} is no member`);
|
|
284
|
+
const c = { [prop]: member };
|
|
285
|
+
readFields(v, fs, c, all);
|
|
286
|
+
out[prop] = c;
|
|
287
|
+
}
|
|
288
|
+
else {
|
|
289
|
+
const x = readField(v, fields, def, def.required && all);
|
|
290
|
+
if (x !== undefined)
|
|
291
|
+
out[prop] = x;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
/** Decoding needs the fields of a writer layout not fetched yet. */
|
|
296
|
+
export class NeedLayout extends Error {
|
|
297
|
+
id;
|
|
298
|
+
constructor(id) {
|
|
299
|
+
super(`the fields of layout ${id} are needed`);
|
|
300
|
+
this.name = "NeedLayout";
|
|
301
|
+
this.id = id;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
/** The value a field has in a version written before the field existed (`spec/schema.md` 4.5),
|
|
305
|
+
* by its type as descriptors write it, in the network API's JSON form: an empty string, zero,
|
|
306
|
+
* false, the first member of an enum, 1970-01-01 for a date and 1970-01-01T00:00:00Z for a
|
|
307
|
+
* timestamp, bytes of zeros, an empty reference. */
|
|
308
|
+
export function defaultOf(ty) {
|
|
309
|
+
const inner = (p) => (ty.startsWith(p) && ty.endsWith(")") ? ty.slice(p.length, -1) : undefined);
|
|
310
|
+
if (ty.startsWith("string(") || ty === "text")
|
|
311
|
+
return "";
|
|
312
|
+
const b = inner("bytes(");
|
|
313
|
+
if (b !== undefined)
|
|
314
|
+
return "00".repeat(Number(b.trim()) || 0);
|
|
315
|
+
const d = inner("decimal(");
|
|
316
|
+
if (d !== undefined) {
|
|
317
|
+
const scale = Number((d.split(",")[1] ?? "0").trim()) || 0;
|
|
318
|
+
return scale === 0 ? "0" : `0.${"0".repeat(scale)}`;
|
|
319
|
+
}
|
|
320
|
+
if (ty.startsWith("int") || ty.startsWith("uint"))
|
|
321
|
+
return 0;
|
|
322
|
+
if (ty === "date")
|
|
323
|
+
return "1970-01-01";
|
|
324
|
+
if (ty === "timestamp")
|
|
325
|
+
return "1970-01-01T00:00:00.000000Z";
|
|
326
|
+
if (ty === "bool")
|
|
327
|
+
return false;
|
|
328
|
+
if (ty === "float64")
|
|
329
|
+
return 0;
|
|
330
|
+
try {
|
|
331
|
+
const v = JSON.parse(ty);
|
|
332
|
+
if (Array.isArray(v.enum))
|
|
333
|
+
return (v.enum[0] ?? {}).name ?? "";
|
|
334
|
+
}
|
|
335
|
+
catch {
|
|
336
|
+
// not JSON: a reference or an unknown type, read as text
|
|
337
|
+
}
|
|
338
|
+
return "";
|
|
339
|
+
}
|
|
340
|
+
/** Whether a value written as type `written` reads as type `model` under the same field number:
|
|
341
|
+
* the same type, an enum the model's widens (every member, name and stored value, still there),
|
|
342
|
+
* or a reference (its value is the target's path either way). */
|
|
343
|
+
export function compatible(written, model) {
|
|
344
|
+
if (written === model)
|
|
345
|
+
return true;
|
|
346
|
+
let w, m;
|
|
347
|
+
try {
|
|
348
|
+
w = JSON.parse(written);
|
|
349
|
+
m = JSON.parse(model);
|
|
350
|
+
}
|
|
351
|
+
catch {
|
|
352
|
+
return false;
|
|
353
|
+
}
|
|
354
|
+
if (Array.isArray(w.enum) && Array.isArray(m.enum)) {
|
|
355
|
+
const me = m.enum;
|
|
356
|
+
return w.enum.every((a) => me.some((b) => a.name === b.name && a.value === b.value));
|
|
357
|
+
}
|
|
358
|
+
return w.ref !== undefined && m.ref !== undefined;
|
|
359
|
+
}
|
|
360
|
+
/** The node as the model's layout shows it (`spec/sdk-dsl.md` 1): as it is when written with that
|
|
361
|
+
* layout; else its fields read by field number from the writer layout's fields: a field the
|
|
362
|
+
* writer's layout lacks gets the value the server showed for it or its declared default, a field
|
|
363
|
+
* the model lacks is left out, a field under another name is renamed. A field whose written type
|
|
364
|
+
* conflicts with the model's is a SchemaMismatchError naming it and both types. */
|
|
365
|
+
export function adapt(mt, v, layouts) {
|
|
366
|
+
const got = String(v.layout);
|
|
367
|
+
if (got === mt.layout)
|
|
368
|
+
return v;
|
|
369
|
+
const written = layouts?.fields(got);
|
|
370
|
+
if (written === undefined && layouts)
|
|
371
|
+
throw new NeedLayout(got);
|
|
372
|
+
if (!written)
|
|
373
|
+
throw new SchemaMismatchError(`${mt.type}: the node was written with layout ${got}, whose fields the connection does not know (the generated code has ${mt.layout})`);
|
|
374
|
+
const had = (v.fields ?? {});
|
|
375
|
+
const out = {};
|
|
376
|
+
for (const [no, name, ty] of mt.numbered) {
|
|
377
|
+
const w = written.find((x) => x[0] === no);
|
|
378
|
+
if (w) {
|
|
379
|
+
if (!compatible(w[2], ty))
|
|
380
|
+
throw new SchemaMismatchError(`${mt.type}.${name} (field ${no}): the node was written with layout ${got}, where the field is ${w[2]}; the generated code has ${ty}`);
|
|
381
|
+
if (had[w[1]] !== undefined)
|
|
382
|
+
out[name] = had[w[1]];
|
|
383
|
+
}
|
|
384
|
+
else {
|
|
385
|
+
out[name] = had[name] !== undefined ? had[name] : defaultOf(ty);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
return { ...v, fields: out, layout: mt.layout };
|
|
389
|
+
}
|
|
390
|
+
/** The model of a node in the network API's node form: checked to be of the type, and read by
|
|
391
|
+
* the layout the generated code knows (a node of another layout through `adapt`). */
|
|
392
|
+
export function decode(mt, node, layouts) {
|
|
393
|
+
const got = nodeName(node);
|
|
394
|
+
if (got !== typeName(mt.type))
|
|
395
|
+
throw new DecodeError(`a ${got} node where the generated code reads ${mt.type}`);
|
|
396
|
+
const v = adapt(mt, node, layouts);
|
|
397
|
+
const out = {};
|
|
398
|
+
const key = (v.key ?? {});
|
|
399
|
+
for (const [prop, def] of Object.entries(mt.key)) {
|
|
400
|
+
if (!(def.name in key))
|
|
401
|
+
throw new DecodeError(`${got}.${def.name}: the answer has no key part ${def.name}`);
|
|
402
|
+
out[prop] = readField(v, key, def, true);
|
|
403
|
+
}
|
|
404
|
+
if (mt.twin && typeof key["~"] === "string")
|
|
405
|
+
out.ordinal = key["~"];
|
|
406
|
+
readFields(v, mt.fields, out, true);
|
|
407
|
+
const kids = v.children;
|
|
408
|
+
if (Object.keys(mt.children).length > 0) {
|
|
409
|
+
out.isTree = kids !== undefined;
|
|
410
|
+
if (kids)
|
|
411
|
+
for (const [prop, [t, m]] of Object.entries(mt.children))
|
|
412
|
+
out[prop] = (kids[t] ?? []).map((c) => decode(m(), c, layouts));
|
|
413
|
+
}
|
|
414
|
+
return out;
|
|
415
|
+
}
|
|
416
|
+
/** Fields of an object of the language's names as the network API's `fields` (variant cases
|
|
417
|
+
* with their discriminator). */
|
|
418
|
+
export function encodeFields(defs, o, out = {}) {
|
|
419
|
+
for (const [prop, x] of Object.entries(o)) {
|
|
420
|
+
if (x === undefined)
|
|
421
|
+
continue;
|
|
422
|
+
const def = defs[prop];
|
|
423
|
+
if (!def)
|
|
424
|
+
continue;
|
|
425
|
+
if (def.cases) {
|
|
426
|
+
const c = x;
|
|
427
|
+
const member = c[prop];
|
|
428
|
+
out[def.name] = member;
|
|
429
|
+
encodeFields(def.cases[member] ?? {}, c, out);
|
|
430
|
+
}
|
|
431
|
+
else
|
|
432
|
+
out[def.name] = toJson(x);
|
|
433
|
+
}
|
|
434
|
+
return out;
|
|
435
|
+
}
|
|
436
|
+
// ---- paths ----
|
|
437
|
+
/** Percent-encoding of a path level or a query value (`spec/path-keys.md`). */
|
|
438
|
+
export function enc(s) {
|
|
439
|
+
let o = "";
|
|
440
|
+
for (const c of new TextEncoder().encode(s)) {
|
|
441
|
+
const ch = String.fromCharCode(c);
|
|
442
|
+
if (/[A-Za-z0-9]/.test(ch) || "-._:".includes(ch))
|
|
443
|
+
o += ch;
|
|
444
|
+
else
|
|
445
|
+
o += `%${c.toString(16).toUpperCase().padStart(2, "0")}`;
|
|
446
|
+
}
|
|
447
|
+
return o;
|
|
448
|
+
}
|
|
449
|
+
/** A path of the network API, built level by level; key parts are percent-encoded and joined
|
|
450
|
+
* by `,`, a twin's ordinal follows `~` (`spec/path-keys.md`). */
|
|
451
|
+
export class Path {
|
|
452
|
+
text;
|
|
453
|
+
constructor(text) {
|
|
454
|
+
this.text = text;
|
|
455
|
+
}
|
|
456
|
+
static root(aggregate) {
|
|
457
|
+
return new Path(enc(aggregate));
|
|
458
|
+
}
|
|
459
|
+
/** A node's level: its key parts (each a value of the key part's type). */
|
|
460
|
+
key(...parts) {
|
|
461
|
+
return this.level(parts.map((p) => enc(keyText(p))).join(","));
|
|
462
|
+
}
|
|
463
|
+
/** A twin by its ordinal, on the level just given (or alone for a type without a key). */
|
|
464
|
+
ordinal(ord) {
|
|
465
|
+
return new Path(`${this.text}~${enc(ord)}`);
|
|
466
|
+
}
|
|
467
|
+
/** A child type's level. */
|
|
468
|
+
child(type) {
|
|
469
|
+
return new Path(`${this.text}/${enc(type)}`);
|
|
470
|
+
}
|
|
471
|
+
/** A level given as its encoded text. */
|
|
472
|
+
level(encoded) {
|
|
473
|
+
return new Path(`${this.text}/${encoded}`);
|
|
474
|
+
}
|
|
475
|
+
toString() {
|
|
476
|
+
return this.text;
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
/** The suffix a twin adds to its level. */
|
|
480
|
+
export function twinSuffix(t) {
|
|
481
|
+
return "ord" in t ? `~${enc(t.ord)}` : `@${t.at}`;
|
|
482
|
+
}
|
|
483
|
+
/** Grants. Generated path classes carry the brand of each operation the profile they were
|
|
484
|
+
* generated for grants (every one without `--profile`): an operation it does not grant does
|
|
485
|
+
* not type-check. */
|
|
486
|
+
export const GET = Symbol("oliviadb.get");
|
|
487
|
+
export const TREE = Symbol("oliviadb.tree");
|
|
488
|
+
export const LIST = Symbol("oliviadb.list");
|
|
489
|
+
export const INSERT = Symbol("oliviadb.insert");
|
|
490
|
+
export const UPDATE = Symbol("oliviadb.update");
|
|
491
|
+
export const DELETE = Symbol("oliviadb.delete");
|
|
492
|
+
export const WATCH = Symbol("oliviadb.watch");
|
|
493
|
+
/** A path to one node of a type. */
|
|
494
|
+
export class NodePath {
|
|
495
|
+
path;
|
|
496
|
+
type;
|
|
497
|
+
constructor(path, type) {
|
|
498
|
+
this.path = path;
|
|
499
|
+
this.type = type;
|
|
500
|
+
}
|
|
501
|
+
toString() {
|
|
502
|
+
return this.path.text;
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
/** The nodes of one type under one parent (or an aggregate's roots); `N` is what an insert takes. */
|
|
506
|
+
export class CollPath {
|
|
507
|
+
path;
|
|
508
|
+
type;
|
|
509
|
+
constructor(path, type) {
|
|
510
|
+
this.path = path;
|
|
511
|
+
this.type = type;
|
|
512
|
+
}
|
|
513
|
+
toString() {
|
|
514
|
+
return this.path.text;
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
/** A change record in the HTTP JSON form: each side decoded as a node of the record's type,
|
|
518
|
+
* key and layout (the layout of the version shown last). */
|
|
519
|
+
export function changeOf(v, types, layouts) {
|
|
520
|
+
const t = types[textOf(v.type)];
|
|
521
|
+
if (!t)
|
|
522
|
+
throw new DecodeError(`a change of type ${textOf(v.type)}, which the generated code does not know`);
|
|
523
|
+
const side = (s) => {
|
|
524
|
+
const f = v[s];
|
|
525
|
+
if (!f || typeof f !== "object")
|
|
526
|
+
return undefined;
|
|
527
|
+
const node = { type: v.type, path: v.path, key: v.node_key, fields: f, layout: v.layout };
|
|
528
|
+
return { type: t[0], node: decode(t[1], node, layouts) };
|
|
529
|
+
};
|
|
530
|
+
const op = v.op;
|
|
531
|
+
if (op !== "insert" && op !== "replace" && op !== "delete")
|
|
532
|
+
throw new DecodeError(`change op ${String(op)}`);
|
|
533
|
+
const c = {
|
|
534
|
+
key: textOf(v.key),
|
|
535
|
+
position: textOf(v.position),
|
|
536
|
+
path: textOf(v.path),
|
|
537
|
+
type: textOf(v.type),
|
|
538
|
+
op,
|
|
539
|
+
version: versionOf(v),
|
|
540
|
+
};
|
|
541
|
+
const b = side("before");
|
|
542
|
+
const a = side("after");
|
|
543
|
+
if (b !== undefined)
|
|
544
|
+
c.before = b;
|
|
545
|
+
if (a !== undefined)
|
|
546
|
+
c.after = a;
|
|
547
|
+
return c;
|
|
548
|
+
}
|
|
549
|
+
function query(params) {
|
|
550
|
+
const q = Object.entries(params).map(([k, v]) => `${k}=${enc(v)}`);
|
|
551
|
+
return q.length ? `?${q.join("&")}` : "";
|
|
552
|
+
}
|
|
553
|
+
function checked([st, v]) {
|
|
554
|
+
if (st >= 200 && st < 300)
|
|
555
|
+
return v;
|
|
556
|
+
throw new OliviaDbError(st, v);
|
|
557
|
+
}
|
|
558
|
+
class Conn {
|
|
559
|
+
http;
|
|
560
|
+
native;
|
|
561
|
+
constructor(c) {
|
|
562
|
+
if (c instanceof OliviaDbClient)
|
|
563
|
+
this.http = c;
|
|
564
|
+
else
|
|
565
|
+
this.native = c;
|
|
566
|
+
}
|
|
567
|
+
/** A node, tree or listing as the network API's JSON (rows given in that form). */
|
|
568
|
+
async read(path, params, listing) {
|
|
569
|
+
if (this.http)
|
|
570
|
+
return this.http.request("GET", `/v1/aggregates/${path.text}${query(params)}`);
|
|
571
|
+
return (await this.native.get(path.text, params)).toJson(listing);
|
|
572
|
+
}
|
|
573
|
+
async write(method, path, body) {
|
|
574
|
+
if (this.http)
|
|
575
|
+
return this.http.request(method, `/v1/aggregates/${path.text}`, body);
|
|
576
|
+
return checked(await this.native.write(method, path.text, body));
|
|
577
|
+
}
|
|
578
|
+
async txn(body) {
|
|
579
|
+
if (this.http)
|
|
580
|
+
return this.http.request("POST", "/v1/txn", body);
|
|
581
|
+
return checked(await this.native.txn(body));
|
|
582
|
+
}
|
|
583
|
+
/** A writer layout's fields: `GET /v1/layouts/{id}` over HTTP, the connection's descriptors
|
|
584
|
+
* over the native protocol; null when neither knows it. */
|
|
585
|
+
async layoutFields(id) {
|
|
586
|
+
if (this.native)
|
|
587
|
+
return this.native.layoutFields?.(id) ?? null;
|
|
588
|
+
try {
|
|
589
|
+
const v = await this.http.request("GET", `/v1/layouts/${enc(id)}`);
|
|
590
|
+
return (v.fields ?? []).map((f) => [Number(f.number), textOf(f.name), textOf(f.type)]);
|
|
591
|
+
}
|
|
592
|
+
catch (e) {
|
|
593
|
+
if (e instanceof OliviaDbError && e.status === 404)
|
|
594
|
+
return null;
|
|
595
|
+
throw e;
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
async changes(paths, from, limit) {
|
|
599
|
+
if (!this.http)
|
|
600
|
+
throw new Error("a batch of the change stream is an HTTP request; over the native protocol use watchStream");
|
|
601
|
+
const q = [...paths.map((p) => `path=${enc(p)}`), `from=${enc(from)}`];
|
|
602
|
+
if (limit !== undefined)
|
|
603
|
+
q.push(`limit=${limit}`);
|
|
604
|
+
return this.http.request("GET", `/v1/changes?${q.join("&")}`);
|
|
605
|
+
}
|
|
606
|
+
async *stream(paths, from) {
|
|
607
|
+
if (!this.native)
|
|
608
|
+
throw new Error("the change stream as it comes needs the native protocol; over HTTP read batches with watch");
|
|
609
|
+
for await (const c of this.native.changes(paths, from))
|
|
610
|
+
yield c.toJson();
|
|
611
|
+
}
|
|
612
|
+
async lookup(index, key) {
|
|
613
|
+
if (this.http) {
|
|
614
|
+
const v = await this.http.request("GET", `/v1/lookup/${enc(index)}${query({ key })}`);
|
|
615
|
+
return (v.results ?? []).map((h) => ({
|
|
616
|
+
path: textOf(h.path),
|
|
617
|
+
record: textOf(h.record),
|
|
618
|
+
root: h.root && typeof h.root === "object" ? h.root : undefined,
|
|
619
|
+
}));
|
|
620
|
+
}
|
|
621
|
+
const out = [];
|
|
622
|
+
for (const e of (await this.native.lookup(index, { key })).entries()) {
|
|
623
|
+
if ("node" in e) {
|
|
624
|
+
const root = e.node.toJson("", true);
|
|
625
|
+
const record = String(root.path);
|
|
626
|
+
out.push({ path: e.node.hit ?? record, record, root });
|
|
627
|
+
}
|
|
628
|
+
else
|
|
629
|
+
out.push({ path: e.hitPath, record: e.path, root: undefined });
|
|
630
|
+
}
|
|
631
|
+
return out;
|
|
632
|
+
}
|
|
633
|
+
async search(aggregate, body) {
|
|
634
|
+
if (this.http) {
|
|
635
|
+
const v = await this.http.request("POST", `/v1/search/${enc(aggregate)}`, body);
|
|
636
|
+
return (v.results ?? []).map((h) => [h, typeof h.score === "number" ? h.score : 0]);
|
|
637
|
+
}
|
|
638
|
+
return (await this.native.search(aggregate, body))
|
|
639
|
+
.nodes()
|
|
640
|
+
.map((n) => [n.toJson(n.parent ?? "", true), n.score ?? 0]);
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
/** A text member of an answer, or "". */
|
|
644
|
+
function textOf(x) {
|
|
645
|
+
return typeof x === "string" ? x : "";
|
|
646
|
+
}
|
|
647
|
+
function versionOf(v) {
|
|
648
|
+
const x = v.version;
|
|
649
|
+
if (typeof x === "number" || typeof x === "string" || typeof x === "bigint")
|
|
650
|
+
return BigInt(x);
|
|
651
|
+
throw new DecodeError(`version: ${JSON.stringify(x)}`);
|
|
652
|
+
}
|
|
653
|
+
function writeBody(fields, add) {
|
|
654
|
+
const b = {};
|
|
655
|
+
if (Object.keys(fields).length > 0 || Object.keys(add).length === 0)
|
|
656
|
+
b.fields = fields;
|
|
657
|
+
if (Object.keys(add).length > 0)
|
|
658
|
+
b.add = add;
|
|
659
|
+
return b;
|
|
660
|
+
}
|
|
661
|
+
function patchBody(t, p) {
|
|
662
|
+
return writeBody(encodeFields(t.decl, (p.set ?? {})), encodeFields(t.decl, (p.add ?? {})));
|
|
663
|
+
}
|
|
664
|
+
function insertOp(c, n, position) {
|
|
665
|
+
const o = n;
|
|
666
|
+
const keys = Object.keys(c.type.key);
|
|
667
|
+
const level = keys.length ? keys.map((k) => enc(keyText(o[k]))).join(",") : undefined;
|
|
668
|
+
const rest = Object.fromEntries(Object.entries(o).filter(([k]) => !(k in c.type.key)));
|
|
669
|
+
const body = { fields: encodeFields(c.type.decl, rest) };
|
|
670
|
+
if (position !== undefined && position !== "last")
|
|
671
|
+
body.position =
|
|
672
|
+
position === "first"
|
|
673
|
+
? "first"
|
|
674
|
+
: "before" in position
|
|
675
|
+
? { before: `${level ?? ""}~${position.before}` }
|
|
676
|
+
: { after: `${level ?? ""}~${position.after}` };
|
|
677
|
+
return [level === undefined ? c.path : c.path.level(level), body];
|
|
678
|
+
}
|
|
679
|
+
function written(v) {
|
|
680
|
+
const w = { version: versionOf(v) };
|
|
681
|
+
if (typeof v.path === "string")
|
|
682
|
+
w.path = v.path;
|
|
683
|
+
return w;
|
|
684
|
+
}
|
|
685
|
+
function cursor(k) {
|
|
686
|
+
if (k && typeof k === "object" && "next" in k && typeof k.next === "string")
|
|
687
|
+
return k.next;
|
|
688
|
+
return (Array.isArray(k) ? k : [k]).map((p) => enc(keyText(p))).join(",");
|
|
689
|
+
}
|
|
690
|
+
function listParams(o) {
|
|
691
|
+
const p = {};
|
|
692
|
+
if (o.after !== undefined)
|
|
693
|
+
p.after = cursor(o.after);
|
|
694
|
+
if (o.to !== undefined)
|
|
695
|
+
p.to = cursor(o.to);
|
|
696
|
+
if (o.prefix !== undefined)
|
|
697
|
+
p.prefix = cursor(o.prefix);
|
|
698
|
+
if (o.limit !== undefined)
|
|
699
|
+
p.limit = String(o.limit);
|
|
700
|
+
if (o.asOf !== undefined)
|
|
701
|
+
p.as_of = String(o.asOf);
|
|
702
|
+
return p;
|
|
703
|
+
}
|
|
704
|
+
function getParams(o) {
|
|
705
|
+
const p = {};
|
|
706
|
+
if (o.tree)
|
|
707
|
+
p.tree = "true";
|
|
708
|
+
if (o.each !== undefined)
|
|
709
|
+
p.each = String(o.each);
|
|
710
|
+
if (o.asOf !== undefined)
|
|
711
|
+
p.as_of = String(o.asOf);
|
|
712
|
+
return p;
|
|
713
|
+
}
|
|
714
|
+
/** A lookup through a `unique` index: the record's root, or undefined. */
|
|
715
|
+
export class Unique {
|
|
716
|
+
kind = "unique";
|
|
717
|
+
index;
|
|
718
|
+
key;
|
|
719
|
+
root;
|
|
720
|
+
constructor(index, parts, root) {
|
|
721
|
+
this.index = index;
|
|
722
|
+
this.key = parts.map((p) => enc(keyText(p))).join(",");
|
|
723
|
+
this.root = root;
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
/** A lookup through an index that is not unique: every node found. */
|
|
727
|
+
export class Many {
|
|
728
|
+
kind = "many";
|
|
729
|
+
index;
|
|
730
|
+
key;
|
|
731
|
+
root;
|
|
732
|
+
constructor(index, parts, root) {
|
|
733
|
+
this.index = index;
|
|
734
|
+
this.key = parts.map((p) => enc(keyText(p))).join(",");
|
|
735
|
+
this.root = root;
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
/** An aggregate that may be searched; `H` the union of its hits (`{ type, node }`). */
|
|
739
|
+
export class Searchable {
|
|
740
|
+
aggregate;
|
|
741
|
+
/** Hit types by type name: the name the hit carries and the model. */
|
|
742
|
+
hits;
|
|
743
|
+
constructor(aggregate, hits) {
|
|
744
|
+
this.aggregate = aggregate;
|
|
745
|
+
this.hits = hits;
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
function untyped(v) {
|
|
749
|
+
const obj = (k) => (v[k] && typeof v[k] === "object" ? v[k] : {});
|
|
750
|
+
const n = {
|
|
751
|
+
type: textOf(v.type),
|
|
752
|
+
path: textOf(v.path),
|
|
753
|
+
key: obj("key"),
|
|
754
|
+
fields: obj("fields"),
|
|
755
|
+
layout: textOf(v.layout),
|
|
756
|
+
};
|
|
757
|
+
if (v.children && typeof v.children === "object")
|
|
758
|
+
n.children = Object.fromEntries(Object.entries(v.children).map(([t, a]) => [t, a.map(untyped)]));
|
|
759
|
+
return n;
|
|
760
|
+
}
|
|
761
|
+
/** How often `txn` runs its function again after a 412. */
|
|
762
|
+
export const TXN_RETRIES = 3;
|
|
763
|
+
/** A typed database over HTTP (OliviaDbClient) or the native protocol (NativeClient). */
|
|
764
|
+
export class Db {
|
|
765
|
+
conn;
|
|
766
|
+
constructor(client) {
|
|
767
|
+
this.conn = new Conn(client);
|
|
768
|
+
}
|
|
769
|
+
/** Writer layouts fetched so far, by id (null: the connection does not know it). */
|
|
770
|
+
layouts = new Map();
|
|
771
|
+
layoutsView = { fields: (id) => this.layouts.get(id) };
|
|
772
|
+
/** `f` run with the writer layouts it needs: each one it stops at (`NeedLayout`) is fetched
|
|
773
|
+
* once (`GET /v1/layouts/{id}`, or the connection's descriptors), then `f` runs again. */
|
|
774
|
+
async decoded(f) {
|
|
775
|
+
for (;;) {
|
|
776
|
+
try {
|
|
777
|
+
return f(this.layoutsView);
|
|
778
|
+
}
|
|
779
|
+
catch (e) {
|
|
780
|
+
if (!(e instanceof NeedLayout) || this.layouts.has(e.id))
|
|
781
|
+
throw e;
|
|
782
|
+
this.layouts.set(e.id, await this.conn.layoutFields(e.id));
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
async get(p, o = {}) {
|
|
787
|
+
return (await this.readOne(p, o)).model;
|
|
788
|
+
}
|
|
789
|
+
getVersioned(p, o = {}) {
|
|
790
|
+
return this.readOne(p, o);
|
|
791
|
+
}
|
|
792
|
+
async readOne(p, o) {
|
|
793
|
+
const v = await this.conn.read(p.path, getParams(o), false);
|
|
794
|
+
return { model: await this.decoded((l) => decode(p.type, v, l)), version: versionOf(v) };
|
|
795
|
+
}
|
|
796
|
+
/** A page of a listing. */
|
|
797
|
+
async list(c, o = {}) {
|
|
798
|
+
const v = await this.conn.read(c.path, listParams(o), true);
|
|
799
|
+
return {
|
|
800
|
+
nodes: await this.decoded((l) => (v.nodes ?? []).map((n) => decode(c.type, n, l))),
|
|
801
|
+
next: typeof v.next === "string" ? v.next : undefined,
|
|
802
|
+
version: versionOf(v),
|
|
803
|
+
};
|
|
804
|
+
}
|
|
805
|
+
async lookup(k) {
|
|
806
|
+
const hits = await this.conn.lookup(k.index, k.key);
|
|
807
|
+
const root = (r, l) => (r === undefined ? undefined : decode(k.root, r, l));
|
|
808
|
+
if (k.kind === "many")
|
|
809
|
+
return this.decoded((l) => hits.map((h) => ({ path: h.path, record: h.record, root: root(h.root, l) })));
|
|
810
|
+
const h = hits[0];
|
|
811
|
+
if (!h)
|
|
812
|
+
return undefined;
|
|
813
|
+
if (!h.root)
|
|
814
|
+
throw new DecodeError(`${h.record}: the profile does not show the record's root`);
|
|
815
|
+
const r = h.root;
|
|
816
|
+
return this.decoded((l) => root(r, l));
|
|
817
|
+
}
|
|
818
|
+
/** Ranked text search over an aggregate. */
|
|
819
|
+
async search(s, text, o = {}) {
|
|
820
|
+
const body = { query: text };
|
|
821
|
+
if (o.budget !== undefined)
|
|
822
|
+
body.budget = o.budget;
|
|
823
|
+
if (o.limit !== undefined)
|
|
824
|
+
body.limit = o.limit;
|
|
825
|
+
const found = await this.conn.search(s.aggregate, body);
|
|
826
|
+
return this.decoded((l) => found.map(([v, score]) => {
|
|
827
|
+
const h = s.hits[nodeName(v)];
|
|
828
|
+
if (!h)
|
|
829
|
+
throw new DecodeError(`a search hit of type ${nodeName(v)}, which the generated code does not know`);
|
|
830
|
+
return { hit: { type: h[0], node: decode(h[1], v, l) }, path: textOf(v.path), score };
|
|
831
|
+
}));
|
|
832
|
+
}
|
|
833
|
+
async insert(c, n, o = {}) {
|
|
834
|
+
const [path, body] = insertOp(c, n, o.position);
|
|
835
|
+
return written(await this.conn.write("POST", path, body));
|
|
836
|
+
}
|
|
837
|
+
async update(p, patch) {
|
|
838
|
+
return written(await this.conn.write("PATCH", p.path, patchBody(p.type, patch)));
|
|
839
|
+
}
|
|
840
|
+
/** `ifExists`: a missing node deletes nothing instead of answering 404 (in a transaction). */
|
|
841
|
+
async delete(p, o = {}) {
|
|
842
|
+
if (o.ifExists) {
|
|
843
|
+
const v = await this.conn.txn({ ops: [{ op: "delete", path: p.path.text, if_exists: true }] });
|
|
844
|
+
return written(v);
|
|
845
|
+
}
|
|
846
|
+
return written(await this.conn.write("DELETE", p.path, {}));
|
|
847
|
+
}
|
|
848
|
+
/**
|
|
849
|
+
* One batch of the change stream under the paths (`GET /v1/changes`, HTTP): the changes after
|
|
850
|
+
* `from` (`start`, `now` (the default) or a record's position) up to `limit`, and the position
|
|
851
|
+
* after them. The native protocol streams changes instead: `watchStream`.
|
|
852
|
+
*/
|
|
853
|
+
async watch(paths, o = {}) {
|
|
854
|
+
const ws = Array.isArray(paths) ? paths : [paths];
|
|
855
|
+
const v = await this.conn.changes(ws.map((w) => w.path.text), o.from ?? "now", o.limit);
|
|
856
|
+
const types = Object.assign({}, ...ws.map((w) => w.watchTypes()));
|
|
857
|
+
const changes = await this.decoded((l) => (v.changes ?? []).map((c) => changeOf(c, types, l)));
|
|
858
|
+
return { changes, position: textOf(v.position) };
|
|
859
|
+
}
|
|
860
|
+
/** The changes as they come, over the native protocol's change stream, until the iteration
|
|
861
|
+
* stops (the stream is then cancelled). Over HTTP, read batches with `watch`. */
|
|
862
|
+
async *watchStream(paths, o = {}) {
|
|
863
|
+
const ws = Array.isArray(paths) ? paths : [paths];
|
|
864
|
+
const types = Object.assign({}, ...ws.map((w) => w.watchTypes()));
|
|
865
|
+
for await (const c of this.conn.stream(ws.map((w) => w.path.text), o.from ?? "now"))
|
|
866
|
+
yield await this.decoded((l) => changeOf(c, types, l));
|
|
867
|
+
}
|
|
868
|
+
/** A node of any type, by an untyped path. */
|
|
869
|
+
async getUntyped(p, o = {}) {
|
|
870
|
+
return untyped(await this.conn.read(p, getParams(o), false));
|
|
871
|
+
}
|
|
872
|
+
/** A page of a listing, by an untyped path. */
|
|
873
|
+
async listUntyped(p, o = {}) {
|
|
874
|
+
const v = await this.conn.read(p, listParams(o), true);
|
|
875
|
+
return {
|
|
876
|
+
nodes: (v.nodes ?? []).map(untyped),
|
|
877
|
+
next: typeof v.next === "string" ? v.next : undefined,
|
|
878
|
+
version: versionOf(v),
|
|
879
|
+
};
|
|
880
|
+
}
|
|
881
|
+
/**
|
|
882
|
+
* Operations as one transaction, all or none: `f` collects them (reads in it are sent at
|
|
883
|
+
* once), then they are sent as one `POST /v1/txn`. An answer 412 (a precondition of
|
|
884
|
+
* `unchangedSince` or `updateChecked` failed) runs `f` again, at most TXN_RETRIES times.
|
|
885
|
+
*/
|
|
886
|
+
async txn(f) {
|
|
887
|
+
let last;
|
|
888
|
+
for (let i = 0; i <= TXN_RETRIES; i++) {
|
|
889
|
+
const t = new Txn(this);
|
|
890
|
+
await f(t);
|
|
891
|
+
try {
|
|
892
|
+
return written(await this.conn.txn({ ops: t.ops }));
|
|
893
|
+
}
|
|
894
|
+
catch (e) {
|
|
895
|
+
if (!(e instanceof OliviaDbError && e.status === 412))
|
|
896
|
+
throw e;
|
|
897
|
+
last = e;
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
throw last;
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
/** The operations of one transaction, collected by `Db.txn`'s function. */
|
|
904
|
+
export class Txn {
|
|
905
|
+
db;
|
|
906
|
+
ops = [];
|
|
907
|
+
constructor(db) {
|
|
908
|
+
this.db = db;
|
|
909
|
+
}
|
|
910
|
+
/** Read a node now; its version is what `unchangedSince` takes. */
|
|
911
|
+
get(p) {
|
|
912
|
+
return this.db.getVersioned(p);
|
|
913
|
+
}
|
|
914
|
+
insert(c, n, o = {}) {
|
|
915
|
+
const [path, body] = insertOp(c, n, o.position);
|
|
916
|
+
this.ops.push({ op: "insert", path: path.text, ...body });
|
|
917
|
+
}
|
|
918
|
+
update(p, patch) {
|
|
919
|
+
this.ops.push({ op: "update", path: p.path.text, ...patchBody(p.type, patch) });
|
|
920
|
+
}
|
|
921
|
+
delete(p, o = {}) {
|
|
922
|
+
this.ops.push(o.ifExists ? { op: "delete", path: p.path.text, if_exists: true } : { op: "delete", path: p.path.text });
|
|
923
|
+
}
|
|
924
|
+
/** The transaction applies only if the node is as it was at version `v` (412 otherwise). */
|
|
925
|
+
unchangedSince(p, v) {
|
|
926
|
+
this.ops.push({ op: "unchanged", path: p.path.text, since: toJson(BigInt(v)) });
|
|
927
|
+
}
|
|
928
|
+
/**
|
|
929
|
+
* Read the node, give its model to `f` to change, and write back the fields `f` changed, on
|
|
930
|
+
* the condition that the node is unchanged since the read (a 412 runs the transaction again).
|
|
931
|
+
*/
|
|
932
|
+
async updateChecked(p, f) {
|
|
933
|
+
const { model, version } = await this.db.getVersioned(p);
|
|
934
|
+
const before = encodeFields(p.type.decl, pick(model, p.type.writable));
|
|
935
|
+
const copy = structuredCloneModel(model);
|
|
936
|
+
const after = f(copy) ?? copy;
|
|
937
|
+
const now = encodeFields(p.type.decl, pick(after, p.type.writable));
|
|
938
|
+
const changed = Object.fromEntries(Object.entries(now).filter(([k, x]) => JSON.stringify(before[k]) !== JSON.stringify(x)));
|
|
939
|
+
this.unchangedSince(p, version);
|
|
940
|
+
if (Object.keys(changed).length > 0)
|
|
941
|
+
this.ops.push({ op: "update", path: p.path.text, fields: changed });
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
function pick(m, props) {
|
|
945
|
+
const o = m;
|
|
946
|
+
return Object.fromEntries(props.filter((k) => o[k] !== undefined).map((k) => [k, o[k]]));
|
|
947
|
+
}
|
|
948
|
+
/** A copy of a model that `updateChecked`'s function may change: its fields copied, values
|
|
949
|
+
* (immutable classes) shared. */
|
|
950
|
+
function structuredCloneModel(m) {
|
|
951
|
+
const copy = (x) => Array.isArray(x)
|
|
952
|
+
? x.map(copy)
|
|
953
|
+
: x && typeof x === "object" && Object.getPrototypeOf(x) === Object.prototype
|
|
954
|
+
? Object.fromEntries(Object.entries(x).map(([k, v]) => [k, copy(v)]))
|
|
955
|
+
: x;
|
|
956
|
+
return copy(m);
|
|
957
|
+
}
|