@olivia-db/client 0.0.0-stage → 0.1.1

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/src/native.ts ADDED
@@ -0,0 +1,1254 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ /**
3
+ * Client of OliviaDB's native protocol (`native-protocol.md` of the specification repository),
4
+ * for Node.js: one long-lived connection (TCP, TLS or a Unix socket) carrying many requests at
5
+ * once. Reads are answered as rows: each node's stored key component and value bytes,
6
+ * described by type descriptors the connection receives once; a field is decoded only when it
7
+ * is read (`node.str(f)`, `node.int(f)`, `node.decimal(f)`, ...). Writes are acknowledged with
8
+ * the HTTP API's JSON answer; agent memory and state stay on HTTP (`OliviaDbClient`).
9
+ *
10
+ * const db = await NativeClient.connectTls("localhost", 7655, "token", apiKey, { caFile: "oliviadb-ca.pem" });
11
+ * const rows = await db.get("Customer/C1", { tree: "true" });
12
+ * for (const n of rows.nodes()) {
13
+ * const f = n.desc.field("amount");
14
+ * if (f) console.log(n.desc.typeName, n.decimal(f));
15
+ * }
16
+ * db.close();
17
+ *
18
+ * `Rows.toJson` gives a result as the HTTP API's JSON answer (for debugging and the contract
19
+ * tests, which compare the two). Failures reject with OliviaDbError (an error frame: the HTTP
20
+ * status and problem document) or NativeProtocolError.
21
+ */
22
+ import * as net from "node:net";
23
+ import * as tls from "node:tls";
24
+ import { readFileSync } from "node:fs";
25
+ import { OliviaDbError, type Json } from "./index.ts";
26
+
27
+ const HEADER = 10;
28
+ const MORE = 0x02;
29
+ const OP = {
30
+ HELLO: 0x01,
31
+ READY: 0x02,
32
+ AUTH: 0x03,
33
+ AUTH_OK: 0x04,
34
+ REQUEST: 0x10,
35
+ DESCRIBE: 0x11,
36
+ ROWS: 0x12,
37
+ JSON: 0x13,
38
+ ERROR: 0x14,
39
+ CHANGE: 0x15,
40
+ END: 0x16,
41
+ UNDESCRIBE: 0x17,
42
+ CANCEL: 0x20,
43
+ } as const;
44
+
45
+ /** A frame the server sent that this client cannot read (a protocol error). */
46
+ export class NativeProtocolError extends Error {}
47
+
48
+ const utf8 = new TextDecoder("utf-8", { fatal: true });
49
+ const enc = new TextEncoder();
50
+
51
+ function text(b: Uint8Array): string {
52
+ try {
53
+ return utf8.decode(b);
54
+ } catch {
55
+ throw new NativeProtocolError("a string that is not UTF-8");
56
+ }
57
+ }
58
+
59
+ // ---- body fields (spec section 2: big-endian integers, LEB128 varints) ----
60
+
61
+ class Rd {
62
+ p: number;
63
+ readonly b: Uint8Array;
64
+ constructor(b: Uint8Array, p = 0) {
65
+ this.b = b;
66
+ this.p = p;
67
+ }
68
+ take(n: number): Uint8Array {
69
+ if (n < 0 || this.p + n > this.b.length) throw new NativeProtocolError("a frame shorter than its fields");
70
+ const s = this.b.subarray(this.p, this.p + n);
71
+ this.p += n;
72
+ return s;
73
+ }
74
+ u8(): number {
75
+ return this.take(1)[0];
76
+ }
77
+ u16(): number {
78
+ const s = this.take(2);
79
+ return (s[0] << 8) | s[1];
80
+ }
81
+ u32(): number {
82
+ const s = this.take(4);
83
+ return new DataView(s.buffer, s.byteOffset, 4).getUint32(0);
84
+ }
85
+ u64(): bigint {
86
+ const s = this.take(8);
87
+ return new DataView(s.buffer, s.byteOffset, 8).getBigUint64(0);
88
+ }
89
+ varint(): number {
90
+ let v = 0n;
91
+ for (let i = 0; i < 10; i++) {
92
+ const x = this.u8();
93
+ v |= BigInt(x & 0x7f) << BigInt(7 * i);
94
+ if ((x & 0x80) === 0) return Number(v);
95
+ }
96
+ throw new NativeProtocolError("a varint longer than 10 bytes");
97
+ }
98
+ lp(): Uint8Array {
99
+ return this.take(this.varint());
100
+ }
101
+ str(): string {
102
+ return text(this.lp());
103
+ }
104
+ done(): boolean {
105
+ return this.p === this.b.length;
106
+ }
107
+ }
108
+
109
+ function putVarint(out: number[], v: number): void {
110
+ let x = BigInt(v);
111
+ while (x >= 0x80n) {
112
+ out.push(Number(x & 0x7fn) | 0x80);
113
+ x >>= 7n;
114
+ }
115
+ out.push(Number(x));
116
+ }
117
+
118
+ function putLp(out: number[], b: Uint8Array): void {
119
+ putVarint(out, b.length);
120
+ for (const x of b) out.push(x);
121
+ }
122
+
123
+ function frame(op: number, stream: number, body: Uint8Array | number[]): Uint8Array {
124
+ const f = new Uint8Array(HEADER + body.length);
125
+ const d = new DataView(f.buffer);
126
+ d.setUint32(0, HEADER - 4 + body.length);
127
+ f[4] = op;
128
+ f[5] = 0;
129
+ d.setUint32(6, stream);
130
+ f.set(body, HEADER);
131
+ return f;
132
+ }
133
+
134
+ function hex(b: Uint8Array): string {
135
+ return Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
136
+ }
137
+
138
+ // ---- types ----
139
+
140
+ /** A logical type of a field or key part (`schema.md` 4.1). */
141
+ export type Type =
142
+ | { kind: "string" | "date" | "timestamp" | "bool" | "float64" | "text" | "ref" }
143
+ | { kind: "bytes"; length: number }
144
+ | { kind: "int"; signed: boolean }
145
+ | { kind: "decimal"; scale: number }
146
+ | { kind: "enum"; members: Array<[string, string]> };
147
+
148
+ export function parseType(t: string): Type {
149
+ const bad = () => new NativeProtocolError(`type ${t}`);
150
+ if (t.startsWith("string(")) return { kind: "string" };
151
+ if (t.startsWith("bytes(") && t.endsWith(")")) {
152
+ const n = Number(t.slice(6, -1));
153
+ if (!Number.isInteger(n)) throw bad();
154
+ return { kind: "bytes", length: n };
155
+ }
156
+ if (t.startsWith("decimal(") && t.endsWith(")")) {
157
+ const s = Number((t.slice(8, -1).split(",")[1] ?? "0").trim());
158
+ if (!Number.isInteger(s)) throw bad();
159
+ return { kind: "decimal", scale: s };
160
+ }
161
+ if (t.startsWith("int")) return { kind: "int", signed: true };
162
+ if (t.startsWith("uint")) return { kind: "int", signed: false };
163
+ switch (t) {
164
+ case "date":
165
+ case "timestamp":
166
+ case "bool":
167
+ case "float64":
168
+ case "text":
169
+ return { kind: t };
170
+ }
171
+ let v: unknown;
172
+ try {
173
+ v = JSON.parse(t);
174
+ } catch {
175
+ throw bad();
176
+ }
177
+ if (v && typeof v === "object") {
178
+ const o = v as Json;
179
+ if (Array.isArray(o.enum)) {
180
+ return {
181
+ kind: "enum",
182
+ members: (o.enum as Json[]).map(
183
+ (m) =>
184
+ [typeof m.name === "string" ? m.name : "", typeof m.value === "string" ? m.value : ""] as [string, string],
185
+ ),
186
+ };
187
+ }
188
+ if ("ref" in o) return { kind: "ref" };
189
+ }
190
+ throw bad();
191
+ }
192
+
193
+ /** A field of a descriptor: where it lies in a node's data and whether the caller sees it. */
194
+ export interface Field {
195
+ number: number;
196
+ name: string;
197
+ type: Type;
198
+ /** In the tail (`offset` is then the index among the tail fields). */
199
+ tail: boolean;
200
+ offset: number;
201
+ length: number;
202
+ scale: number;
203
+ /** 0 hidden, 1 shown, 2 masked (spec section 5). */
204
+ shown: number;
205
+ /** A variant case's discriminator and values, when the field belongs to one. */
206
+ caseOf?: { disc: number; values: string[] };
207
+ }
208
+
209
+ export interface KeyPart {
210
+ name: string;
211
+ type: Type;
212
+ descending: boolean;
213
+ }
214
+
215
+ /** A type descriptor (spec section 5). */
216
+ export class Desc {
217
+ readonly strs: Array<[number, number]>;
218
+ readonly layout: string;
219
+ readonly typePath: string;
220
+ readonly bucket: number;
221
+ readonly ordinal: boolean;
222
+ readonly key: KeyPart[];
223
+ readonly fixed: number;
224
+ readonly fields: Field[];
225
+ readonly defaults: Array<[Field, Uint8Array]>;
226
+ readonly children: Map<number, string>;
227
+ constructor(
228
+ layout: string,
229
+ typePath: string,
230
+ bucket: number,
231
+ ordinal: boolean,
232
+ key: KeyPart[],
233
+ fixed: number,
234
+ fields: Field[],
235
+ defaults: Array<[Field, Uint8Array]>,
236
+ children: Map<number, string>,
237
+ ) {
238
+ this.layout = layout;
239
+ this.typePath = typePath;
240
+ this.bucket = bucket;
241
+ this.ordinal = ordinal;
242
+ this.key = key;
243
+ this.fixed = fixed;
244
+ this.fields = fields;
245
+ this.defaults = defaults;
246
+ this.children = children;
247
+ // Fixed string(n) fields outside variant cases, by offset (spec section 6.3).
248
+ this.strs = fields
249
+ .filter((f) => !f.caseOf && !f.tail && f.type.kind === "string")
250
+ .map((f) => [f.offset, f.length] as [number, number])
251
+ .sort((a, b) => a[0] - b[0] || a[1] - b[1]);
252
+ }
253
+ /** The node type's name (the last segment of its type path). */
254
+ get typeName(): string {
255
+ return this.typePath.slice(this.typePath.lastIndexOf("/") + 1);
256
+ }
257
+ /** The aggregate's name. */
258
+ get aggregate(): string {
259
+ return this.typePath.split("/")[0];
260
+ }
261
+ /** A field by name, to read it from nodes of this descriptor. */
262
+ field(name: string): Field | undefined {
263
+ return this.fields.find((f) => f.name === name);
264
+ }
265
+ }
266
+
267
+ function readField(r: Rd): Field {
268
+ return {
269
+ number: r.varint(),
270
+ name: r.str(),
271
+ type: parseType(r.str()),
272
+ tail: r.u8() === 1,
273
+ offset: r.varint(),
274
+ length: r.varint(),
275
+ scale: r.u8(),
276
+ shown: r.u8(),
277
+ };
278
+ }
279
+
280
+ function describe(body: Uint8Array): [number, Desc] {
281
+ const r = new Rd(body);
282
+ const id = r.varint();
283
+ const layout = `sha256:${hex(r.take(32))}`;
284
+ r.str();
285
+ const typePath = r.str();
286
+ r.u16();
287
+ const bucket = r.u8();
288
+ const ordinal = r.u8() === 1;
289
+ const key: KeyPart[] = [];
290
+ for (let i = r.varint(); i > 0; i--) {
291
+ const name = r.str();
292
+ const type = parseType(r.str());
293
+ const descending = r.u8() === 1;
294
+ const coll = r.str();
295
+ if (coll !== "" && coll !== "binary") {
296
+ throw new NativeProtocolError(`key collation ${coll}: this client reads binary collations only`);
297
+ }
298
+ key.push({ name, type, descending });
299
+ }
300
+ const fixed = r.varint();
301
+ const fields: Field[] = [];
302
+ for (let i = r.varint(); i > 0; i--) fields.push(readField(r));
303
+ for (let i = r.varint(); i > 0; i--) {
304
+ const disc = r.varint();
305
+ const values: string[] = [];
306
+ for (let j = r.varint(); j > 0; j--) values.push(r.str());
307
+ for (let j = r.varint(); j > 0; j--) fields.push({ ...readField(r), caseOf: { disc, values } });
308
+ }
309
+ const defaults: Array<[Field, Uint8Array]> = [];
310
+ for (let i = r.varint(); i > 0; i--) {
311
+ const f = readField(r);
312
+ defaults.push([f, r.lp().slice()]);
313
+ }
314
+ const children = new Map<number, string>();
315
+ for (let i = r.varint(); i > 0; i--) {
316
+ const c = r.u16();
317
+ children.set(c, r.str());
318
+ }
319
+ return [id, new Desc(layout, typePath, bucket, ordinal, key, fixed, fields, defaults, children)];
320
+ }
321
+
322
+ type Descs = ReadonlyMap<number, Desc>;
323
+
324
+ // ---- values ----
325
+
326
+ function beInt(b: Uint8Array, signed: boolean): bigint {
327
+ let v = 0n;
328
+ for (const x of b) v = (v << 8n) | BigInt(x);
329
+ if (signed && b.length > 0 && b[0] & 0x80) v -= 1n << BigInt(8 * b.length);
330
+ return v;
331
+ }
332
+
333
+ /** A packed decimal's unscaled value; undefined when the bytes are not packed decimal. */
334
+ function packed(b: Uint8Array): bigint | undefined {
335
+ let v = 0n;
336
+ for (let i = 0; i < b.length; i++) {
337
+ const hi = b[i] >> 4;
338
+ const lo = b[i] & 15;
339
+ if (hi > 9) return undefined;
340
+ v = v * 10n + BigInt(hi);
341
+ if (i + 1 < b.length) {
342
+ if (lo > 9) return undefined;
343
+ v = v * 10n + BigInt(lo);
344
+ } else {
345
+ if (lo === 0xc || lo === 0xf || lo === 0xa || lo === 0xe) return v;
346
+ if (lo === 0xd || lo === 0xb) return -v;
347
+ return undefined;
348
+ }
349
+ }
350
+ return undefined;
351
+ }
352
+
353
+ /** A decimal's text with `scale` digits after the point. */
354
+ export function decimalText(unscaled: bigint, scale: number): string {
355
+ const digits = (unscaled < 0n ? -unscaled : unscaled).toString();
356
+ let body = digits;
357
+ if (scale > 0) {
358
+ const d = digits.padStart(scale + 1, "0");
359
+ body = `${d.slice(0, d.length - scale)}.${d.slice(d.length - scale)}`;
360
+ }
361
+ return unscaled < 0n ? `-${body}` : body;
362
+ }
363
+
364
+ function civil(z0: number): [number, number, number] {
365
+ const z = z0 + 719468;
366
+ const era = Math.floor(z / 146097);
367
+ const doe = z - era * 146097;
368
+ const yoe = Math.floor((doe - Math.floor(doe / 1460) + Math.floor(doe / 36524) - Math.floor(doe / 146096)) / 365);
369
+ const doy = doe - (365 * yoe + Math.floor(yoe / 4) - Math.floor(yoe / 100));
370
+ const mp = Math.floor((5 * doy + 2) / 153);
371
+ const d = doy - Math.floor((153 * mp + 2) / 5) + 1;
372
+ const m = mp < 10 ? mp + 3 : mp - 9;
373
+ return [yoe + era * 400 + (m <= 2 ? 1 : 0), m, d];
374
+ }
375
+
376
+ const p2 = (n: number | bigint, w = 2) => n.toString().padStart(w, "0");
377
+
378
+ /** `YYYY-MM-DD` of days since 1970-01-01. */
379
+ export function dateText(days: number): string {
380
+ const [y, m, d] = civil(days);
381
+ return `${p2(y, 4)}-${p2(m)}-${p2(d)}`;
382
+ }
383
+
384
+ /** `YYYY-MM-DDTHH:MM:SS.ffffffZ` of microseconds since the epoch. */
385
+ export function timestampText(us: bigint): string {
386
+ const day = 86_400_000_000n;
387
+ let days = us / day;
388
+ let rem = us % day;
389
+ if (rem < 0n) {
390
+ rem += day;
391
+ days -= 1n;
392
+ }
393
+ return `${dateText(Number(days))}T${p2(rem / 3_600_000_000n)}:${p2((rem / 60_000_000n) % 60n)}:${p2((rem / 1_000_000n) % 60n)}.${p2(rem % 1_000_000n, 6)}Z`;
394
+ }
395
+
396
+ function intJson(v: bigint): number | string {
397
+ const a = v < 0n ? -v : v;
398
+ return a < 1n << 53n ? Number(v) : v.toString();
399
+ }
400
+
401
+ /** A key part's value. */
402
+ export type KeyValue = bigint | number | boolean | Uint8Array | string;
403
+
404
+ function stripPad(s: string): string {
405
+ return s.replace(/ +$/, "");
406
+ }
407
+
408
+ // ---- nodes ----
409
+
410
+ /** One node of a result: its bytes are views into the frame it came in. */
411
+ export class Node {
412
+ readonly desc: Desc;
413
+ readonly depth: number;
414
+ /** The node's own key component, as stored (`path-keys.md`). */
415
+ readonly key: Uint8Array;
416
+ /** The value as received: layout bytes, with the fixed strings trimmed (`trim`). */
417
+ private readonly data: Uint8Array;
418
+ /** Per fixed string: layout offset, n, offset in data, trimmed length. */
419
+ private readonly trim: Array<[number, number, number, number]>;
420
+ private readonly masks: Array<[number, string]>;
421
+ /** The granted child listings (a tree read), by type name. */
422
+ readonly lists: string[] | undefined;
423
+ /** LOOKUP: the indexed node's path. */
424
+ readonly hit: string | undefined;
425
+ /** SEARCH: the parent path and the score. */
426
+ readonly parent: string | undefined;
427
+ readonly score: number | undefined;
428
+ constructor(
429
+ desc: Desc,
430
+ depth: number,
431
+ key: Uint8Array,
432
+ data: Uint8Array,
433
+ trim: Array<[number, number, number, number]>,
434
+ masks: Array<[number, string]>,
435
+ lists: string[] | undefined,
436
+ hit: string | undefined,
437
+ parent: string | undefined,
438
+ score: number | undefined,
439
+ ) {
440
+ this.desc = desc;
441
+ this.depth = depth;
442
+ this.key = key;
443
+ this.data = data;
444
+ this.trim = trim;
445
+ this.masks = masks;
446
+ this.lists = lists;
447
+ this.hit = hit;
448
+ this.parent = parent;
449
+ this.score = score;
450
+ }
451
+
452
+ private span(off: number, len: number): Uint8Array | undefined {
453
+ if (this.trim.length === 0) return off + len <= this.data.length ? this.data.subarray(off, off + len) : undefined;
454
+ const t = this.trim.find((x) => x[0] === off && x[1] === len);
455
+ if (t) return this.data.subarray(t[2], t[2] + t[3]);
456
+ const at = this.wireAt(off);
457
+ return at !== undefined && at + len <= this.data.length ? this.data.subarray(at, at + len) : undefined;
458
+ }
459
+
460
+ private wireAt(off: number): number | undefined {
461
+ let at = off;
462
+ for (const [lo, n, wo, k] of this.trim) {
463
+ if (lo + n <= off) at = off - (lo + n) + wo + k;
464
+ else if (lo < off) return undefined;
465
+ }
466
+ return at;
467
+ }
468
+
469
+ private tails(): Uint8Array[] {
470
+ const out: Uint8Array[] = [];
471
+ let p = this.wireAt(this.desc.fixed);
472
+ if (p === undefined) return out;
473
+ const d = this.data;
474
+ while (p < d.length) {
475
+ let n = 0;
476
+ for (let i = 0; i < 10 && p < d.length; i++) {
477
+ const x = d[p++];
478
+ n += (x & 0x7f) * 2 ** (7 * i);
479
+ if ((x & 0x80) === 0) break;
480
+ }
481
+ out.push(d.subarray(p, Math.min(p + n, d.length)));
482
+ p += n;
483
+ }
484
+ return out;
485
+ }
486
+
487
+ private present(f: Field): boolean {
488
+ if (!f.caseOf) return true;
489
+ const c = f.caseOf;
490
+ const x = this.desc.fields.find((y) => y.number === c.disc);
491
+ if (!x) return false;
492
+ const b = this.span(x.offset, x.length);
493
+ if (!b) return false;
494
+ try {
495
+ return c.values.includes(stripPad(utf8.decode(b)));
496
+ } catch {
497
+ return false;
498
+ }
499
+ }
500
+
501
+ private bytesOf(f: Field): Uint8Array | undefined {
502
+ if (f.shown !== 1 || !this.present(f)) return undefined;
503
+ if (f.tail) return this.tails()[f.offset];
504
+ return this.span(f.offset, f.length);
505
+ }
506
+
507
+ /** A string, text, enum member or reference field (fixed strings without their padding);
508
+ * a masked field's masked text. Undefined: hidden, or not in this node's variant case. */
509
+ str(f: Field): string | undefined {
510
+ if (f.shown === 2) return this.masks.find(([n]) => n === f.number)?.[1];
511
+ const b = this.bytesOf(f);
512
+ if (!b) return undefined;
513
+ let s: string;
514
+ try {
515
+ s = utf8.decode(b);
516
+ } catch {
517
+ return undefined;
518
+ }
519
+ return f.tail ? s : stripPad(s);
520
+ }
521
+
522
+ /** An integer field. */
523
+ int(f: Field): bigint | undefined {
524
+ if (f.type.kind !== "int") return undefined;
525
+ const b = this.bytesOf(f);
526
+ return b && beInt(b, f.type.signed);
527
+ }
528
+
529
+ /** A decimal field: the unscaled value and the scale. */
530
+ decimal(f: Field): { unscaled: bigint; scale: number } | undefined {
531
+ if (f.type.kind !== "decimal") return undefined;
532
+ const b = this.bytesOf(f);
533
+ const v = b && packed(b);
534
+ return v === undefined ? undefined : { unscaled: v, scale: f.type.scale };
535
+ }
536
+
537
+ /** A timestamp field: microseconds since 1970-01-01T00:00:00Z. */
538
+ timestamp(f: Field): bigint | undefined {
539
+ if (f.type.kind !== "timestamp") return undefined;
540
+ const b = this.bytesOf(f);
541
+ return b && beInt(b, true);
542
+ }
543
+
544
+ /** A date field: days since 1970-01-01. */
545
+ date(f: Field): number | undefined {
546
+ if (f.type.kind !== "date") return undefined;
547
+ const b = this.bytesOf(f);
548
+ return b && Number(beInt(b, true));
549
+ }
550
+
551
+ /** A field's value as the HTTP API's JSON shows it. */
552
+ json(f: Field): unknown {
553
+ if (f.shown === 2) return this.str(f);
554
+ const b = this.bytesOf(f);
555
+ if (!b) return undefined;
556
+ const t = f.type;
557
+ switch (t.kind) {
558
+ case "string":
559
+ case "text":
560
+ case "ref":
561
+ return this.str(f);
562
+ case "bytes":
563
+ return hex(b);
564
+ case "int":
565
+ return intJson(beInt(b, t.signed));
566
+ case "decimal": {
567
+ const v = packed(b);
568
+ return v === undefined ? undefined : decimalText(v, t.scale);
569
+ }
570
+ case "date":
571
+ return dateText(Number(beInt(b, true)));
572
+ case "timestamp":
573
+ return timestampText(beInt(b, true));
574
+ case "bool":
575
+ return b[0] === 1;
576
+ case "float64": {
577
+ if (b.length !== 8) return undefined;
578
+ const x = new DataView(b.buffer, b.byteOffset, 8).getFloat64(0);
579
+ return Number.isFinite(x) ? x : null;
580
+ }
581
+ case "enum": {
582
+ let s: string;
583
+ try {
584
+ s = stripPad(utf8.decode(b));
585
+ } catch {
586
+ return undefined;
587
+ }
588
+ return t.members.find(([, v]) => v === s)?.[0] ?? s;
589
+ }
590
+ }
591
+ }
592
+
593
+ /** The node's key parts, decoded from its component (`path-keys.md`, format 2). */
594
+ keyParts(): KeyValue[] {
595
+ const p = { at: 2 + this.desc.bucket };
596
+ return this.desc.key.map((k) => keyPart(this.key, p, k.type, k.descending));
597
+ }
598
+
599
+ /** The ordinal of a twin, as hexadecimal (`~` in paths). */
600
+ ordinal(): string | undefined {
601
+ if (!this.desc.ordinal) return undefined;
602
+ const p = { at: 2 + this.desc.bucket };
603
+ for (const k of this.desc.key) keyPart(this.key, p, k.type, k.descending);
604
+ return hex(this.key.subarray(p.at, Math.max(p.at, this.key.length - 1)));
605
+ }
606
+
607
+ /** The node's level as a path segment (`key,key~ordinal`, percent-encoded). */
608
+ segment(): string {
609
+ const parts = this.keyParts();
610
+ let s = this.desc.key.map((k, i) => pct(keyText(k.type, parts[i]))).join(",");
611
+ const o = this.ordinal();
612
+ if (o !== undefined) s += `~${o}`;
613
+ return s;
614
+ }
615
+
616
+ private keyJson(): Json {
617
+ const parts = this.keyParts();
618
+ const m: Json = {};
619
+ this.desc.key.forEach((k, i) => (m[k.name] = keyValueJson(k.type, parts[i])));
620
+ const o = this.ordinal();
621
+ if (o !== undefined) m["~"] = o;
622
+ return m;
623
+ }
624
+
625
+ /** The node as the HTTP API's JSON shows it, under `parent` (a path, "" for a root). */
626
+ toJson(parent: string, defaults: boolean): Json {
627
+ const fields: Json = {};
628
+ for (const f of this.desc.fields) {
629
+ const v = this.json(f);
630
+ if (v !== undefined) fields[f.name] = v;
631
+ }
632
+ if (defaults) {
633
+ for (const [f, b] of this.desc.defaults) {
634
+ if (f.shown === 1) {
635
+ if (f.tail) fields[f.name] = "";
636
+ else {
637
+ const n = new Node(this.desc, 0, new Uint8Array(), b, [], [], undefined, undefined, undefined, undefined);
638
+ fields[f.name] = n.json({ ...f, offset: 0 }) ?? null;
639
+ }
640
+ } else if (f.shown === 2) {
641
+ fields[f.name] = new TextDecoder().decode(b);
642
+ }
643
+ }
644
+ }
645
+ const seg = this.segment();
646
+ const path = parent === "" ? `${this.desc.aggregate}/${seg}` : `${parent}/${this.desc.typeName}/${seg}`;
647
+ return { fields, key: this.keyJson(), layout: this.desc.layout, path, type: this.desc.typeName };
648
+ }
649
+ }
650
+
651
+ function pct(s: string): string {
652
+ let o = "";
653
+ for (const c of enc.encode(s)) {
654
+ const ch = String.fromCharCode(c);
655
+ if (/[A-Za-z0-9]/.test(ch) || "-._:".includes(ch)) o += ch;
656
+ else o += `%${c.toString(16).toUpperCase().padStart(2, "0")}`;
657
+ }
658
+ return o;
659
+ }
660
+
661
+ function keyValueJson(t: Type, v: KeyValue): unknown {
662
+ if (t.kind === "enum" && typeof v === "string") return t.members.find(([, x]) => x === v)?.[0] ?? v;
663
+ if (typeof v === "bigint") {
664
+ if (t.kind === "decimal") return decimalText(v, t.scale);
665
+ if (t.kind === "date") return dateText(Number(v));
666
+ if (t.kind === "timestamp") return timestampText(v);
667
+ return intJson(v);
668
+ }
669
+ if (typeof v === "number") return Number.isFinite(v) ? v : null;
670
+ if (v instanceof Uint8Array) return hex(v);
671
+ return v;
672
+ }
673
+
674
+ function keyText(t: Type, v: KeyValue): string {
675
+ const j = keyValueJson(t, v);
676
+ return typeof j === "string" ? j : JSON.stringify(j);
677
+ }
678
+
679
+ /** One key part from a component (`path-keys.md`, format 2, "Part encodings"). */
680
+ function keyPart(b: Uint8Array, p: { at: number }, t: Type, desc: boolean): KeyValue {
681
+ const by = (i: number) => {
682
+ if (i >= b.length) throw new NativeProtocolError("a key part shorter than its encoding");
683
+ return desc ? ~b[i] & 0xff : b[i];
684
+ };
685
+ switch (t.kind) {
686
+ case "int":
687
+ case "decimal":
688
+ case "date":
689
+ case "timestamp": {
690
+ const h = by(p.at);
691
+ const n = h >= 0x80 ? h - 0x80 : 0x80 - h;
692
+ let m = 0n;
693
+ for (let i = 0; i < n; i++) {
694
+ const x = by(p.at + 1 + i);
695
+ m = (m << 8n) | BigInt(h >= 0x80 ? x : ~x & 0xff);
696
+ }
697
+ p.at += 1 + n;
698
+ return h >= 0x80 ? m : -m;
699
+ }
700
+ case "float64": {
701
+ let k = 0n;
702
+ for (let i = 0; i < 8; i++) k = (k << 8n) | BigInt(by(p.at + i));
703
+ p.at += 8;
704
+ const bits = k >> 63n === 1n ? k & ~(1n << 63n) : ~k & ((1n << 64n) - 1n);
705
+ const dv = new DataView(new ArrayBuffer(8));
706
+ dv.setBigUint64(0, bits);
707
+ return dv.getFloat64(0);
708
+ }
709
+ case "bool":
710
+ return by(p.at++) !== 0;
711
+ case "bytes": {
712
+ const v = new Uint8Array(t.length);
713
+ for (let i = 0; i < t.length; i++) v[i] = by(p.at + i);
714
+ p.at += t.length;
715
+ return v;
716
+ }
717
+ case "string":
718
+ case "text":
719
+ case "enum": {
720
+ // Escaped (0x00 as 0x00 0xFF), ended by 0x00 0x01.
721
+ const v: number[] = [];
722
+ for (;;) {
723
+ const x = by(p.at);
724
+ if (x === 0) {
725
+ const y = by(p.at + 1);
726
+ p.at += 2;
727
+ if (y === 0x01) break;
728
+ v.push(0);
729
+ } else {
730
+ v.push(x);
731
+ p.at += 1;
732
+ }
733
+ }
734
+ return text(Uint8Array.from(v));
735
+ }
736
+ default:
737
+ throw new NativeProtocolError("a reference as a key part");
738
+ }
739
+ }
740
+
741
+ /** An entry of a LOOKUP answer: a node, or a record whose root the profile does not show. */
742
+ export type Entry = { node: Node } | { path: string; hitPath: string };
743
+
744
+ function entry(r: Rd, descs: Descs): Entry {
745
+ const id = r.varint();
746
+ if (id === 0) return { path: r.str(), hitPath: r.str() };
747
+ const desc = descs.get(id);
748
+ if (!desc) throw new NativeProtocolError(`descriptor ${id} not held (protocol error P10)`);
749
+ const depth = r.varint();
750
+ const key = r.lp();
751
+ const data = r.lp();
752
+ const trim = trimmed(desc, data);
753
+ const nf = r.u8();
754
+ let lists: string[] | undefined;
755
+ if (nf & 1) {
756
+ lists = [];
757
+ for (let n = r.varint(); n > 0; n--) lists.push(desc.children.get(r.u16()) ?? "");
758
+ }
759
+ const masks: Array<[number, string]> = [];
760
+ if (nf & 2) for (let n = r.varint(); n > 0; n--) masks.push([r.varint(), r.str()]);
761
+ const parent = nf & 4 ? r.str() : undefined;
762
+ let score: number | undefined;
763
+ if (nf & 8) {
764
+ const dv = new DataView(new ArrayBuffer(4));
765
+ dv.setUint32(0, r.u32());
766
+ score = dv.getFloat32(0);
767
+ }
768
+ const hit = nf & 16 ? r.str() : undefined;
769
+ return { node: new Node(desc, depth, key, data, trim, masks, lists, hit, parent, score) };
770
+ }
771
+
772
+ /** Where a value's trimmed fixed strings are (spec section 6.3). */
773
+ export function trimmed(desc: Desc, data: Uint8Array): Array<[number, number, number, number]> {
774
+ const bad = (m: string) => new NativeProtocolError(`${m} (protocol error P13)`);
775
+ const out: Array<[number, number, number, number]> = [];
776
+ let p = 0;
777
+ let end = 0;
778
+ for (const [off, n] of desc.strs) {
779
+ p += off - end;
780
+ let k = 0;
781
+ for (let i = 0; ; i++) {
782
+ if (i === 10) throw bad("a varint longer than 10 bytes");
783
+ if (p >= data.length) throw bad("a value that ends before a fixed string");
784
+ const x = data[p++];
785
+ k += (x & 0x7f) * 2 ** (7 * i);
786
+ if ((x & 0x80) === 0) break;
787
+ }
788
+ if (k > n) throw bad("a trimmed length above the field's");
789
+ if (p + k > data.length) throw bad("a value that ends inside a fixed string");
790
+ out.push([off, n, p, k]);
791
+ p += k;
792
+ end = off + n;
793
+ }
794
+ if (data.length < p + Math.max(0, desc.fixed - end)) throw bad("a value that ends inside the fixed area");
795
+ return out;
796
+ }
797
+
798
+ // ---- results ----
799
+
800
+ function head(b: Uint8Array) {
801
+ const r = new Rd(b);
802
+ const f = r.u8();
803
+ const version = f & 1 ? r.u64() : undefined;
804
+ const next = f & 2 ? r.str() : undefined;
805
+ const base = f & 4 ? r.str() : undefined;
806
+ const applied = f & 8 ? { through: r.u64(), caughtUp: r.u8() === 1 } : undefined;
807
+ const tokens = f & 16 ? r.u64() : undefined;
808
+ return { at: r.p, version, next, base, applied, tokens };
809
+ }
810
+
811
+ /** A read's answer: its frames as received, nodes read from them on demand. */
812
+ export class Rows {
813
+ frames: Array<[Uint8Array, Descs]> = [];
814
+ version: bigint | undefined;
815
+ /** A listing page's `after` for the next page. */
816
+ next: string | undefined;
817
+ /** The path of the depth-0 nodes' parent. */
818
+ base = "";
819
+ appliedThrough: { through: bigint; caughtUp: boolean } | undefined;
820
+ tokens: bigint | undefined;
821
+
822
+ /** Every entry (node, or LOOKUP's path-only entry) in order. */
823
+ *entries(): Generator<Entry> {
824
+ for (const [b, descs] of this.frames) {
825
+ const r = new Rd(b, head(b).at);
826
+ while (!r.done()) yield entry(r, descs);
827
+ }
828
+ }
829
+
830
+ /** The nodes, in order (pre-order for a tree). */
831
+ nodes(): Node[] {
832
+ const out: Node[] = [];
833
+ for (const e of this.entries()) if ("node" in e) out.push(e.node);
834
+ return out;
835
+ }
836
+
837
+ /** The answer as the HTTP API's JSON for a GET of a node (`listing` false) or a listing. */
838
+ toJson(listing: boolean): Json {
839
+ const paths: string[] = [];
840
+ const stack: Array<[Json, string]> = [];
841
+ const tops: Json[] = [];
842
+ const attach = () => {
843
+ const [done, tn] = stack.pop()!;
844
+ const p = stack[stack.length - 1];
845
+ if (!p) {
846
+ tops.push(done);
847
+ return;
848
+ }
849
+ const ch = (p[0].children ??= {}) as Record<string, Json[]>;
850
+ (ch[tn] ??= []).push(done);
851
+ };
852
+ for (const n of this.nodes()) {
853
+ const parent = n.depth === 0 ? (n.parent ?? this.base) : paths[n.depth - 1];
854
+ const v = n.toJson(parent, true);
855
+ paths.length = n.depth;
856
+ paths.push(String(v.path));
857
+ while (stack.length > n.depth) attach();
858
+ if (n.lists && n.lists.length > 0) v.children = Object.fromEntries(n.lists.map((t) => [t, []]));
859
+ stack.push([v, n.desc.typeName]);
860
+ }
861
+ while (stack.length > 0) attach();
862
+ const version = this.version === undefined ? null : intJson(this.version);
863
+ if (listing) return { next: this.next ?? null, nodes: tops, version };
864
+ const v = tops.pop();
865
+ if (!v) throw new NativeProtocolError("a node read without its node");
866
+ v.version = version;
867
+ return v;
868
+ }
869
+ }
870
+
871
+ // ---- the connection ----
872
+
873
+ type Received = { op: number; flags: number; body: Uint8Array; descs: Descs } | { closed: string };
874
+
875
+ class Queue<T> {
876
+ private items: T[] = [];
877
+ private waiting: Array<(v: T) => void> = [];
878
+ push(v: T): void {
879
+ const w = this.waiting.shift();
880
+ if (w) w(v);
881
+ else this.items.push(v);
882
+ }
883
+ take(): Promise<T> {
884
+ const v = this.items.shift();
885
+ if (v !== undefined) return Promise.resolve(v);
886
+ return new Promise((r) => this.waiting.push(r));
887
+ }
888
+ }
889
+
890
+ function problem(body: Uint8Array): OliviaDbError {
891
+ const r = new Rd(body);
892
+ const st = r.u16();
893
+ let p: Json;
894
+ try {
895
+ p = JSON.parse(text(r.lp())) as Json;
896
+ } catch (e) {
897
+ throw new NativeProtocolError(String(e));
898
+ }
899
+ const s = typeof p.status === "number" && p.status !== 0 ? p.status : st;
900
+ return new OliviaDbError(s, p);
901
+ }
902
+
903
+ const ALPN = "oliviadb/1";
904
+
905
+ /** TLS settings of `NativeClient.connectTls`, besides the options of `node:tls`. */
906
+ export interface TlsOptions extends tls.ConnectionOptions {
907
+ /** Trust the certificates of this PEM file instead of the platform's roots. */
908
+ caFile?: string;
909
+ /** The name to verify in the server's certificate, when it is not the host connected to. */
910
+ serverName?: string;
911
+ }
912
+
913
+ /** A native-protocol connection. Concurrent requests share it, each on its own stream. */
914
+ export class NativeClient {
915
+ private streams = new Map<number, Queue<Received>>();
916
+ private nextStream = 3;
917
+ private descs: Descs = new Map();
918
+ private buf = new Uint8Array(0);
919
+ private closedWhy: string | undefined;
920
+ private handshake: Queue<[number, Uint8Array]> | undefined = new Queue();
921
+
922
+ private readonly sock: net.Socket;
923
+
924
+ private constructor(sock: net.Socket) {
925
+ this.sock = sock;
926
+ sock.setNoDelay?.(true);
927
+ sock.on("data", (d: Buffer) => this.onData(d));
928
+ sock.on("error", (e) => this.onClose(e.message));
929
+ sock.on("close", () => this.onClose("the server closed the connection"));
930
+ }
931
+
932
+ /** Connects over plain TCP (the server serves plain text on loopback only, unless configured
933
+ * otherwise) and authenticates with `scheme` (`token` or `bearer`) and the credential the
934
+ * HTTP Authorization header would carry. */
935
+ static connectTcp(host: string, port: number, scheme: string, credential: string): Promise<NativeClient> {
936
+ return NativeClient.start(net.connect({ host, port }), "connect", scheme, credential);
937
+ }
938
+
939
+ /** Connects over TLS (spec `native-protocol.md` section 1): TLS from the first byte, ALPN
940
+ * `oliviadb/1` offered and required, the certificate chain verified against the platform's
941
+ * roots (`tls.getCACertificates("system")`, Node 22.15 and later; earlier Node versions use
942
+ * Node's own roots) or `options.caFile` / `options.ca`, and the server name
943
+ * (`options.serverName`, else `host`) verified against the certificate. Other `options` are
944
+ * passed to `node:tls`. */
945
+ static async connectTls(
946
+ host: string,
947
+ port: number,
948
+ scheme: string,
949
+ credential: string,
950
+ options: TlsOptions = {},
951
+ ): Promise<NativeClient> {
952
+ const { caFile, serverName, ...rest } = options;
953
+ let ca = rest.ca;
954
+ if (ca === undefined && caFile !== undefined) ca = readFileSync(caFile, "utf8");
955
+ if (ca === undefined) {
956
+ const sys = (tls as { getCACertificates?: (kind: string) => string[] }).getCACertificates;
957
+ if (sys) ca = sys("system");
958
+ }
959
+ const name = serverName ?? rest.servername ?? host;
960
+ const sock = tls.connect({
961
+ ...rest,
962
+ host,
963
+ port,
964
+ ca,
965
+ servername: name,
966
+ ALPNProtocols: [ALPN],
967
+ rejectUnauthorized: true,
968
+ checkServerIdentity: (_h, cert) => tls.checkServerIdentity(name, cert),
969
+ });
970
+ try {
971
+ await new Promise<void>((res, rej) => {
972
+ sock.once("secureConnect", () => res());
973
+ sock.once("error", (e: Error) => rej(new Error(`${host}:${port}: TLS handshake: ${e.message}`)));
974
+ });
975
+ } catch (e) {
976
+ sock.destroy();
977
+ throw e;
978
+ }
979
+ if (sock.alpnProtocol !== ALPN) {
980
+ sock.destroy();
981
+ throw new Error(`${host}:${port}: the server selected ALPN ${sock.alpnProtocol || "none"}, not ${ALPN}`);
982
+ }
983
+ return NativeClient.start(sock, null, scheme, credential);
984
+ }
985
+
986
+ /** Connects over a Unix socket. */
987
+ static connectUnix(path: string, scheme: string, credential: string): Promise<NativeClient> {
988
+ return NativeClient.start(net.connect({ path }), "connect", scheme, credential);
989
+ }
990
+
991
+ private static async start(
992
+ sock: net.Socket,
993
+ ready: string | null,
994
+ scheme: string,
995
+ credential: string,
996
+ ): Promise<NativeClient> {
997
+ if (ready !== null) {
998
+ await new Promise<void>((res, rej) => {
999
+ sock.once(ready, () => res());
1000
+ sock.once("error", rej);
1001
+ });
1002
+ }
1003
+ const c = new NativeClient(sock);
1004
+ // HELLO and AUTH together (spec section 3), then READY and AUTH_OK.
1005
+ const hello: number[] = [0, 1, 0, 1];
1006
+ putVarint(hello, 1);
1007
+ putLp(hello, enc.encode("client"));
1008
+ putLp(hello, enc.encode("oliviadb-js 0.1.1"));
1009
+ const auth: number[] = [];
1010
+ putLp(auth, enc.encode(scheme));
1011
+ putLp(auth, enc.encode(credential));
1012
+ sock.write(frame(OP.HELLO, 1, hello));
1013
+ sock.write(frame(OP.AUTH, 1, auth));
1014
+ for (const want of [OP.READY, OP.AUTH_OK]) {
1015
+ const [o, body] = await c.handshake!.take();
1016
+ if (o === -1) {
1017
+ sock.destroy();
1018
+ throw new Error(`closed during the handshake: ${text(body)}`);
1019
+ }
1020
+ if (o === OP.ERROR) {
1021
+ sock.destroy();
1022
+ throw problem(body);
1023
+ }
1024
+ if (o !== want) {
1025
+ sock.destroy();
1026
+ throw new NativeProtocolError(`opcode 0x${o.toString(16).padStart(2, "0")} in the handshake`);
1027
+ }
1028
+ }
1029
+ c.handshake = undefined;
1030
+ return c;
1031
+ }
1032
+
1033
+ private onData(d: Buffer): void {
1034
+ const b = new Uint8Array(this.buf.length + d.length);
1035
+ b.set(this.buf);
1036
+ b.set(d, this.buf.length);
1037
+ let p = 0;
1038
+ try {
1039
+ while (b.length - p >= 4) {
1040
+ const len = new DataView(b.buffer, b.byteOffset + p, 4).getUint32(0);
1041
+ if (len < 6) throw new NativeProtocolError("a frame shorter than its header");
1042
+ if (b.length - p < 4 + len) break;
1043
+ const op = b[p + 4];
1044
+ const flags = b[p + 5];
1045
+ const stream = new DataView(b.buffer, b.byteOffset + p + 6, 4).getUint32(0);
1046
+ const body = b.slice(p + HEADER, p + 4 + len);
1047
+ p += 4 + len;
1048
+ this.dispatch(op, flags, stream, body);
1049
+ }
1050
+ } catch (e) {
1051
+ this.sock.destroy();
1052
+ this.onClose(String(e instanceof Error ? e.message : e));
1053
+ return;
1054
+ }
1055
+ this.buf = b.slice(p);
1056
+ }
1057
+
1058
+ /** Frames to their streams, descriptors kept in arrival order. */
1059
+ private dispatch(op: number, flags: number, stream: number, body: Uint8Array): void {
1060
+ if (this.handshake) {
1061
+ this.handshake.push([op, body]);
1062
+ return;
1063
+ }
1064
+ if (op === OP.DESCRIBE) {
1065
+ const [id, d] = describe(body);
1066
+ const m = new Map(this.descs);
1067
+ m.set(id, d);
1068
+ this.descs = m;
1069
+ } else if (op === OP.UNDESCRIBE) {
1070
+ const m = new Map(this.descs);
1071
+ m.delete(new Rd(body).varint());
1072
+ this.descs = m;
1073
+ } else {
1074
+ this.streams.get(stream)?.push({ op, flags, body, descs: this.descs });
1075
+ }
1076
+ }
1077
+
1078
+ private onClose(why: string): void {
1079
+ if (this.closedWhy !== undefined) return;
1080
+ this.closedWhy = why;
1081
+ this.handshake?.push([-1, enc.encode(why)]);
1082
+ for (const q of this.streams.values()) q.push({ closed: why });
1083
+ }
1084
+
1085
+ private send(
1086
+ route: number,
1087
+ path: string,
1088
+ params: Record<string, string>,
1089
+ body: Uint8Array,
1090
+ ): [number, Queue<Received>] {
1091
+ const s = this.nextStream;
1092
+ this.nextStream += 2;
1093
+ const q = new Queue<Received>();
1094
+ this.streams.set(s, q);
1095
+ if (this.closedWhy !== undefined) {
1096
+ q.push({ closed: this.closedWhy });
1097
+ return [s, q];
1098
+ }
1099
+ const b: number[] = [route];
1100
+ putLp(b, enc.encode(path));
1101
+ const keys = Object.keys(params).sort();
1102
+ putVarint(b, keys.length);
1103
+ for (const k of keys) {
1104
+ putLp(b, enc.encode(k));
1105
+ putLp(b, enc.encode(params[k]));
1106
+ }
1107
+ putLp(b, body);
1108
+ this.sock.write(frame(OP.REQUEST, s, b));
1109
+ return [s, q];
1110
+ }
1111
+
1112
+ private async rows(route: number, path: string, params: Record<string, string>, body: Uint8Array): Promise<Rows> {
1113
+ const [s, q] = this.send(route, path, params, body);
1114
+ try {
1115
+ const rows = new Rows();
1116
+ for (;;) {
1117
+ const r = await q.take();
1118
+ if ("closed" in r) throw new Error(r.closed);
1119
+ if (r.op === OP.ROWS) {
1120
+ const h = head(r.body);
1121
+ if (h.base !== undefined) rows.base = h.base;
1122
+ rows.frames.push([r.body, r.descs]);
1123
+ if ((r.flags & MORE) === 0) {
1124
+ rows.version = h.version;
1125
+ rows.next = h.next;
1126
+ rows.appliedThrough = h.applied;
1127
+ rows.tokens = h.tokens;
1128
+ return rows;
1129
+ }
1130
+ } else if (r.op === OP.ERROR) {
1131
+ throw problem(r.body);
1132
+ } else {
1133
+ throw new NativeProtocolError(`opcode 0x${r.op.toString(16)} in a result`);
1134
+ }
1135
+ }
1136
+ } finally {
1137
+ this.streams.delete(s);
1138
+ }
1139
+ }
1140
+
1141
+ /** `GET /v1/aggregates/{path}` (a node, `tree=true` with `each`, or a listing page). */
1142
+ get(path: string, params: Record<string, string> = {}): Promise<Rows> {
1143
+ return this.rows(0x01, path, params, new Uint8Array());
1144
+ }
1145
+
1146
+ /** `GET /v1/lookup/{index}`. */
1147
+ lookup(index: string, params: Record<string, string> = {}): Promise<Rows> {
1148
+ return this.rows(0x02, index, params, new Uint8Array());
1149
+ }
1150
+
1151
+ /** `POST /v1/search/{aggregate}` with the HTTP body. */
1152
+ search(aggregate: string, body: Json): Promise<Rows> {
1153
+ return this.rows(0x03, aggregate, {}, enc.encode(JSON.stringify(body)));
1154
+ }
1155
+
1156
+ private async json(route: number, path: string, params: Record<string, string>, body: Json): Promise<[number, Json]> {
1157
+ const [s, q] = this.send(route, path, params, enc.encode(JSON.stringify(body)));
1158
+ try {
1159
+ const r = await q.take();
1160
+ if ("closed" in r) throw new Error(r.closed);
1161
+ if (r.op === OP.JSON) {
1162
+ const d = new Rd(r.body);
1163
+ const st = d.u16();
1164
+ return [st, JSON.parse(text(d.lp())) as Json];
1165
+ }
1166
+ if (r.op === OP.ERROR) throw problem(r.body);
1167
+ throw new NativeProtocolError(`opcode 0x${r.op.toString(16)} for a write`);
1168
+ } finally {
1169
+ this.streams.delete(s);
1170
+ }
1171
+ }
1172
+
1173
+ /** `POST /v1/txn`: the HTTP route's status and answer. */
1174
+ txn(body: Json): Promise<[number, Json]> {
1175
+ return this.json(0x04, "", {}, body);
1176
+ }
1177
+
1178
+ /** `POST`, `PATCH` or `DELETE /v1/aggregates/{path}`: the status and the JSON answer. */
1179
+ write(method: string, path: string, body: Json): Promise<[number, Json]> {
1180
+ return this.json(0x05, path, { method }, body);
1181
+ }
1182
+
1183
+ /** The change stream of native aggregates under `paths`, from a position (`start`, `now` or
1184
+ * a record's): its records as they come, until the iteration stops (the stream is then
1185
+ * cancelled). */
1186
+ async *changes(paths: string[], from: string): AsyncGenerator<Change> {
1187
+ const [s, q] = this.send(0x06, "", { path: paths.join(" "), from }, new Uint8Array());
1188
+ try {
1189
+ for (;;) {
1190
+ const r = await q.take();
1191
+ if ("closed" in r) throw new Error(r.closed);
1192
+ if (r.op === OP.CHANGE) yield new Change(r.body, r.descs);
1193
+ else if (r.op === OP.END) return;
1194
+ else if (r.op === OP.ERROR) throw problem(r.body);
1195
+ else throw new NativeProtocolError(`opcode 0x${r.op.toString(16)} in a change stream`);
1196
+ }
1197
+ } finally {
1198
+ const c = new Uint8Array(4);
1199
+ new DataView(c.buffer).setUint32(0, s);
1200
+ if (this.closedWhy === undefined) this.sock.write(frame(OP.CANCEL, 0, c));
1201
+ this.streams.delete(s);
1202
+ }
1203
+ }
1204
+
1205
+ close(): void {
1206
+ this.sock.destroy();
1207
+ }
1208
+ }
1209
+
1210
+ /** One change record. */
1211
+ export class Change {
1212
+ private readonly body: Uint8Array;
1213
+ private readonly descs: Descs;
1214
+ constructor(body: Uint8Array, descs: Descs) {
1215
+ this.body = body;
1216
+ this.descs = descs;
1217
+ }
1218
+
1219
+ /** The record as the HTTP change stream's JSON object. */
1220
+ toJson(): Json {
1221
+ const r = new Rd(this.body);
1222
+ const cflags = r.u8();
1223
+ const position = r.str();
1224
+ const version = r.u64();
1225
+ const op = ({ 1: "insert", 2: "replace", 3: "delete" } as Record<number, string>)[r.u8()];
1226
+ if (!op) throw new NativeProtocolError("change op");
1227
+ const id = hex(r.take(16));
1228
+ const parent = r.str();
1229
+ const sides: Array<[number, Json, Desc]> = [];
1230
+ for (const bit of [1, 2]) {
1231
+ if (cflags & bit) {
1232
+ const e = entry(r, this.descs);
1233
+ if (!("node" in e)) throw new NativeProtocolError("an entry in a change");
1234
+ sides.push([bit, e.node.toJson(parent, false), e.node.desc]);
1235
+ }
1236
+ }
1237
+ const last = sides[sides.length - 1];
1238
+ if (!last) throw new NativeProtocolError("a change without a node");
1239
+ const [, lv, ld] = last;
1240
+ const rec: Json = {
1241
+ key: id,
1242
+ position,
1243
+ collection: ld.aggregate,
1244
+ path: lv.path,
1245
+ type: ld.typeName,
1246
+ node_key: lv.key,
1247
+ op,
1248
+ version: intJson(version),
1249
+ layout: lv.layout,
1250
+ };
1251
+ for (const [bit, v] of sides) rec[bit === 1 ? "before" : "after"] = v.fields;
1252
+ return rec;
1253
+ }
1254
+ }