@noego/sqlego 0.1.2 → 0.1.3-dev.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/src/client.ts CHANGED
@@ -7,6 +7,7 @@ import { fileURLToPath } from 'node:url';
7
7
  import { Result, Trust } from '@noego/trust';
8
8
  import { locateServerBinary, type BinaryMissing } from './binary.ts';
9
9
  import {
10
+ FrameReader,
10
11
  PROTOCOL_VERSION,
11
12
  encodeRequestFrame,
12
13
  errnoCode,
@@ -25,7 +26,6 @@ import {
25
26
  parseStopResult,
26
27
  parseTransactionEndResult,
27
28
  samePragmas,
28
- splitFrames,
29
29
  type BatchResult,
30
30
  type BeginResult,
31
31
  type ErrorCode,
@@ -62,10 +62,11 @@ export type ClientOptions = Readonly<{
62
62
  /**
63
63
  * Pragmas the owner must have applied on open (`--pragma`), replacing its
64
64
  * defaults. A spawned owner gets them; an owner already running with other
65
- * pragmas is asked to stop and a fresh one is spawned with these, the way
66
- * an owner from another build is retired. Two clients insisting on
67
- * different pragmas for one file would keep restarting its owner: agree on
68
- * one list per file, or leave this unset to accept whatever is running.
65
+ * pragmas is retired and a fresh one spawned with these when this client
66
+ * is its file's only one, the way an owner from another build is. While
67
+ * other clients use it, `connect` fails with `owner-in-use` instead and the
68
+ * owner keeps serving them. Agree on one list per file, or leave this unset
69
+ * to accept whatever is running.
69
70
  */
70
71
  serverPragmas?: readonly string[];
71
72
  /**
@@ -87,6 +88,31 @@ export type ClientOptions = Readonly<{
87
88
 
88
89
  export const DEFAULT_MAX_OWNERS = 4;
89
90
 
91
+ /** How an owner a client uses differs from the one it asked for. */
92
+ export type OwnerMismatch = 'version' | 'pragmas';
93
+
94
+ /**
95
+ * The owner process a client is connected to, as its hello reported it. It
96
+ * stays on the client after the connection is lost, so whoever logs the loss
97
+ * can name the owner that went (pid, build). `mismatches` lists how the
98
+ * owner differs from what this client asked for while the client uses it
99
+ * anyway: `version` (another build, kept because other clients use it or
100
+ * because `spawn` is false) and `pragmas` (only with `spawn: false`). Empty
101
+ * when it is the owner this client wants.
102
+ */
103
+ export type OwnerInfo = Readonly<{ pid: number; serverVersion: string; protocol: number; file: string; mismatches: readonly OwnerMismatch[] }>;
104
+
105
+ /** What the owner said to this client's hello: its hello, or that it speaks another protocol. */
106
+ type Greeting =
107
+ | Readonly<{ kind: 'hello'; hello: HelloResult }>
108
+ | Readonly<{ kind: 'other-protocol'; message: string }>;
109
+
110
+ /** Whether this client may retire its file's owner: only as that file's sole connection, with no transaction open. */
111
+ type Use = Readonly<{ sole: boolean; why: string }>;
112
+
113
+ /** An owner this client cannot use (another protocol, or pragmas it requires) and may not retire, because other clients use it. */
114
+ type OwnerInUse = Readonly<{ kind: 'owner-in-use'; message: string }>;
115
+
90
116
  /** One live owner process of this build, as the meta files of the files it serves report it. */
91
117
  type OwnerProcess = Readonly<{ pid: number; socket: string; files: number; startedAt: number }>;
92
118
 
@@ -166,10 +192,13 @@ function callerStatement<Row extends SqlRow>(result: StatementResult): Statement
166
192
  export class SqlegoClient {
167
193
  readonly paths: FilePaths;
168
194
  private socket: net.Socket | null = null;
169
- private buffer = '';
195
+ /** Reply frames from `socket`; the socket decodes UTF-8 itself (`setEncoding`), split characters included. */
196
+ private readonly frames = new FrameReader();
170
197
  private nextId = 1;
171
198
  private readonly pending = new Map<number, Waiter>();
172
199
  private hello: HelloResult | null = null;
200
+ /** How the owner in `hello` differs from the one this client asked for (see `OwnerInfo`). */
201
+ private mismatches: readonly OwnerMismatch[] = [];
173
202
  /** Why the server this client spawned did not come up, if it did not. */
174
203
  private spawnFailure: string | null = null;
175
204
  /** True while this client is the one spawning an owner process (see `placeFile`). */
@@ -197,6 +226,17 @@ export class SqlegoClient {
197
226
  return unwrap(Result.err({ kind: 'not-connected', message: 'client is not connected' }));
198
227
  }
199
228
 
229
+ /**
230
+ * The owner this client talks to (see `OwnerInfo`); null before `connect`
231
+ * succeeded. Unlike `server` it never throws, and it is kept after the
232
+ * connection is lost, so the loss can be logged with the owner's pid and build.
233
+ */
234
+ get owner(): OwnerInfo | null {
235
+ const hello = this.hello;
236
+ if (!hello) return null;
237
+ return { pid: hello.pid, serverVersion: hello.serverVersion, protocol: hello.protocol, file: hello.file, mismatches: this.mismatches };
238
+ }
239
+
200
240
  /** Opt this socket into committed-snapshot plain reads and queued plain writes. */
201
241
  async enableDetachedPlain(): Promise<boolean> {
202
242
  if (!this.server.capabilities.includes('detached-plain')) return false;
@@ -298,7 +338,11 @@ export class SqlegoClient {
298
338
  return unwrap(await this.call({ op: 'status' }, parseStatusResult));
299
339
  }
300
340
 
301
- /** Asks the server to shut down; the connection closes as a consequence. */
341
+ /**
342
+ * Asks the owner to release this file; the connection closes as a
343
+ * consequence. Refused with `owner-busy` while other clients are connected
344
+ * to the file (or another client's transaction is open): nothing is released.
345
+ */
302
346
  async stop(): Promise<void> {
303
347
  unwrap(await this.stopServer());
304
348
  }
@@ -310,6 +354,7 @@ export class SqlegoClient {
310
354
  await new Promise<void>((resolve) => endSocket(socket, resolve));
311
355
  }
312
356
 
357
+ /** `stop`, closing this client once it is granted; a refusal (`owner-busy`) or any other error reply is returned as is. */
313
358
  private async stopServer() {
314
359
  const stopped = await this.call({ op: 'stop' }, parseStopResult, STOP_TIMEOUT_MS);
315
360
  if (!stopped.ok) {
@@ -329,43 +374,132 @@ export class SqlegoClient {
329
374
  return Result.ok(undefined);
330
375
  }
331
376
 
377
+ /**
378
+ * Connects and settles which owner this client uses. An owner other than
379
+ * the one it wants (another build or protocol, or other pragmas than
380
+ * `serverPragmas`) is retired — asked to release the file, which is then
381
+ * placed anew — only when this client is the file's sole connection and no
382
+ * transaction is open, as the owner's `status` reports. Otherwise the owner
383
+ * keeps serving the clients that use it (2026-10-18: a CLI from another
384
+ * build retired the running app's owner, a 7-minute outage): this client
385
+ * uses it as it is when only the build differs, noting that in `owner`, and
386
+ * fails with `owner-in-use` when it cannot (another protocol, or pragmas it
387
+ * requires); it never sends `stop` then. With `spawn: false` nothing is
388
+ * replaced. A connect that fails closes its connection, so a process whose
389
+ * connects keep failing never holds an owner busy.
390
+ */
332
391
  private async open() {
333
392
  const deadline = Date.now() + (this.options.connectTimeoutMs ?? 10_000);
334
- const socket = await this.connectOrSpawn(deadline);
335
- if (!socket.ok) return socket;
336
- const attached = this.attach(socket.value);
337
- if (!attached.ok) return attached;
338
- const hello = await this.call({ op: 'hello', clientVersion: VERSION, protocol: PROTOCOL_VERSION }, parseHelloResult);
339
- if (!hello.ok) return hello;
340
- if (!this.mustReplace(hello.value) || this.options.spawn === false) {
341
- this.hello = hello.value;
342
- return Result.ok(undefined);
393
+ const greeted = await this.handshake(deadline);
394
+ if (!greeted.ok) return this.abandon(greeted);
395
+ const greeting = greeted.value;
396
+ const mismatches = greeting.kind === 'hello' ? this.mismatchesOf(greeting.hello) : [];
397
+ if (greeting.kind === 'hello' && (mismatches.length === 0 || this.options.spawn === false)) return this.settle(greeting.hello, mismatches);
398
+ if (greeting.kind === 'other-protocol' && this.options.spawn === false) {
399
+ return this.abandon(Result.err({ kind: 'protocol-mismatch' as const, message: greeting.message }));
400
+ }
401
+ const use = await this.ownerUse();
402
+ if (use.sole) {
403
+ const stopped = await this.stopServer();
404
+ if (stopped.ok) return this.replace(deadline);
405
+ // A client that connected since `status` keeps the owner; any other failure is this connect's.
406
+ if (stopped.error.kind !== 'owner-busy') return this.abandon(stopped);
343
407
  }
344
- // A stale owner (older build, or opened with other pragmas than this
345
- // client requires): have it release the file, then place the file anew.
346
- // The owner process itself may live on, serving other files.
347
- const stopped = await this.stopServer();
348
- if (!stopped.ok) return stopped;
408
+ if (greeting.kind === 'hello' && !mismatches.includes('pragmas')) return this.settle(greeting.hello, mismatches);
409
+ const what = greeting.kind === 'hello'
410
+ ? `its owner (pid ${greeting.hello.pid}) opened it with other pragmas than serverPragmas requires`
411
+ : `its owner speaks another protocol (${greeting.message})`;
412
+ const why = use.sole ? 'another client connected meanwhile' : use.why;
413
+ return this.abandon(Result.err<OwnerInUse>({ kind: 'owner-in-use', message: `${this.paths.file}: ${what}, and ${why}; it was left running` }));
414
+ }
415
+
416
+ /**
417
+ * Connects (placing the file when nothing serves it) and says hello. An
418
+ * owner that drops the connection before answering was releasing the file
419
+ * at that moment: wait until it is gone and start again, until the
420
+ * deadline. Another protocol is an answer, not a failure: `open` decides.
421
+ */
422
+ private async handshake(deadline: number) {
423
+ for (;;) {
424
+ const socket = await this.connectOrSpawn(deadline);
425
+ if (!socket.ok) return socket;
426
+ const attached = this.attach(socket.value);
427
+ if (!attached.ok) return attached;
428
+ const hello = await this.call({ op: 'hello', clientVersion: VERSION, protocol: PROTOCOL_VERSION }, parseHelloResult);
429
+ if (hello.ok) return Result.ok<Greeting>({ kind: 'hello', hello: hello.value });
430
+ switch (hello.error.kind) {
431
+ case 'protocol-mismatch':
432
+ return Result.ok<Greeting>({ kind: 'other-protocol', message: hello.error.message });
433
+ case 'closed':
434
+ case 'not-connected':
435
+ case 'socket':
436
+ case 'shutting-down':
437
+ if (Date.now() >= deadline) return hello;
438
+ await this.close();
439
+ await this.waitForRelease(deadline);
440
+ break;
441
+ default:
442
+ return hello;
443
+ }
444
+ }
445
+ }
446
+
447
+ /**
448
+ * After the old owner granted `stop`: waits until it no longer answers (it
449
+ * closes the file before its socket stops answering), places the file anew
450
+ * and settles on whichever owner then serves it. Another client may have
451
+ * placed it first, with an owner that differs again: that one is used as it
452
+ * is, not retired in turn.
453
+ */
454
+ private async replace(deadline: number) {
349
455
  await this.waitForRelease(deadline);
350
- const fresh = await this.connectOrSpawn(deadline);
351
- if (!fresh.ok) return fresh;
352
- const reattached = this.attach(fresh.value);
353
- if (!reattached.ok) return reattached;
354
- const freshHello = await this.call({ op: 'hello', clientVersion: VERSION, protocol: PROTOCOL_VERSION }, parseHelloResult);
355
- if (!freshHello.ok) return freshHello;
356
- this.hello = freshHello.value;
456
+ const fresh = await this.handshake(deadline);
457
+ if (!fresh.ok) return this.abandon(fresh);
458
+ if (fresh.value.kind === 'other-protocol') {
459
+ return this.abandon(Result.err({ kind: 'protocol-mismatch' as const, message: fresh.value.message }));
460
+ }
461
+ return this.settle(fresh.value.hello, this.mismatchesOf(fresh.value.hello));
462
+ }
463
+
464
+ /** The owner that answered `hello` is the one this client uses; `mismatches` says how it differs from the one asked for. */
465
+ private settle(hello: HelloResult, mismatches: readonly OwnerMismatch[]) {
466
+ this.hello = hello;
467
+ this.mismatches = mismatches;
357
468
  return Result.ok(undefined);
358
469
  }
359
470
 
471
+ /** A failed connect closes its connection, so it never counts as a client of the owner it could not use. */
472
+ private async abandon<Failed>(failed: Failed): Promise<Failed> {
473
+ await this.close();
474
+ return failed;
475
+ }
476
+
477
+ /**
478
+ * Whether this client is its file's sole connection with no transaction
479
+ * open, as the owner's `status` reports (owners of every build answer it,
480
+ * before a hello too): the one case in which it may retire the owner. A
481
+ * status that cannot be read never is.
482
+ */
483
+ private async ownerUse(): Promise<Use> {
484
+ const status = await this.call({ op: 'status' }, parseStatusResult);
485
+ if (!status.ok) return { sole: false, why: `its status could not be read (${status.error.kind}: ${status.error.message})` };
486
+ const others = status.value.clients - 1;
487
+ if (others > 0) return { sole: false, why: `${others} other client${others === 1 ? ' uses' : 's use'} it` };
488
+ if (status.value.transaction !== null) return { sole: false, why: `transaction ${status.value.transaction.txId} is open` };
489
+ return { sole: true, why: '' };
490
+ }
491
+
360
492
  /**
361
- * Whether the running owner must be retired for this client: it was built
362
- * from other source than this client, or it opened the file with other
493
+ * How the owner that answered `hello` differs from the one this client
494
+ * wants: built from other source than this client, or opened with other
363
495
  * pragmas than this client requires (`serverPragmas` unset accepts any).
364
496
  */
365
- private mustReplace(hello: HelloResult): boolean {
366
- if (hello.serverVersion !== VERSION) return true;
497
+ private mismatchesOf(hello: HelloResult): readonly OwnerMismatch[] {
498
+ const mismatches: OwnerMismatch[] = [];
499
+ if (hello.serverVersion !== VERSION) mismatches.push('version');
367
500
  const required = this.options.serverPragmas;
368
- return required !== undefined && !samePragmas(required, hello.pragmas);
501
+ if (required !== undefined && !samePragmas(required, hello.pragmas)) mismatches.push('pragmas');
502
+ return mismatches;
369
503
  }
370
504
 
371
505
  private async connectOrSpawn(deadline: number) {
@@ -463,8 +597,9 @@ export class SqlegoClient {
463
597
  /**
464
598
  * Owner processes of this build under this runtime directory, fewest files
465
599
  * first, from the meta files their files wrote. An owner of another build
466
- * is never adopted into (its files are retired one by one as their clients
467
- * arrive); a dead one's metas are ignored.
600
+ * is never adopted into (its files are retired one by one by clients that
601
+ * find themselves alone on them, or released when idle); a dead one's metas
602
+ * are ignored.
468
603
  */
469
604
  private currentOwners() {
470
605
  const directory = path.dirname(this.paths.lock);
@@ -510,7 +645,7 @@ export class SqlegoClient {
510
645
  if (!released.ok && released.error.kind === 'lock-failed') this.spawnFailure = `spawn lock not released: ${released.error.message}`;
511
646
  }
512
647
 
513
- /** Waits until nothing answers on the file's socket (the old owner released it), or the deadline. */
648
+ /** Waits until nothing answers on the file's socket (the old owner released it, its database closed first), or the deadline. */
514
649
  private async waitForRelease(deadline: number): Promise<void> {
515
650
  while (Date.now() < deadline) {
516
651
  const socket = await tryConnect(this.paths.socket);
@@ -570,7 +705,7 @@ export class SqlegoClient {
570
705
 
571
706
  private attach(socket: net.Socket) {
572
707
  this.socket = socket;
573
- this.buffer = '';
708
+ this.frames.reset();
574
709
  return Trust.try(
575
710
  () => {
576
711
  socket.setEncoding('utf8');
@@ -590,16 +725,14 @@ export class SqlegoClient {
590
725
  }
591
726
 
592
727
  private onData(chunk: string): void {
593
- const { frames, rest } = splitFrames(this.buffer + chunk);
594
- this.buffer = rest;
595
- for (const frame of frames) {
728
+ for (const frame of this.frames.push(chunk)) {
596
729
  const json = fromJson(frame);
597
730
  const parsed = json.ok ? parseResponse(json.value) : json;
598
731
  if (!parsed.ok) {
599
732
  // A corrupt frame means the stream is unrecoverable; fail every waiter
600
733
  // and drop the socket rather than throwing out of a 'data' handler.
601
734
  if (parsed.error.kind === 'invalid') {
602
- this.buffer = '';
735
+ this.frames.reset();
603
736
  this.settleAll({ kind: 'protocol', message: `malformed frame from server: ${parsed.error.message}` });
604
737
  this.socket?.destroy();
605
738
  }
@@ -862,7 +995,7 @@ function oneShot<T>(socketPath: string, body: RequestBody, parse: (input: unknow
862
995
  if (frame.error.kind === 'bad-request' || frame.error.kind === 'encode-failed') resolve(probeFailed(frame.error.message));
863
996
  return;
864
997
  }
865
- let buffer = '';
998
+ const frames = new FrameReader();
866
999
  let settled = false;
867
1000
  const started = Trust.try(
868
1001
  () => {
@@ -880,9 +1013,7 @@ function oneShot<T>(socketPath: string, body: RequestBody, parse: (input: unknow
880
1013
  socket.once('error', (error) => finish(null, error.message));
881
1014
  socket.once('close', () => finish(null, 'connection closed before a reply'));
882
1015
  socket.on('data', (chunk: string) => {
883
- const { frames, rest } = splitFrames(buffer + chunk);
884
- buffer = rest;
885
- const line = frames[0];
1016
+ const line = frames.push(chunk)[0];
886
1017
  if (line === undefined) return;
887
1018
  const reply = parseOneShotReply(line, parse);
888
1019
  if (reply.ok) finish(reply.value, '');
package/src/index.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export {
2
2
  DEFAULT_MAX_OWNERS, SqlegoClient, SqlegoClientError, SqlegoTransaction, defaultServerCommand, type BeginOptions, type ClientOptions,
3
+ type OwnerInfo, type OwnerMismatch,
3
4
  } from './client.ts';
4
5
  export {
5
6
  SUPPORTED_PLATFORMS, binaryFileName, localBinaryName, locateServerBinary, platformPackageName, unpackedAsarPath, type BinaryLookup,
package/src/protocol.ts CHANGED
@@ -153,7 +153,14 @@ export type ErrorCode =
153
153
  /** Another client's transaction kept the request waiting past the server's queue limit. */
154
154
  | 'tx-busy'
155
155
  /** The owner could not take on the file an `adopt` named (cannot open it, cannot listen for it). */
156
- | 'adopt-failed';
156
+ | 'adopt-failed'
157
+ /**
158
+ * A `stop` refused because other clients are using the file (or another
159
+ * client's transaction is open); nothing was released. A client of a build
160
+ * from before this code does not know it: its parser rejects the frame, so
161
+ * its request fails as `protocol` and its own connection closes.
162
+ */
163
+ | 'owner-busy';
157
164
 
158
165
  export type Response =
159
166
  | { id: number; ok: true; result: unknown }
@@ -546,6 +553,7 @@ export function parseRequest(input: unknown) {
546
553
 
547
554
  const ERROR_CODES: readonly ErrorCode[] = [
548
555
  'sqlite', 'bad-request', 'protocol-mismatch', 'shutting-down', 'encode-failed', 'tx-expired', 'tx-invalid', 'tx-busy', 'adopt-failed',
556
+ 'owner-busy',
549
557
  ];
550
558
 
551
559
  //trust:validator_function
@@ -979,6 +987,70 @@ export function splitFrames(buffer: string): { frames: string[]; rest: string }
979
987
  return { frames: lines.filter((line) => line.length > 0), rest };
980
988
  }
981
989
 
990
+ /**
991
+ * The frames of one socket, read chunk by chunk in work proportional to what
992
+ * arrives, however finely it is chunked: only the new chunk is searched for
993
+ * newlines, and the pieces of an unfinished frame are kept apart and joined
994
+ * once, by the chunk that ends it. Splitting everything received so far on
995
+ * every chunk (`splitFrames(buffer + chunk)`) cost O(K²) for a frame that
996
+ * arrived in K chunks: 786 ms for a 4 MB reply in ~525 chunks (sqlego#7).
997
+ * Empty lines are skipped, as `splitFrames` skips them.
998
+ */
999
+ export class FrameReader {
1000
+ private pieces: string[] = [];
1001
+ private decoder: TextDecoder | null = null;
1002
+ private searched = 0;
1003
+
1004
+ /** Characters searched for a newline so far: each one pushed is searched once. */
1005
+ get scannedCharacters(): number {
1006
+ return this.searched;
1007
+ }
1008
+
1009
+ /** The frames `chunk` completes, in order; its unterminated tail waits for the next chunk. */
1010
+ push(chunk: string): string[] {
1011
+ let newline = chunk.indexOf('\n');
1012
+ if (newline < 0) {
1013
+ this.searched += chunk.length;
1014
+ if (chunk.length > 0) this.pieces.push(chunk);
1015
+ return [];
1016
+ }
1017
+ const frames: string[] = [];
1018
+ let start = 0;
1019
+ while (newline >= 0) {
1020
+ this.searched += newline + 1 - start;
1021
+ let frame = chunk.slice(start, newline);
1022
+ if (this.pieces.length > 0) {
1023
+ this.pieces.push(frame);
1024
+ frame = this.pieces.join('');
1025
+ this.pieces = [];
1026
+ }
1027
+ if (frame.length > 0) frames.push(frame);
1028
+ start = newline + 1;
1029
+ newline = chunk.indexOf('\n', start);
1030
+ }
1031
+ this.searched += chunk.length - start;
1032
+ if (start < chunk.length) this.pieces.push(chunk.slice(start));
1033
+ return frames;
1034
+ }
1035
+
1036
+ /**
1037
+ * `push` for raw bytes, as the server's sockets deliver them. UTF-8 is
1038
+ * decoded as one stream, so a character whose bytes straddle two chunks
1039
+ * arrives whole; decoding each chunk alone turned it into U+FFFD. A BOM is
1040
+ * kept, as `Buffer.toString('utf8')` keeps it.
1041
+ */
1042
+ pushBytes(chunk: Uint8Array): string[] {
1043
+ this.decoder ??= new TextDecoder('utf-8', { ignoreBOM: true });
1044
+ return this.push(this.decoder.decode(chunk, { stream: true }));
1045
+ }
1046
+
1047
+ /** Drops an unfinished frame (and a partly received character): the stream is starting over or was given up. */
1048
+ reset(): void {
1049
+ this.pieces = [];
1050
+ this.decoder = null;
1051
+ }
1052
+ }
1053
+
982
1054
  function replaceBigInt(_key: string, value: unknown): unknown {
983
1055
  return typeof value === 'bigint' ? Number(value) : value;
984
1056
  }