@olivia-db/client 0.1.3 → 0.2.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/dist/dsl.d.ts CHANGED
@@ -391,7 +391,10 @@ export interface Node {
391
391
  }
392
392
  /** How often `txn` runs its function again after a 412. */
393
393
  export declare const TXN_RETRIES = 3;
394
- /** A typed database over HTTP (OliviaDbClient) or the native protocol (NativeClient). */
394
+ /** A typed database over HTTP (OliviaDbClient) or the native protocol (NativeClient). Create one
395
+ * per process over a shared client and use it from every request handler: requests in flight at
396
+ * once each get their own answer. The argument of a `txn` callback collects one transaction and
397
+ * is sent when the callback returns: use it only inside the callback. */
395
398
  export declare class Db {
396
399
  private readonly conn;
397
400
  constructor(client: OliviaDbClient | NativeConn);
package/dist/dsl.js CHANGED
@@ -760,7 +760,10 @@ function untyped(v) {
760
760
  }
761
761
  /** How often `txn` runs its function again after a 412. */
762
762
  export const TXN_RETRIES = 3;
763
- /** A typed database over HTTP (OliviaDbClient) or the native protocol (NativeClient). */
763
+ /** A typed database over HTTP (OliviaDbClient) or the native protocol (NativeClient). Create one
764
+ * per process over a shared client and use it from every request handler: requests in flight at
765
+ * once each get their own answer. The argument of a `txn` callback collects one transaction and
766
+ * is sent when the callback returns: use it only inside the callback. */
764
767
  export class Db {
765
768
  conn;
766
769
  constructor(client) {
package/dist/index.d.ts CHANGED
@@ -9,6 +9,11 @@
9
9
  *
10
10
  * Arguments and results are those of the MCP tools of the same name; failures throw
11
11
  * OliviaDbError (an RFC 9457 problem document), retried when the server says retryable.
12
+ *
13
+ * Concurrency and lifecycle: create one client per process and share it; any number of requests
14
+ * may be in flight at once. Nothing to open or close: fetch makes and keeps the connections, so
15
+ * the next request after a server restart connects again, and with several nodes a refused
16
+ * connection or a retryable 503 moves the client to the primary (failover). Do not pool clients.
12
17
  */
13
18
  export type Json = Record<string, unknown>;
14
19
  /**
@@ -66,6 +71,11 @@ export interface StateItem {
66
71
  visibility: "private" | "tenant";
67
72
  score?: number;
68
73
  }
74
+ /** One page of a state listing: `next` is the cursor of the following page, `null` on the last. */
75
+ export interface StatePage<T> {
76
+ items: T[];
77
+ next: string | null;
78
+ }
69
79
  export interface WatchEvent {
70
80
  id: string;
71
81
  data: Json;
@@ -174,25 +184,71 @@ export declare class OliviaDbClient {
174
184
  }>;
175
185
  stateGet(namespace: string[], key: string): Promise<StateItem | null>;
176
186
  stateDelete(namespace: string[], key?: string, prefix?: boolean): Promise<number>;
187
+ /** One page of a namespace's documents; `after` is the previous page's `next` (or a key). */
177
188
  stateList(namespace: string[], o?: {
178
189
  after?: string;
179
190
  limit?: number;
180
191
  reverse?: boolean;
181
192
  }): Promise<StateItem[]>;
193
+ stateListPage(namespace: string[], o?: {
194
+ after?: string;
195
+ limit?: number;
196
+ reverse?: boolean;
197
+ }): Promise<StatePage<StateItem>>;
198
+ /** Every document of a namespace, `page` at a time (1 to 1000), following the server's cursors. */
199
+ iterStateList(namespace: string[], o?: {
200
+ reverse?: boolean;
201
+ page?: number;
202
+ }): AsyncGenerator<StateItem>;
182
203
  stateNamespaces(o?: {
183
204
  prefix?: string[];
184
205
  suffix?: string[];
185
206
  max_depth?: number;
186
207
  limit?: number;
187
208
  offset?: number;
209
+ after?: string;
188
210
  }): Promise<string[][]>;
211
+ stateNamespacesPage(o?: {
212
+ prefix?: string[];
213
+ suffix?: string[];
214
+ max_depth?: number;
215
+ limit?: number;
216
+ offset?: number;
217
+ after?: string;
218
+ }): Promise<StatePage<string[]>>;
219
+ /** Every namespace under `prefix` (sorted), following the server's cursors. */
220
+ iterStateNamespaces(o?: {
221
+ prefix?: string[];
222
+ suffix?: string[];
223
+ max_depth?: number;
224
+ page?: number;
225
+ }): AsyncGenerator<string[]>;
189
226
  stateSearch(namespace_prefix: string[], o?: {
190
227
  query?: string;
191
228
  vector?: number[];
192
229
  filter?: Json;
193
230
  limit?: number;
194
231
  offset?: number;
232
+ semantic?: boolean;
233
+ after?: string;
195
234
  }): Promise<StateItem[]>;
235
+ stateSearchPage(namespace_prefix: string[], o?: {
236
+ query?: string;
237
+ vector?: number[];
238
+ filter?: Json;
239
+ limit?: number;
240
+ offset?: number;
241
+ semantic?: boolean;
242
+ after?: string;
243
+ }): Promise<StatePage<StateItem>>;
244
+ /** Every hit of a search, in its order, following the server's cursors. */
245
+ iterStateSearch(namespace_prefix: string[], o?: {
246
+ query?: string;
247
+ vector?: number[];
248
+ filter?: Json;
249
+ semantic?: boolean;
250
+ page?: number;
251
+ }): AsyncGenerator<StateItem>;
196
252
  watch(w: {
197
253
  entities?: string[];
198
254
  paths?: string[];
package/dist/index.js CHANGED
@@ -10,11 +10,40 @@
10
10
  *
11
11
  * Arguments and results are those of the MCP tools of the same name; failures throw
12
12
  * OliviaDbError (an RFC 9457 problem document), retried when the server says retryable.
13
+ *
14
+ * Concurrency and lifecycle: create one client per process and share it; any number of requests
15
+ * may be in flight at once. Nothing to open or close: fetch makes and keeps the connections, so
16
+ * the next request after a server restart connects again, and with several nodes a refused
17
+ * connection or a retryable 503 moves the client to the primary (failover). Do not pool clients.
13
18
  */
19
+ import { trimEndChar } from "./text.js";
14
20
  /** A U64 from a result as a bigint (exact). */
15
21
  export function u64(v) {
16
22
  return typeof v === "bigint" ? v : BigInt(v);
17
23
  }
24
+ /**
25
+ * The items of every page, passing each page's `next` as `after` to `fetch`. A full page
26
+ * without `next` comes from a server that does not page with cursors: refused, since the
27
+ * rest could not be read (spec server-limits.md 9).
28
+ */
29
+ async function* follow(fetch, page) {
30
+ let after;
31
+ for (;;) {
32
+ const r = await fetch(after);
33
+ yield* r.items;
34
+ if (r.next === undefined) {
35
+ if (r.items.length < page)
36
+ return;
37
+ throw new OliviaDbError(0, {
38
+ type: "unsupported",
39
+ detail: "the server answered a full page without next: it does not page with cursors (spec server-limits.md 9)",
40
+ });
41
+ }
42
+ if (r.next === null)
43
+ return;
44
+ after = r.next;
45
+ }
46
+ }
18
47
  export class OliviaDbError extends Error {
19
48
  status;
20
49
  type;
@@ -44,7 +73,7 @@ export class OliviaDbClient {
44
73
  constructor(o) {
45
74
  if ((o.token === undefined) === (o.apiKey === undefined))
46
75
  throw new Error("give either token or apiKey");
47
- this.bases = (Array.isArray(o.baseUrl) ? o.baseUrl : [o.baseUrl]).map((u) => u.replace(/\/+$/, ""));
76
+ this.bases = (Array.isArray(o.baseUrl) ? o.baseUrl : [o.baseUrl]).map((u) => trimEndChar(u, "/"));
48
77
  if (this.bases.length === 0)
49
78
  throw new Error("no base URL");
50
79
  this.auth = o.token !== undefined ? `Bearer ${o.token}` : `Token ${o.apiKey}`;
@@ -62,7 +91,7 @@ export class OliviaDbClient {
62
91
  return this.bases[this.cur];
63
92
  }
64
93
  next(primary) {
65
- const p = primary?.replace(/\/+$/, "");
94
+ const p = primary == null ? primary : trimEndChar(primary, "/");
66
95
  const i = p ? this.bases.indexOf(p) : -1;
67
96
  this.cur = i >= 0 ? i : (this.cur + 1) % this.bases.length;
68
97
  }
@@ -189,14 +218,65 @@ export class OliviaDbClient {
189
218
  async stateDelete(namespace, key, prefix = false) {
190
219
  return (await this.json("POST", "/v1/state/delete", { namespace, key, prefix: prefix || undefined })).deleted;
191
220
  }
221
+ /** One page of a namespace's documents; `after` is the previous page's `next` (or a key). */
192
222
  async stateList(namespace, o = {}) {
193
- return (await this.json("POST", "/v1/state/list", { namespace, ...o })).items;
223
+ return (await this.stateListPage(namespace, o)).items;
224
+ }
225
+ async stateListPage(namespace, o = {}) {
226
+ const r = await this.json("POST", "/v1/state/list", {
227
+ namespace,
228
+ ...o,
229
+ });
230
+ return { items: r.items, next: r.next ?? null };
231
+ }
232
+ /** Every document of a namespace, `page` at a time (1 to 1000), following the server's cursors. */
233
+ iterStateList(namespace, o = {}) {
234
+ const page = o.page ?? 1000;
235
+ return follow((after) => this.json("POST", "/v1/state/list", {
236
+ namespace,
237
+ after,
238
+ limit: page,
239
+ reverse: o.reverse || undefined,
240
+ }), page);
194
241
  }
195
242
  async stateNamespaces(o = {}) {
196
- return (await this.json("POST", "/v1/state/namespaces", o)).namespaces;
243
+ return (await this.stateNamespacesPage(o)).items;
244
+ }
245
+ async stateNamespacesPage(o = {}) {
246
+ const r = await this.json("POST", "/v1/state/namespaces", o);
247
+ return { items: r.namespaces, next: r.next ?? null };
248
+ }
249
+ /** Every namespace under `prefix` (sorted), following the server's cursors. */
250
+ iterStateNamespaces(o = {}) {
251
+ const { page = 1000, ...rest } = o;
252
+ return follow(async (after) => {
253
+ const r = await this.json("POST", "/v1/state/namespaces", {
254
+ ...rest,
255
+ limit: page,
256
+ after,
257
+ });
258
+ return { items: r.namespaces, next: r.next };
259
+ }, page);
197
260
  }
198
261
  async stateSearch(namespace_prefix, o = {}) {
199
- return (await this.json("POST", "/v1/state/search", { namespace_prefix, ...o })).items;
262
+ return (await this.stateSearchPage(namespace_prefix, o)).items;
263
+ }
264
+ async stateSearchPage(namespace_prefix, o = {}) {
265
+ const r = await this.json("POST", "/v1/state/search", {
266
+ namespace_prefix,
267
+ ...o,
268
+ });
269
+ return { items: r.items, next: r.next ?? null };
270
+ }
271
+ /** Every hit of a search, in its order, following the server's cursors. */
272
+ iterStateSearch(namespace_prefix, o = {}) {
273
+ const { page = 1000, ...rest } = o;
274
+ return follow((after) => this.json("POST", "/v1/state/search", {
275
+ namespace_prefix,
276
+ ...rest,
277
+ limit: page,
278
+ after,
279
+ }), page);
200
280
  }
201
281
  async watch(w) {
202
282
  return (await this.json("POST", "/v1/watches", w)).id;
package/dist/native.d.ts CHANGED
@@ -1,5 +1,9 @@
1
1
  import * as tls from "node:tls";
2
2
  import { type Json } from "./index.ts";
3
+ /** How often a quiet connection is kept open with a PING by default, in milliseconds: the server
4
+ * closes a connection with no frame in either direction for `idle_timeout` (300 s by default;
5
+ * spec native-protocol.md section 3, "Clients send PING to keep a quiet connection open"). */
6
+ export declare const KEEPALIVE_MS = 60000;
3
7
  /** A frame the server sent that this client cannot read (a protocol error). */
4
8
  export declare class NativeProtocolError extends Error {
5
9
  }
@@ -66,6 +70,7 @@ export declare class Desc {
66
70
  /** A field by name, to read it from nodes of this descriptor. */
67
71
  field(name: string): Field | undefined;
68
72
  }
73
+ declare function describe(body: Uint8Array): [number, Desc];
69
74
  type Descs = ReadonlyMap<number, Desc>;
70
75
  /** A decimal's text with `scale` digits after the point. */
71
76
  export declare function decimalText(unscaled: bigint, scale: number): string;
@@ -154,6 +159,19 @@ export declare class Rows {
154
159
  /** The answer as the HTTP API's JSON for a GET of a node (`listing` false) or a listing. */
155
160
  toJson(listing: boolean): Json;
156
161
  }
162
+ /**
163
+ * One fuzz input for the decoders of what a server sends (the property test
164
+ * test/fuzz.test.ts drives it with fast-check): a sequence of `[kind][length: u16 big-endian][body]`.
165
+ * An even kind is a DESCRIBE body (its layout is kept, as a connection keeps it); an odd kind
166
+ * is a ROWS body, decoded with the layouts described so far: every entry, every node's fields,
167
+ * key parts and JSON. A malformed body raises {@link NativeProtocolError}, which this
168
+ * swallows; any other exception (a TypeError, a RangeError) is a decoder bug and propagates.
169
+ * Returns how many nodes decoded.
170
+ * @internal
171
+ */
172
+ export declare function fuzzFrames(data: Uint8Array): number;
173
+ /** The DESCRIBE body decoder, for the decoder tests. @internal */
174
+ export { describe as decodeDescribe };
157
175
  /** TLS settings of `NativeClient.connectTls`, besides the options of `node:tls`. */
158
176
  export interface TlsOptions extends tls.ConnectionOptions {
159
177
  /** Trust the certificates of this PEM file instead of the platform's roots. */
@@ -173,8 +191,15 @@ export declare class NativeClient {
173
191
  private buf;
174
192
  private closedWhy;
175
193
  private handshake;
194
+ private pinger;
176
195
  private readonly sock;
177
196
  private constructor();
197
+ /** Whether the connection has ended: no request on it can succeed any more. */
198
+ get closed(): boolean;
199
+ /** The keep-alive interval in milliseconds: a PING every `ms` (`null` or 0: never). The default,
200
+ * `KEEPALIVE_MS`, suits the server's default `idle_timeout` of 300 s; set a shorter one for a
201
+ * server whose `idle_timeout_ms` is below 60 s. The timer does not keep the process running. */
202
+ keepalive(ms: number | null): this;
178
203
  /** Connects over plain TCP (the server serves plain text on loopback only, unless configured
179
204
  * otherwise) and authenticates with `scheme` (`token` or `bearer`) and the credential the
180
205
  * HTTP Authorization header would carry. */
@@ -213,6 +238,7 @@ export declare class NativeClient {
213
238
  /** The fields of a writer layout a descriptor of this connection described: [number, name,
214
239
  * type text] each, the fixed, variant-case and tail fields (spec native-protocol.md 5). */
215
240
  layoutFields(id: string): ReadonlyArray<readonly [number, string, string]> | undefined;
241
+ /** Closes the connection: requests in flight and later ones reject ("closed by the client"). */
216
242
  close(): void;
217
243
  }
218
244
  /** One change record. */
@@ -223,4 +249,3 @@ export declare class Change {
223
249
  /** The record as the HTTP change stream's JSON object. */
224
250
  toJson(): Json;
225
251
  }
226
- export {};
package/dist/native.js CHANGED
@@ -18,11 +18,21 @@
18
18
  * `Rows.toJson` gives a result as the HTTP API's JSON answer (for debugging and the contract
19
19
  * tests, which compare the two). Failures reject with OliviaDbError (an error frame: the HTTP
20
20
  * status and problem document) or NativeProtocolError.
21
+ *
22
+ * Concurrency and lifecycle: one `NativeClient` is one connection that carries many requests at
23
+ * once. Start any number of requests without awaiting the previous one (`Promise.all`): each
24
+ * travels on its own stream and resolves with its own answer. Create one per process (per
25
+ * server) and share it; do not open one per request and do not pool it. It belongs to the
26
+ * thread that created it: each worker thread (`node:worker_threads`) connects its own. A quiet
27
+ * connection sends PING every 60 s (`keepalive`). `close()` when the application stops: an open
28
+ * connection keeps the Node.js process running. A connection that ended (server restart,
29
+ * failover, network) is not reconnected: requests reject and `closed` is true; connect again.
21
30
  */
22
31
  import * as net from "node:net";
23
32
  import * as tls from "node:tls";
24
33
  import { readFileSync } from "node:fs";
25
34
  import { OliviaDbError } from "./index.js";
35
+ import { trimEndChar } from "./text.js";
26
36
  const HEADER = 10;
27
37
  const MORE = 0x02;
28
38
  const OP = {
@@ -39,7 +49,12 @@ const OP = {
39
49
  END: 0x16,
40
50
  UNDESCRIBE: 0x17,
41
51
  CANCEL: 0x20,
52
+ PING: 0x21,
42
53
  };
54
+ /** How often a quiet connection is kept open with a PING by default, in milliseconds: the server
55
+ * closes a connection with no frame in either direction for `idle_timeout` (300 s by default;
56
+ * spec native-protocol.md section 3, "Clients send PING to keep a quiet connection open"). */
57
+ export const KEEPALIVE_MS = 60_000;
43
58
  /** A frame the server sent that this client cannot read (a protocol error). */
44
59
  export class NativeProtocolError extends Error {
45
60
  }
@@ -354,7 +369,7 @@ function intJson(v) {
354
369
  return a < 1n << 53n ? Number(v) : v.toString();
355
370
  }
356
371
  function stripPad(s) {
357
- return s.replace(/ +$/, "");
372
+ return trimEndChar(s, " ");
358
373
  }
359
374
  // ---- nodes ----
360
375
  /** One node of a result: its bytes are views into the frame it came in. */
@@ -738,6 +753,10 @@ export function trimmed(desc, data) {
738
753
  let p = 0;
739
754
  let end = 0;
740
755
  for (const [off, n] of desc.strs) {
756
+ // The descriptor's fixed strings are in offset order and do not overlap (spec section 6.3);
757
+ // one that starts before the previous one ends cannot be restored.
758
+ if (off < end)
759
+ throw bad("fixed strings that overlap");
741
760
  p += off - end;
742
761
  let k = 0;
743
762
  for (let i = 0;; i++) {
@@ -815,6 +834,10 @@ export class Rows {
815
834
  (ch[tn] ??= []).push(done);
816
835
  };
817
836
  for (const n of this.nodes()) {
837
+ // A node's parent is the nearest earlier node with depth one less (spec
838
+ // native-protocol.md section 6): a deeper jump has no parent, a malformed body.
839
+ if (n.depth > paths.length)
840
+ throw new NativeProtocolError(`a node at depth ${n.depth} without a parent at depth ${n.depth - 1} (protocol error P01)`);
818
841
  const parent = n.depth === 0 ? (n.parent ?? this.base) : paths[n.depth - 1];
819
842
  const v = n.toJson(parent, true);
820
843
  paths.length = n.depth;
@@ -837,6 +860,78 @@ export class Rows {
837
860
  return v;
838
861
  }
839
862
  }
863
+ /**
864
+ * One fuzz input for the decoders of what a server sends (the property test
865
+ * test/fuzz.test.ts drives it with fast-check): a sequence of `[kind][length: u16 big-endian][body]`.
866
+ * An even kind is a DESCRIBE body (its layout is kept, as a connection keeps it); an odd kind
867
+ * is a ROWS body, decoded with the layouts described so far: every entry, every node's fields,
868
+ * key parts and JSON. A malformed body raises {@link NativeProtocolError}, which this
869
+ * swallows; any other exception (a TypeError, a RangeError) is a decoder bug and propagates.
870
+ * Returns how many nodes decoded.
871
+ * @internal
872
+ */
873
+ export function fuzzFrames(data) {
874
+ const descs = new Map();
875
+ let at = 0;
876
+ let nodes = 0;
877
+ const expected = (e) => {
878
+ if (!(e instanceof NativeProtocolError))
879
+ throw e;
880
+ };
881
+ while (data.length - at >= 3) {
882
+ const kind = data[at];
883
+ const n = Math.min((data[at + 1] << 8) | data[at + 2], data.length - at - 3);
884
+ const body = data.subarray(at + 3, at + 3 + n);
885
+ at += 3 + n;
886
+ if (kind % 2 === 0) {
887
+ try {
888
+ const [id, d] = describe(body);
889
+ if (descs.size < 64)
890
+ descs.set(id, d);
891
+ }
892
+ catch (e) {
893
+ expected(e);
894
+ }
895
+ continue;
896
+ }
897
+ const rows = new Rows();
898
+ rows.frames.push([body, new Map(descs)]);
899
+ try {
900
+ for (const e of rows.entries()) {
901
+ if (!("node" in e))
902
+ continue;
903
+ const node = e.node;
904
+ nodes++;
905
+ node.toJson("", true);
906
+ node.keyParts();
907
+ node.segment();
908
+ node.ordinal();
909
+ for (const f of node.desc.fields) {
910
+ node.str(f);
911
+ node.int(f);
912
+ node.decimal(f);
913
+ node.timestamp(f);
914
+ node.date(f);
915
+ node.json(f);
916
+ }
917
+ }
918
+ }
919
+ catch (e) {
920
+ expected(e);
921
+ }
922
+ for (const listing of [false, true]) {
923
+ try {
924
+ rows.toJson(listing);
925
+ }
926
+ catch (e) {
927
+ expected(e);
928
+ }
929
+ }
930
+ }
931
+ return nodes;
932
+ }
933
+ /** The DESCRIBE body decoder, for the decoder tests. @internal */
934
+ export { describe as decodeDescribe };
840
935
  class Queue {
841
936
  items = [];
842
937
  waiting = [];
@@ -880,6 +975,7 @@ export class NativeClient {
880
975
  buf = new Uint8Array(0);
881
976
  closedWhy;
882
977
  handshake = new Queue();
978
+ pinger;
883
979
  sock;
884
980
  constructor(sock) {
885
981
  this.sock = sock;
@@ -888,6 +984,28 @@ export class NativeClient {
888
984
  sock.on("error", (e) => this.onClose(e.message));
889
985
  sock.on("close", () => this.onClose("the server closed the connection"));
890
986
  }
987
+ /** Whether the connection has ended: no request on it can succeed any more. */
988
+ get closed() {
989
+ return this.closedWhy !== undefined;
990
+ }
991
+ /** The keep-alive interval in milliseconds: a PING every `ms` (`null` or 0: never). The default,
992
+ * `KEEPALIVE_MS`, suits the server's default `idle_timeout` of 300 s; set a shorter one for a
993
+ * server whose `idle_timeout_ms` is below 60 s. The timer does not keep the process running. */
994
+ keepalive(ms) {
995
+ if (this.pinger !== undefined)
996
+ clearInterval(this.pinger);
997
+ this.pinger = undefined;
998
+ if (ms && this.closedWhy === undefined) {
999
+ const ping = [];
1000
+ putLp(ping, new Uint8Array());
1001
+ this.pinger = setInterval(() => {
1002
+ if (this.closedWhy === undefined)
1003
+ this.sock.write(frame(OP.PING, 0, ping));
1004
+ }, ms);
1005
+ this.pinger.unref?.();
1006
+ }
1007
+ return this;
1008
+ }
891
1009
  /** Connects over plain TCP (the server serves plain text on loopback only, unless configured
892
1010
  * otherwise) and authenticates with `scheme` (`token` or `bearer`) and the credential the
893
1011
  * HTTP Authorization header would carry. */
@@ -953,7 +1071,7 @@ export class NativeClient {
953
1071
  const hello = [0, 1, 0, 1];
954
1072
  putVarint(hello, 1);
955
1073
  putLp(hello, enc.encode("client"));
956
- putLp(hello, enc.encode("oliviadb-js 0.1.3"));
1074
+ putLp(hello, enc.encode("oliviadb-js 0.2.0"));
957
1075
  const auth = [];
958
1076
  putLp(auth, enc.encode(scheme));
959
1077
  putLp(auth, enc.encode(credential));
@@ -975,6 +1093,7 @@ export class NativeClient {
975
1093
  }
976
1094
  }
977
1095
  c.handshake = undefined;
1096
+ c.keepalive(KEEPALIVE_MS);
978
1097
  return c;
979
1098
  }
980
1099
  onData(d) {
@@ -1031,6 +1150,9 @@ export class NativeClient {
1031
1150
  if (this.closedWhy !== undefined)
1032
1151
  return;
1033
1152
  this.closedWhy = why;
1153
+ if (this.pinger !== undefined)
1154
+ clearInterval(this.pinger);
1155
+ this.pinger = undefined;
1034
1156
  this.handshake?.push([-1, enc.encode(why)]);
1035
1157
  for (const q of this.streams.values())
1036
1158
  q.push({ closed: why });
@@ -1161,7 +1283,9 @@ export class NativeClient {
1161
1283
  layoutFields(id) {
1162
1284
  return this.layouts.get(id);
1163
1285
  }
1286
+ /** Closes the connection: requests in flight and later ones reject ("closed by the client"). */
1164
1287
  close() {
1288
+ this.onClose("closed by the client");
1165
1289
  this.sock.destroy();
1166
1290
  }
1167
1291
  }
package/dist/text.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Removes every trailing `ch` from `s` in one pass from the end (linear in the length).
3
+ * Replaces `s.replace(/x+$/, "")`: a regular expression anchored only at the end is tried at
4
+ * every start position, which is quadratic on a long run of `ch` that is not at the end (a
5
+ * base URL or a server's `primary` of many slashes followed by another character).
6
+ */
7
+ export declare function trimEndChar(s: string, ch: string): string;
package/dist/text.js ADDED
@@ -0,0 +1,14 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ /**
3
+ * Removes every trailing `ch` from `s` in one pass from the end (linear in the length).
4
+ * Replaces `s.replace(/x+$/, "")`: a regular expression anchored only at the end is tried at
5
+ * every start position, which is quadratic on a long run of `ch` that is not at the end (a
6
+ * base URL or a server's `primary` of many slashes followed by another character).
7
+ */
8
+ export function trimEndChar(s, ch) {
9
+ const c = ch.charCodeAt(0);
10
+ let e = s.length;
11
+ while (e > 0 && s.charCodeAt(e - 1) === c)
12
+ e--;
13
+ return e === s.length ? s : s.slice(0, e);
14
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@olivia-db/client",
3
- "version": "0.1.3",
3
+ "version": "0.2.0",
4
4
  "description": "Client for OliviaDB's network API: agent memory and layer-1 reads, and the native protocol (Node.js)",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -37,6 +37,9 @@
37
37
  "build": "tsc -p tsconfig.build.json",
38
38
  "prepack": "npm run build",
39
39
  "typecheck": "tsc -p .",
40
- "test": "node --test test/*.test.ts"
40
+ "test": "node --test --test-concurrency=1 test/*.test.ts"
41
+ },
42
+ "devDependencies": {
43
+ "fast-check": "4.11.0"
41
44
  }
42
45
  }
package/src/dsl.ts CHANGED
@@ -990,7 +990,10 @@ function untyped(v: Json): Node {
990
990
  /** How often `txn` runs its function again after a 412. */
991
991
  export const TXN_RETRIES = 3;
992
992
 
993
- /** A typed database over HTTP (OliviaDbClient) or the native protocol (NativeClient). */
993
+ /** A typed database over HTTP (OliviaDbClient) or the native protocol (NativeClient). Create one
994
+ * per process over a shared client and use it from every request handler: requests in flight at
995
+ * once each get their own answer. The argument of a `txn` callback collects one transaction and
996
+ * is sent when the callback returns: use it only inside the callback. */
994
997
  export class Db {
995
998
  private readonly conn: Conn;
996
999
  constructor(client: OliviaDbClient | NativeConn) {
package/src/index.ts CHANGED
@@ -10,8 +10,15 @@
10
10
  *
11
11
  * Arguments and results are those of the MCP tools of the same name; failures throw
12
12
  * OliviaDbError (an RFC 9457 problem document), retried when the server says retryable.
13
+ *
14
+ * Concurrency and lifecycle: create one client per process and share it; any number of requests
15
+ * may be in flight at once. Nothing to open or close: fetch makes and keeps the connections, so
16
+ * the next request after a server restart connects again, and with several nodes a refused
17
+ * connection or a retryable 503 moves the client to the primary (failover). Do not pool clients.
13
18
  */
14
19
 
20
+ import { trimEndChar } from "./text.ts";
21
+
15
22
  export type Json = Record<string, unknown>;
16
23
 
17
24
  /**
@@ -79,6 +86,37 @@ export interface StateItem {
79
86
  score?: number;
80
87
  }
81
88
 
89
+ /** One page of a state listing: `next` is the cursor of the following page, `null` on the last. */
90
+ export interface StatePage<T> {
91
+ items: T[];
92
+ next: string | null;
93
+ }
94
+
95
+ /**
96
+ * The items of every page, passing each page's `next` as `after` to `fetch`. A full page
97
+ * without `next` comes from a server that does not page with cursors: refused, since the
98
+ * rest could not be read (spec server-limits.md 9).
99
+ */
100
+ async function* follow<T>(
101
+ fetch: (after: string | undefined) => Promise<{ items: T[]; next?: string | null }>,
102
+ page: number,
103
+ ): AsyncGenerator<T> {
104
+ let after: string | undefined;
105
+ for (;;) {
106
+ const r = await fetch(after);
107
+ yield* r.items;
108
+ if (r.next === undefined) {
109
+ if (r.items.length < page) return;
110
+ throw new OliviaDbError(0, {
111
+ type: "unsupported",
112
+ detail: "the server answered a full page without next: it does not page with cursors (spec server-limits.md 9)",
113
+ });
114
+ }
115
+ if (r.next === null) return;
116
+ after = r.next;
117
+ }
118
+ }
119
+
82
120
  export interface WatchEvent {
83
121
  id: string;
84
122
  data: Json;
@@ -129,7 +167,7 @@ export class OliviaDbClient {
129
167
 
130
168
  constructor(o: ClientOptions) {
131
169
  if ((o.token === undefined) === (o.apiKey === undefined)) throw new Error("give either token or apiKey");
132
- this.bases = (Array.isArray(o.baseUrl) ? o.baseUrl : [o.baseUrl]).map((u) => u.replace(/\/+$/, ""));
170
+ this.bases = (Array.isArray(o.baseUrl) ? o.baseUrl : [o.baseUrl]).map((u) => trimEndChar(u, "/"));
133
171
  if (this.bases.length === 0) throw new Error("no base URL");
134
172
  this.auth = o.token !== undefined ? `Bearer ${o.token}` : `Token ${o.apiKey}`;
135
173
  this.retries = o.retries ?? 3;
@@ -148,7 +186,7 @@ export class OliviaDbClient {
148
186
  }
149
187
 
150
188
  private next(primary: string | null): void {
151
- const p = primary?.replace(/\/+$/, "");
189
+ const p = primary == null ? primary : trimEndChar(primary, "/");
152
190
  const i = p ? this.bases.indexOf(p) : -1;
153
191
  this.cur = i >= 0 ? i : (this.cur + 1) % this.bases.length;
154
192
  }
@@ -309,22 +347,124 @@ export class OliviaDbClient {
309
347
  await this.json<{ deleted: number }>("POST", "/v1/state/delete", { namespace, key, prefix: prefix || undefined })
310
348
  ).deleted;
311
349
  }
350
+ /** One page of a namespace's documents; `after` is the previous page's `next` (or a key). */
312
351
  async stateList(
313
352
  namespace: string[],
314
353
  o: { after?: string; limit?: number; reverse?: boolean } = {},
315
354
  ): Promise<StateItem[]> {
316
- return (await this.json<{ items: StateItem[] }>("POST", "/v1/state/list", { namespace, ...o })).items;
355
+ return (await this.stateListPage(namespace, o)).items;
356
+ }
357
+ async stateListPage(
358
+ namespace: string[],
359
+ o: { after?: string; limit?: number; reverse?: boolean } = {},
360
+ ): Promise<StatePage<StateItem>> {
361
+ const r = await this.json<{ items: StateItem[]; next?: string | null }>("POST", "/v1/state/list", {
362
+ namespace,
363
+ ...o,
364
+ });
365
+ return { items: r.items, next: r.next ?? null };
366
+ }
367
+ /** Every document of a namespace, `page` at a time (1 to 1000), following the server's cursors. */
368
+ iterStateList(namespace: string[], o: { reverse?: boolean; page?: number } = {}): AsyncGenerator<StateItem> {
369
+ const page = o.page ?? 1000;
370
+ return follow(
371
+ (after) =>
372
+ this.json<{ items: StateItem[]; next?: string | null }>("POST", "/v1/state/list", {
373
+ namespace,
374
+ after,
375
+ limit: page,
376
+ reverse: o.reverse || undefined,
377
+ }),
378
+ page,
379
+ );
317
380
  }
318
381
  async stateNamespaces(
319
- o: { prefix?: string[]; suffix?: string[]; max_depth?: number; limit?: number; offset?: number } = {},
382
+ o: {
383
+ prefix?: string[];
384
+ suffix?: string[];
385
+ max_depth?: number;
386
+ limit?: number;
387
+ offset?: number;
388
+ after?: string;
389
+ } = {},
320
390
  ): Promise<string[][]> {
321
- return (await this.json<{ namespaces: string[][] }>("POST", "/v1/state/namespaces", o)).namespaces;
391
+ return (await this.stateNamespacesPage(o)).items;
392
+ }
393
+ async stateNamespacesPage(
394
+ o: {
395
+ prefix?: string[];
396
+ suffix?: string[];
397
+ max_depth?: number;
398
+ limit?: number;
399
+ offset?: number;
400
+ after?: string;
401
+ } = {},
402
+ ): Promise<StatePage<string[]>> {
403
+ const r = await this.json<{ namespaces: string[][]; next?: string | null }>("POST", "/v1/state/namespaces", o);
404
+ return { items: r.namespaces, next: r.next ?? null };
405
+ }
406
+ /** Every namespace under `prefix` (sorted), following the server's cursors. */
407
+ iterStateNamespaces(
408
+ o: { prefix?: string[]; suffix?: string[]; max_depth?: number; page?: number } = {},
409
+ ): AsyncGenerator<string[]> {
410
+ const { page = 1000, ...rest } = o;
411
+ return follow(async (after) => {
412
+ const r = await this.json<{ namespaces: string[][]; next?: string | null }>("POST", "/v1/state/namespaces", {
413
+ ...rest,
414
+ limit: page,
415
+ after,
416
+ });
417
+ return { items: r.namespaces, next: r.next };
418
+ }, page);
322
419
  }
323
420
  async stateSearch(
324
421
  namespace_prefix: string[],
325
- o: { query?: string; vector?: number[]; filter?: Json; limit?: number; offset?: number } = {},
422
+ o: {
423
+ query?: string;
424
+ vector?: number[];
425
+ filter?: Json;
426
+ limit?: number;
427
+ offset?: number;
428
+ semantic?: boolean;
429
+ after?: string;
430
+ } = {},
326
431
  ): Promise<StateItem[]> {
327
- return (await this.json<{ items: StateItem[] }>("POST", "/v1/state/search", { namespace_prefix, ...o })).items;
432
+ return (await this.stateSearchPage(namespace_prefix, o)).items;
433
+ }
434
+ async stateSearchPage(
435
+ namespace_prefix: string[],
436
+ o: {
437
+ query?: string;
438
+ vector?: number[];
439
+ filter?: Json;
440
+ limit?: number;
441
+ offset?: number;
442
+ semantic?: boolean;
443
+ after?: string;
444
+ } = {},
445
+ ): Promise<StatePage<StateItem>> {
446
+ const r = await this.json<{ items: StateItem[]; next?: string | null }>("POST", "/v1/state/search", {
447
+ namespace_prefix,
448
+ ...o,
449
+ });
450
+ return { items: r.items, next: r.next ?? null };
451
+ }
452
+ /** Every hit of a search, in its order, following the server's cursors. */
453
+ iterStateSearch(
454
+ namespace_prefix: string[],
455
+ o: { query?: string; vector?: number[]; filter?: Json; semantic?: boolean; page?: number } = {},
456
+ ): AsyncGenerator<StateItem> {
457
+ const { page = 1000, ...rest } = o;
458
+ return follow(
459
+ (after) =>
460
+ this.json<{ items: StateItem[]; next?: string | null }>("POST", "/v1/state/search", {
461
+ namespace_prefix,
462
+ ...rest,
463
+ limit: page,
464
+ after,
465
+ }),
466
+ page,
467
+ );
328
468
  }
329
469
 
330
470
  async watch(w: { entities?: string[]; paths?: string[] }): Promise<string> {
package/src/native.ts CHANGED
@@ -18,11 +18,21 @@
18
18
  * `Rows.toJson` gives a result as the HTTP API's JSON answer (for debugging and the contract
19
19
  * tests, which compare the two). Failures reject with OliviaDbError (an error frame: the HTTP
20
20
  * status and problem document) or NativeProtocolError.
21
+ *
22
+ * Concurrency and lifecycle: one `NativeClient` is one connection that carries many requests at
23
+ * once. Start any number of requests without awaiting the previous one (`Promise.all`): each
24
+ * travels on its own stream and resolves with its own answer. Create one per process (per
25
+ * server) and share it; do not open one per request and do not pool it. It belongs to the
26
+ * thread that created it: each worker thread (`node:worker_threads`) connects its own. A quiet
27
+ * connection sends PING every 60 s (`keepalive`). `close()` when the application stops: an open
28
+ * connection keeps the Node.js process running. A connection that ended (server restart,
29
+ * failover, network) is not reconnected: requests reject and `closed` is true; connect again.
21
30
  */
22
31
  import * as net from "node:net";
23
32
  import * as tls from "node:tls";
24
33
  import { readFileSync } from "node:fs";
25
34
  import { OliviaDbError, type Json } from "./index.ts";
35
+ import { trimEndChar } from "./text.ts";
26
36
 
27
37
  const HEADER = 10;
28
38
  const MORE = 0x02;
@@ -40,8 +50,14 @@ const OP = {
40
50
  END: 0x16,
41
51
  UNDESCRIBE: 0x17,
42
52
  CANCEL: 0x20,
53
+ PING: 0x21,
43
54
  } as const;
44
55
 
56
+ /** How often a quiet connection is kept open with a PING by default, in milliseconds: the server
57
+ * closes a connection with no frame in either direction for `idle_timeout` (300 s by default;
58
+ * spec native-protocol.md section 3, "Clients send PING to keep a quiet connection open"). */
59
+ export const KEEPALIVE_MS = 60_000;
60
+
45
61
  /** A frame the server sent that this client cannot read (a protocol error). */
46
62
  export class NativeProtocolError extends Error {}
47
63
 
@@ -409,7 +425,7 @@ function intJson(v: bigint): number | string {
409
425
  export type KeyValue = bigint | number | boolean | Uint8Array | string;
410
426
 
411
427
  function stripPad(s: string): string {
412
- return s.replace(/ +$/, "");
428
+ return trimEndChar(s, " ");
413
429
  }
414
430
 
415
431
  // ---- nodes ----
@@ -783,6 +799,9 @@ export function trimmed(desc: Desc, data: Uint8Array): Array<[number, number, nu
783
799
  let p = 0;
784
800
  let end = 0;
785
801
  for (const [off, n] of desc.strs) {
802
+ // The descriptor's fixed strings are in offset order and do not overlap (spec section 6.3);
803
+ // one that starts before the previous one ends cannot be restored.
804
+ if (off < end) throw bad("fixed strings that overlap");
786
805
  p += off - end;
787
806
  let k = 0;
788
807
  for (let i = 0; ; i++) {
@@ -857,6 +876,12 @@ export class Rows {
857
876
  (ch[tn] ??= []).push(done);
858
877
  };
859
878
  for (const n of this.nodes()) {
879
+ // A node's parent is the nearest earlier node with depth one less (spec
880
+ // native-protocol.md section 6): a deeper jump has no parent, a malformed body.
881
+ if (n.depth > paths.length)
882
+ throw new NativeProtocolError(
883
+ `a node at depth ${n.depth} without a parent at depth ${n.depth - 1} (protocol error P01)`,
884
+ );
860
885
  const parent = n.depth === 0 ? (n.parent ?? this.base) : paths[n.depth - 1];
861
886
  const v = n.toJson(parent, true);
862
887
  paths.length = n.depth;
@@ -879,6 +904,74 @@ export class Rows {
879
904
 
880
905
  type Received = { op: number; flags: number; body: Uint8Array; descs: Descs } | { closed: string };
881
906
 
907
+ /**
908
+ * One fuzz input for the decoders of what a server sends (the property test
909
+ * test/fuzz.test.ts drives it with fast-check): a sequence of `[kind][length: u16 big-endian][body]`.
910
+ * An even kind is a DESCRIBE body (its layout is kept, as a connection keeps it); an odd kind
911
+ * is a ROWS body, decoded with the layouts described so far: every entry, every node's fields,
912
+ * key parts and JSON. A malformed body raises {@link NativeProtocolError}, which this
913
+ * swallows; any other exception (a TypeError, a RangeError) is a decoder bug and propagates.
914
+ * Returns how many nodes decoded.
915
+ * @internal
916
+ */
917
+ export function fuzzFrames(data: Uint8Array): number {
918
+ const descs = new Map<number, Desc>();
919
+ let at = 0;
920
+ let nodes = 0;
921
+ const expected = (e: unknown) => {
922
+ if (!(e instanceof NativeProtocolError)) throw e;
923
+ };
924
+ while (data.length - at >= 3) {
925
+ const kind = data[at];
926
+ const n = Math.min((data[at + 1] << 8) | data[at + 2], data.length - at - 3);
927
+ const body = data.subarray(at + 3, at + 3 + n);
928
+ at += 3 + n;
929
+ if (kind % 2 === 0) {
930
+ try {
931
+ const [id, d] = describe(body);
932
+ if (descs.size < 64) descs.set(id, d);
933
+ } catch (e) {
934
+ expected(e);
935
+ }
936
+ continue;
937
+ }
938
+ const rows = new Rows();
939
+ rows.frames.push([body, new Map(descs)]);
940
+ try {
941
+ for (const e of rows.entries()) {
942
+ if (!("node" in e)) continue;
943
+ const node = e.node;
944
+ nodes++;
945
+ node.toJson("", true);
946
+ node.keyParts();
947
+ node.segment();
948
+ node.ordinal();
949
+ for (const f of node.desc.fields) {
950
+ node.str(f);
951
+ node.int(f);
952
+ node.decimal(f);
953
+ node.timestamp(f);
954
+ node.date(f);
955
+ node.json(f);
956
+ }
957
+ }
958
+ } catch (e) {
959
+ expected(e);
960
+ }
961
+ for (const listing of [false, true]) {
962
+ try {
963
+ rows.toJson(listing);
964
+ } catch (e) {
965
+ expected(e);
966
+ }
967
+ }
968
+ }
969
+ return nodes;
970
+ }
971
+
972
+ /** The DESCRIBE body decoder, for the decoder tests. @internal */
973
+ export { describe as decodeDescribe };
974
+
882
975
  class Queue<T> {
883
976
  private items: T[] = [];
884
977
  private waiting: Array<(v: T) => void> = [];
@@ -929,6 +1022,7 @@ export class NativeClient {
929
1022
  private buf = new Uint8Array(0);
930
1023
  private closedWhy: string | undefined;
931
1024
  private handshake: Queue<[number, Uint8Array]> | undefined = new Queue();
1025
+ private pinger: ReturnType<typeof setInterval> | undefined;
932
1026
 
933
1027
  private readonly sock: net.Socket;
934
1028
 
@@ -940,6 +1034,28 @@ export class NativeClient {
940
1034
  sock.on("close", () => this.onClose("the server closed the connection"));
941
1035
  }
942
1036
 
1037
+ /** Whether the connection has ended: no request on it can succeed any more. */
1038
+ get closed(): boolean {
1039
+ return this.closedWhy !== undefined;
1040
+ }
1041
+
1042
+ /** The keep-alive interval in milliseconds: a PING every `ms` (`null` or 0: never). The default,
1043
+ * `KEEPALIVE_MS`, suits the server's default `idle_timeout` of 300 s; set a shorter one for a
1044
+ * server whose `idle_timeout_ms` is below 60 s. The timer does not keep the process running. */
1045
+ keepalive(ms: number | null): this {
1046
+ if (this.pinger !== undefined) clearInterval(this.pinger);
1047
+ this.pinger = undefined;
1048
+ if (ms && this.closedWhy === undefined) {
1049
+ const ping: number[] = [];
1050
+ putLp(ping, new Uint8Array());
1051
+ this.pinger = setInterval(() => {
1052
+ if (this.closedWhy === undefined) this.sock.write(frame(OP.PING, 0, ping));
1053
+ }, ms);
1054
+ this.pinger.unref?.();
1055
+ }
1056
+ return this;
1057
+ }
1058
+
943
1059
  /** Connects over plain TCP (the server serves plain text on loopback only, unless configured
944
1060
  * otherwise) and authenticates with `scheme` (`token` or `bearer`) and the credential the
945
1061
  * HTTP Authorization header would carry. */
@@ -1016,7 +1132,7 @@ export class NativeClient {
1016
1132
  const hello: number[] = [0, 1, 0, 1];
1017
1133
  putVarint(hello, 1);
1018
1134
  putLp(hello, enc.encode("client"));
1019
- putLp(hello, enc.encode("oliviadb-js 0.1.3"));
1135
+ putLp(hello, enc.encode("oliviadb-js 0.2.0"));
1020
1136
  const auth: number[] = [];
1021
1137
  putLp(auth, enc.encode(scheme));
1022
1138
  putLp(auth, enc.encode(credential));
@@ -1038,6 +1154,7 @@ export class NativeClient {
1038
1154
  }
1039
1155
  }
1040
1156
  c.handshake = undefined;
1157
+ c.keepalive(KEEPALIVE_MS);
1041
1158
  return c;
1042
1159
  }
1043
1160
 
@@ -1094,6 +1211,8 @@ export class NativeClient {
1094
1211
  private onClose(why: string): void {
1095
1212
  if (this.closedWhy !== undefined) return;
1096
1213
  this.closedWhy = why;
1214
+ if (this.pinger !== undefined) clearInterval(this.pinger);
1215
+ this.pinger = undefined;
1097
1216
  this.handshake?.push([-1, enc.encode(why)]);
1098
1217
  for (const q of this.streams.values()) q.push({ closed: why });
1099
1218
  }
@@ -1224,7 +1343,9 @@ export class NativeClient {
1224
1343
  return this.layouts.get(id);
1225
1344
  }
1226
1345
 
1346
+ /** Closes the connection: requests in flight and later ones reject ("closed by the client"). */
1227
1347
  close(): void {
1348
+ this.onClose("closed by the client");
1228
1349
  this.sock.destroy();
1229
1350
  }
1230
1351
  }
package/src/text.ts ADDED
@@ -0,0 +1,13 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ /**
3
+ * Removes every trailing `ch` from `s` in one pass from the end (linear in the length).
4
+ * Replaces `s.replace(/x+$/, "")`: a regular expression anchored only at the end is tried at
5
+ * every start position, which is quadratic on a long run of `ch` that is not at the end (a
6
+ * base URL or a server's `primary` of many slashes followed by another character).
7
+ */
8
+ export function trimEndChar(s: string, ch: string): string {
9
+ const c = ch.charCodeAt(0);
10
+ let e = s.length;
11
+ while (e > 0 && s.charCodeAt(e - 1) === c) e--;
12
+ return e === s.length ? s : s.slice(0, e);
13
+ }