@noego/sqlego 0.0.3 → 0.1.2-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // src/client.ts
2
2
  import { spawn } from "node:child_process";
3
- import { closeSync, openSync, readFileSync as readFileSync2, rmSync, writeSync, existsSync as existsSync3 } from "node:fs";
3
+ import { closeSync, openSync, readdirSync as readdirSync2, readFileSync as readFileSync2, rmSync, writeSync, existsSync as existsSync3 } from "node:fs";
4
4
  import net from "node:net";
5
5
  import path3 from "node:path";
6
6
  import { fileURLToPath as fileURLToPath2 } from "node:url";
@@ -217,7 +217,8 @@ var ERROR_CODES = [
217
217
  "encode-failed",
218
218
  "tx-expired",
219
219
  "tx-invalid",
220
- "tx-busy"
220
+ "tx-busy",
221
+ "adopt-failed"
221
222
  ];
222
223
  function parseErrorCode(input) {
223
224
  const code = ERROR_CODES.find((known) => known === input);
@@ -345,12 +346,23 @@ function parseExecResult(input) {
345
346
  const result = { statements: fields.statements, changes: fields.changes, lastInsertRowid: rowid.value };
346
347
  return Result.ok(result);
347
348
  }
349
+ function parsePragmas(input) {
350
+ if (input === undefined)
351
+ return Result.ok([]);
352
+ if (!Array.isArray(input) || !input.every((item) => typeof item === "string")) {
353
+ return invalid("pragmas must be an array of strings");
354
+ }
355
+ return Result.ok([...input]);
356
+ }
348
357
  function parseHelloResult(input) {
349
358
  const fields = fieldsOf(input);
350
359
  if (!fields || typeof fields.serverVersion !== "string" || typeof fields.protocol !== "number" || typeof fields.file !== "string" || typeof fields.pid !== "number") {
351
360
  return invalid("a hello result needs serverVersion, protocol, file and pid");
352
361
  }
353
- const result = { serverVersion: fields.serverVersion, protocol: fields.protocol, file: fields.file, pid: fields.pid };
362
+ const pragmas = parsePragmas(fields.pragmas);
363
+ if (!pragmas.ok)
364
+ return pragmas;
365
+ const result = { serverVersion: fields.serverVersion, protocol: fields.protocol, file: fields.file, pid: fields.pid, pragmas: pragmas.value };
354
366
  return Result.ok(result);
355
367
  }
356
368
  function parseBeginResult(input) {
@@ -368,6 +380,14 @@ function parseTransactionEndResult(input) {
368
380
  const result = { txId: f.txId };
369
381
  return Result.ok(result);
370
382
  }
383
+ function parseAdoptResult(input) {
384
+ const f = fieldsOf(input);
385
+ if (!f || typeof f.file !== "string" || typeof f.socket !== "string" || typeof f.pid !== "number") {
386
+ return invalid("an adopt result needs file, socket (strings) and pid (number)");
387
+ }
388
+ const result = { file: f.file, socket: f.socket, pid: f.pid };
389
+ return Result.ok(result);
390
+ }
371
391
  function parseTransactionStatus(input) {
372
392
  if (input === null)
373
393
  return Result.ok(null);
@@ -393,12 +413,20 @@ function parseStatusResult(input) {
393
413
  const transaction = parseTransactionStatus(f.transaction);
394
414
  if (!transaction.ok)
395
415
  return transaction;
416
+ const pragmas = parsePragmas(f.pragmas);
417
+ if (!pragmas.ok)
418
+ return pragmas;
419
+ const files = f.files === undefined ? 1 : f.files;
420
+ if (typeof files !== "number")
421
+ return invalid("status.files must be a number");
396
422
  const result = {
397
423
  file: f.file,
398
424
  socket: f.socket,
399
425
  pid: f.pid,
400
426
  serverVersion: f.serverVersion,
401
427
  protocol: f.protocol,
428
+ pragmas: pragmas.value,
429
+ files,
402
430
  clients: f.clients,
403
431
  uptimeMs: f.uptimeMs,
404
432
  idleMs: f.idleMs,
@@ -424,6 +452,12 @@ function errnoCode(cause) {
424
452
  function errorMessage(cause) {
425
453
  return cause instanceof Error ? cause.message : String(cause);
426
454
  }
455
+ function normalizePragma(pragma) {
456
+ return pragma.replace(/\s+/g, " ").replace(/\s*([=(),])\s*/g, "$1").trim().toLowerCase();
457
+ }
458
+ function samePragmas(a, b) {
459
+ return a.length === b.length && a.every((pragma, index) => normalizePragma(pragma) === normalizePragma(b[index]));
460
+ }
427
461
  function splitFrames(buffer) {
428
462
  const lines = buffer.split(`
429
463
  `);
@@ -463,6 +497,10 @@ function resolveCanonicalFile(file) {
463
497
  }, (cause) => ({ kind: "canonical-path", message: `cannot resolve ${file}: ${errorMessage(cause)}` }));
464
498
  }
465
499
  var MAX_SOCKET_PATH_BYTES = 100;
500
+ var USES_NAMED_PIPES = process.platform === "win32";
501
+ function isNamedPipe(socket) {
502
+ return /^\\\\[.?]\\pipe\\/i.test(socket);
503
+ }
466
504
  function resolvePaths(file) {
467
505
  const canonical = resolveCanonicalFile(file);
468
506
  if (!canonical.ok)
@@ -472,13 +510,14 @@ function resolvePaths(file) {
472
510
  return directory;
473
511
  const derived = Trust.try(() => {
474
512
  const key = createHash("sha1").update(canonical.value).digest("hex").slice(0, 16);
475
- const socket = path.join(directory.value, `${key}.sock`);
513
+ const scope = createHash("sha1").update(directory.value.toLowerCase()).digest("hex").slice(0, 8);
514
+ const socket = USES_NAMED_PIPES ? `\\\\.\\pipe\\sqlego-${scope}-${key}` : path.join(directory.value, `${key}.sock`);
476
515
  return { key, socket, socketBytes: Buffer.byteLength(socket) };
477
516
  }, (cause) => ({ kind: "hash-failed", message: `cannot hash ${canonical.value}: ${errorMessage(cause)}` }));
478
517
  if (!derived.ok)
479
518
  return derived;
480
519
  const { key, socket, socketBytes } = derived.value;
481
- if (socketBytes > MAX_SOCKET_PATH_BYTES) {
520
+ if (!USES_NAMED_PIPES && socketBytes > MAX_SOCKET_PATH_BYTES) {
482
521
  return Result.err({
483
522
  kind: "socket-path-too-long",
484
523
  message: `sqlego runtime directory too deep for a Unix socket (${socketBytes} bytes > ${MAX_SOCKET_PATH_BYTES}): ${socket}. ` + "Point SQLEGO_RUNTIME_DIR at a shorter path."
@@ -511,6 +550,20 @@ function pathsFor(file) {
511
550
  return paths.value;
512
551
  throw new Error(paths.error.message);
513
552
  }
553
+ function parseServerMeta(input) {
554
+ const fields = typeof input === "object" && input !== null && !Array.isArray(input) ? input : null;
555
+ if (!fields || typeof fields.file !== "string" || typeof fields.socket !== "string" || typeof fields.pid !== "number" || typeof fields.serverVersion !== "string" || typeof fields.startedAt !== "number") {
556
+ return Result.err({ kind: "invalid", message: "server meta needs file, socket, pid, serverVersion and startedAt" });
557
+ }
558
+ const meta = {
559
+ file: fields.file,
560
+ socket: fields.socket,
561
+ pid: fields.pid,
562
+ serverVersion: fields.serverVersion,
563
+ startedAt: fields.startedAt
564
+ };
565
+ return Result.ok(meta);
566
+ }
514
567
  function isProcessAlive(pid) {
515
568
  const probe = Trust.try(() => process.kill(pid, 0), (cause) => errnoCode(cause) === "EPERM" ? { kind: "not-permitted" } : { kind: "no-such-process" });
516
569
  if (probe.ok)
@@ -531,14 +584,19 @@ import { fileURLToPath } from "node:url";
531
584
  // package.json
532
585
  var package_default = {
533
586
  name: "@noego/sqlego",
534
- version: "0.0.3",
535
- description: "One owner process per SQLite file. Clients (CLI, Node, Bun) pass SQL over a local socket; the server boots on demand and exits when idle.",
587
+ version: "0.1.2-dev.1",
588
+ 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.",
536
589
  type: "module",
537
590
  license: "ISC",
538
591
  author: "Shavauhn Gabay",
539
592
  bin: {
540
- sqlego: "./bin/sqlego"
593
+ sqlego: "./bin/sqlego.cjs"
541
594
  },
595
+ os: [
596
+ "darwin",
597
+ "linux",
598
+ "win32"
599
+ ],
542
600
  main: "./dist/index.js",
543
601
  types: "./dist/index.d.ts",
544
602
  exports: {
@@ -559,8 +617,10 @@ var package_default = {
559
617
  scripts: {
560
618
  prepare: "bun scripts/build.ts all",
561
619
  build: "bun scripts/build.ts all",
620
+ "build:all": "bun scripts/build.ts all:platforms",
562
621
  "build:lib": "bun scripts/build.ts lib",
563
622
  "build:bin": "bun scripts/build.ts bin",
623
+ "build:bin:all": "bun scripts/build.ts bin:all",
564
624
  typecheck: "bunx tsc --noEmit",
565
625
  trust: "trust check src",
566
626
  test: "bun test"
@@ -589,8 +649,8 @@ function sourceBuildId(sourceDirectory) {
589
649
  }, (cause) => ({ kind: "source-unreadable", message: `cannot hash sources in ${sourceDirectory}: ${errorMessage(cause)}` }));
590
650
  }
591
651
  function resolveBuildId() {
592
- if ("ed6f3704ee47".length > 0)
593
- return "ed6f3704ee47";
652
+ if ("e0ab394649fb".length > 0)
653
+ return "e0ab394649fb";
594
654
  const directory = Trust.try(() => path2.dirname(fileURLToPath(import.meta.url)), (cause) => ({ kind: "module-path", message: errorMessage(cause) }));
595
655
  if (!directory.ok)
596
656
  return decideUnknownBuild(directory.error.kind);
@@ -615,6 +675,8 @@ var BUILD_ID = resolveBuildId();
615
675
  var VERSION = process.env.SQLEGO_VERSION_OVERRIDE || `${package_default.version}+${BUILD_ID}`;
616
676
 
617
677
  // src/client.ts
678
+ var DEFAULT_MAX_OWNERS = 1;
679
+ var ADOPT_TIMEOUT_MS = 5000;
618
680
  var SAVEPOINT_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
619
681
 
620
682
  class SqlegoClientError extends Error {
@@ -645,6 +707,7 @@ class SqlegoClient {
645
707
  pending = new Map;
646
708
  hello = null;
647
709
  spawnFailure = null;
710
+ holdsSpawnLock = false;
648
711
  options;
649
712
  constructor(paths, options) {
650
713
  this.paths = paths;
@@ -753,14 +816,14 @@ class SqlegoClient {
753
816
  const hello = await this.call({ op: "hello", clientVersion: VERSION, protocol: PROTOCOL_VERSION }, parseHelloResult);
754
817
  if (!hello.ok)
755
818
  return hello;
756
- if (hello.value.serverVersion === VERSION || this.options.spawn === false) {
819
+ if (!this.mustReplace(hello.value) || this.options.spawn === false) {
757
820
  this.hello = hello.value;
758
821
  return Result.ok(undefined);
759
822
  }
760
823
  const stopped = await this.stopServer();
761
824
  if (!stopped.ok)
762
825
  return stopped;
763
- await this.waitForExit(hello.value.pid, deadline);
826
+ await this.waitForRelease(deadline);
764
827
  const fresh = await this.connectOrSpawn(deadline);
765
828
  if (!fresh.ok)
766
829
  return fresh;
@@ -773,6 +836,12 @@ class SqlegoClient {
773
836
  this.hello = freshHello.value;
774
837
  return Result.ok(undefined);
775
838
  }
839
+ mustReplace(hello) {
840
+ if (hello.serverVersion !== VERSION)
841
+ return true;
842
+ const required = this.options.serverPragmas;
843
+ return required !== undefined && !samePragmas(required, hello.pragmas);
844
+ }
776
845
  async connectOrSpawn(deadline) {
777
846
  const first = await tryConnect(this.paths.socket);
778
847
  if (first)
@@ -784,43 +853,118 @@ class SqlegoClient {
784
853
  if (!claimed.ok)
785
854
  return claimed;
786
855
  if (claimed.value) {
787
- const spawned = this.spawnServer();
788
- if (!spawned.ok)
789
- return spawned;
856
+ const placed = await this.placeFile(deadline);
857
+ if (!placed.ok) {
858
+ const released = this.releaseLock();
859
+ const suffix = !released.ok && released.error.kind === "lock-failed" ? `; lock not released: ${released.error.message}` : "";
860
+ return Result.err({ kind: placed.error.kind, message: `${placed.error.message}${suffix}` });
861
+ }
790
862
  }
791
863
  while (Date.now() < deadline) {
792
864
  const socket = await tryConnect(this.paths.socket);
793
- if (socket)
865
+ if (socket) {
866
+ this.releaseSpawnLock();
794
867
  return Result.ok(socket);
868
+ }
795
869
  await sleep(25);
796
870
  }
871
+ this.releaseSpawnLock();
797
872
  const cause = this.spawnFailure ? ` (${this.spawnFailure})` : "";
798
873
  return Result.err({ kind: "connect-timeout", message: `no sqlego server became reachable for ${this.paths.file}${cause}` });
799
874
  }
800
875
  claimLock() {
801
- const lock = this.paths.lock;
802
- for (let attempt = 0;attempt < 2; attempt += 1) {
803
- const created = Trust.try(() => {
804
- const fd = openSync(lock, "wx");
805
- writeSync(fd, String(process.pid));
806
- closeSync(fd);
807
- }, (cause) => errnoCode(cause) === "EEXIST" ? { kind: "lock-held", message: `${lock} exists` } : { kind: "lock-failed", message: `cannot create ${lock}: ${errorMessage(cause)}` });
808
- if (created.ok)
809
- return Result.ok(true);
810
- if (created.error.kind === "lock-failed")
811
- return Result.err({ kind: "lock-failed", message: created.error.message });
812
- if (created.error.kind === "lock-held") {
813
- const holder = Trust.try(() => Number(readFileSync2(lock, "utf8").trim()), (cause) => ({ kind: "lock-unreadable", message: errorMessage(cause) }));
814
- if (holder.ok) {
815
- if (Number.isFinite(holder.value) && holder.value > 0 && isProcessAlive(holder.value))
816
- return Result.ok(false);
817
- } else if (holder.error.kind === "lock-unreadable") {}
818
- const removed = Trust.try(() => rmSync(lock, { force: true }), (cause) => ({ kind: "lock-failed", message: `cannot remove stale ${lock}: ${errorMessage(cause)}` }));
819
- if (!removed.ok)
820
- return removed;
876
+ return claimLockAt(this.paths.lock);
877
+ }
878
+ ownerBudget() {
879
+ const configured = this.options.maxOwners ?? Number(process.env.SQLEGO_MAX_OWNERS ?? DEFAULT_MAX_OWNERS);
880
+ return Number.isFinite(configured) && configured >= 0 ? Math.floor(configured) : DEFAULT_MAX_OWNERS;
881
+ }
882
+ spawnLockPath() {
883
+ return path3.join(path3.dirname(this.paths.lock), "spawn.lock");
884
+ }
885
+ async placeFile(deadline) {
886
+ const budget = this.ownerBudget();
887
+ let lastRefusal = null;
888
+ while (Date.now() < deadline) {
889
+ const owners = this.currentOwners();
890
+ if (!owners.ok)
891
+ return owners;
892
+ if (budget === 0 || owners.value.length < budget) {
893
+ if (budget === 0)
894
+ return this.spawnServer();
895
+ const claimed = claimLockAt(this.spawnLockPath());
896
+ if (!claimed.ok)
897
+ return claimed;
898
+ if (claimed.value) {
899
+ this.holdsSpawnLock = true;
900
+ return this.spawnServer();
901
+ }
902
+ await sleep(25);
903
+ continue;
904
+ }
905
+ for (const owner of owners.value) {
906
+ const remaining = deadline - Date.now();
907
+ if (remaining <= 0)
908
+ break;
909
+ const adopted = await oneShot(owner.socket, {
910
+ op: "adopt",
911
+ file: this.paths.file,
912
+ pragmas: this.options.serverPragmas,
913
+ idleTimeoutMs: this.options.idleTimeoutMs ?? 30000
914
+ }, parseAdoptResult, Math.min(ADOPT_TIMEOUT_MS, remaining));
915
+ if (adopted.ok)
916
+ return Result.ok(undefined);
917
+ if (adopted.error.kind === "probe-failed")
918
+ lastRefusal = `owner ${owner.pid}: ${adopted.error.message}`;
821
919
  }
920
+ await sleep(25);
921
+ }
922
+ const why = lastRefusal ? `: ${lastRefusal}` : "";
923
+ return Result.err({ kind: "connect-timeout", message: `no sqlego owner took on ${this.paths.file}${why}` });
924
+ }
925
+ currentOwners() {
926
+ const directory = path3.dirname(this.paths.lock);
927
+ const names = Trust.try(() => readdirSync2(directory), (cause) => ({ kind: "runtime-directory", message: `cannot list sqlego owners in ${directory}: ${errorMessage(cause)}` }));
928
+ if (!names.ok)
929
+ return names;
930
+ const byPid = new Map;
931
+ for (const name of names.value) {
932
+ if (!name.endsWith(".json"))
933
+ continue;
934
+ const text = Trust.try(() => readFileSync2(path3.join(directory, name), "utf8"), () => ({ kind: "invalid", message: "unreadable" }));
935
+ const json = text.ok ? fromJson(text.value) : text;
936
+ const meta = json.ok ? parseServerMeta(json.value) : json;
937
+ if (meta.ok) {
938
+ if (meta.value.serverVersion !== VERSION || !isProcessAlive(meta.value.pid))
939
+ continue;
940
+ const known = byPid.get(meta.value.pid);
941
+ if (known) {
942
+ known.files += 1;
943
+ known.startedAt = Math.min(known.startedAt, meta.value.startedAt);
944
+ } else {
945
+ byPid.set(meta.value.pid, { pid: meta.value.pid, socket: meta.value.socket, files: 1, startedAt: meta.value.startedAt });
946
+ }
947
+ } else if (meta.error.kind === "invalid") {}
948
+ }
949
+ const owners = [...byPid.values()].sort((a, b) => a.files - b.files || a.startedAt - b.startedAt);
950
+ return Result.ok(owners);
951
+ }
952
+ releaseSpawnLock() {
953
+ if (!this.holdsSpawnLock)
954
+ return;
955
+ this.holdsSpawnLock = false;
956
+ const released = Trust.try(() => rmSync(this.spawnLockPath(), { force: true }), (cause) => ({ kind: "lock-failed", message: errorMessage(cause) }));
957
+ if (!released.ok && released.error.kind === "lock-failed")
958
+ this.spawnFailure = `spawn lock not released: ${released.error.message}`;
959
+ }
960
+ async waitForRelease(deadline) {
961
+ while (Date.now() < deadline) {
962
+ const socket = await tryConnect(this.paths.socket);
963
+ if (!socket)
964
+ return;
965
+ socket.destroy();
966
+ await sleep(25);
822
967
  }
823
- return Result.ok(false);
824
968
  }
825
969
  spawnServer() {
826
970
  const [command, ...args] = this.options.serverCommand ?? defaultServerCommand();
@@ -828,6 +972,7 @@ class SqlegoClient {
828
972
  return Trust.try(() => {
829
973
  const child = spawn(command, [...args, "serve", this.paths.file, "--idle-ms", String(this.options.idleTimeoutMs ?? 30000), ...pragmaArgs], {
830
974
  detached: true,
975
+ windowsHide: true,
831
976
  stdio: ["ignore", "ignore", "pipe"],
832
977
  env: { ...process.env, SQLEGO_CLAIMED_BY: String(process.pid) }
833
978
  });
@@ -850,10 +995,13 @@ class SqlegoClient {
850
995
  }
851
996
  onSpawnError(command, error) {
852
997
  this.spawnFailure = `spawn ${command} failed: ${error.message}`;
853
- const released = Trust.try(() => rmSync(this.paths.lock, { force: true }), (cause) => ({ kind: "lock-failed", message: errorMessage(cause) }));
998
+ const released = this.releaseLock();
854
999
  if (!released.ok && released.error.kind === "lock-failed")
855
1000
  this.spawnFailure += `; lock not released: ${released.error.message}`;
856
1001
  }
1002
+ releaseLock() {
1003
+ return Trust.try(() => rmSync(this.paths.lock, { force: true }), (cause) => ({ kind: "lock-failed", message: errorMessage(cause) }));
1004
+ }
857
1005
  attach(socket) {
858
1006
  this.socket = socket;
859
1007
  this.buffer = "";
@@ -936,10 +1084,30 @@ class SqlegoClient {
936
1084
  }
937
1085
  this.pending.clear();
938
1086
  }
939
- async waitForExit(pid, deadline) {
940
- while (Date.now() < deadline && isProcessAlive(pid))
941
- await sleep(25);
1087
+ }
1088
+ function claimLockAt(lock) {
1089
+ for (let attempt = 0;attempt < 2; attempt += 1) {
1090
+ const created = Trust.try(() => {
1091
+ const fd = openSync(lock, "wx");
1092
+ writeSync(fd, String(process.pid));
1093
+ closeSync(fd);
1094
+ }, (cause) => errnoCode(cause) === "EEXIST" ? { kind: "lock-held", message: `${lock} exists` } : { kind: "lock-failed", message: `cannot create ${lock}: ${errorMessage(cause)}` });
1095
+ if (created.ok)
1096
+ return Result.ok(true);
1097
+ if (created.error.kind === "lock-failed")
1098
+ return Result.err({ kind: "lock-failed", message: created.error.message });
1099
+ if (created.error.kind === "lock-held") {
1100
+ const holder = Trust.try(() => Number(readFileSync2(lock, "utf8").trim()), (cause) => ({ kind: "lock-unreadable", message: errorMessage(cause) }));
1101
+ if (holder.ok) {
1102
+ if (Number.isFinite(holder.value) && holder.value > 0 && isProcessAlive(holder.value))
1103
+ return Result.ok(false);
1104
+ } else if (holder.error.kind === "lock-unreadable") {}
1105
+ const removed = Trust.try(() => rmSync(lock, { force: true }), (cause) => ({ kind: "lock-failed", message: `cannot remove stale ${lock}: ${errorMessage(cause)}` }));
1106
+ if (!removed.ok)
1107
+ return removed;
1108
+ }
942
1109
  }
1110
+ return Result.ok(false);
943
1111
  }
944
1112
 
945
1113
  class SqlegoTransaction {
@@ -992,6 +1160,10 @@ function savepointName(name) {
992
1160
  return name;
993
1161
  return unwrap(Result.err({ kind: "bad-request", message: `savepoint name must be an identifier (letters, digits, _), not "${name}"` }));
994
1162
  }
1163
+ function platformBinaryNames(platform = process.platform, arch = process.arch) {
1164
+ const suffix = platform === "win32" ? ".exe" : "";
1165
+ return [`sqlego${suffix}`, `sqlego-${platform}-${arch}${suffix}`];
1166
+ }
995
1167
  function defaultServerCommand() {
996
1168
  const configured = process.env.SQLEGO_BIN;
997
1169
  if (configured && configured.length > 0)
@@ -1015,12 +1187,80 @@ function defaultServerCommand() {
1015
1187
  return [process.execPath];
1016
1188
  }
1017
1189
  if (here !== null) {
1018
- const local = path3.join(here, "..", "bin", "sqlego");
1019
- if (existsSync3(local))
1020
- return [local];
1190
+ for (const name of platformBinaryNames()) {
1191
+ const local = path3.join(here, "..", "bin", name);
1192
+ if (existsSync3(local))
1193
+ return [local];
1194
+ }
1021
1195
  }
1022
1196
  return ["sqlego"];
1023
1197
  }
1198
+ var probeFailed = (message) => Result.err({ kind: "probe-failed", message });
1199
+ function oneShot(socketPath, body, parse, timeoutMs) {
1200
+ return new Promise((resolve) => {
1201
+ const frame = encodeRequestFrame({ id: 1, ...body });
1202
+ if (!frame.ok) {
1203
+ if (frame.error.kind === "bad-request" || frame.error.kind === "encode-failed")
1204
+ resolve(probeFailed(frame.error.message));
1205
+ return;
1206
+ }
1207
+ let buffer = "";
1208
+ let settled = false;
1209
+ const started = Trust.try(() => {
1210
+ const socket = new net.Socket;
1211
+ const finish = (value, reason) => {
1212
+ if (settled)
1213
+ return;
1214
+ settled = true;
1215
+ clearTimeout(timer);
1216
+ socket.destroy();
1217
+ resolve(value === null ? probeFailed(reason) : Result.ok(value));
1218
+ };
1219
+ const timer = setTimeout(() => finish(null, `no ${body.op} reply within ${timeoutMs} ms`), timeoutMs);
1220
+ socket.setEncoding("utf8");
1221
+ socket.once("error", (error) => finish(null, error.message));
1222
+ socket.once("close", () => finish(null, "connection closed before a reply"));
1223
+ socket.on("data", (chunk) => {
1224
+ const { frames, rest } = splitFrames(buffer + chunk);
1225
+ buffer = rest;
1226
+ const line = frames[0];
1227
+ if (line === undefined)
1228
+ return;
1229
+ const reply = parseOneShotReply(line, parse);
1230
+ if (reply.ok)
1231
+ finish(reply.value, "");
1232
+ else if (reply.error.kind === "probe-failed")
1233
+ finish(null, reply.error.message);
1234
+ });
1235
+ socket.connect(socketPath, () => {
1236
+ const written = Trust.try(() => socket.write(frame.value), (cause) => ({ kind: "socket", message: errorMessage(cause) }));
1237
+ if (!written.ok && written.error.kind === "socket")
1238
+ finish(null, written.error.message);
1239
+ });
1240
+ }, (cause) => ({ kind: "connect-failed", message: errorMessage(cause) }));
1241
+ if (!started.ok && started.error.kind === "connect-failed")
1242
+ resolve(probeFailed(started.error.message));
1243
+ });
1244
+ }
1245
+ function parseOneShotReply(line, parse) {
1246
+ const json = fromJson(line);
1247
+ const response = json.ok ? parseResponse(json.value) : json;
1248
+ if (!response.ok) {
1249
+ if (response.error.kind === "invalid")
1250
+ return probeFailed(`malformed reply: ${response.error.message}`);
1251
+ const unhandled = response.error.kind;
1252
+ return unhandled;
1253
+ }
1254
+ if (!response.value.ok)
1255
+ return probeFailed(`${response.value.error.code}: ${response.value.error.message}`);
1256
+ const parsed = parse(response.value.result);
1257
+ if (parsed.ok)
1258
+ return parsed;
1259
+ if (parsed.error.kind === "invalid")
1260
+ return probeFailed(`unexpected reply: ${parsed.error.message}`);
1261
+ const unhandled = parsed.error.kind;
1262
+ return unhandled;
1263
+ }
1024
1264
  function tryConnect(socketPath) {
1025
1265
  return new Promise((resolve) => {
1026
1266
  const started = Trust.try(() => {
@@ -1066,13 +1306,17 @@ function sleep(ms) {
1066
1306
  return new Promise((resolve) => setTimeout(resolve, ms));
1067
1307
  }
1068
1308
  export {
1309
+ DEFAULT_MAX_OWNERS,
1069
1310
  PROTOCOL_VERSION,
1070
1311
  SqlegoClient,
1071
1312
  SqlegoClientError,
1072
1313
  SqlegoTransaction,
1314
+ USES_NAMED_PIPES,
1073
1315
  VERSION,
1074
1316
  canonicalFile,
1075
1317
  defaultServerCommand,
1318
+ isNamedPipe,
1076
1319
  pathsFor,
1320
+ platformBinaryNames,
1077
1321
  runtimeDirectory
1078
1322
  };
package/dist/paths.d.ts CHANGED
@@ -18,10 +18,19 @@ export declare function resolveCanonicalFile(file: string): Result<string, {
18
18
  export type FilePaths = Readonly<{
19
19
  file: string;
20
20
  key: string;
21
+ /** Unix domain socket path, or a `\\.\pipe\` named pipe on Windows (see `isNamedPipe`). */
21
22
  socket: string;
22
23
  lock: string;
23
24
  meta: string;
24
25
  }>;
26
+ /** Windows has no Unix domain sockets; the local transport there is a named pipe. */
27
+ export declare const USES_NAMED_PIPES: boolean;
28
+ /**
29
+ * True for a named-pipe endpoint. A pipe is not a file: it never exists on
30
+ * disk before the server listens, cannot be `rm`ed, and vanishes with the
31
+ * listener — callers skip the socket-file housekeeping for one.
32
+ */
33
+ export declare function isNamedPipe(socket: string): boolean;
25
34
  export declare function resolvePaths(file: string): import("@noego/trust").Err<{
26
35
  kind: "runtime-directory";
27
36
  message: string;
@@ -37,6 +46,7 @@ export declare function resolvePaths(file: string): import("@noego/trust").Err<{
37
46
  }> | import("@noego/trust").Ok<Readonly<{
38
47
  file: string;
39
48
  key: string;
49
+ /** Unix domain socket path, or a `\\.\pipe\` named pipe on Windows (see `isNamedPipe`). */
40
50
  socket: string;
41
51
  lock: string;
42
52
  meta: string;
@@ -101,6 +101,18 @@ export type Request = {
101
101
  } | {
102
102
  id: number;
103
103
  op: 'stop';
104
+ }
105
+ /**
106
+ * Asks this owner process to serve one more file: open it with `pragmas`
107
+ * (its defaults when absent), listen on that file's own socket, release
108
+ * that file's claim lock. The reply names the socket to connect to.
109
+ */
110
+ | {
111
+ id: number;
112
+ op: 'adopt';
113
+ file: string;
114
+ pragmas?: readonly string[];
115
+ idleTimeoutMs?: number;
104
116
  };
105
117
  export type RunResult = Readonly<{
106
118
  changes: number;
@@ -150,6 +162,12 @@ export type BeginResult = Readonly<{
150
162
  export type TransactionEndResult = Readonly<{
151
163
  txId: number;
152
164
  }>;
165
+ /** One `adopt`: the file (canonical) now served by `pid`, and the socket a client connects to for it. */
166
+ export type AdoptResult = Readonly<{
167
+ file: string;
168
+ socket: string;
169
+ pid: number;
170
+ }>;
153
171
  /** The open transaction as `status` reports it. */
154
172
  export type TransactionStatus = Readonly<{
155
173
  txId: number;
@@ -167,6 +185,8 @@ export type HelloResult = Readonly<{
167
185
  protocol: number;
168
186
  file: string;
169
187
  pid: number;
188
+ /** The pragmas the owner applied on open (its defaults, or its `--pragma` list). */
189
+ pragmas: readonly string[];
170
190
  }>;
171
191
  export type StatusResult = Readonly<{
172
192
  file: string;
@@ -174,6 +194,9 @@ export type StatusResult = Readonly<{
174
194
  pid: number;
175
195
  serverVersion: string;
176
196
  protocol: number;
197
+ pragmas: readonly string[];
198
+ /** Files this owner process serves, this one included. */
199
+ files: number;
177
200
  clients: number;
178
201
  uptimeMs: number;
179
202
  idleMs: number | null;
@@ -189,7 +212,9 @@ export type ErrorCode = 'sqlite' | 'bad-request' | 'protocol-mismatch' | 'shutti
189
212
  /** No such open transaction on this connection (wrong id, already ended, or a second `begin`). */
190
213
  | 'tx-invalid'
191
214
  /** Another client's transaction kept the request waiting past the server's queue limit. */
192
- | 'tx-busy';
215
+ | 'tx-busy'
216
+ /** The owner could not take on the file an `adopt` named (cannot open it, cannot listen for it). */
217
+ | 'adopt-failed';
193
218
  export type Response = {
194
219
  id: number;
195
220
  ok: true;
@@ -348,6 +373,8 @@ export declare function parseHelloResult(input: unknown): import("@noego/trust")
348
373
  protocol: number;
349
374
  file: string;
350
375
  pid: number;
376
+ /** The pragmas the owner applied on open (its defaults, or its `--pragma` list). */
377
+ pragmas: readonly string[];
351
378
  }>>;
352
379
  export declare function parseBeginResult(input: unknown): import("@noego/trust").Err<Readonly<{
353
380
  kind: "invalid";
@@ -363,6 +390,14 @@ export declare function parseTransactionEndResult(input: unknown): import("@noeg
363
390
  }>> | import("@noego/trust").Ok<Readonly<{
364
391
  txId: number;
365
392
  }>>;
393
+ export declare function parseAdoptResult(input: unknown): import("@noego/trust").Err<Readonly<{
394
+ kind: "invalid";
395
+ message: string;
396
+ }>> | import("@noego/trust").Ok<Readonly<{
397
+ file: string;
398
+ socket: string;
399
+ pid: number;
400
+ }>>;
366
401
  export declare function parseStatusResult(input: unknown): import("@noego/trust").Err<Readonly<{
367
402
  kind: "invalid";
368
403
  message: string;
@@ -372,6 +407,9 @@ export declare function parseStatusResult(input: unknown): import("@noego/trust"
372
407
  pid: number;
373
408
  serverVersion: string;
374
409
  protocol: number;
410
+ pragmas: readonly string[];
411
+ /** Files this owner process serves, this one included. */
412
+ files: number;
375
413
  clients: number;
376
414
  uptimeMs: number;
377
415
  idleMs: number | null;
@@ -405,6 +443,13 @@ export declare function parseStopResult(input: unknown): import("@noego/trust").
405
443
  export declare function errnoCode(cause: unknown): unknown;
406
444
  /** The message of a caught value, whatever was thrown. */
407
445
  export declare function errorMessage(cause: unknown): string;
446
+ /**
447
+ * One form of a pragma for comparing a running owner's pragmas with a
448
+ * client's: case and spacing differences are not a different configuration.
449
+ */
450
+ export declare function normalizePragma(pragma: string): string;
451
+ /** Whether two pragma lists configure an owner the same way (order matters: pragmas apply in order). */
452
+ export declare function samePragmas(a: readonly string[], b: readonly string[]): boolean;
408
453
  /**
409
454
  * Splits accumulated socket bytes into complete frames; returns the frames
410
455
  * and the unterminated remainder to carry into the next chunk.