@noego/sqlego 0.1.5 → 0.1.6-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/README.md CHANGED
@@ -20,6 +20,7 @@ owner. WAL files also have a readonly connection for opted-in plain reads.
20
20
  | `bin/sqlego.cjs` | Node | The `sqlego` command npm installs: runs the binary for this platform (npm shims cannot launch a native `.exe` on Windows) |
21
21
  | `@noego/sqlego` (`src/client.ts`) | Node or Bun; `node:net` only | Protocol-only client — no SQLite dependency, no native addon, no binary |
22
22
  | `src/server.ts` | Bun (`bun:sqlite`) | The owner: per file one writer, a readonly connection for WAL files, and one socket; many files per process; idle release |
23
+ | `src/reader_pool.ts`, `src/reader_worker.ts` | Bun (`Worker`, `bun:sqlite`) | The owner's reader workers: a bounded pool of threads, each with its own readonly connection per WAL file, where opted-in plain reads run off the owner thread |
23
24
 
24
25
  Platforms: macOS (arm64, x64), Linux (x64, arm64, glibc), Windows x64. The
25
26
  Windows build is cross-compiled and exercised only as a build; it has not been
@@ -125,10 +126,11 @@ with no owner is adopted by the running owner (of the client's build, under
125
126
  the same runtime directory) that serves the fewest files; a new process is
126
127
  spawned only while fewer than `maxOwners` exist (`SQLEGO_MAX_OWNERS` or the
127
128
  `maxOwners` client option). Default `4`: files are spread over up to four
128
- processes — SQL for files sharing a process runs on one thread, so a long
129
- statement on one file delays only the files that share its process, while an
130
- app holding tens of databases open still costs a handful of processes, not
131
- tens. `1` puts every file in one process; `0` means one process per file, as
129
+ processes — writes and legacy reads for files sharing a process run on one
130
+ thread, so a long write on one file delays only the files that share its
131
+ process, while an app holding tens of databases open still costs a handful
132
+ of processes, not tens. Opted-in plain reads leave that thread altogether
133
+ (see [Reader workers](#reader-workers)). `1` puts every file in one process; `0` means one process per file, as
132
134
  before owners could adopt. The limit counts every owner of the client's
133
135
  build under the runtime directory, whichever app started it. Nothing is ever
134
136
  refused for lack of a process.
@@ -254,6 +256,48 @@ For an opted-in socket:
254
256
  Both connections close when the file is stopped; adopted WAL files get the
255
257
  same reader automatically.
256
258
 
259
+ ### Reader workers
260
+
261
+ The readonly connection above buys isolation from the writer's transaction,
262
+ not parallelism: SQL in the owner is synchronous, and before 0.1.6 a slow
263
+ plain read ran on the owner thread and stalled the writer and every other
264
+ file sharing the process for its duration. Now an owner process keeps a
265
+ bounded pool of reader workers — threads, each holding its own readonly
266
+ connection (same `busy_timeout`, `query_only = ON`) to every WAL file it
267
+ has read — and an opted-in plain read runs on one of them:
268
+
269
+ - `SQLEGO_READERS` (or `serve --readers N`) is the number of workers,
270
+ default `2`; `0` disables the pool and keeps such reads on the owner
271
+ thread's readonly connection, as before. `SQLEGO_READER_QUEUE` (or
272
+ `--reader-queue N`, default `256`) bounds the reads waiting for a worker;
273
+ a read arriving at a full queue runs on the owner thread at once rather
274
+ than being refused. Both are per owner process, whichever files it serves;
275
+ the client's environment reaches the owner it spawns.
276
+ - WAL owners with the pool enabled advertise `capabilities:
277
+ ['detached-plain', 'reader-pool']`. Nothing changes for the client: the
278
+ opt-in, the SQL that qualifies, the reply shapes, `SQLITE_READONLY`
279
+ fallback to the writer, and the committed-snapshot semantics are those of
280
+ the section above. Transaction-scoped requests (`txId`) still run on the
281
+ writer and see their own uncommitted writes.
282
+ - Replies are correlated by `id`, never by order: a detached read answered
283
+ from a worker may arrive after a later writer-path request from the same
284
+ socket. `await`ing each request (every client API does) keeps the program
285
+ order; only pipelined requests that were never awaited can observe this.
286
+ - A worker that fails (an error event, a thread that exits) fails only the
287
+ read it was running, and that read is run again on the owner thread; the
288
+ next read starts a fresh worker. Workers never keep an idle owner alive.
289
+ - When a file stops, the owner asks every worker to close it and waits up to
290
+ 250 ms for them — a worker deep in a long read answers late — so the
291
+ writer's close is the file's last and checkpoints the WAL as before; past
292
+ the wait the next opener checkpoints instead.
293
+ - `status` reports `readers` (`size`, `queueLimit`, `workers`, `busy`,
294
+ `queued`, `served`, `refused`, `failed`, `restarts`, `queueMsMax`,
295
+ `execMsMax`; `null` for a non-WAL file) and, per file, `detachedReads:
296
+ { pooled, inline }`. A verbose owner (`serve --verbose`) logs every
297
+ detached read that took 250 ms or more with its queue, execution and
298
+ round-trip times, so a saturated pool shows as queue time and a slow
299
+ statement as execution time.
300
+
257
301
  ## CLI
258
302
 
259
303
  ```
@@ -262,7 +306,7 @@ sqlego <file> "DELETE …"
262
306
  sqlego <file> status | stop
263
307
  sqlego <file> watch "SELECT count(*) FROM logs" --every 2s
264
308
  sqlego ls
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>"]...
309
+ sqlego serve <file> [--idle-ms 30000] [--file-check-ms 5000] [--tx-lease-ms 10000] [--tx-max-ms 60000] [--tx-queue-ms 30000] [--readers 2] [--reader-queue 256] [--pragma "<name = value>"]...
266
310
  ```
267
311
 
268
312
  ## Library
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
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
- 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';
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 ReaderPoolStatus, type HelloResult, type TransactionMode, type TransactionStatus, } from './protocol.ts';
5
5
  export { VERSION } from './version.ts';
package/dist/index.js CHANGED
@@ -522,6 +522,12 @@ function parseStatusResult(input) {
522
522
  const files = f.files === undefined ? 1 : f.files;
523
523
  if (typeof files !== "number")
524
524
  return invalid("status.files must be a number");
525
+ const readers = parseReaderPoolStatus(f.readers);
526
+ if (!readers.ok)
527
+ return readers;
528
+ const detachedReads = parseDetachedReads(f.detachedReads);
529
+ if (!detachedReads.ok)
530
+ return detachedReads;
525
531
  const result = {
526
532
  file: f.file,
527
533
  socket: f.socket,
@@ -536,10 +542,38 @@ function parseStatusResult(input) {
536
542
  idleTimeoutMs: f.idleTimeoutMs,
537
543
  requestsServed: f.requestsServed,
538
544
  transaction: transaction.value,
539
- capabilities: capabilities.value
545
+ capabilities: capabilities.value,
546
+ ...readers.value === undefined ? {} : { readers: readers.value },
547
+ ...detachedReads.value === undefined ? {} : { detachedReads: detachedReads.value }
540
548
  };
541
549
  return Result.ok(result);
542
550
  }
551
+ var READER_POOL_COUNTERS = ["size", "queueLimit", "workers", "busy", "queued", "served", "refused", "failed", "restarts", "queueMsMax", "execMsMax"];
552
+ function parseReaderPoolStatus(input) {
553
+ if (input === undefined)
554
+ return Result.ok(undefined);
555
+ if (input === null)
556
+ return Result.ok(null);
557
+ const f = fieldsOf(input);
558
+ if (!f)
559
+ return invalid("status.readers must be null or an object");
560
+ const counters = {};
561
+ for (const name of READER_POOL_COUNTERS) {
562
+ const value = f[name];
563
+ if (typeof value !== "number")
564
+ return invalid(`status.readers.${name} must be a number`);
565
+ counters[name] = value;
566
+ }
567
+ return Result.ok(counters);
568
+ }
569
+ function parseDetachedReads(input) {
570
+ if (input === undefined)
571
+ return Result.ok(undefined);
572
+ const f = fieldsOf(input);
573
+ if (!f || typeof f.pooled !== "number" || typeof f.inline !== "number")
574
+ return invalid("status.detachedReads must carry pooled and inline counts");
575
+ return Result.ok({ pooled: f.pooled, inline: f.inline });
576
+ }
543
577
  var SQL_SPACE = new Set([" ", "\t", `
544
578
  `, "\f", "\r", "\uFEFF"]);
545
579
  function parseStopResult(input) {
@@ -727,7 +761,7 @@ import { fileURLToPath } from "node:url";
727
761
  // package.json
728
762
  var package_default = {
729
763
  name: "@noego/sqlego",
730
- version: "0.1.5",
764
+ version: "0.1.6-dev.1",
731
765
  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.",
732
766
  type: "module",
733
767
  license: "ISC",
@@ -758,7 +792,7 @@ var package_default = {
758
792
  "README.md"
759
793
  ],
760
794
  scripts: {
761
- prepare: "bun scripts/build.ts all",
795
+ prepare: "bun scripts/build.ts lib",
762
796
  build: "bun scripts/build.ts all",
763
797
  "build:all": "bun scripts/build.ts all:platforms",
764
798
  "build:lib": "bun scripts/build.ts lib",
@@ -778,11 +812,11 @@ var package_default = {
778
812
  "@noego/trust": "^0.5.1"
779
813
  },
780
814
  optionalDependencies: {
781
- "@noego/sqlego-darwin-arm64": "0.1.5",
782
- "@noego/sqlego-darwin-x64": "0.1.5",
783
- "@noego/sqlego-linux-x64": "0.1.5",
784
- "@noego/sqlego-linux-arm64": "0.1.5",
785
- "@noego/sqlego-win32-x64": "0.1.5"
815
+ "@noego/sqlego-darwin-arm64": "0.1.6-dev.1",
816
+ "@noego/sqlego-darwin-x64": "0.1.6-dev.1",
817
+ "@noego/sqlego-linux-x64": "0.1.6-dev.1",
818
+ "@noego/sqlego-linux-arm64": "0.1.6-dev.1",
819
+ "@noego/sqlego-win32-x64": "0.1.6-dev.1"
786
820
  }
787
821
  };
788
822
 
@@ -800,8 +834,8 @@ function sourceBuildId(sourceDirectory) {
800
834
  }, (cause) => ({ kind: "source-unreadable", message: `cannot hash sources in ${sourceDirectory}: ${errorMessage(cause)}` }));
801
835
  }
802
836
  function resolveBuildId() {
803
- if ("ff247411ec41".length > 0)
804
- return "ff247411ec41";
837
+ if ("51daed1bd424".length > 0)
838
+ return "51daed1bd424";
805
839
  const directory = Trust.try(() => path3.dirname(fileURLToPath(import.meta.url)), (cause) => ({ kind: "module-path", message: errorMessage(cause) }));
806
840
  if (!directory.ok)
807
841
  return decideUnknownBuild(directory.error.kind);
@@ -206,6 +206,32 @@ export type StatusResult = Readonly<{
206
206
  idleTimeoutMs: number;
207
207
  requestsServed: number;
208
208
  transaction: TransactionStatus | null;
209
+ /**
210
+ * The owner process's reader-worker pool, as `status` found it: null for a
211
+ * non-WAL file (no reader), absent from an owner from before the pool.
212
+ */
213
+ readers?: ReaderPoolStatus | null;
214
+ /** Opted-in plain reads of this file so far: on a worker, or on the owner thread's reader. Absent from an older owner. */
215
+ detachedReads?: Readonly<{
216
+ pooled: number;
217
+ inline: number;
218
+ }>;
219
+ }>;
220
+ /** The reader-worker pool of an owner process (see `reader_pool.ts`); counters are per process. */
221
+ export type ReaderPoolStatus = Readonly<{
222
+ /** Workers at most; 0 means the pool is disabled. */
223
+ size: number;
224
+ /** Reads waiting for a worker at most; past it the owner reads in-thread. */
225
+ queueLimit: number;
226
+ workers: number;
227
+ busy: number;
228
+ queued: number;
229
+ served: number;
230
+ refused: number;
231
+ failed: number;
232
+ restarts: number;
233
+ queueMsMax: number;
234
+ execMsMax: number;
209
235
  }>;
210
236
  export type ErrorCode = 'sqlite' | 'bad-request' | 'protocol-mismatch' | 'shutting-down'
211
237
  /** The server could not serialize a result (a value JSON cannot hold). */
@@ -428,6 +454,16 @@ export declare function parseStatusResult(input: unknown): import("@noego/trust"
428
454
  idleTimeoutMs: number;
429
455
  requestsServed: number;
430
456
  transaction: TransactionStatus | null;
457
+ /**
458
+ * The owner process's reader-worker pool, as `status` found it: null for a
459
+ * non-WAL file (no reader), absent from an owner from before the pool.
460
+ */
461
+ readers?: ReaderPoolStatus | null;
462
+ /** Opted-in plain reads of this file so far: on a worker, or on the owner thread's reader. Absent from an older owner. */
463
+ detachedReads?: Readonly<{
464
+ pooled: number;
465
+ inline: number;
466
+ }>;
431
467
  }>>;
432
468
  /**
433
469
  * The transaction-control statement a SQL text starts with, or null. Leading
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noego/sqlego",
3
- "version": "0.1.5",
3
+ "version": "0.1.6-dev.1",
4
4
  "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.",
5
5
  "type": "module",
6
6
  "license": "ISC",
@@ -31,7 +31,7 @@
31
31
  "README.md"
32
32
  ],
33
33
  "scripts": {
34
- "prepare": "bun scripts/build.ts all",
34
+ "prepare": "bun scripts/build.ts lib",
35
35
  "build": "bun scripts/build.ts all",
36
36
  "build:all": "bun scripts/build.ts all:platforms",
37
37
  "build:lib": "bun scripts/build.ts lib",
@@ -51,10 +51,10 @@
51
51
  "@noego/trust": "^0.5.1"
52
52
  },
53
53
  "optionalDependencies": {
54
- "@noego/sqlego-darwin-arm64": "0.1.5",
55
- "@noego/sqlego-darwin-x64": "0.1.5",
56
- "@noego/sqlego-linux-x64": "0.1.5",
57
- "@noego/sqlego-linux-arm64": "0.1.5",
58
- "@noego/sqlego-win32-x64": "0.1.5"
54
+ "@noego/sqlego-darwin-arm64": "0.1.6-dev.1",
55
+ "@noego/sqlego-darwin-x64": "0.1.6-dev.1",
56
+ "@noego/sqlego-linux-x64": "0.1.6-dev.1",
57
+ "@noego/sqlego-linux-arm64": "0.1.6-dev.1",
58
+ "@noego/sqlego-win32-x64": "0.1.6-dev.1"
59
59
  }
60
60
  }
package/src/cli.ts CHANGED
@@ -63,7 +63,7 @@ function usage(): Outcome {
63
63
  sqlego <file> status | stop
64
64
  sqlego <file> watch "<sql>" [--every 1s]
65
65
  sqlego ls
66
- 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>"]...
66
+ sqlego serve <file> [--idle-ms 30000] [--file-check-ms 5000] [--tx-lease-ms 10000] [--tx-max-ms 60000] [--tx-queue-ms 30000] [--readers 2] [--reader-queue 256] [--pragma "<name = value>"]...
67
67
  `);
68
68
  return exit(2);
69
69
  }
@@ -127,6 +127,15 @@ async function serve(file: string, flags: Flags, pragmas: readonly string[]) {
127
127
  const { SqlegoServer, DEFAULT_PRAGMAS, stopAll } = loaded.value;
128
128
  const idleTimeoutMs = flags['idle-ms'] ? Number(flags['idle-ms']) : 30_000;
129
129
  const millis = (flag: string) => (typeof flags[flag] === 'string' ? Number(flags[flag]) : undefined);
130
+ const log = flags.verbose ? (message: string, fields?: Record<string, unknown>) => err(`[sqlego] ${message} ${displayJson(fields ?? {})}\n`) : undefined;
131
+ // The pool is per process; flags set it for every file this process serves
132
+ // (adopted ones inherit these options). Without them, `SQLEGO_READERS` /
133
+ // `SQLEGO_READER_QUEUE` size the shared pool.
134
+ const readers = millis('readers');
135
+ const readerQueue = millis('reader-queue');
136
+ const readerPool = readers === undefined && readerQueue === undefined
137
+ ? undefined
138
+ : new loaded.value.ReaderPool({ size: readers ?? loaded.value.DEFAULT_READERS, queueLimit: readerQueue ?? loaded.value.DEFAULT_READER_QUEUE_LIMIT, log });
130
139
  // The first file of this owner process; clients add more through `adopt`.
131
140
  const started = SqlegoServer.start({
132
141
  file,
@@ -137,7 +146,8 @@ async function serve(file: string, flags: Flags, pragmas: readonly string[]) {
137
146
  txQueueTimeoutMs: millis('tx-queue-ms'),
138
147
  // Every file this process adopts later checks its path at the same pace.
139
148
  fileCheckMs: millis('file-check-ms'),
140
- log: flags.verbose ? (message, fields) => err(`[sqlego] ${message} ${displayJson(fields ?? {})}\n`) : undefined,
149
+ readerPool,
150
+ log,
141
151
  });
142
152
  if (!started.ok) return started;
143
153
  const shutdown = (signal: string) => { stopAll(signal); process.exit(0); };
package/src/index.ts CHANGED
@@ -19,6 +19,7 @@ export {
19
19
  type ExecResult,
20
20
  type BeginResult,
21
21
  type StatusResult,
22
+ type ReaderPoolStatus,
22
23
  type HelloResult,
23
24
  type TransactionMode,
24
25
  type TransactionStatus,
package/src/protocol.ts CHANGED
@@ -137,6 +137,30 @@ export type StatusResult = Readonly<{
137
137
  idleTimeoutMs: number;
138
138
  requestsServed: number;
139
139
  transaction: TransactionStatus | null;
140
+ /**
141
+ * The owner process's reader-worker pool, as `status` found it: null for a
142
+ * non-WAL file (no reader), absent from an owner from before the pool.
143
+ */
144
+ readers?: ReaderPoolStatus | null;
145
+ /** Opted-in plain reads of this file so far: on a worker, or on the owner thread's reader. Absent from an older owner. */
146
+ detachedReads?: Readonly<{ pooled: number; inline: number }>;
147
+ }>;
148
+
149
+ /** The reader-worker pool of an owner process (see `reader_pool.ts`); counters are per process. */
150
+ export type ReaderPoolStatus = Readonly<{
151
+ /** Workers at most; 0 means the pool is disabled. */
152
+ size: number;
153
+ /** Reads waiting for a worker at most; past it the owner reads in-thread. */
154
+ queueLimit: number;
155
+ workers: number;
156
+ busy: number;
157
+ queued: number;
158
+ served: number;
159
+ refused: number;
160
+ failed: number;
161
+ restarts: number;
162
+ queueMsMax: number;
163
+ execMsMax: number;
140
164
  }>;
141
165
 
142
166
  export type ErrorCode =
@@ -868,15 +892,47 @@ export function parseStatusResult(input: unknown) {
868
892
  // An owner from before multi-file owners served exactly one file.
869
893
  const files = f.files === undefined ? 1 : f.files;
870
894
  if (typeof files !== 'number') return invalid('status.files must be a number');
895
+ const readers = parseReaderPoolStatus(f.readers);
896
+ if (!readers.ok) return readers;
897
+ const detachedReads = parseDetachedReads(f.detachedReads);
898
+ if (!detachedReads.ok) return detachedReads;
871
899
  const result: StatusResult = {
872
900
  file: f.file, socket: f.socket, pid: f.pid, serverVersion: f.serverVersion, protocol: f.protocol, pragmas: pragmas.value, files,
873
901
  clients: f.clients, uptimeMs: f.uptimeMs, idleMs: f.idleMs, idleTimeoutMs: f.idleTimeoutMs, requestsServed: f.requestsServed,
874
902
  transaction: transaction.value,
875
903
  capabilities: capabilities.value,
904
+ ...(readers.value === undefined ? {} : { readers: readers.value }),
905
+ ...(detachedReads.value === undefined ? {} : { detachedReads: detachedReads.value }),
876
906
  };
877
907
  return Result.ok(result);
878
908
  }
879
909
 
910
+ const READER_POOL_COUNTERS = ['size', 'queueLimit', 'workers', 'busy', 'queued', 'served', 'refused', 'failed', 'restarts', 'queueMsMax', 'execMsMax'] as const;
911
+
912
+ /** `status.readers`: absent (older owner), null (no reader), or every counter a number. */
913
+ //trust:validator_function
914
+ function parseReaderPoolStatus(input: unknown) {
915
+ if (input === undefined) return Result.ok<ReaderPoolStatus | null | undefined>(undefined);
916
+ if (input === null) return Result.ok<ReaderPoolStatus | null | undefined>(null);
917
+ const f = fieldsOf(input);
918
+ if (!f) return invalid('status.readers must be null or an object');
919
+ const counters: Partial<Record<(typeof READER_POOL_COUNTERS)[number], number>> = {};
920
+ for (const name of READER_POOL_COUNTERS) {
921
+ const value = f[name];
922
+ if (typeof value !== 'number') return invalid(`status.readers.${name} must be a number`);
923
+ counters[name] = value;
924
+ }
925
+ return Result.ok<ReaderPoolStatus | null | undefined>(counters as ReaderPoolStatus);
926
+ }
927
+
928
+ //trust:validator_function
929
+ function parseDetachedReads(input: unknown) {
930
+ if (input === undefined) return Result.ok<StatusResult['detachedReads']>(undefined);
931
+ const f = fieldsOf(input);
932
+ if (!f || typeof f.pooled !== 'number' || typeof f.inline !== 'number') return invalid('status.detachedReads must carry pooled and inline counts');
933
+ return Result.ok<StatusResult['detachedReads']>({ pooled: f.pooled, inline: f.inline });
934
+ }
935
+
880
936
  /**
881
937
  * The transaction-control statement a SQL text starts with, or null. Leading
882
938
  * whitespace and comments are skipped so `/* x *\/ BEGIN` is still seen.