@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/src/protocol.ts CHANGED
@@ -70,7 +70,13 @@ export type Request =
70
70
  | { id: number; op: 'commit'; txId: number }
71
71
  | { id: number; op: 'rollback'; txId: number }
72
72
  | { id: number; op: 'status' }
73
- | { id: number; op: 'stop' };
73
+ | { id: number; op: 'stop' }
74
+ /**
75
+ * Asks this owner process to serve one more file: open it with `pragmas`
76
+ * (its defaults when absent), listen on that file's own socket, release
77
+ * that file's claim lock. The reply names the socket to connect to.
78
+ */
79
+ | { id: number; op: 'adopt'; file: string; pragmas?: readonly string[]; idleTimeoutMs?: number };
74
80
 
75
81
  export type RunResult = Readonly<{ changes: number; lastInsertRowid: number | bigint }>;
76
82
  export type QueryResult = Readonly<{ rows: SqlRow[] }>;
@@ -89,6 +95,8 @@ export type ExecWireResult = Readonly<{ statements: number; changes: number; las
89
95
  /** The lease the server granted (its own cap applies) and the hard cap on the transaction's life. */
90
96
  export type BeginResult = Readonly<{ txId: number; leaseMs: number; maxDurationMs: number }>;
91
97
  export type TransactionEndResult = Readonly<{ txId: number }>;
98
+ /** One `adopt`: the file (canonical) now served by `pid`, and the socket a client connects to for it. */
99
+ export type AdoptResult = Readonly<{ file: string; socket: string; pid: number }>;
92
100
 
93
101
  /** The open transaction as `status` reports it. */
94
102
  export type TransactionStatus = Readonly<{
@@ -108,6 +116,8 @@ export type HelloResult = Readonly<{
108
116
  protocol: number;
109
117
  file: string;
110
118
  pid: number;
119
+ /** The pragmas the owner applied on open (its defaults, or its `--pragma` list). */
120
+ pragmas: readonly string[];
111
121
  }>;
112
122
 
113
123
  export type StatusResult = Readonly<{
@@ -116,6 +126,9 @@ export type StatusResult = Readonly<{
116
126
  pid: number;
117
127
  serverVersion: string;
118
128
  protocol: number;
129
+ pragmas: readonly string[];
130
+ /** Files this owner process serves, this one included. */
131
+ files: number;
119
132
  clients: number;
120
133
  uptimeMs: number;
121
134
  idleMs: number | null;
@@ -136,7 +149,9 @@ export type ErrorCode =
136
149
  /** No such open transaction on this connection (wrong id, already ended, or a second `begin`). */
137
150
  | 'tx-invalid'
138
151
  /** Another client's transaction kept the request waiting past the server's queue limit. */
139
- | 'tx-busy';
152
+ | 'tx-busy'
153
+ /** The owner could not take on the file an `adopt` named (cannot open it, cannot listen for it). */
154
+ | 'adopt-failed';
140
155
 
141
156
  export type Response =
142
157
  | { id: number; ok: true; result: unknown }
@@ -509,13 +524,24 @@ export function parseRequest(input: unknown) {
509
524
  const request: Request = { id, op: fields.op };
510
525
  return Result.ok(request);
511
526
  }
527
+ case 'adopt': {
528
+ if (typeof fields.file !== 'string' || fields.file.length === 0) return reject(id, 'adopt needs file (string)');
529
+ const pragmas = fields.pragmas;
530
+ if (pragmas !== undefined && (!Array.isArray(pragmas) || !pragmas.every((item): item is string => typeof item === 'string'))) {
531
+ return reject(id, 'adopt pragmas must be an array of strings');
532
+ }
533
+ const idleTimeoutMs = fields.idleTimeoutMs;
534
+ if (idleTimeoutMs !== undefined && (typeof idleTimeoutMs !== 'number' || !(idleTimeoutMs > 0))) return reject(id, 'idleTimeoutMs must be a positive number');
535
+ const request: Request = { id, op: 'adopt', file: fields.file, pragmas: pragmas === undefined ? undefined : [...pragmas], idleTimeoutMs };
536
+ return Result.ok(request);
537
+ }
512
538
  default:
513
539
  return reject(id, `unknown op ${String(fields.op)}`);
514
540
  }
515
541
  }
516
542
 
517
543
  const ERROR_CODES: readonly ErrorCode[] = [
518
- 'sqlite', 'bad-request', 'protocol-mismatch', 'shutting-down', 'encode-failed', 'tx-expired', 'tx-invalid', 'tx-busy',
544
+ 'sqlite', 'bad-request', 'protocol-mismatch', 'shutting-down', 'encode-failed', 'tx-expired', 'tx-invalid', 'tx-busy', 'adopt-failed',
519
545
  ];
520
546
 
521
547
  //trust:validator_function
@@ -645,6 +671,20 @@ export function parseExecResult(input: unknown) {
645
671
  return Result.ok(result);
646
672
  }
647
673
 
674
+ /**
675
+ * The owner's pragma list. Absent on the wire (an owner from before the
676
+ * field existed) reads as empty: such an owner is retired by the version
677
+ * check anyway, so the shape of its hello must not fail the handshake first.
678
+ */
679
+ //trust:validator_function
680
+ function parsePragmas(input: unknown) {
681
+ if (input === undefined) return Result.ok<readonly string[]>([]);
682
+ if (!Array.isArray(input) || !input.every((item): item is string => typeof item === 'string')) {
683
+ return invalid('pragmas must be an array of strings');
684
+ }
685
+ return Result.ok<readonly string[]>([...input]);
686
+ }
687
+
648
688
  //trust:validator_function
649
689
  export function parseHelloResult(input: unknown) {
650
690
  const fields = fieldsOf(input);
@@ -655,7 +695,9 @@ export function parseHelloResult(input: unknown) {
655
695
  ) {
656
696
  return invalid('a hello result needs serverVersion, protocol, file and pid');
657
697
  }
658
- const result: HelloResult = { serverVersion: fields.serverVersion, protocol: fields.protocol, file: fields.file, pid: fields.pid };
698
+ const pragmas = parsePragmas(fields.pragmas);
699
+ if (!pragmas.ok) return pragmas;
700
+ const result: HelloResult = { serverVersion: fields.serverVersion, protocol: fields.protocol, file: fields.file, pid: fields.pid, pragmas: pragmas.value };
659
701
  return Result.ok(result);
660
702
  }
661
703
 
@@ -677,6 +719,16 @@ export function parseTransactionEndResult(input: unknown) {
677
719
  return Result.ok(result);
678
720
  }
679
721
 
722
+ //trust:validator_function
723
+ export function parseAdoptResult(input: unknown) {
724
+ const f = fieldsOf(input);
725
+ if (!f || typeof f.file !== 'string' || typeof f.socket !== 'string' || typeof f.pid !== 'number') {
726
+ return invalid('an adopt result needs file, socket (strings) and pid (number)');
727
+ }
728
+ const result: AdoptResult = { file: f.file, socket: f.socket, pid: f.pid };
729
+ return Result.ok(result);
730
+ }
731
+
680
732
  //trust:validator_function
681
733
  function parseTransactionStatus(input: unknown) {
682
734
  if (input === null) return Result.ok<TransactionStatus | null>(null);
@@ -707,8 +759,13 @@ export function parseStatusResult(input: unknown) {
707
759
  }
708
760
  const transaction = parseTransactionStatus(f.transaction);
709
761
  if (!transaction.ok) return transaction;
762
+ const pragmas = parsePragmas(f.pragmas);
763
+ if (!pragmas.ok) return pragmas;
764
+ // An owner from before multi-file owners served exactly one file.
765
+ const files = f.files === undefined ? 1 : f.files;
766
+ if (typeof files !== 'number') return invalid('status.files must be a number');
710
767
  const result: StatusResult = {
711
- file: f.file, socket: f.socket, pid: f.pid, serverVersion: f.serverVersion, protocol: f.protocol,
768
+ file: f.file, socket: f.socket, pid: f.pid, serverVersion: f.serverVersion, protocol: f.protocol, pragmas: pragmas.value, files,
712
769
  clients: f.clients, uptimeMs: f.uptimeMs, idleMs: f.idleMs, idleTimeoutMs: f.idleTimeoutMs, requestsServed: f.requestsServed,
713
770
  transaction: transaction.value,
714
771
  };
@@ -885,6 +942,19 @@ export function errorMessage(cause: unknown): string {
885
942
  return cause instanceof Error ? cause.message : String(cause);
886
943
  }
887
944
 
945
+ /**
946
+ * One form of a pragma for comparing a running owner's pragmas with a
947
+ * client's: case and spacing differences are not a different configuration.
948
+ */
949
+ export function normalizePragma(pragma: string): string {
950
+ return pragma.replace(/\s+/g, ' ').replace(/\s*([=(),])\s*/g, '$1').trim().toLowerCase();
951
+ }
952
+
953
+ /** Whether two pragma lists configure an owner the same way (order matters: pragmas apply in order). */
954
+ export function samePragmas(a: readonly string[], b: readonly string[]): boolean {
955
+ return a.length === b.length && a.every((pragma, index) => normalizePragma(pragma) === normalizePragma(b[index]));
956
+ }
957
+
888
958
  /**
889
959
  * Splits accumulated socket bytes into complete frames; returns the frames
890
960
  * and the unterminated remainder to carry into the next chunk.
package/src/server.ts CHANGED
@@ -15,6 +15,7 @@ import {
15
15
  splitSqlStatements,
16
16
  toJson,
17
17
  transactionControl,
18
+ type AdoptResult,
18
19
  type BatchResult,
19
20
  type BeginResult,
20
21
  type ExecWireResult,
@@ -32,7 +33,7 @@ import {
32
33
  type TransactionMode,
33
34
  type TransactionStatus,
34
35
  } from './protocol.ts';
35
- import { resolvePaths, type FilePaths, type ServerMeta } from './paths.ts';
36
+ import { isNamedPipe, resolvePaths, type FilePaths, type ServerMeta } from './paths.ts';
36
37
  import { VERSION } from './version.ts';
37
38
 
38
39
  export type ServerOptions = Readonly<{
@@ -58,9 +59,11 @@ export type ServerOptions = Readonly<{
58
59
  * Applied in order on open. `auto_vacuum` must precede anything that writes
59
60
  * the first page (journal_mode = WAL does), and only binds on a file with no
60
61
  * pages yet: a brand-new file gets incremental vacuum, an existing file keeps
61
- * whatever it was created with. Callers override with `--pragma`.
62
+ * whatever it was created with. `foreign_keys` is per connection and off by
63
+ * default in SQLite; the owner holds the only connection, so it is enabled
64
+ * here or nowhere. Callers override with `--pragma`.
62
65
  */
63
- export const DEFAULT_PRAGMAS: readonly string[] = ['auto_vacuum = INCREMENTAL', 'journal_mode = WAL', 'busy_timeout = 5000'];
66
+ export const DEFAULT_PRAGMAS: readonly string[] = ['auto_vacuum = INCREMENTAL', 'journal_mode = WAL', 'busy_timeout = 5000', 'foreign_keys = ON'];
64
67
 
65
68
  export const DEFAULT_TX_LEASE_MS = 10_000;
66
69
  export const DEFAULT_TX_MAX_DURATION_MS = 60_000;
@@ -127,6 +130,27 @@ type EndedTransaction = { code: 'tx-expired' | 'tx-invalid'; message: string };
127
130
 
128
131
  const REMEMBERED_ENDINGS = 32;
129
132
 
133
+ /**
134
+ * The files this process owns as a standalone owner (`SqlegoServer.start`):
135
+ * one `SqlegoServer` per file, each with its own socket, `Database`,
136
+ * transaction and idle timer. The process exits once the last of them is
137
+ * released (idle, `stop`, or a signal). Servers opened in-process with
138
+ * `open` + `listen` (tests, embedding) are not in here and never exit the
139
+ * process.
140
+ */
141
+ const owned = new Set<SqlegoServer>();
142
+
143
+ /** How many files this process serves as a standalone owner. */
144
+ export function ownedFiles(): number {
145
+ return owned.size;
146
+ }
147
+
148
+ /** Stops every file this process serves; the caller exits the process. */
149
+ export function stopAll(reason: string): void {
150
+ for (const server of [...owned]) server.stop(reason);
151
+ owned.clear();
152
+ }
153
+
130
154
  /**
131
155
  * The single owner of one SQLite file. Every request from every client runs,
132
156
  * in arrival order, on this process's one connection; SQLite's write lock is
@@ -135,9 +159,16 @@ const REMEMBERED_ENDINGS = 32;
135
159
  * While a client holds a transaction, that client's statements run at once
136
160
  * and every other client's statements wait in arrival order; the transaction
137
161
  * cannot outlive its socket, its lease, or the server's hard cap.
162
+ *
163
+ * One owner process serves any number of files: the first through `start`
164
+ * (what `sqlego serve` does), the rest through the `adopt` request a client
165
+ * sends when it finds no owner for its file. Each file is still its own
166
+ * `SqlegoServer`, so nothing above this comment changes with the count.
138
167
  */
139
168
  export class SqlegoServer {
140
169
  readonly paths: FilePaths;
170
+ /** The pragmas applied on open, as given; reported to clients so one asking for others can tell. */
171
+ readonly pragmas: readonly string[];
141
172
  private readonly db: Database;
142
173
  private readonly options: ServerOptions;
143
174
  private readonly startedAt = Date.now();
@@ -154,10 +185,11 @@ export class SqlegoServer {
154
185
  private readonly ended = new Map<number, EndedTransaction>();
155
186
  private readonly log: NonNullable<ServerOptions['log']>;
156
187
 
157
- private constructor(options: ServerOptions, paths: FilePaths, db: Database) {
188
+ private constructor(options: ServerOptions, paths: FilePaths, db: Database, pragmas: readonly string[]) {
158
189
  this.options = options;
159
190
  this.paths = paths;
160
191
  this.db = db;
192
+ this.pragmas = pragmas;
161
193
  this.log = options.log ?? (() => undefined);
162
194
  }
163
195
 
@@ -165,19 +197,49 @@ export class SqlegoServer {
165
197
  static open(options: ServerOptions) {
166
198
  const paths = resolvePaths(options.file);
167
199
  if (!paths.ok) return paths;
200
+ const pragmas = options.pragmas ?? DEFAULT_PRAGMAS;
168
201
  const db = Trust.try(
169
202
  () => {
170
203
  mkdirSync(path.dirname(paths.value.file), { recursive: true });
171
204
  // safeIntegers: SQLite integers arrive as bigint so `statement`/`exec`
172
205
  // can return all 64 bits; `query`/`run`/`batch` still send JSON numbers.
173
206
  const opened = new Database(paths.value.file, { create: true, strict: false, safeIntegers: true });
174
- for (const pragma of options.pragmas ?? DEFAULT_PRAGMAS) opened.exec(`PRAGMA ${pragma}`);
207
+ for (const pragma of pragmas) opened.exec(`PRAGMA ${pragma}`);
175
208
  return opened;
176
209
  },
177
210
  (cause) => ({ kind: 'open-failed', message: `cannot open ${paths.value.file}: ${errorMessage(cause)}` }),
178
211
  );
179
212
  if (!db.ok) return db;
180
- return Result.ok(new SqlegoServer(options, paths.value, db.value));
213
+ return Result.ok(new SqlegoServer(options, paths.value, db.value, [...pragmas]));
214
+ }
215
+
216
+ /**
217
+ * Serves one file as (part of) a standalone owner process: opens it,
218
+ * listens, releases the claimer's lock now that the socket is live, and
219
+ * registers the file so the process exits when its last file is released.
220
+ * A file this process already serves is returned as is.
221
+ */
222
+ static start(options: ServerOptions) {
223
+ const paths = resolvePaths(options.file);
224
+ if (!paths.ok) return paths;
225
+ for (const server of owned) {
226
+ if (server.paths.file === paths.value.file) return Result.ok(server);
227
+ }
228
+ const opened = SqlegoServer.open(options);
229
+ if (!opened.ok) return opened;
230
+ const server = opened.value;
231
+ const listening = server.listen();
232
+ if (!listening.ok) {
233
+ server.stop('listen failed');
234
+ return listening;
235
+ }
236
+ const released = Trust.try(
237
+ () => rmSync(server.paths.lock, { force: true }),
238
+ (cause) => ({ kind: 'cleanup-failed' as const, message: errorMessage(cause) }),
239
+ );
240
+ server.reportCleanup('release claim lock', released);
241
+ owned.add(server);
242
+ return Result.ok(server);
181
243
  }
182
244
 
183
245
  /** Binds the socket and publishes meta. Clients can connect once this returns ok. */
@@ -189,7 +251,8 @@ export class SqlegoServer {
189
251
  if (!metaJson.ok) return Result.err({ kind: 'listen-failed', message: `cannot encode server meta: ${metaJson.error.message}` });
190
252
  const bound = Trust.try(
191
253
  () => {
192
- if (existsSync(this.paths.socket)) rmSync(this.paths.socket, { force: true });
254
+ // A socket file left by a dead owner must go before bind; a named pipe has no file.
255
+ if (!isNamedPipe(this.paths.socket) && existsSync(this.paths.socket)) rmSync(this.paths.socket, { force: true });
193
256
  this.listener = Bun.listen<Connection | null>({
194
257
  unix: this.paths.socket,
195
258
  data: null,
@@ -221,7 +284,9 @@ export class SqlegoServer {
221
284
  for (const queued of this.queue.splice(0)) clearTimeout(queued.timer);
222
285
  // Socket file first: a client that connects after this point falls through
223
286
  // to claim-and-spawn instead of racing a closing server.
224
- this.reportCleanup('remove socket', Trust.try(() => rmSync(this.paths.socket, { force: true }), cleanupFailure));
287
+ if (!isNamedPipe(this.paths.socket)) {
288
+ this.reportCleanup('remove socket', Trust.try(() => rmSync(this.paths.socket, { force: true }), cleanupFailure));
289
+ }
225
290
  this.reportCleanup('remove meta', Trust.try(() => rmSync(this.paths.meta, { force: true }), cleanupFailure));
226
291
  this.reportCleanup('remove lock', Trust.try(() => rmSync(this.paths.lock, { force: true }), cleanupFailure));
227
292
  for (const connection of this.connections.values()) {
@@ -232,6 +297,19 @@ export class SqlegoServer {
232
297
  this.reportCleanup('close database', Trust.try(() => this.db.close(), cleanupFailure));
233
298
  }
234
299
 
300
+ /**
301
+ * Stops this file and lets the owner process go when it was the last one.
302
+ * The exit is deferred a moment so the reply to a `stop` reaches its client.
303
+ */
304
+ private release(reason: string): void {
305
+ const wasOwned = owned.delete(this);
306
+ this.stop(reason);
307
+ if (wasOwned && owned.size === 0) {
308
+ this.log('last file released; exiting', { reason });
309
+ setTimeout(() => process.exit(0), 20);
310
+ }
311
+ }
312
+
235
313
  status(): StatusResult {
236
314
  return {
237
315
  file: this.paths.file,
@@ -239,6 +317,8 @@ export class SqlegoServer {
239
317
  pid: process.pid,
240
318
  serverVersion: VERSION,
241
319
  protocol: PROTOCOL_VERSION,
320
+ pragmas: this.pragmas,
321
+ files: owned.has(this) ? owned.size : 1,
242
322
  clients: this.connections.size,
243
323
  uptimeMs: Date.now() - this.startedAt,
244
324
  idleMs: this.idleSince === null ? null : Date.now() - this.idleSince,
@@ -390,8 +470,8 @@ export class SqlegoServer {
390
470
  const response = this.respond(connection, request);
391
471
  this.reply(connection, response);
392
472
  if (response.ok && request.op === 'stop') {
393
- this.stop('client request');
394
- setTimeout(() => process.exit(0), 20);
473
+ // Only this file: an owner serving other files keeps serving them.
474
+ this.release('client request');
395
475
  return;
396
476
  }
397
477
  // A commit, rollback or expiry may have freed the file for whoever was waiting.
@@ -410,6 +490,7 @@ export class SqlegoServer {
410
490
  case 'tx-expired': return { id: request.id, ok: false, error: { code: 'tx-expired', message: outcome.error.message } };
411
491
  case 'tx-invalid': return { id: request.id, ok: false, error: { code: 'tx-invalid', message: outcome.error.message } };
412
492
  case 'encode-failed': return { id: request.id, ok: false, error: { code: 'encode-failed', message: outcome.error.message } };
493
+ case 'adopt-failed': return { id: request.id, ok: false, error: { code: 'adopt-failed', message: outcome.error.message } };
413
494
  default: {
414
495
  const unhandled: never = outcome.error;
415
496
  return unhandled;
@@ -430,6 +511,7 @@ export class SqlegoServer {
430
511
  case 'rollback': return this.finish(connection, request.txId, 'rollback');
431
512
  case 'status': return Result.ok(this.status());
432
513
  case 'stop': return Result.ok({ stopping: true });
514
+ case 'adopt': return this.adopt(request.file, request.pragmas, request.idleTimeoutMs);
433
515
  default: {
434
516
  const unhandled: never = request;
435
517
  return unhandled;
@@ -437,11 +519,32 @@ export class SqlegoServer {
437
519
  }
438
520
  }
439
521
 
522
+ /**
523
+ * Serves one more file from this process, with this file's transaction
524
+ * settings and log but its own pragmas and idle timeout. Only a standalone
525
+ * owner (`start`) may adopt: an embedded server has no process to lend.
526
+ */
527
+ private adopt(file: string, pragmas: readonly string[] | undefined, idleTimeoutMs: number | undefined) {
528
+ if (!owned.has(this)) return badRequest('this owner is embedded in another process and cannot adopt files');
529
+ const started = SqlegoServer.start({
530
+ ...this.options,
531
+ file,
532
+ pragmas: pragmas ?? DEFAULT_PRAGMAS,
533
+ idleTimeoutMs: idleTimeoutMs ?? this.options.idleTimeoutMs,
534
+ });
535
+ if (!started.ok) {
536
+ return Result.err({ kind: 'adopt-failed' as const, message: `cannot adopt ${file}: ${started.error.message}` });
537
+ }
538
+ this.log('adopted', { file: started.value.paths.file, files: owned.size });
539
+ const result: AdoptResult = { file: started.value.paths.file, socket: started.value.paths.socket, pid: process.pid };
540
+ return Result.ok(result);
541
+ }
542
+
440
543
  private hello(protocol: number) {
441
544
  if (protocol !== PROTOCOL_VERSION) {
442
545
  return Result.err({ kind: 'protocol-mismatch', message: `server speaks protocol ${PROTOCOL_VERSION}, client sent ${protocol}` });
443
546
  }
444
- const hello: HelloResult = { serverVersion: VERSION, protocol: PROTOCOL_VERSION, file: this.paths.file, pid: process.pid };
547
+ const hello: HelloResult = { serverVersion: VERSION, protocol: PROTOCOL_VERSION, file: this.paths.file, pid: process.pid, pragmas: this.pragmas };
445
548
  return Result.ok(hello);
446
549
  }
447
550
 
@@ -849,8 +952,7 @@ export class SqlegoServer {
849
952
  /** Never while a client is connected or a transaction is open (its owner is connected, but the guard is explicit). */
850
953
  private onIdle(): void {
851
954
  if (this.connections.size > 0 || this.transaction !== null) return;
852
- this.stop('idle');
853
- process.exit(0);
955
+ this.release('idle');
854
956
  }
855
957
 
856
958
  private disarmIdleTimer(): void {