@noego/sqlego 0.1.4 → 0.1.6-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/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/client.d.ts CHANGED
@@ -81,6 +81,9 @@ export declare class SqlegoClient {
81
81
  private socket;
82
82
  /** Reply frames from `socket`; the socket decodes UTF-8 itself (`setEncoding`), split characters included. */
83
83
  private readonly frames;
84
+ /** Request frames queued in this microtask turn, joined and written once before the turn ends. */
85
+ private readonly outbound;
86
+ private flushScheduled;
84
87
  private nextId;
85
88
  private readonly pending;
86
89
  private hello;
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
@@ -98,7 +98,8 @@ var SAFE_MIN = -9007199254740991n;
98
98
  var DECIMAL_INTEGER = /^(?:0|-?[1-9][0-9]{0,18})$/;
99
99
  var BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
100
100
  function toJson(value, indent) {
101
- const encoded = Trust.try(() => JSON.stringify(value, replaceBigInt, indent), (cause) => ({ kind: "encode-failed", message: errorMessage(cause) }));
101
+ const fast = Trust.try(() => indent === undefined ? JSON.stringify(value) : JSON.stringify(value, undefined, indent), (cause) => ({ kind: "encode-failed", message: errorMessage(cause) }));
102
+ const encoded = fast.ok ? fast : Trust.try(() => JSON.stringify(value, replaceBigInt, indent), (cause) => ({ kind: "encode-failed", message: errorMessage(cause) }));
102
103
  if (!encoded.ok)
103
104
  return encoded;
104
105
  if (typeof encoded.value !== "string")
@@ -125,21 +126,30 @@ function encodeRequestParams(request) {
125
126
  const params = encodeSqlParams(request.params);
126
127
  if (!params.ok)
127
128
  return params;
129
+ if (params.value === request.params)
130
+ return Result.ok(request);
128
131
  return Result.ok({ ...request, params: params.value });
129
132
  }
130
133
  case "batch": {
131
- const statements = [];
132
- for (const [index, statement] of request.statements.entries()) {
134
+ let changed = false;
135
+ const statements = new Array(request.statements.length);
136
+ for (let index = 0;index < request.statements.length; index += 1) {
137
+ const statement = request.statements[index];
133
138
  if (statement.params === undefined) {
134
- statements.push(statement);
139
+ statements[index] = statement;
135
140
  continue;
136
141
  }
137
142
  const params = encodeSqlParams(statement.params);
138
143
  if (!params.ok)
139
144
  return invalid(`statements[${index}].${params.error.message}`);
140
- statements.push({ ...statement, params: params.value });
145
+ if (params.value === statement.params) {
146
+ statements[index] = statement;
147
+ } else {
148
+ changed = true;
149
+ statements[index] = { ...statement, params: params.value };
150
+ }
141
151
  }
142
- return Result.ok({ ...request, statements });
152
+ return Result.ok(changed ? { ...request, statements } : request);
143
153
  }
144
154
  default:
145
155
  return Result.ok(request);
@@ -150,23 +160,51 @@ function encodeSqlParams(params) {
150
160
  return invalid("params must be an array or an object");
151
161
  const shape = paramsShape(params);
152
162
  if (shape.kind === "positional") {
153
- const values = [];
154
- for (const [index, item] of shape.values.entries()) {
163
+ const items = shape.values;
164
+ let values = null;
165
+ for (let index = 0;index < items.length; index += 1) {
166
+ const item = items[index];
167
+ if (item === null || typeof item === "string" || typeof item === "boolean" || typeof item === "number" && Number.isFinite(item)) {
168
+ if (values !== null)
169
+ values[index] = item;
170
+ continue;
171
+ }
155
172
  const value = encodeParamValue(item);
156
173
  if (!value.ok)
157
174
  return invalid(`params[${index}]: ${value.error.message}`);
158
- values.push(value.value);
175
+ if (values === null) {
176
+ values = new Array(items.length);
177
+ for (let prev = 0;prev < index; prev += 1)
178
+ values[prev] = items[prev];
179
+ }
180
+ values[index] = value.value;
159
181
  }
160
- return Result.ok(values);
182
+ return Result.ok(values ?? items);
161
183
  }
162
- const entries = [];
163
- for (const [name, item] of Object.entries(shape.values)) {
184
+ const fields = shape.values;
185
+ const keys = Object.keys(fields);
186
+ let entries = null;
187
+ for (let index = 0;index < keys.length; index += 1) {
188
+ const name = keys[index];
189
+ const item = fields[name];
190
+ if (item === null || typeof item === "string" || typeof item === "boolean" || typeof item === "number" && Number.isFinite(item)) {
191
+ if (entries !== null)
192
+ entries.push([name, item]);
193
+ continue;
194
+ }
164
195
  const value = encodeParamValue(item);
165
196
  if (!value.ok)
166
197
  return invalid(`params.${name}: ${value.error.message}`);
198
+ if (entries === null) {
199
+ entries = [];
200
+ for (let prev = 0;prev < index; prev += 1) {
201
+ const prevKey = keys[prev];
202
+ entries.push([prevKey, fields[prevKey]]);
203
+ }
204
+ }
167
205
  entries.push([name, value.value]);
168
206
  }
169
- return Result.ok(Object.fromEntries(entries));
207
+ return Result.ok(entries === null ? fields : Object.fromEntries(entries));
170
208
  }
171
209
  function paramsShape(params) {
172
210
  return Array.isArray(params) ? { kind: "positional", values: params } : { kind: "named", values: params };
@@ -230,17 +268,25 @@ function parseWireBigInt(input) {
230
268
  return Result.ok(parsed.value);
231
269
  }
232
270
  function parseWireBlob(input) {
233
- if (typeof input !== "string" || !BASE64.test(input))
271
+ if (typeof input !== "string" || !BASE64.test(input) || !hasCanonicalBase64Padding(input)) {
234
272
  return invalid("$blob must be canonical padded base64");
235
- const decoded = Trust.try(() => {
236
- const bytes = Buffer.from(input, "base64");
237
- return { bytes: new Uint8Array(bytes), canonical: bytes.toString("base64") };
238
- }, (cause) => ({ kind: "invalid", message: `$blob: ${errorMessage(cause)}` }));
273
+ }
274
+ const decoded = Trust.try(() => new Uint8Array(Buffer.from(input, "base64")), (cause) => ({ kind: "invalid", message: `$blob: ${errorMessage(cause)}` }));
239
275
  if (!decoded.ok)
240
276
  return decoded;
241
- if (decoded.value.canonical !== input)
242
- return invalid("$blob must be canonical padded base64");
243
- return Result.ok(decoded.value.bytes);
277
+ return Result.ok(decoded.value);
278
+ }
279
+ function hasCanonicalBase64Padding(input) {
280
+ const length = input.length;
281
+ if (length === 0 || input.charCodeAt(length - 1) !== 61)
282
+ return true;
283
+ if (input.charCodeAt(length - 2) === 61) {
284
+ const c = input.charCodeAt(length - 3);
285
+ return c === 65 || c === 81 || c === 103 || c === 119;
286
+ }
287
+ const c = input.charCodeAt(length - 2);
288
+ const sextet = c >= 65 && c <= 90 ? c - 65 : c >= 97 && c <= 122 ? c - 97 + 26 : c >= 48 && c <= 57 ? c - 48 + 52 : c === 43 ? 62 : 63;
289
+ return (sextet & 3) === 0;
244
290
  }
245
291
  function parseWireInteger(input, at) {
246
292
  if (typeof input === "number" && Number.isSafeInteger(input))
@@ -291,22 +337,22 @@ function parseResponse(input) {
291
337
  const response = { id, ok: false, error: { code: code.value, message: error.message } };
292
338
  return Result.ok(response);
293
339
  }
294
- function parseRow(input) {
295
- const fields = fieldsOf(input);
296
- if (!fields)
297
- return invalid("a row must be an object");
298
- const row = { ...fields };
299
- return Result.ok(row);
300
- }
301
340
  function parseRows(input) {
302
341
  if (!Array.isArray(input))
303
342
  return invalid("rows must be an array");
304
- const rows = [];
305
- for (const [index, item] of input.entries()) {
306
- const row = parseRow(item);
307
- if (!row.ok)
308
- return invalid(`rows[${index}]: ${row.error.message}`);
309
- rows.push(row.value);
343
+ const rows = new Array(input.length);
344
+ for (let index = 0;index < input.length; index += 1) {
345
+ const item = input[index];
346
+ const fields = fieldsOf(item);
347
+ if (!fields)
348
+ return invalid(`rows[${index}]: a row must be an object`);
349
+ const row = item;
350
+ for (const column in fields) {
351
+ const raw = fields[column];
352
+ if (typeof raw === "bigint")
353
+ row[column] = Number(raw);
354
+ }
355
+ rows[index] = row;
310
356
  }
311
357
  return Result.ok(rows);
312
358
  }
@@ -348,20 +394,23 @@ function parseBatchResult(input) {
348
394
  function parseWireRows(input) {
349
395
  if (!Array.isArray(input))
350
396
  return invalid("rows must be an array");
351
- const rows = [];
352
- for (const [index, item] of input.entries()) {
397
+ const rows = new Array(input.length);
398
+ for (let index = 0;index < input.length; index += 1) {
399
+ const item = input[index];
353
400
  const fields = fieldsOf(item);
354
401
  if (!fields)
355
402
  return invalid(`rows[${index}] must be an object`);
356
- const entries = [];
357
- for (const [column, raw] of Object.entries(fields)) {
403
+ const record = item;
404
+ for (const column in fields) {
405
+ const raw = fields[column];
406
+ if (raw === null || typeof raw === "string" || typeof raw === "boolean" || typeof raw === "number" && Number.isFinite(raw))
407
+ continue;
358
408
  const value = parseSqlValue(raw);
359
409
  if (!value.ok)
360
410
  return invalid(`rows[${index}].${column}: ${value.error.message}`);
361
- entries.push([column, value.value]);
411
+ record[column] = value.value;
362
412
  }
363
- const row = Object.fromEntries(entries);
364
- rows.push(row);
413
+ rows[index] = record;
365
414
  }
366
415
  return Result.ok(rows);
367
416
  }
@@ -473,6 +522,12 @@ function parseStatusResult(input) {
473
522
  const files = f.files === undefined ? 1 : f.files;
474
523
  if (typeof files !== "number")
475
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;
476
531
  const result = {
477
532
  file: f.file,
478
533
  socket: f.socket,
@@ -487,10 +542,38 @@ function parseStatusResult(input) {
487
542
  idleTimeoutMs: f.idleTimeoutMs,
488
543
  requestsServed: f.requestsServed,
489
544
  transaction: transaction.value,
490
- capabilities: capabilities.value
545
+ capabilities: capabilities.value,
546
+ ...readers.value === undefined ? {} : { readers: readers.value },
547
+ ...detachedReads.value === undefined ? {} : { detachedReads: detachedReads.value }
491
548
  };
492
549
  return Result.ok(result);
493
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
+ }
494
577
  var SQL_SPACE = new Set([" ", "\t", `
495
578
  `, "\f", "\r", "\uFEFF"]);
496
579
  function parseStopResult(input) {
@@ -605,8 +688,7 @@ function resolvePaths(file) {
605
688
  return directory;
606
689
  const derived = Trust.try(() => {
607
690
  const key = createHash("sha1").update(canonical.value).digest("hex").slice(0, 16);
608
- const scope = createHash("sha1").update(directory.value.toLowerCase()).digest("hex").slice(0, 8);
609
- const socket = USES_NAMED_PIPES ? `\\\\.\\pipe\\sqlego-${scope}-${key}` : path2.join(directory.value, `${key}.sock`);
691
+ const socket = USES_NAMED_PIPES ? `\\\\.\\pipe\\sqlego-${createHash("sha1").update(directory.value.toLowerCase()).digest("hex").slice(0, 8)}-${key}` : path2.join(directory.value, `${key}.sock`);
610
692
  return { key, socket, socketBytes: Buffer.byteLength(socket) };
611
693
  }, (cause) => ({ kind: "hash-failed", message: `cannot hash ${canonical.value}: ${errorMessage(cause)}` }));
612
694
  if (!derived.ok)
@@ -679,7 +761,7 @@ import { fileURLToPath } from "node:url";
679
761
  // package.json
680
762
  var package_default = {
681
763
  name: "@noego/sqlego",
682
- version: "0.1.4",
764
+ version: "0.1.6-dev.0",
683
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.",
684
766
  type: "module",
685
767
  license: "ISC",
@@ -730,11 +812,11 @@ var package_default = {
730
812
  "@noego/trust": "^0.5.1"
731
813
  },
732
814
  optionalDependencies: {
733
- "@noego/sqlego-darwin-arm64": "0.1.4",
734
- "@noego/sqlego-darwin-x64": "0.1.4",
735
- "@noego/sqlego-linux-x64": "0.1.4",
736
- "@noego/sqlego-linux-arm64": "0.1.4",
737
- "@noego/sqlego-win32-x64": "0.1.4"
815
+ "@noego/sqlego-darwin-arm64": "0.1.6-dev.0",
816
+ "@noego/sqlego-darwin-x64": "0.1.6-dev.0",
817
+ "@noego/sqlego-linux-x64": "0.1.6-dev.0",
818
+ "@noego/sqlego-linux-arm64": "0.1.6-dev.0",
819
+ "@noego/sqlego-win32-x64": "0.1.6-dev.0"
738
820
  }
739
821
  };
740
822
 
@@ -752,8 +834,8 @@ function sourceBuildId(sourceDirectory) {
752
834
  }, (cause) => ({ kind: "source-unreadable", message: `cannot hash sources in ${sourceDirectory}: ${errorMessage(cause)}` }));
753
835
  }
754
836
  function resolveBuildId() {
755
- if ("3f3144144273".length > 0)
756
- return "3f3144144273";
837
+ if ("51daed1bd424".length > 0)
838
+ return "51daed1bd424";
757
839
  const directory = Trust.try(() => path3.dirname(fileURLToPath(import.meta.url)), (cause) => ({ kind: "module-path", message: errorMessage(cause) }));
758
840
  if (!directory.ok)
759
841
  return decideUnknownBuild(directory.error.kind);
@@ -806,6 +888,8 @@ class SqlegoClient {
806
888
  paths;
807
889
  socket = null;
808
890
  frames = new FrameReader;
891
+ outbound = [];
892
+ flushScheduled = false;
809
893
  nextId = 1;
810
894
  pending = new Map;
811
895
  hello = null;
@@ -1037,13 +1121,13 @@ class SqlegoClient {
1037
1121
  return Result.err({ kind: placed.error.kind, message: `${placed.error.message}${suffix}` });
1038
1122
  }
1039
1123
  }
1040
- while (Date.now() < deadline) {
1124
+ for (let delayMs = 2;Date.now() < deadline; delayMs = Math.min(25, delayMs * 2)) {
1041
1125
  const socket = await tryConnect(this.paths.socket);
1042
1126
  if (socket) {
1043
1127
  this.releaseSpawnLock();
1044
1128
  return Result.ok(socket);
1045
1129
  }
1046
- await sleep(25);
1130
+ await sleep(delayMs);
1047
1131
  }
1048
1132
  this.releaseSpawnLock();
1049
1133
  const cause = this.spawnFailure ? ` (${this.spawnFailure})` : "";
@@ -1112,13 +1196,13 @@ class SqlegoClient {
1112
1196
  const json = text.ok ? fromJson(text.value) : text;
1113
1197
  const meta = json.ok ? parseServerMeta(json.value) : json;
1114
1198
  if (meta.ok) {
1115
- if (meta.value.serverVersion !== VERSION || !isProcessAlive(meta.value.pid))
1199
+ if (meta.value.serverVersion !== VERSION)
1116
1200
  continue;
1117
1201
  const known = byPid.get(meta.value.pid);
1118
1202
  if (known) {
1119
1203
  known.files += 1;
1120
1204
  known.startedAt = Math.min(known.startedAt, meta.value.startedAt);
1121
- } else {
1205
+ } else if (isProcessAlive(meta.value.pid)) {
1122
1206
  byPid.set(meta.value.pid, { pid: meta.value.pid, socket: meta.value.socket, files: 1, startedAt: meta.value.startedAt });
1123
1207
  }
1124
1208
  } else if (meta.error.kind === "invalid") {}
@@ -1135,12 +1219,12 @@ class SqlegoClient {
1135
1219
  this.spawnFailure = `spawn lock not released: ${released.error.message}`;
1136
1220
  }
1137
1221
  async waitForRelease(deadline) {
1138
- while (Date.now() < deadline) {
1222
+ for (let delayMs = 2;Date.now() < deadline; delayMs = Math.min(25, delayMs * 2)) {
1139
1223
  const socket = await tryConnect(this.paths.socket);
1140
1224
  if (!socket)
1141
1225
  return;
1142
1226
  socket.destroy();
1143
- await sleep(25);
1227
+ await sleep(delayMs);
1144
1228
  }
1145
1229
  }
1146
1230
  spawnServer() {
@@ -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.4",
3
+ "version": "0.1.6-dev.0",
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",
@@ -51,10 +51,10 @@
51
51
  "@noego/trust": "^0.5.1"
52
52
  },
53
53
  "optionalDependencies": {
54
- "@noego/sqlego-darwin-arm64": "0.1.4",
55
- "@noego/sqlego-darwin-x64": "0.1.4",
56
- "@noego/sqlego-linux-x64": "0.1.4",
57
- "@noego/sqlego-linux-arm64": "0.1.4",
58
- "@noego/sqlego-win32-x64": "0.1.4"
54
+ "@noego/sqlego-darwin-arm64": "0.1.6-dev.0",
55
+ "@noego/sqlego-darwin-x64": "0.1.6-dev.0",
56
+ "@noego/sqlego-linux-x64": "0.1.6-dev.0",
57
+ "@noego/sqlego-linux-arm64": "0.1.6-dev.0",
58
+ "@noego/sqlego-win32-x64": "0.1.6-dev.0"
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/client.ts CHANGED
@@ -194,6 +194,9 @@ export class SqlegoClient {
194
194
  private socket: net.Socket | null = null;
195
195
  /** Reply frames from `socket`; the socket decodes UTF-8 itself (`setEncoding`), split characters included. */
196
196
  private readonly frames = new FrameReader();
197
+ /** Request frames queued in this microtask turn, joined and written once before the turn ends. */
198
+ private readonly outbound: string[] = [];
199
+ private flushScheduled = false;
197
200
  private nextId = 1;
198
201
  private readonly pending = new Map<number, Waiter>();
199
202
  private hello: HelloResult | null = null;
@@ -520,13 +523,13 @@ export class SqlegoClient {
520
523
  }
521
524
  }
522
525
  // Claimer or not, the socket appears when the winner is listening.
523
- while (Date.now() < deadline) {
526
+ for (let delayMs = 2; Date.now() < deadline; delayMs = Math.min(25, delayMs * 2)) {
524
527
  const socket = await tryConnect(this.paths.socket);
525
528
  if (socket) {
526
529
  this.releaseSpawnLock();
527
530
  return Result.ok(socket);
528
531
  }
529
- await sleep(25);
532
+ await sleep(delayMs);
530
533
  }
531
534
  this.releaseSpawnLock();
532
535
  const cause = this.spawnFailure ? ` (${this.spawnFailure})` : '';
@@ -618,12 +621,12 @@ export class SqlegoClient {
618
621
  const json = text.ok ? fromJson(text.value) : text;
619
622
  const meta = json.ok ? parseServerMeta(json.value) : json;
620
623
  if (meta.ok) {
621
- if (meta.value.serverVersion !== VERSION || !isProcessAlive(meta.value.pid)) continue;
624
+ if (meta.value.serverVersion !== VERSION) continue;
622
625
  const known = byPid.get(meta.value.pid);
623
626
  if (known) {
624
627
  known.files += 1;
625
628
  known.startedAt = Math.min(known.startedAt, meta.value.startedAt);
626
- } else {
629
+ } else if (isProcessAlive(meta.value.pid)) {
627
630
  byPid.set(meta.value.pid, { pid: meta.value.pid, socket: meta.value.socket, files: 1, startedAt: meta.value.startedAt });
628
631
  }
629
632
  } else if (meta.error.kind === 'invalid') {
@@ -647,11 +650,11 @@ export class SqlegoClient {
647
650
 
648
651
  /** Waits until nothing answers on the file's socket (the old owner released it, its database closed first), or the deadline. */
649
652
  private async waitForRelease(deadline: number): Promise<void> {
650
- while (Date.now() < deadline) {
653
+ for (let delayMs = 2; Date.now() < deadline; delayMs = Math.min(25, delayMs * 2)) {
651
654
  const socket = await tryConnect(this.paths.socket);
652
655
  if (!socket) return;
653
656
  socket.destroy();
654
- await sleep(25);
657
+ await sleep(delayMs);
655
658
  }
656
659
  }
657
660
 
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/paths.ts CHANGED
@@ -83,8 +83,9 @@ export function resolvePaths(file: string) {
83
83
  // `\\.\pipe\sqlego-<dir hash>-<key>` — the pipe namespace is flat and
84
84
  // shared machine-wide, so the runtime directory (per user, or per test)
85
85
  // is hashed into the name to keep the isolation the directory gives on Unix.
86
- const scope = createHash('sha1').update(directory.value.toLowerCase()).digest('hex').slice(0, 8);
87
- const socket = USES_NAMED_PIPES ? `\\\\.\\pipe\\sqlego-${scope}-${key}` : path.join(directory.value, `${key}.sock`);
86
+ const socket = USES_NAMED_PIPES
87
+ ? `\\\\.\\pipe\\sqlego-${createHash('sha1').update(directory.value.toLowerCase()).digest('hex').slice(0, 8)}-${key}`
88
+ : path.join(directory.value, `${key}.sock`);
88
89
  return { key, socket, socketBytes: Buffer.byteLength(socket) };
89
90
  },
90
91
  (cause) => ({ kind: 'hash-failed', message: `cannot hash ${canonical.value}: ${errorMessage(cause)}` }),