@noego/sqlego 0.1.2-dev.4 → 0.1.2-dev.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -94,7 +94,8 @@ client: connect(socket) ──ok──▶ hello ──▶ requests
94
94
  └──────────────────────────▶ connect ◀─────────┴────────────────┘
95
95
 
96
96
  owner: per file: open db ▶ listen ▶ write <key>.json ▶ release <key>.lock ▶ serve
97
- file's last client leaves ▶ idle timer (default 30 s) ▶ rm socket+meta ▶ close db
97
+ file's last client leaves ▶ idle timer (default 30 s) ▶ close db ▶ rm lock+socket+meta
98
+ file deleted or replaced at its path (checked every 5 s) ▶ same release, clients or not
98
99
  last file released ▶ exit 0
99
100
  ```
100
101
 
@@ -105,10 +106,17 @@ Unix socket paths cap at 104 bytes. On Windows the socket is the named pipe
105
106
 
106
107
  A client whose version differs from the owner's asks it to release the file
107
108
  and places the file anew, so a rebuilt binary never keeps talking to an old
108
- owner. The same happens when a client sets `serverPragmas` and the running
109
- owner opened the file with a different list (`hello` and `status` report the
110
- owner's pragmas). An owner of another build is never adopted into; its other
111
- files are retired one by one as their own clients arrive.
109
+ owner — but only when it is the file's sole client and no transaction is
110
+ open (it asks `status` first). The same holds when a client sets
111
+ `serverPragmas` and the running owner opened the file with a different list
112
+ (`hello` and `status` report the owner's pragmas), or the owner speaks
113
+ another protocol. While other clients use the owner it is never retired: a
114
+ client of another build uses it as it is (`client.owner.mismatches` says
115
+ `version`), and one that cannot (another protocol, or pragmas it requires)
116
+ fails with `owner-in-use`. The owner itself refuses a `stop` with
117
+ `owner-busy` while other clients are connected. An owner of another build is
118
+ never adopted into; its other files are retired one by one as their own
119
+ clients arrive alone, or released when idle.
112
120
 
113
121
  ### Owner processes
114
122
 
@@ -126,8 +134,9 @@ build under the runtime directory, whichever app started it. Nothing is ever
126
134
  refused for lack of a process.
127
135
 
128
136
  Each file keeps its own socket, database connection, leased transaction and
129
- idle timer. `sqlego <file> stop` and the idle timeout release that one file;
130
- the process exits when its last file is released. Spawning is serialized
137
+ idle timer. `sqlego <file> stop` (refused while other clients use the file)
138
+ and the idle timeout release that one file; so does deleting the file or its
139
+ directory. The process exits when its last file is released. Spawning is serialized
131
140
  through `spawn.lock` in the runtime directory so 40 files opened at once
132
141
  share one process instead of starting 40.
133
142
 
@@ -253,7 +262,7 @@ sqlego <file> "DELETE …"
253
262
  sqlego <file> status | stop
254
263
  sqlego <file> watch "SELECT count(*) FROM logs" --every 2s
255
264
  sqlego ls
256
- sqlego serve <file> [--idle-ms 30000] [--tx-lease-ms 10000] [--tx-max-ms 60000] [--tx-queue-ms 30000] [--pragma "<name = value>"]...
265
+ sqlego serve <file> [--idle-ms 30000] [--file-check-ms 5000] [--tx-lease-ms 10000] [--tx-max-ms 60000] [--tx-queue-ms 30000] [--pragma "<name = value>"]...
257
266
  ```
258
267
 
259
268
  ## Library
@@ -287,7 +296,12 @@ await db.close();
287
296
 
288
297
  A `SqlegoClientError` with code `tx-expired` means the server rolled the
289
298
  transaction back (lease, hard cap, or disconnect); `tx-busy` means another
290
- client's transaction kept the request waiting too long.
299
+ client's transaction kept the request waiting too long; `owner-in-use` (from
300
+ `connect`) means the running owner cannot serve this client and other clients
301
+ are using it, so it was left running; `owner-busy` (from `stop`) means other
302
+ clients are using the file. `client.owner` (pid, `serverVersion`, protocol,
303
+ `mismatches`) stays readable after the connection is lost, for logging which
304
+ owner went.
291
305
 
292
306
  Server location: see [Where the server binary comes from](#where-the-server-binary-comes-from);
293
307
  pass `serverCommand` to override.
package/dist/client.d.ts CHANGED
@@ -21,10 +21,11 @@ export type ClientOptions = Readonly<{
21
21
  /**
22
22
  * Pragmas the owner must have applied on open (`--pragma`), replacing its
23
23
  * defaults. A spawned owner gets them; an owner already running with other
24
- * pragmas is asked to stop and a fresh one is spawned with these, the way
25
- * an owner from another build is retired. Two clients insisting on
26
- * different pragmas for one file would keep restarting its owner: agree on
27
- * one list per file, or leave this unset to accept whatever is running.
24
+ * pragmas is retired and a fresh one spawned with these when this client
25
+ * is its file's only one, the way an owner from another build is. While
26
+ * other clients use it, `connect` fails with `owner-in-use` instead and the
27
+ * owner keeps serving them. Agree on one list per file, or leave this unset
28
+ * to accept whatever is running.
28
29
  */
29
30
  serverPragmas?: readonly string[];
30
31
  /**
@@ -44,6 +45,24 @@ export type ClientOptions = Readonly<{
44
45
  requestTimeoutMs?: number;
45
46
  }>;
46
47
  export declare const DEFAULT_MAX_OWNERS = 4;
48
+ /** How an owner a client uses differs from the one it asked for. */
49
+ export type OwnerMismatch = 'version' | 'pragmas';
50
+ /**
51
+ * The owner process a client is connected to, as its hello reported it. It
52
+ * stays on the client after the connection is lost, so whoever logs the loss
53
+ * can name the owner that went (pid, build). `mismatches` lists how the
54
+ * owner differs from what this client asked for while the client uses it
55
+ * anyway: `version` (another build, kept because other clients use it or
56
+ * because `spawn` is false) and `pragmas` (only with `spawn: false`). Empty
57
+ * when it is the owner this client wants.
58
+ */
59
+ export type OwnerInfo = Readonly<{
60
+ pid: number;
61
+ serverVersion: string;
62
+ protocol: number;
63
+ file: string;
64
+ mismatches: readonly OwnerMismatch[];
65
+ }>;
47
66
  export type BeginOptions = Readonly<{
48
67
  /** `immediate` takes the write lock at `begin`; `deferred` (default) on the first write. */
49
68
  mode?: TransactionMode;
@@ -60,10 +79,13 @@ export declare class SqlegoClientError extends Error {
60
79
  export declare class SqlegoClient {
61
80
  readonly paths: FilePaths;
62
81
  private socket;
63
- private buffer;
82
+ /** Reply frames from `socket`; the socket decodes UTF-8 itself (`setEncoding`), split characters included. */
83
+ private readonly frames;
64
84
  private nextId;
65
85
  private readonly pending;
66
86
  private hello;
87
+ /** How the owner in `hello` differs from the one this client asked for (see `OwnerInfo`). */
88
+ private mismatches;
67
89
  /** Why the server this client spawned did not come up, if it did not. */
68
90
  private spawnFailure;
69
91
  /** True while this client is the one spawning an owner process (see `placeFile`). */
@@ -72,6 +94,12 @@ export declare class SqlegoClient {
72
94
  private constructor();
73
95
  static connect(file: string, options?: ClientOptions): Promise<SqlegoClient>;
74
96
  get server(): HelloResult;
97
+ /**
98
+ * The owner this client talks to (see `OwnerInfo`); null before `connect`
99
+ * succeeded. Unlike `server` it never throws, and it is kept after the
100
+ * connection is lost, so the loss can be logged with the owner's pid and build.
101
+ */
102
+ get owner(): OwnerInfo | null;
75
103
  /** Opt this socket into committed-snapshot plain reads and queued plain writes. */
76
104
  enableDetachedPlain(): Promise<boolean>;
77
105
  query<Row extends SqlRow = SqlRow>(sql: string, params?: SqlParams): Promise<Row[]>;
@@ -113,17 +141,62 @@ export declare class SqlegoClient {
113
141
  /** @internal */
114
142
  transactionEnd(txId: number, how: 'commit' | 'rollback'): Promise<void>;
115
143
  status(): Promise<StatusResult>;
116
- /** Asks the server to shut down; the connection closes as a consequence. */
144
+ /**
145
+ * Asks the owner to release this file; the connection closes as a
146
+ * consequence. Refused with `owner-busy` while other clients are connected
147
+ * to the file (or another client's transaction is open): nothing is released.
148
+ */
117
149
  stop(): Promise<void>;
118
150
  close(): Promise<void>;
151
+ /** `stop`, closing this client once it is granted; a refusal (`owner-busy`) or any other error reply is returned as is. */
119
152
  private stopServer;
153
+ /**
154
+ * Connects and settles which owner this client uses. An owner other than
155
+ * the one it wants (another build or protocol, or other pragmas than
156
+ * `serverPragmas`) is retired — asked to release the file, which is then
157
+ * placed anew — only when this client is the file's sole connection and no
158
+ * transaction is open, as the owner's `status` reports. Otherwise the owner
159
+ * keeps serving the clients that use it (2026-10-18: a CLI from another
160
+ * build retired the running app's owner, a 7-minute outage): this client
161
+ * uses it as it is when only the build differs, noting that in `owner`, and
162
+ * fails with `owner-in-use` when it cannot (another protocol, or pragmas it
163
+ * requires); it never sends `stop` then. With `spawn: false` nothing is
164
+ * replaced. A connect that fails closes its connection, so a process whose
165
+ * connects keep failing never holds an owner busy.
166
+ */
120
167
  private open;
121
168
  /**
122
- * Whether the running owner must be retired for this client: it was built
123
- * from other source than this client, or it opened the file with other
169
+ * Connects (placing the file when nothing serves it) and says hello. An
170
+ * owner that drops the connection before answering was releasing the file
171
+ * at that moment: wait until it is gone and start again, until the
172
+ * deadline. Another protocol is an answer, not a failure: `open` decides.
173
+ */
174
+ private handshake;
175
+ /**
176
+ * After the old owner granted `stop`: waits until it no longer answers (it
177
+ * closes the file before its socket stops answering), places the file anew
178
+ * and settles on whichever owner then serves it. Another client may have
179
+ * placed it first, with an owner that differs again: that one is used as it
180
+ * is, not retired in turn.
181
+ */
182
+ private replace;
183
+ /** The owner that answered `hello` is the one this client uses; `mismatches` says how it differs from the one asked for. */
184
+ private settle;
185
+ /** A failed connect closes its connection, so it never counts as a client of the owner it could not use. */
186
+ private abandon;
187
+ /**
188
+ * Whether this client is its file's sole connection with no transaction
189
+ * open, as the owner's `status` reports (owners of every build answer it,
190
+ * before a hello too): the one case in which it may retire the owner. A
191
+ * status that cannot be read never is.
192
+ */
193
+ private ownerUse;
194
+ /**
195
+ * How the owner that answered `hello` differs from the one this client
196
+ * wants: built from other source than this client, or opened with other
124
197
  * pragmas than this client requires (`serverPragmas` unset accepts any).
125
198
  */
126
- private mustReplace;
199
+ private mismatchesOf;
127
200
  private connectOrSpawn;
128
201
  /** The file's own claim lock: whoever holds it places the file with an owner. */
129
202
  private claimLock;
@@ -142,12 +215,13 @@ export declare class SqlegoClient {
142
215
  /**
143
216
  * Owner processes of this build under this runtime directory, fewest files
144
217
  * first, from the meta files their files wrote. An owner of another build
145
- * is never adopted into (its files are retired one by one as their clients
146
- * arrive); a dead one's metas are ignored.
218
+ * is never adopted into (its files are retired one by one by clients that
219
+ * find themselves alone on them, or released when idle); a dead one's metas
220
+ * are ignored.
147
221
  */
148
222
  private currentOwners;
149
223
  private releaseSpawnLock;
150
- /** Waits until nothing answers on the file's socket (the old owner released it), or the deadline. */
224
+ /** Waits until nothing answers on the file's socket (the old owner released it, its database closed first), or the deadline. */
151
225
  private waitForRelease;
152
226
  private spawnServer;
153
227
  /** The spawn never started: record why, and release the lock so another claimer can try. */
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { DEFAULT_MAX_OWNERS, SqlegoClient, SqlegoClientError, SqlegoTransaction, defaultServerCommand, type BeginOptions, type ClientOptions, } from './client.ts';
1
+ export { DEFAULT_MAX_OWNERS, SqlegoClient, SqlegoClientError, SqlegoTransaction, defaultServerCommand, type BeginOptions, type ClientOptions, type OwnerInfo, type OwnerMismatch, } from './client.ts';
2
2
  export { SUPPORTED_PLATFORMS, binaryFileName, localBinaryName, locateServerBinary, platformPackageName, unpackedAsarPath, type BinaryLookup, } from './binary.ts';
3
3
  export { USES_NAMED_PIPES, isNamedPipe, pathsFor, runtimeDirectory, canonicalFile, type FilePaths, type ServerMeta } from './paths.ts';
4
4
  export { PROTOCOL_VERSION, type SqlParams, type SqlRow, type SqlValue, type Statement, type RunResult, type QueryResult, type BatchResult, type StatementResult, type ExecResult, type BeginResult, type StatusResult, type HelloResult, type TransactionMode, type TransactionStatus, } from './protocol.ts';
package/dist/index.js CHANGED
@@ -262,7 +262,8 @@ var ERROR_CODES = [
262
262
  "tx-expired",
263
263
  "tx-invalid",
264
264
  "tx-busy",
265
- "adopt-failed"
265
+ "adopt-failed",
266
+ "owner-busy"
266
267
  ];
267
268
  function parseErrorCode(input) {
268
269
  const code = ERROR_CODES.find((known) => known === input);
@@ -276,8 +277,8 @@ function parseResponse(input) {
276
277
  if (typeof id !== "number")
277
278
  return invalid("a response needs a numeric id");
278
279
  if (fields.ok === true) {
279
- const response2 = { id, ok: true, result: fields.result };
280
- return Result.ok(response2);
280
+ const response = { id, ok: true, result: fields.result };
281
+ return Result.ok(response);
281
282
  }
282
283
  if (fields.ok !== false)
283
284
  return invalid("a response needs ok: true or false");
@@ -512,11 +513,51 @@ function normalizePragma(pragma) {
512
513
  function samePragmas(a, b) {
513
514
  return a.length === b.length && a.every((pragma, index) => normalizePragma(pragma) === normalizePragma(b[index]));
514
515
  }
515
- function splitFrames(buffer) {
516
- const lines = buffer.split(`
516
+ class FrameReader {
517
+ pieces = [];
518
+ decoder = null;
519
+ searched = 0;
520
+ get scannedCharacters() {
521
+ return this.searched;
522
+ }
523
+ push(chunk) {
524
+ let newline = chunk.indexOf(`
517
525
  `);
518
- const rest = lines.pop() ?? "";
519
- return { frames: lines.filter((line) => line.length > 0), rest };
526
+ if (newline < 0) {
527
+ this.searched += chunk.length;
528
+ if (chunk.length > 0)
529
+ this.pieces.push(chunk);
530
+ return [];
531
+ }
532
+ const frames = [];
533
+ let start = 0;
534
+ while (newline >= 0) {
535
+ this.searched += newline + 1 - start;
536
+ let frame = chunk.slice(start, newline);
537
+ if (this.pieces.length > 0) {
538
+ this.pieces.push(frame);
539
+ frame = this.pieces.join("");
540
+ this.pieces = [];
541
+ }
542
+ if (frame.length > 0)
543
+ frames.push(frame);
544
+ start = newline + 1;
545
+ newline = chunk.indexOf(`
546
+ `, start);
547
+ }
548
+ this.searched += chunk.length - start;
549
+ if (start < chunk.length)
550
+ this.pieces.push(chunk.slice(start));
551
+ return frames;
552
+ }
553
+ pushBytes(chunk) {
554
+ this.decoder ??= new TextDecoder("utf-8", { ignoreBOM: true });
555
+ return this.push(this.decoder.decode(chunk, { stream: true }));
556
+ }
557
+ reset() {
558
+ this.pieces = [];
559
+ this.decoder = null;
560
+ }
520
561
  }
521
562
  function replaceBigInt(_key, value) {
522
563
  return typeof value === "bigint" ? Number(value) : value;
@@ -563,10 +604,10 @@ function resolvePaths(file) {
563
604
  if (!directory.ok)
564
605
  return directory;
565
606
  const derived = Trust.try(() => {
566
- const key2 = createHash("sha1").update(canonical.value).digest("hex").slice(0, 16);
607
+ const key = createHash("sha1").update(canonical.value).digest("hex").slice(0, 16);
567
608
  const scope = createHash("sha1").update(directory.value.toLowerCase()).digest("hex").slice(0, 8);
568
- const socket2 = USES_NAMED_PIPES ? `\\\\.\\pipe\\sqlego-${scope}-${key2}` : path2.join(directory.value, `${key2}.sock`);
569
- return { key: key2, socket: socket2, socketBytes: Buffer.byteLength(socket2) };
609
+ const socket = USES_NAMED_PIPES ? `\\\\.\\pipe\\sqlego-${scope}-${key}` : path2.join(directory.value, `${key}.sock`);
610
+ return { key, socket, socketBytes: Buffer.byteLength(socket) };
570
611
  }, (cause) => ({ kind: "hash-failed", message: `cannot hash ${canonical.value}: ${errorMessage(cause)}` }));
571
612
  if (!derived.ok)
572
613
  return derived;
@@ -638,7 +679,7 @@ import { fileURLToPath } from "node:url";
638
679
  // package.json
639
680
  var package_default = {
640
681
  name: "@noego/sqlego",
641
- version: "0.1.2-dev.4",
682
+ version: "0.1.2-dev.6",
642
683
  description: "One owner per SQLite file, many files per owner process. Clients (CLI, Node, Bun) pass SQL over a local socket (Unix) or named pipe (Windows); the owner starts on demand and exits when idle.",
643
684
  type: "module",
644
685
  license: "ISC",
@@ -689,11 +730,11 @@ var package_default = {
689
730
  "@noego/trust": "0.5.0-dev.0"
690
731
  },
691
732
  optionalDependencies: {
692
- "@noego/sqlego-darwin-arm64": "0.1.2-dev.4",
693
- "@noego/sqlego-darwin-x64": "0.1.2-dev.4",
694
- "@noego/sqlego-linux-x64": "0.1.2-dev.4",
695
- "@noego/sqlego-linux-arm64": "0.1.2-dev.4",
696
- "@noego/sqlego-win32-x64": "0.1.2-dev.4"
733
+ "@noego/sqlego-darwin-arm64": "0.1.2-dev.6",
734
+ "@noego/sqlego-darwin-x64": "0.1.2-dev.6",
735
+ "@noego/sqlego-linux-x64": "0.1.2-dev.6",
736
+ "@noego/sqlego-linux-arm64": "0.1.2-dev.6",
737
+ "@noego/sqlego-win32-x64": "0.1.2-dev.6"
697
738
  }
698
739
  };
699
740
 
@@ -711,8 +752,8 @@ function sourceBuildId(sourceDirectory) {
711
752
  }, (cause) => ({ kind: "source-unreadable", message: `cannot hash sources in ${sourceDirectory}: ${errorMessage(cause)}` }));
712
753
  }
713
754
  function resolveBuildId() {
714
- if ("e5711cce187d".length > 0)
715
- return "e5711cce187d";
755
+ if ("3f3144144273".length > 0)
756
+ return "3f3144144273";
716
757
  const directory = Trust.try(() => path3.dirname(fileURLToPath(import.meta.url)), (cause) => ({ kind: "module-path", message: errorMessage(cause) }));
717
758
  if (!directory.ok)
718
759
  return decideUnknownBuild(directory.error.kind);
@@ -764,10 +805,11 @@ function callerStatement(result) {
764
805
  class SqlegoClient {
765
806
  paths;
766
807
  socket = null;
767
- buffer = "";
808
+ frames = new FrameReader;
768
809
  nextId = 1;
769
810
  pending = new Map;
770
811
  hello = null;
812
+ mismatches = [];
771
813
  spawnFailure = null;
772
814
  holdsSpawnLock = false;
773
815
  options;
@@ -789,6 +831,12 @@ class SqlegoClient {
789
831
  return this.hello;
790
832
  return unwrap(Result.err({ kind: "not-connected", message: "client is not connected" }));
791
833
  }
834
+ get owner() {
835
+ const hello = this.hello;
836
+ if (!hello)
837
+ return null;
838
+ return { pid: hello.pid, serverVersion: hello.serverVersion, protocol: hello.protocol, file: hello.file, mismatches: this.mismatches };
839
+ }
792
840
  async enableDetachedPlain() {
793
841
  if (!this.server.capabilities.includes("detached-plain"))
794
842
  return false;
@@ -880,40 +928,96 @@ class SqlegoClient {
880
928
  }
881
929
  async open() {
882
930
  const deadline = Date.now() + (this.options.connectTimeoutMs ?? 1e4);
883
- const socket = await this.connectOrSpawn(deadline);
884
- if (!socket.ok)
885
- return socket;
886
- const attached = this.attach(socket.value);
887
- if (!attached.ok)
888
- return attached;
889
- const hello = await this.call({ op: "hello", clientVersion: VERSION, protocol: PROTOCOL_VERSION }, parseHelloResult);
890
- if (!hello.ok)
891
- return hello;
892
- if (!this.mustReplace(hello.value) || this.options.spawn === false) {
893
- this.hello = hello.value;
894
- return Result.ok(undefined);
931
+ const greeted = await this.handshake(deadline);
932
+ if (!greeted.ok)
933
+ return this.abandon(greeted);
934
+ const greeting = greeted.value;
935
+ const mismatches = greeting.kind === "hello" ? this.mismatchesOf(greeting.hello) : [];
936
+ if (greeting.kind === "hello" && (mismatches.length === 0 || this.options.spawn === false))
937
+ return this.settle(greeting.hello, mismatches);
938
+ if (greeting.kind === "other-protocol" && this.options.spawn === false) {
939
+ return this.abandon(Result.err({ kind: "protocol-mismatch", message: greeting.message }));
940
+ }
941
+ const use = await this.ownerUse();
942
+ if (use.sole) {
943
+ const stopped = await this.stopServer();
944
+ if (stopped.ok)
945
+ return this.replace(deadline);
946
+ if (stopped.error.kind !== "owner-busy")
947
+ return this.abandon(stopped);
948
+ }
949
+ if (greeting.kind === "hello" && !mismatches.includes("pragmas"))
950
+ return this.settle(greeting.hello, mismatches);
951
+ const what = greeting.kind === "hello" ? `its owner (pid ${greeting.hello.pid}) opened it with other pragmas than serverPragmas requires` : `its owner speaks another protocol (${greeting.message})`;
952
+ const why = use.sole ? "another client connected meanwhile" : use.why;
953
+ return this.abandon(Result.err({ kind: "owner-in-use", message: `${this.paths.file}: ${what}, and ${why}; it was left running` }));
954
+ }
955
+ async handshake(deadline) {
956
+ for (;; ) {
957
+ const socket = await this.connectOrSpawn(deadline);
958
+ if (!socket.ok)
959
+ return socket;
960
+ const attached = this.attach(socket.value);
961
+ if (!attached.ok)
962
+ return attached;
963
+ const hello = await this.call({ op: "hello", clientVersion: VERSION, protocol: PROTOCOL_VERSION }, parseHelloResult);
964
+ if (hello.ok)
965
+ return Result.ok({ kind: "hello", hello: hello.value });
966
+ switch (hello.error.kind) {
967
+ case "protocol-mismatch":
968
+ return Result.ok({ kind: "other-protocol", message: hello.error.message });
969
+ case "closed":
970
+ case "not-connected":
971
+ case "socket":
972
+ case "shutting-down":
973
+ if (Date.now() >= deadline)
974
+ return hello;
975
+ await this.close();
976
+ await this.waitForRelease(deadline);
977
+ break;
978
+ default:
979
+ return hello;
980
+ }
895
981
  }
896
- const stopped = await this.stopServer();
897
- if (!stopped.ok)
898
- return stopped;
982
+ }
983
+ async replace(deadline) {
899
984
  await this.waitForRelease(deadline);
900
- const fresh = await this.connectOrSpawn(deadline);
985
+ const fresh = await this.handshake(deadline);
901
986
  if (!fresh.ok)
902
- return fresh;
903
- const reattached = this.attach(fresh.value);
904
- if (!reattached.ok)
905
- return reattached;
906
- const freshHello = await this.call({ op: "hello", clientVersion: VERSION, protocol: PROTOCOL_VERSION }, parseHelloResult);
907
- if (!freshHello.ok)
908
- return freshHello;
909
- this.hello = freshHello.value;
987
+ return this.abandon(fresh);
988
+ if (fresh.value.kind === "other-protocol") {
989
+ return this.abandon(Result.err({ kind: "protocol-mismatch", message: fresh.value.message }));
990
+ }
991
+ return this.settle(fresh.value.hello, this.mismatchesOf(fresh.value.hello));
992
+ }
993
+ settle(hello, mismatches) {
994
+ this.hello = hello;
995
+ this.mismatches = mismatches;
910
996
  return Result.ok(undefined);
911
997
  }
912
- mustReplace(hello) {
998
+ async abandon(failed) {
999
+ await this.close();
1000
+ return failed;
1001
+ }
1002
+ async ownerUse() {
1003
+ const status = await this.call({ op: "status" }, parseStatusResult);
1004
+ if (!status.ok)
1005
+ return { sole: false, why: `its status could not be read (${status.error.kind}: ${status.error.message})` };
1006
+ const others = status.value.clients - 1;
1007
+ if (others > 0)
1008
+ return { sole: false, why: `${others} other client${others === 1 ? " uses" : "s use"} it` };
1009
+ if (status.value.transaction !== null)
1010
+ return { sole: false, why: `transaction ${status.value.transaction.txId} is open` };
1011
+ return { sole: true, why: "" };
1012
+ }
1013
+ mismatchesOf(hello) {
1014
+ const mismatches = [];
913
1015
  if (hello.serverVersion !== VERSION)
914
- return true;
1016
+ mismatches.push("version");
915
1017
  const required = this.options.serverPragmas;
916
- return required !== undefined && !samePragmas(required, hello.pragmas);
1018
+ if (required !== undefined && !samePragmas(required, hello.pragmas))
1019
+ mismatches.push("pragmas");
1020
+ return mismatches;
917
1021
  }
918
1022
  async connectOrSpawn(deadline) {
919
1023
  const first = await tryConnect(this.paths.socket);
@@ -1080,7 +1184,7 @@ class SqlegoClient {
1080
1184
  }
1081
1185
  attach(socket) {
1082
1186
  this.socket = socket;
1083
- this.buffer = "";
1187
+ this.frames.reset();
1084
1188
  return Trust.try(() => {
1085
1189
  socket.setEncoding("utf8");
1086
1190
  socket.on("data", (chunk) => this.onData(chunk));
@@ -1095,14 +1199,12 @@ class SqlegoClient {
1095
1199
  this.settleAll({ kind: "closed", message: "connection closed" });
1096
1200
  }
1097
1201
  onData(chunk) {
1098
- const { frames, rest } = splitFrames(this.buffer + chunk);
1099
- this.buffer = rest;
1100
- for (const frame of frames) {
1202
+ for (const frame of this.frames.push(chunk)) {
1101
1203
  const json = fromJson(frame);
1102
1204
  const parsed = json.ok ? parseResponse(json.value) : json;
1103
1205
  if (!parsed.ok) {
1104
1206
  if (parsed.error.kind === "invalid") {
1105
- this.buffer = "";
1207
+ this.frames.reset();
1106
1208
  this.settleAll({ kind: "protocol", message: `malformed frame from server: ${parsed.error.message}` });
1107
1209
  this.socket?.destroy();
1108
1210
  }
@@ -1296,7 +1398,7 @@ function oneShot(socketPath, body, parse, timeoutMs) {
1296
1398
  resolve(probeFailed(frame.error.message));
1297
1399
  return;
1298
1400
  }
1299
- let buffer = "";
1401
+ const frames = new FrameReader;
1300
1402
  let settled = false;
1301
1403
  const started = Trust.try(() => {
1302
1404
  const socket = new net.Socket;
@@ -1313,9 +1415,7 @@ function oneShot(socketPath, body, parse, timeoutMs) {
1313
1415
  socket.once("error", (error) => finish(null, error.message));
1314
1416
  socket.once("close", () => finish(null, "connection closed before a reply"));
1315
1417
  socket.on("data", (chunk) => {
1316
- const { frames, rest } = splitFrames(buffer + chunk);
1317
- buffer = rest;
1318
- const line = frames[0];
1418
+ const line = frames.push(chunk)[0];
1319
1419
  if (line === undefined)
1320
1420
  return;
1321
1421
  const reply = parseOneShotReply(line, parse);
@@ -1340,8 +1440,8 @@ function parseOneShotReply(line, parse) {
1340
1440
  if (!response.ok) {
1341
1441
  if (response.error.kind === "invalid")
1342
1442
  return probeFailed(`malformed reply: ${response.error.message}`);
1343
- const unhandled2 = response.error.kind;
1344
- return unhandled2;
1443
+ const unhandled = response.error.kind;
1444
+ return unhandled;
1345
1445
  }
1346
1446
  if (!response.value.ok)
1347
1447
  return probeFailed(`${response.value.error.code}: ${response.value.error.message}`);
@@ -1398,22 +1498,22 @@ function sleep(ms) {
1398
1498
  return new Promise((resolve) => setTimeout(resolve, ms));
1399
1499
  }
1400
1500
  export {
1401
- unpackedAsarPath,
1402
- runtimeDirectory,
1403
- platformPackageName,
1404
- pathsFor,
1405
- locateServerBinary,
1406
- localBinaryName,
1407
- isNamedPipe,
1408
- defaultServerCommand,
1409
- canonicalFile,
1410
- binaryFileName,
1411
- VERSION,
1412
- USES_NAMED_PIPES,
1413
- SqlegoTransaction,
1414
- SqlegoClientError,
1415
- SqlegoClient,
1416
- SUPPORTED_PLATFORMS,
1501
+ DEFAULT_MAX_OWNERS,
1417
1502
  PROTOCOL_VERSION,
1418
- DEFAULT_MAX_OWNERS
1503
+ SUPPORTED_PLATFORMS,
1504
+ SqlegoClient,
1505
+ SqlegoClientError,
1506
+ SqlegoTransaction,
1507
+ USES_NAMED_PIPES,
1508
+ VERSION,
1509
+ binaryFileName,
1510
+ canonicalFile,
1511
+ defaultServerCommand,
1512
+ isNamedPipe,
1513
+ localBinaryName,
1514
+ locateServerBinary,
1515
+ pathsFor,
1516
+ platformPackageName,
1517
+ runtimeDirectory,
1518
+ unpackedAsarPath
1419
1519
  };
@@ -217,7 +217,14 @@ export type ErrorCode = 'sqlite' | 'bad-request' | 'protocol-mismatch' | 'shutti
217
217
  /** Another client's transaction kept the request waiting past the server's queue limit. */
218
218
  | 'tx-busy'
219
219
  /** The owner could not take on the file an `adopt` named (cannot open it, cannot listen for it). */
220
- | 'adopt-failed';
220
+ | 'adopt-failed'
221
+ /**
222
+ * A `stop` refused because other clients are using the file (or another
223
+ * client's transaction is open); nothing was released. A client of a build
224
+ * from before this code does not know it: its parser rejects the frame, so
225
+ * its request fails as `protocol` and its own connection closes.
226
+ */
227
+ | 'owner-busy';
221
228
  export type Response = {
222
229
  id: number;
223
230
  ok: true;
@@ -463,3 +470,30 @@ export declare function splitFrames(buffer: string): {
463
470
  frames: string[];
464
471
  rest: string;
465
472
  };
473
+ /**
474
+ * The frames of one socket, read chunk by chunk in work proportional to what
475
+ * arrives, however finely it is chunked: only the new chunk is searched for
476
+ * newlines, and the pieces of an unfinished frame are kept apart and joined
477
+ * once, by the chunk that ends it. Splitting everything received so far on
478
+ * every chunk (`splitFrames(buffer + chunk)`) cost O(K²) for a frame that
479
+ * arrived in K chunks: 786 ms for a 4 MB reply in ~525 chunks (sqlego#7).
480
+ * Empty lines are skipped, as `splitFrames` skips them.
481
+ */
482
+ export declare class FrameReader {
483
+ private pieces;
484
+ private decoder;
485
+ private searched;
486
+ /** Characters searched for a newline so far: each one pushed is searched once. */
487
+ get scannedCharacters(): number;
488
+ /** The frames `chunk` completes, in order; its unterminated tail waits for the next chunk. */
489
+ push(chunk: string): string[];
490
+ /**
491
+ * `push` for raw bytes, as the server's sockets deliver them. UTF-8 is
492
+ * decoded as one stream, so a character whose bytes straddle two chunks
493
+ * arrives whole; decoding each chunk alone turned it into U+FFFD. A BOM is
494
+ * kept, as `Buffer.toString('utf8')` keeps it.
495
+ */
496
+ pushBytes(chunk: Uint8Array): string[];
497
+ /** Drops an unfinished frame (and a partly received character): the stream is starting over or was given up. */
498
+ reset(): void;
499
+ }