@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/README.md +81 -20
- package/bin/sqlego +2 -2
- package/bin/sqlego.cjs +26 -0
- package/dist/client.d.ts +65 -8
- package/dist/index.d.ts +2 -2
- package/dist/index.js +288 -44
- package/dist/paths.d.ts +10 -0
- package/dist/protocol.d.ts +46 -1
- package/package.json +10 -3
- package/src/cli.ts +7 -11
- package/src/client.ts +312 -50
- package/src/index.ts +4 -2
- package/src/paths.ts +20 -2
- package/src/protocol.ts +75 -5
- package/src/server.ts +115 -13
package/package.json
CHANGED
|
@@ -1,13 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@noego/sqlego",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "One owner
|
|
3
|
+
"version": "0.1.2-dev.1",
|
|
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",
|
|
7
7
|
"author": "Shavauhn Gabay",
|
|
8
8
|
"bin": {
|
|
9
|
-
"sqlego": "./bin/sqlego"
|
|
9
|
+
"sqlego": "./bin/sqlego.cjs"
|
|
10
10
|
},
|
|
11
|
+
"os": [
|
|
12
|
+
"darwin",
|
|
13
|
+
"linux",
|
|
14
|
+
"win32"
|
|
15
|
+
],
|
|
11
16
|
"main": "./dist/index.js",
|
|
12
17
|
"types": "./dist/index.d.ts",
|
|
13
18
|
"exports": {
|
|
@@ -28,8 +33,10 @@
|
|
|
28
33
|
"scripts": {
|
|
29
34
|
"prepare": "bun scripts/build.ts all",
|
|
30
35
|
"build": "bun scripts/build.ts all",
|
|
36
|
+
"build:all": "bun scripts/build.ts all:platforms",
|
|
31
37
|
"build:lib": "bun scripts/build.ts lib",
|
|
32
38
|
"build:bin": "bun scripts/build.ts bin",
|
|
39
|
+
"build:bin:all": "bun scripts/build.ts bin:all",
|
|
33
40
|
"typecheck": "bunx tsc --noEmit",
|
|
34
41
|
"trust": "trust check src",
|
|
35
42
|
"test": "bun test"
|
package/src/cli.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
/**
|
|
3
|
-
* sqlego — one owner
|
|
3
|
+
* sqlego — one owner per SQLite file; one owner process serves many files.
|
|
4
4
|
*
|
|
5
5
|
* sqlego <file> "<sql>" [--params '<json array>'] [--json|--csv]
|
|
6
6
|
* sqlego <file> status | stop
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* sqlego ls
|
|
9
9
|
* sqlego serve <file> [--idle-ms 30000] (what clients spawn; rarely typed)
|
|
10
10
|
*/
|
|
11
|
-
import { readdirSync, readFileSync
|
|
11
|
+
import { readdirSync, readFileSync } from 'node:fs';
|
|
12
12
|
import path from 'node:path';
|
|
13
13
|
import { Result, Trust } from '@noego/trust';
|
|
14
14
|
import { SqlegoClient, SqlegoClientError } from './client.ts';
|
|
@@ -124,10 +124,11 @@ async function serve(file: string, flags: Flags, pragmas: readonly string[]) {
|
|
|
124
124
|
(cause) => ({ kind: 'failed' as const, message: `cannot load the server: ${errorMessage(cause)}` }),
|
|
125
125
|
);
|
|
126
126
|
if (!loaded.ok) return loaded;
|
|
127
|
-
const { SqlegoServer, DEFAULT_PRAGMAS } = loaded.value;
|
|
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
|
-
|
|
130
|
+
// The first file of this owner process; clients add more through `adopt`.
|
|
131
|
+
const started = SqlegoServer.start({
|
|
131
132
|
file,
|
|
132
133
|
idleTimeoutMs,
|
|
133
134
|
pragmas: pragmas.length > 0 ? pragmas : DEFAULT_PRAGMAS,
|
|
@@ -136,15 +137,10 @@ async function serve(file: string, flags: Flags, pragmas: readonly string[]) {
|
|
|
136
137
|
txQueueTimeoutMs: millis('tx-queue-ms'),
|
|
137
138
|
log: flags.verbose ? (message, fields) => err(`[sqlego] ${message} ${displayJson(fields ?? {})}\n`) : undefined,
|
|
138
139
|
});
|
|
139
|
-
if (!
|
|
140
|
-
const
|
|
141
|
-
const listening = server.listen();
|
|
142
|
-
if (!listening.ok) return listening;
|
|
143
|
-
const shutdown = (signal: string) => { server.stop(signal); process.exit(0); };
|
|
140
|
+
if (!started.ok) return started;
|
|
141
|
+
const shutdown = (signal: string) => { stopAll(signal); process.exit(0); };
|
|
144
142
|
return Trust.try(
|
|
145
143
|
() => {
|
|
146
|
-
// The claimer's lock is ours to release now that the socket is live.
|
|
147
|
-
rmSync(server.paths.lock, { force: true });
|
|
148
144
|
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
|
149
145
|
process.on('SIGINT', () => shutdown('SIGINT'));
|
|
150
146
|
process.on('SIGHUP', () => shutdown('SIGHUP'));
|
package/src/client.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
|
-
import { closeSync, openSync, readFileSync, rmSync, writeSync, existsSync } from 'node:fs';
|
|
2
|
+
import { closeSync, openSync, readdirSync, readFileSync, rmSync, writeSync, existsSync } from 'node:fs';
|
|
3
3
|
import net from 'node:net';
|
|
4
4
|
import path from 'node:path';
|
|
5
5
|
import { fileURLToPath } from 'node:url';
|
|
@@ -13,6 +13,7 @@ import {
|
|
|
13
13
|
parseBatchResult,
|
|
14
14
|
parseBeginResult,
|
|
15
15
|
parseExecResult,
|
|
16
|
+
parseAdoptResult,
|
|
16
17
|
parseHelloResult,
|
|
17
18
|
parseQueryResult,
|
|
18
19
|
parseResponse,
|
|
@@ -21,6 +22,7 @@ import {
|
|
|
21
22
|
parseStatusResult,
|
|
22
23
|
parseStopResult,
|
|
23
24
|
parseTransactionEndResult,
|
|
25
|
+
samePragmas,
|
|
24
26
|
splitFrames,
|
|
25
27
|
type BatchResult,
|
|
26
28
|
type BeginResult,
|
|
@@ -36,15 +38,17 @@ import {
|
|
|
36
38
|
type StatusResult,
|
|
37
39
|
type TransactionMode,
|
|
38
40
|
} from './protocol.ts';
|
|
39
|
-
import { isProcessAlive, resolvePaths, type FilePaths } from './paths.ts';
|
|
41
|
+
import { isProcessAlive, parseServerMeta, resolvePaths, type FilePaths } from './paths.ts';
|
|
40
42
|
import { VERSION } from './version.ts';
|
|
41
43
|
|
|
42
44
|
/**
|
|
43
45
|
* Runs in Node and Bun alike (node:net, node:child_process only; no SQLite
|
|
44
|
-
* dependency). Connects to the file's owner,
|
|
45
|
-
* listening. The sequence is always: connect → else
|
|
46
|
-
*
|
|
47
|
-
*
|
|
46
|
+
* dependency). Connects to the file's owner, placing the file with an owner
|
|
47
|
+
* when none is listening for it. The sequence is always: connect → else
|
|
48
|
+
* claim the file's lock → ask a running owner process to adopt the file, or
|
|
49
|
+
* spawn one when there is none (or fewer than `maxOwners`) → wait for the
|
|
50
|
+
* socket → connect. A claimer that loses the lock waits for the winner's
|
|
51
|
+
* socket instead.
|
|
48
52
|
*/
|
|
49
53
|
export type ClientOptions = Readonly<{
|
|
50
54
|
/** Spawn a server when none is listening. Default true. */
|
|
@@ -53,14 +57,39 @@ export type ClientOptions = Readonly<{
|
|
|
53
57
|
serverCommand?: readonly string[];
|
|
54
58
|
/** Idle timeout passed to a spawned server. Default 30 000. */
|
|
55
59
|
idleTimeoutMs?: number;
|
|
56
|
-
/**
|
|
60
|
+
/**
|
|
61
|
+
* Pragmas the owner must have applied on open (`--pragma`), replacing its
|
|
62
|
+
* defaults. A spawned owner gets them; an owner already running with other
|
|
63
|
+
* pragmas is asked to stop and a fresh one is spawned with these, the way
|
|
64
|
+
* an owner from another build is retired. Two clients insisting on
|
|
65
|
+
* different pragmas for one file would keep restarting its owner: agree on
|
|
66
|
+
* one list per file, or leave this unset to accept whatever is running.
|
|
67
|
+
*/
|
|
57
68
|
serverPragmas?: readonly string[];
|
|
69
|
+
/**
|
|
70
|
+
* How many owner processes (of this client's build, under this runtime
|
|
71
|
+
* directory) may exist. A file with no owner is adopted by the running
|
|
72
|
+
* owner serving the fewest files; a new process is spawned only while
|
|
73
|
+
* there are fewer than this many. 1 (the default) means one process serves
|
|
74
|
+
* every file; N spreads files over up to N processes (SQL for files sharing
|
|
75
|
+
* a process runs on one thread); 0 means one process per file, as before
|
|
76
|
+
* owners could adopt. Default `SQLEGO_MAX_OWNERS`, else 1. Never refuses.
|
|
77
|
+
*/
|
|
78
|
+
maxOwners?: number;
|
|
58
79
|
/** Total time to obtain a connection, including spawn. Default 10 000. */
|
|
59
80
|
connectTimeoutMs?: number;
|
|
60
81
|
/** Per-request timeout. Default 60 000. */
|
|
61
82
|
requestTimeoutMs?: number;
|
|
62
83
|
}>;
|
|
63
84
|
|
|
85
|
+
export const DEFAULT_MAX_OWNERS = 1;
|
|
86
|
+
|
|
87
|
+
/** One live owner process of this build, as the meta files of the files it serves report it. */
|
|
88
|
+
type OwnerProcess = Readonly<{ pid: number; socket: string; files: number; startedAt: number }>;
|
|
89
|
+
|
|
90
|
+
/** `adopt` opens a database and binds a socket; it should take milliseconds, but the owner may be mid-query. */
|
|
91
|
+
const ADOPT_TIMEOUT_MS = 5_000;
|
|
92
|
+
|
|
64
93
|
export type BeginOptions = Readonly<{
|
|
65
94
|
/** `immediate` takes the write lock at `begin`; `deferred` (default) on the first write. */
|
|
66
95
|
mode?: TransactionMode;
|
|
@@ -140,6 +169,8 @@ export class SqlegoClient {
|
|
|
140
169
|
private hello: HelloResult | null = null;
|
|
141
170
|
/** Why the server this client spawned did not come up, if it did not. */
|
|
142
171
|
private spawnFailure: string | null = null;
|
|
172
|
+
/** True while this client is the one spawning an owner process (see `placeFile`). */
|
|
173
|
+
private holdsSpawnLock = false;
|
|
143
174
|
private readonly options: ClientOptions;
|
|
144
175
|
|
|
145
176
|
private constructor(paths: FilePaths, options: ClientOptions) {
|
|
@@ -294,14 +325,16 @@ export class SqlegoClient {
|
|
|
294
325
|
if (!attached.ok) return attached;
|
|
295
326
|
const hello = await this.call({ op: 'hello', clientVersion: VERSION, protocol: PROTOCOL_VERSION }, parseHelloResult);
|
|
296
327
|
if (!hello.ok) return hello;
|
|
297
|
-
if (hello.value
|
|
328
|
+
if (!this.mustReplace(hello.value) || this.options.spawn === false) {
|
|
298
329
|
this.hello = hello.value;
|
|
299
330
|
return Result.ok(undefined);
|
|
300
331
|
}
|
|
301
|
-
//
|
|
332
|
+
// A stale owner (older build, or opened with other pragmas than this
|
|
333
|
+
// client requires): have it release the file, then place the file anew.
|
|
334
|
+
// The owner process itself may live on, serving other files.
|
|
302
335
|
const stopped = await this.stopServer();
|
|
303
336
|
if (!stopped.ok) return stopped;
|
|
304
|
-
await this.
|
|
337
|
+
await this.waitForRelease(deadline);
|
|
305
338
|
const fresh = await this.connectOrSpawn(deadline);
|
|
306
339
|
if (!fresh.ok) return fresh;
|
|
307
340
|
const reattached = this.attach(fresh.value);
|
|
@@ -312,6 +345,17 @@ export class SqlegoClient {
|
|
|
312
345
|
return Result.ok(undefined);
|
|
313
346
|
}
|
|
314
347
|
|
|
348
|
+
/**
|
|
349
|
+
* Whether the running owner must be retired for this client: it was built
|
|
350
|
+
* from other source than this client, or it opened the file with other
|
|
351
|
+
* pragmas than this client requires (`serverPragmas` unset accepts any).
|
|
352
|
+
*/
|
|
353
|
+
private mustReplace(hello: HelloResult): boolean {
|
|
354
|
+
if (hello.serverVersion !== VERSION) return true;
|
|
355
|
+
const required = this.options.serverPragmas;
|
|
356
|
+
return required !== undefined && !samePragmas(required, hello.pragmas);
|
|
357
|
+
}
|
|
358
|
+
|
|
315
359
|
private async connectOrSpawn(deadline: number) {
|
|
316
360
|
const first = await tryConnect(this.paths.socket);
|
|
317
361
|
if (first) return Result.ok(first);
|
|
@@ -321,54 +365,147 @@ export class SqlegoClient {
|
|
|
321
365
|
const claimed = this.claimLock();
|
|
322
366
|
if (!claimed.ok) return claimed;
|
|
323
367
|
if (claimed.value) {
|
|
324
|
-
const
|
|
325
|
-
if (!
|
|
368
|
+
const placed = await this.placeFile(deadline);
|
|
369
|
+
if (!placed.ok) {
|
|
370
|
+
// Nothing will serve the file: the claim must go so the next client can try.
|
|
371
|
+
const released = this.releaseLock();
|
|
372
|
+
const suffix = !released.ok && released.error.kind === 'lock-failed' ? `; lock not released: ${released.error.message}` : '';
|
|
373
|
+
return Result.err({ kind: placed.error.kind, message: `${placed.error.message}${suffix}` });
|
|
374
|
+
}
|
|
326
375
|
}
|
|
327
376
|
// Claimer or not, the socket appears when the winner is listening.
|
|
328
377
|
while (Date.now() < deadline) {
|
|
329
378
|
const socket = await tryConnect(this.paths.socket);
|
|
330
|
-
if (socket)
|
|
379
|
+
if (socket) {
|
|
380
|
+
this.releaseSpawnLock();
|
|
381
|
+
return Result.ok(socket);
|
|
382
|
+
}
|
|
331
383
|
await sleep(25);
|
|
332
384
|
}
|
|
385
|
+
this.releaseSpawnLock();
|
|
333
386
|
const cause = this.spawnFailure ? ` (${this.spawnFailure})` : '';
|
|
334
387
|
return Result.err({ kind: 'connect-timeout', message: `no sqlego server became reachable for ${this.paths.file}${cause}` });
|
|
335
388
|
}
|
|
336
389
|
|
|
337
|
-
/**
|
|
390
|
+
/** The file's own claim lock: whoever holds it places the file with an owner. */
|
|
338
391
|
private claimLock() {
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
392
|
+
return claimLockAt(this.paths.lock);
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/* ------------------------------------------------------------------ *
|
|
396
|
+
* Placing a file with an owner process
|
|
397
|
+
* ------------------------------------------------------------------ */
|
|
398
|
+
|
|
399
|
+
private ownerBudget(): number {
|
|
400
|
+
const configured = this.options.maxOwners ?? Number(process.env.SQLEGO_MAX_OWNERS ?? DEFAULT_MAX_OWNERS);
|
|
401
|
+
return Number.isFinite(configured) && configured >= 0 ? Math.floor(configured) : DEFAULT_MAX_OWNERS;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/** The runtime directory's spawn lock: at most one client spawns an owner process at a time. */
|
|
405
|
+
private spawnLockPath(): string {
|
|
406
|
+
return path.join(path.dirname(this.paths.lock), 'spawn.lock');
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* Gets this client's file served, holding the file's claim lock: by the
|
|
411
|
+
* running owner process (of this build) serving the fewest files, or by a
|
|
412
|
+
* new process while fewer than `maxOwners` are running. Spawning is
|
|
413
|
+
* serialized through the spawn lock so many files opened at once share
|
|
414
|
+
* one process instead of each starting their own; a client that loses
|
|
415
|
+
* that lock waits for the new owner to appear and adopts into it.
|
|
416
|
+
*/
|
|
417
|
+
private async placeFile(deadline: number) {
|
|
418
|
+
const budget = this.ownerBudget();
|
|
419
|
+
let lastRefusal: string | null = null;
|
|
420
|
+
while (Date.now() < deadline) {
|
|
421
|
+
const owners = this.currentOwners();
|
|
422
|
+
if (!owners.ok) return owners;
|
|
423
|
+
if (budget === 0 || owners.value.length < budget) {
|
|
424
|
+
if (budget === 0) return this.spawnServer();
|
|
425
|
+
const claimed = claimLockAt(this.spawnLockPath());
|
|
426
|
+
if (!claimed.ok) return claimed;
|
|
427
|
+
if (claimed.value) {
|
|
428
|
+
this.holdsSpawnLock = true;
|
|
429
|
+
return this.spawnServer();
|
|
430
|
+
}
|
|
431
|
+
// Another client is spawning an owner; it will be adoptable once up.
|
|
432
|
+
await sleep(25);
|
|
433
|
+
continue;
|
|
434
|
+
}
|
|
435
|
+
for (const owner of owners.value) {
|
|
436
|
+
const remaining = deadline - Date.now();
|
|
437
|
+
if (remaining <= 0) break;
|
|
438
|
+
const adopted = await oneShot(owner.socket, {
|
|
439
|
+
op: 'adopt', file: this.paths.file, pragmas: this.options.serverPragmas, idleTimeoutMs: this.options.idleTimeoutMs ?? 30_000,
|
|
440
|
+
}, parseAdoptResult, Math.min(ADOPT_TIMEOUT_MS, remaining));
|
|
441
|
+
if (adopted.ok) return Result.ok(undefined);
|
|
442
|
+
if (adopted.error.kind === 'probe-failed') lastRefusal = `owner ${owner.pid}: ${adopted.error.message}`;
|
|
443
|
+
}
|
|
444
|
+
// Every owner went away or refused; the owner set may have changed.
|
|
445
|
+
await sleep(25);
|
|
446
|
+
}
|
|
447
|
+
const why = lastRefusal ? `: ${lastRefusal}` : '';
|
|
448
|
+
return Result.err({ kind: 'connect-timeout' as const, message: `no sqlego owner took on ${this.paths.file}${why}` });
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* Owner processes of this build under this runtime directory, fewest files
|
|
453
|
+
* first, from the meta files their files wrote. An owner of another build
|
|
454
|
+
* is never adopted into (its files are retired one by one as their clients
|
|
455
|
+
* arrive); a dead one's metas are ignored.
|
|
456
|
+
*/
|
|
457
|
+
private currentOwners() {
|
|
458
|
+
const directory = path.dirname(this.paths.lock);
|
|
459
|
+
const names = Trust.try(
|
|
460
|
+
() => readdirSync(directory),
|
|
461
|
+
(cause) => ({ kind: 'runtime-directory' as const, message: `cannot list sqlego owners in ${directory}: ${errorMessage(cause)}` }),
|
|
462
|
+
);
|
|
463
|
+
if (!names.ok) return names;
|
|
464
|
+
const byPid = new Map<number, { pid: number; socket: string; files: number; startedAt: number }>();
|
|
465
|
+
for (const name of names.value) {
|
|
466
|
+
if (!name.endsWith('.json')) continue;
|
|
467
|
+
const text = Trust.try(
|
|
468
|
+
() => readFileSync(path.join(directory, name), 'utf8'),
|
|
469
|
+
() => ({ kind: 'invalid' as const, message: 'unreadable' }),
|
|
350
470
|
);
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
if (
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
} else if (holder.error.kind === 'lock-unreadable') {
|
|
362
|
-
// The lock vanished between the create and the read: reclaim below and retry.
|
|
471
|
+
const json = text.ok ? fromJson(text.value) : text;
|
|
472
|
+
const meta = json.ok ? parseServerMeta(json.value) : json;
|
|
473
|
+
if (meta.ok) {
|
|
474
|
+
if (meta.value.serverVersion !== VERSION || !isProcessAlive(meta.value.pid)) continue;
|
|
475
|
+
const known = byPid.get(meta.value.pid);
|
|
476
|
+
if (known) {
|
|
477
|
+
known.files += 1;
|
|
478
|
+
known.startedAt = Math.min(known.startedAt, meta.value.startedAt);
|
|
479
|
+
} else {
|
|
480
|
+
byPid.set(meta.value.pid, { pid: meta.value.pid, socket: meta.value.socket, files: 1, startedAt: meta.value.startedAt });
|
|
363
481
|
}
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
(cause) => ({ kind: 'lock-failed' as const, message: `cannot remove stale ${lock}: ${errorMessage(cause)}` }),
|
|
367
|
-
);
|
|
368
|
-
if (!removed.ok) return removed;
|
|
482
|
+
} else if (meta.error.kind === 'invalid') {
|
|
483
|
+
// A meta being written or removed, or not one of ours: not an owner.
|
|
369
484
|
}
|
|
370
485
|
}
|
|
371
|
-
|
|
486
|
+
const owners: OwnerProcess[] = [...byPid.values()].sort((a, b) => a.files - b.files || a.startedAt - b.startedAt);
|
|
487
|
+
return Result.ok(owners);
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
private releaseSpawnLock(): void {
|
|
491
|
+
if (!this.holdsSpawnLock) return;
|
|
492
|
+
this.holdsSpawnLock = false;
|
|
493
|
+
const released = Trust.try(
|
|
494
|
+
() => rmSync(this.spawnLockPath(), { force: true }),
|
|
495
|
+
(cause) => ({ kind: 'lock-failed' as const, message: errorMessage(cause) }),
|
|
496
|
+
);
|
|
497
|
+
// A spawn lock that cannot be removed is reclaimed by the next client once this process is gone.
|
|
498
|
+
if (!released.ok && released.error.kind === 'lock-failed') this.spawnFailure = `spawn lock not released: ${released.error.message}`;
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
/** Waits until nothing answers on the file's socket (the old owner released it), or the deadline. */
|
|
502
|
+
private async waitForRelease(deadline: number): Promise<void> {
|
|
503
|
+
while (Date.now() < deadline) {
|
|
504
|
+
const socket = await tryConnect(this.paths.socket);
|
|
505
|
+
if (!socket) return;
|
|
506
|
+
socket.destroy();
|
|
507
|
+
await sleep(25);
|
|
508
|
+
}
|
|
372
509
|
}
|
|
373
510
|
|
|
374
511
|
private spawnServer() {
|
|
@@ -378,6 +515,8 @@ export class SqlegoClient {
|
|
|
378
515
|
() => {
|
|
379
516
|
const child = spawn(command, [...args, 'serve', this.paths.file, '--idle-ms', String(this.options.idleTimeoutMs ?? 30_000), ...pragmaArgs], {
|
|
380
517
|
detached: true,
|
|
518
|
+
// The owner outlives this process; on Windows it must not open a console window of its own.
|
|
519
|
+
windowsHide: true,
|
|
381
520
|
// stderr is captured (bounded) only to explain a failed start; it never
|
|
382
521
|
// keeps this process alive.
|
|
383
522
|
stdio: ['ignore', 'ignore', 'pipe'],
|
|
@@ -404,11 +543,15 @@ export class SqlegoClient {
|
|
|
404
543
|
/** The spawn never started: record why, and release the lock so another claimer can try. */
|
|
405
544
|
private onSpawnError(command: string, error: Error): void {
|
|
406
545
|
this.spawnFailure = `spawn ${command} failed: ${error.message}`;
|
|
407
|
-
const released =
|
|
546
|
+
const released = this.releaseLock();
|
|
547
|
+
if (!released.ok && released.error.kind === 'lock-failed') this.spawnFailure += `; lock not released: ${released.error.message}`;
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
private releaseLock() {
|
|
551
|
+
return Trust.try(
|
|
408
552
|
() => rmSync(this.paths.lock, { force: true }),
|
|
409
553
|
(cause) => ({ kind: 'lock-failed' as const, message: errorMessage(cause) }),
|
|
410
554
|
);
|
|
411
|
-
if (!released.ok && released.error.kind === 'lock-failed') this.spawnFailure += `; lock not released: ${released.error.message}`;
|
|
412
555
|
}
|
|
413
556
|
|
|
414
557
|
private attach(socket: net.Socket) {
|
|
@@ -508,9 +651,42 @@ export class SqlegoClient {
|
|
|
508
651
|
this.pending.clear();
|
|
509
652
|
}
|
|
510
653
|
|
|
511
|
-
|
|
512
|
-
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
/** O_EXCL create of `lock` holding this pid; a lock left by a dead process (or unreadable) is reclaimed. */
|
|
657
|
+
function claimLockAt(lock: string) {
|
|
658
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
659
|
+
const created = Trust.try(
|
|
660
|
+
() => {
|
|
661
|
+
const fd = openSync(lock, 'wx');
|
|
662
|
+
writeSync(fd, String(process.pid));
|
|
663
|
+
closeSync(fd);
|
|
664
|
+
},
|
|
665
|
+
(cause) => (errnoCode(cause) === 'EEXIST'
|
|
666
|
+
? { kind: 'lock-held' as const, message: `${lock} exists` }
|
|
667
|
+
: { kind: 'lock-failed' as const, message: `cannot create ${lock}: ${errorMessage(cause)}` }),
|
|
668
|
+
);
|
|
669
|
+
if (created.ok) return Result.ok(true);
|
|
670
|
+
if (created.error.kind === 'lock-failed') return Result.err({ kind: 'lock-failed', message: created.error.message });
|
|
671
|
+
if (created.error.kind === 'lock-held') {
|
|
672
|
+
const holder = Trust.try(
|
|
673
|
+
() => Number(readFileSync(lock, 'utf8').trim()),
|
|
674
|
+
(cause) => ({ kind: 'lock-unreadable' as const, message: errorMessage(cause) }),
|
|
675
|
+
);
|
|
676
|
+
if (holder.ok) {
|
|
677
|
+
if (Number.isFinite(holder.value) && holder.value > 0 && isProcessAlive(holder.value)) return Result.ok(false);
|
|
678
|
+
// A dead (or unrecorded) holder: reclaim the lock below.
|
|
679
|
+
} else if (holder.error.kind === 'lock-unreadable') {
|
|
680
|
+
// The lock vanished between the create and the read: reclaim below and retry.
|
|
681
|
+
}
|
|
682
|
+
const removed = Trust.try(
|
|
683
|
+
() => rmSync(lock, { force: true }),
|
|
684
|
+
(cause) => ({ kind: 'lock-failed' as const, message: `cannot remove stale ${lock}: ${errorMessage(cause)}` }),
|
|
685
|
+
);
|
|
686
|
+
if (!removed.ok) return removed;
|
|
687
|
+
}
|
|
513
688
|
}
|
|
689
|
+
return Result.ok(false);
|
|
514
690
|
}
|
|
515
691
|
|
|
516
692
|
/**
|
|
@@ -588,10 +764,21 @@ function savepointName(name: string): string {
|
|
|
588
764
|
return unwrap(Result.err({ kind: 'bad-request', message: `savepoint name must be an identifier (letters, digits, _), not "${name}"` }));
|
|
589
765
|
}
|
|
590
766
|
|
|
767
|
+
/**
|
|
768
|
+
* File names the compiled server binary may have in `bin/`, most specific
|
|
769
|
+
* last: the host build (`sqlego`, `sqlego.exe`) and the per-platform build
|
|
770
|
+
* (`sqlego-<platform>-<arch>[.exe]`, from `bun run build:bin:all`).
|
|
771
|
+
*/
|
|
772
|
+
export function platformBinaryNames(platform: NodeJS.Platform = process.platform, arch: string = process.arch): readonly string[] {
|
|
773
|
+
const suffix = platform === 'win32' ? '.exe' : '';
|
|
774
|
+
return [`sqlego${suffix}`, `sqlego-${platform}-${arch}${suffix}`];
|
|
775
|
+
}
|
|
776
|
+
|
|
591
777
|
/**
|
|
592
778
|
* How to start a server: SQLEGO_BIN if set; the compiled `sqlego` binary when
|
|
593
779
|
* running as one; the dev entry (`bun src/cli.ts`) when running from source
|
|
594
|
-
* under Bun;
|
|
780
|
+
* under Bun; the binary for this platform in the package's `bin/`; else
|
|
781
|
+
* `sqlego` on PATH.
|
|
595
782
|
*/
|
|
596
783
|
export function defaultServerCommand(): readonly string[] {
|
|
597
784
|
const configured = process.env.SQLEGO_BIN;
|
|
@@ -614,12 +801,87 @@ export function defaultServerCommand(): readonly string[] {
|
|
|
614
801
|
if (!entry.endsWith('.js') && !entry.endsWith('.ts')) return [process.execPath];
|
|
615
802
|
}
|
|
616
803
|
if (here !== null) {
|
|
617
|
-
const
|
|
618
|
-
|
|
804
|
+
for (const name of platformBinaryNames()) {
|
|
805
|
+
const local = path.join(here, '..', 'bin', name);
|
|
806
|
+
if (existsSync(local)) return [local];
|
|
807
|
+
}
|
|
619
808
|
}
|
|
620
809
|
return ['sqlego'];
|
|
621
810
|
}
|
|
622
811
|
|
|
812
|
+
/** Why a one-shot request to another owner got no result: the transport, or the owner's own error reply. */
|
|
813
|
+
type ProbeFailure = Readonly<{ kind: 'probe-failed'; message: string }>;
|
|
814
|
+
|
|
815
|
+
const probeFailed = (message: string) => Result.err<ProbeFailure>({ kind: 'probe-failed', message });
|
|
816
|
+
|
|
817
|
+
/**
|
|
818
|
+
* One request on a fresh connection to `socketPath`, parsed with `parse`.
|
|
819
|
+
* Used to ask another owner process to adopt a file; every failure (nothing
|
|
820
|
+
* listening, timeout, an error reply, a reply of the wrong shape) is one
|
|
821
|
+
* `probe-failed` with the reason, so the caller can try the next owner and
|
|
822
|
+
* still report why none took the file.
|
|
823
|
+
*/
|
|
824
|
+
function oneShot<T>(socketPath: string, body: RequestBody, parse: (input: unknown) => Result<T, Invalid>, timeoutMs: number): Promise<Result<T, ProbeFailure>> {
|
|
825
|
+
return new Promise((resolve) => {
|
|
826
|
+
const frame = encodeRequestFrame({ id: 1, ...body } as Request);
|
|
827
|
+
if (!frame.ok) {
|
|
828
|
+
if (frame.error.kind === 'bad-request' || frame.error.kind === 'encode-failed') resolve(probeFailed(frame.error.message));
|
|
829
|
+
return;
|
|
830
|
+
}
|
|
831
|
+
let buffer = '';
|
|
832
|
+
let settled = false;
|
|
833
|
+
const started = Trust.try(
|
|
834
|
+
() => {
|
|
835
|
+
const socket = new net.Socket();
|
|
836
|
+
/** Settles once: with the parsed value, or with why there is none. */
|
|
837
|
+
const finish = (value: T | null, reason: string) => {
|
|
838
|
+
if (settled) return;
|
|
839
|
+
settled = true;
|
|
840
|
+
clearTimeout(timer);
|
|
841
|
+
socket.destroy();
|
|
842
|
+
resolve(value === null ? probeFailed(reason) : Result.ok(value));
|
|
843
|
+
};
|
|
844
|
+
const timer = setTimeout(() => finish(null, `no ${body.op} reply within ${timeoutMs} ms`), timeoutMs);
|
|
845
|
+
socket.setEncoding('utf8');
|
|
846
|
+
socket.once('error', (error) => finish(null, error.message));
|
|
847
|
+
socket.once('close', () => finish(null, 'connection closed before a reply'));
|
|
848
|
+
socket.on('data', (chunk: string) => {
|
|
849
|
+
const { frames, rest } = splitFrames(buffer + chunk);
|
|
850
|
+
buffer = rest;
|
|
851
|
+
const line = frames[0];
|
|
852
|
+
if (line === undefined) return;
|
|
853
|
+
const reply = parseOneShotReply(line, parse);
|
|
854
|
+
if (reply.ok) finish(reply.value, '');
|
|
855
|
+
else if (reply.error.kind === 'probe-failed') finish(null, reply.error.message);
|
|
856
|
+
});
|
|
857
|
+
socket.connect(socketPath, () => {
|
|
858
|
+
const written = Trust.try(() => socket.write(frame.value), (cause) => ({ kind: 'socket' as const, message: errorMessage(cause) }));
|
|
859
|
+
if (!written.ok && written.error.kind === 'socket') finish(null, written.error.message);
|
|
860
|
+
});
|
|
861
|
+
},
|
|
862
|
+
(cause) => ({ kind: 'connect-failed' as const, message: errorMessage(cause) }),
|
|
863
|
+
);
|
|
864
|
+
if (!started.ok && started.error.kind === 'connect-failed') resolve(probeFailed(started.error.message));
|
|
865
|
+
});
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
/** The typed result in one reply frame, or why there is none: a malformed frame, an error reply, or the wrong shape. */
|
|
869
|
+
function parseOneShotReply<T>(line: string, parse: (input: unknown) => Result<T, Invalid>): Result<T, ProbeFailure> {
|
|
870
|
+
const json = fromJson(line);
|
|
871
|
+
const response = json.ok ? parseResponse(json.value) : json;
|
|
872
|
+
if (!response.ok) {
|
|
873
|
+
if (response.error.kind === 'invalid') return probeFailed(`malformed reply: ${response.error.message}`);
|
|
874
|
+
const unhandled: never = response.error.kind;
|
|
875
|
+
return unhandled;
|
|
876
|
+
}
|
|
877
|
+
if (!response.value.ok) return probeFailed(`${response.value.error.code}: ${response.value.error.message}`);
|
|
878
|
+
const parsed = parse(response.value.result);
|
|
879
|
+
if (parsed.ok) return parsed;
|
|
880
|
+
if (parsed.error.kind === 'invalid') return probeFailed(`unexpected reply: ${parsed.error.message}`);
|
|
881
|
+
const unhandled: never = parsed.error.kind;
|
|
882
|
+
return unhandled;
|
|
883
|
+
}
|
|
884
|
+
|
|
623
885
|
/** Resolves the connected socket, or null when nothing is listening (or the attempt could not start). */
|
|
624
886
|
function tryConnect(socketPath: string): Promise<net.Socket | null> {
|
|
625
887
|
return new Promise((resolve) => {
|
package/src/index.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
export {
|
|
2
|
-
|
|
1
|
+
export {
|
|
2
|
+
DEFAULT_MAX_OWNERS, SqlegoClient, SqlegoClientError, SqlegoTransaction, defaultServerCommand, platformBinaryNames, type BeginOptions, type ClientOptions,
|
|
3
|
+
} from './client.ts';
|
|
4
|
+
export { USES_NAMED_PIPES, isNamedPipe, pathsFor, runtimeDirectory, canonicalFile, type FilePaths, type ServerMeta } from './paths.ts';
|
|
3
5
|
export {
|
|
4
6
|
PROTOCOL_VERSION,
|
|
5
7
|
type SqlParams,
|
package/src/paths.ts
CHANGED
|
@@ -50,6 +50,7 @@ export function resolveCanonicalFile(file: string) {
|
|
|
50
50
|
export type FilePaths = Readonly<{
|
|
51
51
|
file: string;
|
|
52
52
|
key: string;
|
|
53
|
+
/** Unix domain socket path, or a `\\.\pipe\` named pipe on Windows (see `isNamedPipe`). */
|
|
53
54
|
socket: string;
|
|
54
55
|
lock: string;
|
|
55
56
|
meta: string;
|
|
@@ -58,6 +59,18 @@ export type FilePaths = Readonly<{
|
|
|
58
59
|
/** macOS caps `sun_path` at 104 bytes (Linux 108); leave headroom. */
|
|
59
60
|
const MAX_SOCKET_PATH_BYTES = 100;
|
|
60
61
|
|
|
62
|
+
/** Windows has no Unix domain sockets; the local transport there is a named pipe. */
|
|
63
|
+
export const USES_NAMED_PIPES: boolean = process.platform === 'win32';
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* True for a named-pipe endpoint. A pipe is not a file: it never exists on
|
|
67
|
+
* disk before the server listens, cannot be `rm`ed, and vanishes with the
|
|
68
|
+
* listener — callers skip the socket-file housekeeping for one.
|
|
69
|
+
*/
|
|
70
|
+
export function isNamedPipe(socket: string): boolean {
|
|
71
|
+
return /^\\\\[.?]\\pipe\\/i.test(socket);
|
|
72
|
+
}
|
|
73
|
+
|
|
61
74
|
export function resolvePaths(file: string) {
|
|
62
75
|
const canonical = resolveCanonicalFile(file);
|
|
63
76
|
if (!canonical.ok) return canonical;
|
|
@@ -66,14 +79,19 @@ export function resolvePaths(file: string) {
|
|
|
66
79
|
const derived = Trust.try(
|
|
67
80
|
() => {
|
|
68
81
|
const key = createHash('sha1').update(canonical.value).digest('hex').slice(0, 16);
|
|
69
|
-
|
|
82
|
+
// The endpoint. Unix: `<runtime dir>/<key>.sock`. Windows:
|
|
83
|
+
// `\\.\pipe\sqlego-<dir hash>-<key>` — the pipe namespace is flat and
|
|
84
|
+
// shared machine-wide, so the runtime directory (per user, or per test)
|
|
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`);
|
|
70
88
|
return { key, socket, socketBytes: Buffer.byteLength(socket) };
|
|
71
89
|
},
|
|
72
90
|
(cause) => ({ kind: 'hash-failed', message: `cannot hash ${canonical.value}: ${errorMessage(cause)}` }),
|
|
73
91
|
);
|
|
74
92
|
if (!derived.ok) return derived;
|
|
75
93
|
const { key, socket, socketBytes } = derived.value;
|
|
76
|
-
if (socketBytes > MAX_SOCKET_PATH_BYTES) {
|
|
94
|
+
if (!USES_NAMED_PIPES && socketBytes > MAX_SOCKET_PATH_BYTES) {
|
|
77
95
|
return Result.err({
|
|
78
96
|
kind: 'socket-path-too-long',
|
|
79
97
|
message: `sqlego runtime directory too deep for a Unix socket (${socketBytes} bytes > ${MAX_SOCKET_PATH_BYTES}): ${socket}. `
|