@noego/sqlego 0.0.0-stage → 0.0.1-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/src/client.ts ADDED
@@ -0,0 +1,497 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { closeSync, openSync, readFileSync, rmSync, writeSync, existsSync } from 'node:fs';
3
+ import net from 'node:net';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { Result, Trust } from '@noego/trust';
7
+ import {
8
+ PROTOCOL_VERSION,
9
+ encodeFrame,
10
+ errnoCode,
11
+ errorMessage,
12
+ fromJson,
13
+ parseBatchResult,
14
+ parseHelloResult,
15
+ parseQueryResult,
16
+ parseResponse,
17
+ parseRunResult,
18
+ parseStatusResult,
19
+ parseStopResult,
20
+ splitFrames,
21
+ type BatchResult,
22
+ type ErrorCode,
23
+ type HelloResult,
24
+ type Request,
25
+ type RunResult,
26
+ type SqlParams,
27
+ type SqlRow,
28
+ type Statement,
29
+ type StatusResult,
30
+ } from './protocol.ts';
31
+ import { isProcessAlive, resolvePaths, type FilePaths } from './paths.ts';
32
+ import { VERSION } from './version.ts';
33
+
34
+ /**
35
+ * Runs in Node and Bun alike (node:net, node:child_process only; no SQLite
36
+ * dependency). Connects to the file's owner, spawning one when none is
37
+ * listening. The sequence is always: connect → else claim lock → spawn → wait
38
+ * for the socket → connect. A claimer that loses the lock waits for the
39
+ * winner's socket instead.
40
+ */
41
+ export type ClientOptions = Readonly<{
42
+ /** Spawn a server when none is listening. Default true. */
43
+ spawn?: boolean;
44
+ /** How the server is started when needed; see `serverCommand`. */
45
+ serverCommand?: readonly string[];
46
+ /** Idle timeout passed to a spawned server. Default 30 000. */
47
+ idleTimeoutMs?: number;
48
+ /** Pragmas a spawned server applies on open (`--pragma`), replacing its defaults. Ignored when a server is already running. */
49
+ serverPragmas?: readonly string[];
50
+ /** Total time to obtain a connection, including spawn. Default 10 000. */
51
+ connectTimeoutMs?: number;
52
+ /** Per-request timeout. Default 60 000. */
53
+ requestTimeoutMs?: number;
54
+ }>;
55
+
56
+ // No TypeScript parameter properties anywhere in the client: Node's
57
+ // strip-only type loading (`--experimental-strip-types`) rejects them, and the
58
+ // client must load in plain Node without a build step.
59
+ export class SqlegoClientError extends Error {
60
+ readonly code: string;
61
+
62
+ constructor(code: string, message: string) {
63
+ super(message);
64
+ this.code = code;
65
+ }
66
+ }
67
+
68
+ /** Why a request did not get a result: the transport's own failures plus every error the server reports. */
69
+ type RequestFailure = Readonly<{
70
+ kind: 'not-connected' | 'closed' | 'socket' | 'request-timeout' | 'protocol' | 'encode-failed' | ErrorCode;
71
+ message: string;
72
+ }>;
73
+
74
+ /** Any failure the client reports: a literal `kind` that becomes `SqlegoClientError.code`. */
75
+ type ClientFailure = Readonly<{ kind: string; message: string }>;
76
+
77
+ /** What a reply parser in protocol.ts reports when the reply has the wrong shape. */
78
+ type Invalid = Readonly<{ kind: 'invalid'; message: string }>;
79
+
80
+ type Waiter = { settle: (outcome: Result<unknown, RequestFailure>) => void; timer: ReturnType<typeof setTimeout> };
81
+
82
+ /** `Omit` distributed over the request union so each op keeps its own fields. */
83
+ type RequestBody = Request extends infer Variant ? (Variant extends Request ? Omit<Variant, 'id'> : never) : never;
84
+
85
+ /** A stop reply may never arrive when the server drops connections first; wait briefly, not the full request timeout. */
86
+ const STOP_TIMEOUT_MS = 1_000;
87
+
88
+ /**
89
+ * The edge of the client: internal code returns `Result`; the public API's
90
+ * contract is a `SqlegoClientError` whose `code` is the failure's kind.
91
+ */
92
+ function unwrap<T>(outcome: Result<T, ClientFailure>): T {
93
+ if (outcome.ok) return outcome.value;
94
+ //trust:accept public API contract: SqlegoClient methods reject with SqlegoClientError(code, message)
95
+ throw new SqlegoClientError(outcome.error.kind, outcome.error.message);
96
+ }
97
+
98
+ /**
99
+ * `query<Row>` lets the caller name the shape of its own SQL's rows, as any
100
+ * typed SQL client does: sqlego checks that each row is an object (in
101
+ * `parseQueryResult`), and the column types are the caller's declaration.
102
+ */
103
+ //trust:validator_function
104
+ function callerRows<Row extends SqlRow>(rows: SqlRow[]): Row[] {
105
+ return rows as Row[];
106
+ }
107
+
108
+ export class SqlegoClient {
109
+ readonly paths: FilePaths;
110
+ private socket: net.Socket | null = null;
111
+ private buffer = '';
112
+ private nextId = 1;
113
+ private readonly pending = new Map<number, Waiter>();
114
+ private hello: HelloResult | null = null;
115
+ /** Why the server this client spawned did not come up, if it did not. */
116
+ private spawnFailure: string | null = null;
117
+ private readonly options: ClientOptions;
118
+
119
+ private constructor(paths: FilePaths, options: ClientOptions) {
120
+ this.paths = paths;
121
+ this.options = options;
122
+ }
123
+
124
+ static async connect(file: string, options: ClientOptions = {}): Promise<SqlegoClient> {
125
+ const paths = resolvePaths(file);
126
+ if (!paths.ok) {
127
+ //trust:accept public API contract: an unusable path rejects with an Error, as pathsFor does
128
+ throw new Error(paths.error.message);
129
+ }
130
+ const client = new SqlegoClient(paths.value, options);
131
+ unwrap(await client.open());
132
+ return client;
133
+ }
134
+
135
+ get server(): HelloResult {
136
+ if (this.hello) return this.hello;
137
+ return unwrap(Result.err({ kind: 'not-connected', message: 'client is not connected' }));
138
+ }
139
+
140
+ async query<Row extends SqlRow = SqlRow>(sql: string, params?: SqlParams): Promise<Row[]> {
141
+ const result = unwrap(await this.call({ op: 'query', sql, params }, parseQueryResult));
142
+ return callerRows<Row>(result.rows);
143
+ }
144
+
145
+ async run(sql: string, params?: SqlParams): Promise<RunResult> {
146
+ return unwrap(await this.call({ op: 'run', sql, params }, parseRunResult));
147
+ }
148
+
149
+ /** One transaction; the whole batch rolls back on the first failure. */
150
+ async batch(statements: readonly Statement[]): Promise<BatchResult['results']> {
151
+ const result = unwrap(await this.call({ op: 'batch', statements }, parseBatchResult));
152
+ return result.results;
153
+ }
154
+
155
+ async status(): Promise<StatusResult> {
156
+ return unwrap(await this.call({ op: 'status' }, parseStatusResult));
157
+ }
158
+
159
+ /** Asks the server to shut down; the connection closes as a consequence. */
160
+ async stop(): Promise<void> {
161
+ unwrap(await this.stopServer());
162
+ }
163
+
164
+ async close(): Promise<void> {
165
+ const socket = this.socket;
166
+ this.socket = null;
167
+ if (!socket || socket.destroyed) return;
168
+ await new Promise<void>((resolve) => endSocket(socket, resolve));
169
+ }
170
+
171
+ private async stopServer() {
172
+ const stopped = await this.call({ op: 'stop' }, parseStopResult, STOP_TIMEOUT_MS);
173
+ if (!stopped.ok) {
174
+ switch (stopped.error.kind) {
175
+ // The server may drop the connection before the reply lands (another
176
+ // client stopped it first); that is the outcome we asked for.
177
+ case 'closed':
178
+ case 'not-connected':
179
+ case 'socket':
180
+ case 'request-timeout':
181
+ break;
182
+ default:
183
+ return stopped;
184
+ }
185
+ }
186
+ await this.close();
187
+ return Result.ok(undefined);
188
+ }
189
+
190
+ private async open() {
191
+ const deadline = Date.now() + (this.options.connectTimeoutMs ?? 10_000);
192
+ const socket = await this.connectOrSpawn(deadline);
193
+ if (!socket.ok) return socket;
194
+ const attached = this.attach(socket.value);
195
+ if (!attached.ok) return attached;
196
+ const hello = await this.call({ op: 'hello', clientVersion: VERSION, protocol: PROTOCOL_VERSION }, parseHelloResult);
197
+ if (!hello.ok) return hello;
198
+ if (hello.value.serverVersion === VERSION || this.options.spawn === false) {
199
+ this.hello = hello.value;
200
+ return Result.ok(undefined);
201
+ }
202
+ // Stale server from an older build: drain it and start a fresh one.
203
+ const stopped = await this.stopServer();
204
+ if (!stopped.ok) return stopped;
205
+ await this.waitForExit(hello.value.pid, deadline);
206
+ const fresh = await this.connectOrSpawn(deadline);
207
+ if (!fresh.ok) return fresh;
208
+ const reattached = this.attach(fresh.value);
209
+ if (!reattached.ok) return reattached;
210
+ const freshHello = await this.call({ op: 'hello', clientVersion: VERSION, protocol: PROTOCOL_VERSION }, parseHelloResult);
211
+ if (!freshHello.ok) return freshHello;
212
+ this.hello = freshHello.value;
213
+ return Result.ok(undefined);
214
+ }
215
+
216
+ private async connectOrSpawn(deadline: number) {
217
+ const first = await tryConnect(this.paths.socket);
218
+ if (first) return Result.ok(first);
219
+ if (this.options.spawn === false) {
220
+ return Result.err({ kind: 'not-running', message: `no sqlego server for ${this.paths.file}` });
221
+ }
222
+ const claimed = this.claimLock();
223
+ if (!claimed.ok) return claimed;
224
+ if (claimed.value) {
225
+ const spawned = this.spawnServer();
226
+ if (!spawned.ok) return spawned;
227
+ }
228
+ // Claimer or not, the socket appears when the winner is listening.
229
+ while (Date.now() < deadline) {
230
+ const socket = await tryConnect(this.paths.socket);
231
+ if (socket) return Result.ok(socket);
232
+ await sleep(25);
233
+ }
234
+ const cause = this.spawnFailure ? ` (${this.spawnFailure})` : '';
235
+ return Result.err({ kind: 'connect-timeout', message: `no sqlego server became reachable for ${this.paths.file}${cause}` });
236
+ }
237
+
238
+ /** O_EXCL create; a lock left by a dead process (or unreadable) is reclaimed. */
239
+ private claimLock() {
240
+ const lock = this.paths.lock;
241
+ for (let attempt = 0; attempt < 2; attempt += 1) {
242
+ const created = Trust.try(
243
+ () => {
244
+ const fd = openSync(lock, 'wx');
245
+ writeSync(fd, String(process.pid));
246
+ closeSync(fd);
247
+ },
248
+ (cause) => (errnoCode(cause) === 'EEXIST'
249
+ ? { kind: 'lock-held' as const, message: `${lock} exists` }
250
+ : { kind: 'lock-failed' as const, message: `cannot create ${lock}: ${errorMessage(cause)}` }),
251
+ );
252
+ if (created.ok) return Result.ok(true);
253
+ if (created.error.kind === 'lock-failed') return Result.err({ kind: 'lock-failed', message: created.error.message });
254
+ if (created.error.kind === 'lock-held') {
255
+ const holder = Trust.try(
256
+ () => Number(readFileSync(lock, 'utf8').trim()),
257
+ (cause) => ({ kind: 'lock-unreadable' as const, message: errorMessage(cause) }),
258
+ );
259
+ if (holder.ok) {
260
+ if (Number.isFinite(holder.value) && holder.value > 0 && isProcessAlive(holder.value)) return Result.ok(false);
261
+ // A dead (or unrecorded) holder: reclaim the lock below.
262
+ } else if (holder.error.kind === 'lock-unreadable') {
263
+ // The lock vanished between the create and the read: reclaim below and retry.
264
+ }
265
+ const removed = Trust.try(
266
+ () => rmSync(lock, { force: true }),
267
+ (cause) => ({ kind: 'lock-failed' as const, message: `cannot remove stale ${lock}: ${errorMessage(cause)}` }),
268
+ );
269
+ if (!removed.ok) return removed;
270
+ }
271
+ }
272
+ return Result.ok(false);
273
+ }
274
+
275
+ private spawnServer() {
276
+ const [command, ...args] = this.options.serverCommand ?? defaultServerCommand();
277
+ const pragmaArgs = (this.options.serverPragmas ?? []).flatMap((pragma) => ['--pragma', pragma]);
278
+ return Trust.try(
279
+ () => {
280
+ const child = spawn(command, [...args, 'serve', this.paths.file, '--idle-ms', String(this.options.idleTimeoutMs ?? 30_000), ...pragmaArgs], {
281
+ detached: true,
282
+ // stderr is captured (bounded) only to explain a failed start; it never
283
+ // keeps this process alive.
284
+ stdio: ['ignore', 'ignore', 'pipe'],
285
+ env: { ...process.env, SQLEGO_CLAIMED_BY: String(process.pid) },
286
+ });
287
+ let stderr = '';
288
+ child.stderr?.on('data', (chunk: Buffer) => { if (stderr.length < 2_000) stderr += chunk.toString(); });
289
+ // The stderr pipe is a net.Socket at runtime, but typed as a Readable,
290
+ // which declares no unref(); feature-test it on `unknown`.
291
+ const stderrPipe: unknown = child.stderr;
292
+ if (typeof stderrPipe === 'object' && stderrPipe !== null && 'unref' in stderrPipe && typeof stderrPipe.unref === 'function') {
293
+ stderrPipe.unref();
294
+ }
295
+ child.on('error', (error) => this.onSpawnError(command, error));
296
+ child.on('exit', (code, signal) => {
297
+ if (!this.hello) this.spawnFailure = `server exited before listening (code ${code}, signal ${signal})${stderr ? `: ${stderr.trim()}` : ''}`;
298
+ });
299
+ child.unref();
300
+ },
301
+ (cause) => ({ kind: 'spawn-failed' as const, message: `spawn ${command} failed: ${errorMessage(cause)}` }),
302
+ );
303
+ }
304
+
305
+ /** The spawn never started: record why, and release the lock so another claimer can try. */
306
+ private onSpawnError(command: string, error: Error): void {
307
+ this.spawnFailure = `spawn ${command} failed: ${error.message}`;
308
+ const released = Trust.try(
309
+ () => rmSync(this.paths.lock, { force: true }),
310
+ (cause) => ({ kind: 'lock-failed' as const, message: errorMessage(cause) }),
311
+ );
312
+ if (!released.ok && released.error.kind === 'lock-failed') this.spawnFailure += `; lock not released: ${released.error.message}`;
313
+ }
314
+
315
+ private attach(socket: net.Socket) {
316
+ this.socket = socket;
317
+ this.buffer = '';
318
+ return Trust.try(
319
+ () => {
320
+ socket.setEncoding('utf8');
321
+ socket.on('data', (chunk: string) => this.onData(chunk));
322
+ // Peer FIN (server stopping): tear down now rather than lingering half-open.
323
+ socket.on('end', () => socket.destroy());
324
+ socket.on('close', () => this.onClose(socket));
325
+ socket.on('error', (error) => this.settleAll({ kind: 'socket', message: error.message }));
326
+ },
327
+ (cause) => ({ kind: 'socket' as const, message: errorMessage(cause) }),
328
+ );
329
+ }
330
+
331
+ private onClose(socket: net.Socket): void {
332
+ if (this.socket === socket) this.socket = null;
333
+ this.settleAll({ kind: 'closed', message: 'connection closed' });
334
+ }
335
+
336
+ private onData(chunk: string): void {
337
+ const { frames, rest } = splitFrames(this.buffer + chunk);
338
+ this.buffer = rest;
339
+ for (const frame of frames) {
340
+ const json = fromJson(frame);
341
+ const parsed = json.ok ? parseResponse(json.value) : json;
342
+ if (!parsed.ok) {
343
+ // A corrupt frame means the stream is unrecoverable; fail every waiter
344
+ // and drop the socket rather than throwing out of a 'data' handler.
345
+ if (parsed.error.kind === 'invalid') {
346
+ this.buffer = '';
347
+ this.settleAll({ kind: 'protocol', message: `malformed frame from server: ${parsed.error.message}` });
348
+ this.socket?.destroy();
349
+ }
350
+ return;
351
+ }
352
+ const response = parsed.value;
353
+ const waiter = this.pending.get(response.id);
354
+ if (!waiter) continue;
355
+ this.pending.delete(response.id);
356
+ clearTimeout(waiter.timer);
357
+ waiter.settle(response.ok ? Result.ok(response.result) : Result.err({ kind: response.error.code, message: response.error.message }));
358
+ }
359
+ }
360
+
361
+ /**
362
+ * One request whose reply `parse` turns from `unknown` into its typed
363
+ * result; a reply that does not parse is a `protocol` failure.
364
+ */
365
+ private async call<T>(body: RequestBody, parse: (input: unknown) => Result<T, Invalid>, timeoutMs?: number) {
366
+ const reply = await this.request(body, timeoutMs);
367
+ if (!reply.ok) return reply;
368
+ const parsed = parse(reply.value);
369
+ if (parsed.ok) return parsed;
370
+ if (parsed.error.kind === 'invalid') {
371
+ return Result.err<RequestFailure>({ kind: 'protocol', message: `unexpected ${body.op} reply: ${parsed.error.message}` });
372
+ }
373
+ const unhandled: never = parsed.error.kind;
374
+ return unhandled;
375
+ }
376
+
377
+ /** Never rejects: every outcome, including transport failures, is a `Result`. The reply is `unknown` until parsed. */
378
+ private request(body: RequestBody, timeoutMs = this.options.requestTimeoutMs ?? 60_000): Promise<Result<unknown, RequestFailure>> {
379
+ const socket = this.socket;
380
+ if (!socket || socket.destroyed) {
381
+ return Promise.resolve(Result.err({ kind: 'not-connected', message: 'client is not connected' }));
382
+ }
383
+ const id = this.nextId++;
384
+ const frame = encodeFrame({ id, ...body } as Request);
385
+ if (!frame.ok) return Promise.resolve(frame);
386
+ return new Promise<Result<unknown, RequestFailure>>((settle) => {
387
+ const timer = setTimeout(() => {
388
+ this.pending.delete(id);
389
+ settle(Result.err({ kind: 'request-timeout', message: `request ${id} (${body.op}) timed out` }));
390
+ }, timeoutMs);
391
+ this.pending.set(id, { settle, timer });
392
+ const written = Trust.try(
393
+ () => socket.write(frame.value),
394
+ (cause) => ({ kind: 'socket' as const, message: errorMessage(cause) }),
395
+ );
396
+ if (!written.ok) {
397
+ this.pending.delete(id);
398
+ clearTimeout(timer);
399
+ settle(written);
400
+ }
401
+ });
402
+ }
403
+
404
+ private settleAll(failure: RequestFailure): void {
405
+ for (const waiter of this.pending.values()) {
406
+ clearTimeout(waiter.timer);
407
+ waiter.settle(Result.err(failure));
408
+ }
409
+ this.pending.clear();
410
+ }
411
+
412
+ private async waitForExit(pid: number, deadline: number): Promise<void> {
413
+ while (Date.now() < deadline && isProcessAlive(pid)) await sleep(25);
414
+ }
415
+ }
416
+
417
+ /**
418
+ * How to start a server: SQLEGO_BIN if set; the compiled `sqlego` binary when
419
+ * running as one; the dev entry (`bun src/cli.ts`) when running from source
420
+ * under Bun; else `sqlego` on PATH.
421
+ */
422
+ export function defaultServerCommand(): readonly string[] {
423
+ const configured = process.env.SQLEGO_BIN;
424
+ if (configured && configured.length > 0) return [configured];
425
+ const entry = process.argv[1] ?? '';
426
+ const located = Trust.try(
427
+ () => path.dirname(fileURLToPath(import.meta.url)),
428
+ (cause) => ({ kind: 'module-path' as const, message: errorMessage(cause) }),
429
+ );
430
+ // A module that cannot locate itself has no sibling cli.ts or bin/ to offer.
431
+ let here: string | null = null;
432
+ if (located.ok) here = located.value;
433
+ else if (located.error.kind === 'module-path') here = null;
434
+ if (process.versions.bun) {
435
+ if (entry.endsWith('cli.ts')) return [process.execPath, entry];
436
+ if (entry.endsWith('.ts') && here !== null) {
437
+ const cli = path.join(here, 'cli.ts');
438
+ if (existsSync(cli)) return [process.execPath, cli];
439
+ }
440
+ if (!entry.endsWith('.js') && !entry.endsWith('.ts')) return [process.execPath];
441
+ }
442
+ if (here !== null) {
443
+ const local = path.join(here, '..', 'bin', 'sqlego');
444
+ if (existsSync(local)) return [local];
445
+ }
446
+ return ['sqlego'];
447
+ }
448
+
449
+ /** Resolves the connected socket, or null when nothing is listening (or the attempt could not start). */
450
+ function tryConnect(socketPath: string): Promise<net.Socket | null> {
451
+ return new Promise((resolve) => {
452
+ // Listeners first: Bun's node:net can emit `error` synchronously from
453
+ // connect() when the socket file is absent.
454
+ const started = Trust.try(
455
+ () => {
456
+ const socket = new net.Socket();
457
+ socket.once('connect', () => resolve(connected(socket)));
458
+ socket.once('error', () => { socket.destroy(); resolve(null); });
459
+ socket.connect(socketPath);
460
+ },
461
+ (cause) => ({ kind: 'connect-failed' as const, message: errorMessage(cause) }),
462
+ );
463
+ if (!started.ok && started.error.kind === 'connect-failed') resolve(null);
464
+ });
465
+ }
466
+
467
+ /** The connect-time error listener must go, or a later error would destroy a live connection. */
468
+ function connected(socket: net.Socket): net.Socket | null {
469
+ const detached = Trust.try(
470
+ () => socket.removeAllListeners('error'),
471
+ (cause) => ({ kind: 'listener-cleanup' as const, message: errorMessage(cause) }),
472
+ );
473
+ if (detached.ok) return socket;
474
+ if (detached.error.kind === 'listener-cleanup') socket.destroy();
475
+ return null;
476
+ }
477
+
478
+ /** Half-closes and resolves on 'close', or after 500 ms for a peer that went away without one. */
479
+ function endSocket(socket: net.Socket, resolve: () => void): void {
480
+ const ended = Trust.try(
481
+ () => {
482
+ const done = () => { clearTimeout(guard); resolve(); };
483
+ const guard = setTimeout(() => { socket.destroy(); done(); }, 500);
484
+ socket.once('close', done);
485
+ socket.end();
486
+ },
487
+ (cause) => ({ kind: 'end-failed' as const, message: errorMessage(cause) }),
488
+ );
489
+ if (!ended.ok && ended.error.kind === 'end-failed') {
490
+ socket.destroy();
491
+ resolve();
492
+ }
493
+ }
494
+
495
+ function sleep(ms: number): Promise<void> {
496
+ return new Promise((resolve) => setTimeout(resolve, ms));
497
+ }
package/src/index.ts ADDED
@@ -0,0 +1,15 @@
1
+ export { SqlegoClient, SqlegoClientError, defaultServerCommand, type ClientOptions } from './client.ts';
2
+ export { pathsFor, runtimeDirectory, canonicalFile, type FilePaths, type ServerMeta } from './paths.ts';
3
+ export {
4
+ PROTOCOL_VERSION,
5
+ type SqlParams,
6
+ type SqlRow,
7
+ type SqlValue,
8
+ type Statement,
9
+ type RunResult,
10
+ type QueryResult,
11
+ type BatchResult,
12
+ type StatusResult,
13
+ type HelloResult,
14
+ } from './protocol.ts';
15
+ export { VERSION } from './version.ts';
package/src/paths.ts ADDED
@@ -0,0 +1,154 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { mkdirSync, realpathSync, existsSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import path from 'node:path';
5
+ import { Result, Trust } from '@noego/trust';
6
+ import { errnoCode, errorMessage } from './protocol.ts';
7
+
8
+ /**
9
+ * Where a file's socket, lock, and meta live. Never beside the database:
10
+ * Unix socket paths cap at 104 bytes on macOS and application-support paths
11
+ * already exceed that. The runtime dir is short and per-user.
12
+ *
13
+ * Override with SQLEGO_RUNTIME_DIR (tests use a scratch dir).
14
+ */
15
+ export function resolveRuntimeDirectory() {
16
+ const configured = process.env.SQLEGO_RUNTIME_DIR;
17
+ const directory = configured && configured.length > 0 ? configured : path.join(tmpdir(), 'sqlego');
18
+ const created = Trust.try(
19
+ () => mkdirSync(directory, { recursive: true }),
20
+ (cause) => ({ kind: 'runtime-directory', message: `cannot create sqlego runtime directory ${directory}: ${errorMessage(cause)}` }),
21
+ );
22
+ if (!created.ok) return created;
23
+ return Result.ok(directory);
24
+ }
25
+
26
+ /** Canonical absolute path of the database; the identity every client and server agree on. */
27
+ export function resolveCanonicalFile(file: string) {
28
+ // path.resolve reads process.cwd() for a relative path, which throws when
29
+ // the working directory was removed; realpathSync is I/O.
30
+ return Trust.try(
31
+ () => {
32
+ const absolute = path.resolve(file);
33
+ // Resolve symlinks on the longest existing ancestor, then re-append the
34
+ // rest, so the identity is the same before and after the directory is
35
+ // created (macOS: /tmp and /var are symlinks into /private).
36
+ const missing: string[] = [];
37
+ let existing = absolute;
38
+ while (!existsSync(existing)) {
39
+ missing.unshift(path.basename(existing));
40
+ const parent = path.dirname(existing);
41
+ if (parent === existing) break;
42
+ existing = parent;
43
+ }
44
+ return path.join(realpathSync(existing), ...missing);
45
+ },
46
+ (cause) => ({ kind: 'canonical-path', message: `cannot resolve ${file}: ${errorMessage(cause)}` }),
47
+ );
48
+ }
49
+
50
+ export type FilePaths = Readonly<{
51
+ file: string;
52
+ key: string;
53
+ socket: string;
54
+ lock: string;
55
+ meta: string;
56
+ }>;
57
+
58
+ /** macOS caps `sun_path` at 104 bytes (Linux 108); leave headroom. */
59
+ const MAX_SOCKET_PATH_BYTES = 100;
60
+
61
+ export function resolvePaths(file: string) {
62
+ const canonical = resolveCanonicalFile(file);
63
+ if (!canonical.ok) return canonical;
64
+ const directory = resolveRuntimeDirectory();
65
+ if (!directory.ok) return directory;
66
+ const derived = Trust.try(
67
+ () => {
68
+ const key = createHash('sha1').update(canonical.value).digest('hex').slice(0, 16);
69
+ const socket = path.join(directory.value, `${key}.sock`);
70
+ return { key, socket, socketBytes: Buffer.byteLength(socket) };
71
+ },
72
+ (cause) => ({ kind: 'hash-failed', message: `cannot hash ${canonical.value}: ${errorMessage(cause)}` }),
73
+ );
74
+ if (!derived.ok) return derived;
75
+ const { key, socket, socketBytes } = derived.value;
76
+ if (socketBytes > MAX_SOCKET_PATH_BYTES) {
77
+ return Result.err({
78
+ kind: 'socket-path-too-long',
79
+ message: `sqlego runtime directory too deep for a Unix socket (${socketBytes} bytes > ${MAX_SOCKET_PATH_BYTES}): ${socket}. `
80
+ + 'Point SQLEGO_RUNTIME_DIR at a shorter path.',
81
+ });
82
+ }
83
+ const paths: FilePaths = Object.freeze({
84
+ file: canonical.value,
85
+ key,
86
+ socket,
87
+ lock: path.join(directory.value, `${key}.lock`),
88
+ meta: path.join(directory.value, `${key}.json`),
89
+ });
90
+ return Result.ok(paths);
91
+ }
92
+
93
+ /** Public, exception-based form of `resolveRuntimeDirectory`. */
94
+ export function runtimeDirectory(): string {
95
+ const directory = resolveRuntimeDirectory();
96
+ if (directory.ok) return directory.value;
97
+ //trust:accept public API contract: the exported path helpers throw an Error
98
+ throw new Error(directory.error.message);
99
+ }
100
+
101
+ /** Public, exception-based form of `resolveCanonicalFile`. */
102
+ export function canonicalFile(file: string): string {
103
+ const canonical = resolveCanonicalFile(file);
104
+ if (canonical.ok) return canonical.value;
105
+ //trust:accept public API contract: the exported path helpers throw an Error
106
+ throw new Error(canonical.error.message);
107
+ }
108
+
109
+ /** Public, exception-based form of `resolvePaths`. */
110
+ export function pathsFor(file: string): FilePaths {
111
+ const paths = resolvePaths(file);
112
+ if (paths.ok) return paths.value;
113
+ //trust:accept public API contract: the exported path helpers throw an Error
114
+ throw new Error(paths.error.message);
115
+ }
116
+
117
+ /** Written by the server once it is listening; read by `sqlego ls` and status. */
118
+ export type ServerMeta = Readonly<{
119
+ file: string;
120
+ socket: string;
121
+ pid: number;
122
+ serverVersion: string;
123
+ startedAt: number;
124
+ }>;
125
+
126
+ /** A meta file's parsed JSON; another process wrote it, so every field is checked. */
127
+ //trust:validator_function
128
+ export function parseServerMeta(input: unknown) {
129
+ const fields = typeof input === 'object' && input !== null && !Array.isArray(input) ? (input as Readonly<Record<string, unknown>>) : null;
130
+ if (
131
+ !fields
132
+ || typeof fields.file !== 'string' || typeof fields.socket !== 'string' || typeof fields.pid !== 'number'
133
+ || typeof fields.serverVersion !== 'string' || typeof fields.startedAt !== 'number'
134
+ ) {
135
+ return Result.err({ kind: 'invalid' as const, message: 'server meta needs file, socket, pid, serverVersion and startedAt' });
136
+ }
137
+ const meta: ServerMeta = {
138
+ file: fields.file, socket: fields.socket, pid: fields.pid, serverVersion: fields.serverVersion, startedAt: fields.startedAt,
139
+ };
140
+ return Result.ok(meta);
141
+ }
142
+
143
+ /** Signal 0 probes without signalling: EPERM means alive but not ours, anything else means gone. */
144
+ export function isProcessAlive(pid: number): boolean {
145
+ const probe = Trust.try(
146
+ () => process.kill(pid, 0),
147
+ (cause) => (errnoCode(cause) === 'EPERM' ? { kind: 'not-permitted' as const } : { kind: 'no-such-process' as const }),
148
+ );
149
+ if (probe.ok) return true;
150
+ if (probe.error.kind === 'not-permitted') return true;
151
+ if (probe.error.kind === 'no-such-process') return false;
152
+ const unhandled: never = probe.error;
153
+ return unhandled;
154
+ }