@noego/sqlego 0.0.0-stage → 0.0.1-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 +128 -2
- package/bin/sqlego +4 -0
- package/dist/client.d.ts +125 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +870 -0
- package/dist/paths.d.ts +70 -0
- package/dist/protocol.d.ts +287 -0
- package/dist/version.d.ts +23 -0
- package/package.json +43 -4
- package/src/cli.ts +314 -0
- package/src/client.ts +621 -0
- package/src/index.ts +18 -0
- package/src/paths.ts +154 -0
- package/src/protocol.ts +477 -0
- package/src/server.ts +723 -0
- package/src/version.ts +78 -0
package/src/client.ts
ADDED
|
@@ -0,0 +1,621 @@
|
|
|
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
|
+
parseBeginResult,
|
|
15
|
+
parseHelloResult,
|
|
16
|
+
parseQueryResult,
|
|
17
|
+
parseResponse,
|
|
18
|
+
parseRunResult,
|
|
19
|
+
parseStatusResult,
|
|
20
|
+
parseStopResult,
|
|
21
|
+
parseTransactionEndResult,
|
|
22
|
+
splitFrames,
|
|
23
|
+
type BatchResult,
|
|
24
|
+
type BeginResult,
|
|
25
|
+
type ErrorCode,
|
|
26
|
+
type HelloResult,
|
|
27
|
+
type Request,
|
|
28
|
+
type RunResult,
|
|
29
|
+
type SqlParams,
|
|
30
|
+
type SqlRow,
|
|
31
|
+
type Statement,
|
|
32
|
+
type StatusResult,
|
|
33
|
+
type TransactionMode,
|
|
34
|
+
} from './protocol.ts';
|
|
35
|
+
import { isProcessAlive, resolvePaths, type FilePaths } from './paths.ts';
|
|
36
|
+
import { VERSION } from './version.ts';
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Runs in Node and Bun alike (node:net, node:child_process only; no SQLite
|
|
40
|
+
* dependency). Connects to the file's owner, spawning one when none is
|
|
41
|
+
* listening. The sequence is always: connect → else claim lock → spawn → wait
|
|
42
|
+
* for the socket → connect. A claimer that loses the lock waits for the
|
|
43
|
+
* winner's socket instead.
|
|
44
|
+
*/
|
|
45
|
+
export type ClientOptions = Readonly<{
|
|
46
|
+
/** Spawn a server when none is listening. Default true. */
|
|
47
|
+
spawn?: boolean;
|
|
48
|
+
/** How the server is started when needed; see `serverCommand`. */
|
|
49
|
+
serverCommand?: readonly string[];
|
|
50
|
+
/** Idle timeout passed to a spawned server. Default 30 000. */
|
|
51
|
+
idleTimeoutMs?: number;
|
|
52
|
+
/** Pragmas a spawned server applies on open (`--pragma`), replacing its defaults. Ignored when a server is already running. */
|
|
53
|
+
serverPragmas?: readonly string[];
|
|
54
|
+
/** Total time to obtain a connection, including spawn. Default 10 000. */
|
|
55
|
+
connectTimeoutMs?: number;
|
|
56
|
+
/** Per-request timeout. Default 60 000. */
|
|
57
|
+
requestTimeoutMs?: number;
|
|
58
|
+
}>;
|
|
59
|
+
|
|
60
|
+
export type BeginOptions = Readonly<{
|
|
61
|
+
/** `immediate` takes the write lock at `begin`; `deferred` (default) on the first write. */
|
|
62
|
+
mode?: TransactionMode;
|
|
63
|
+
/**
|
|
64
|
+
* Roll the transaction back when no request for it arrives within this
|
|
65
|
+
* long; each request renews it. The server caps it at its own lease.
|
|
66
|
+
*/
|
|
67
|
+
leaseMs?: number;
|
|
68
|
+
}>;
|
|
69
|
+
|
|
70
|
+
/** A savepoint name is spliced into SQL text, so it must be a bare identifier. */
|
|
71
|
+
const SAVEPOINT_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
72
|
+
|
|
73
|
+
// No TypeScript parameter properties anywhere in the client: Node's
|
|
74
|
+
// strip-only type loading (`--experimental-strip-types`) rejects them, and the
|
|
75
|
+
// client must load in plain Node without a build step.
|
|
76
|
+
export class SqlegoClientError extends Error {
|
|
77
|
+
readonly code: string;
|
|
78
|
+
|
|
79
|
+
constructor(code: string, message: string) {
|
|
80
|
+
super(message);
|
|
81
|
+
this.code = code;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Why a request did not get a result: the transport's own failures plus every error the server reports. */
|
|
86
|
+
type RequestFailure = Readonly<{
|
|
87
|
+
kind: 'not-connected' | 'closed' | 'socket' | 'request-timeout' | 'protocol' | 'encode-failed' | ErrorCode;
|
|
88
|
+
message: string;
|
|
89
|
+
}>;
|
|
90
|
+
|
|
91
|
+
/** Any failure the client reports: a literal `kind` that becomes `SqlegoClientError.code`. */
|
|
92
|
+
type ClientFailure = Readonly<{ kind: string; message: string }>;
|
|
93
|
+
|
|
94
|
+
/** What a reply parser in protocol.ts reports when the reply has the wrong shape. */
|
|
95
|
+
type Invalid = Readonly<{ kind: 'invalid'; message: string }>;
|
|
96
|
+
|
|
97
|
+
type Waiter = { settle: (outcome: Result<unknown, RequestFailure>) => void; timer: ReturnType<typeof setTimeout> };
|
|
98
|
+
|
|
99
|
+
/** `Omit` distributed over the request union so each op keeps its own fields. */
|
|
100
|
+
type RequestBody = Request extends infer Variant ? (Variant extends Request ? Omit<Variant, 'id'> : never) : never;
|
|
101
|
+
|
|
102
|
+
/** A stop reply may never arrive when the server drops connections first; wait briefly, not the full request timeout. */
|
|
103
|
+
const STOP_TIMEOUT_MS = 1_000;
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* The edge of the client: internal code returns `Result`; the public API's
|
|
107
|
+
* contract is a `SqlegoClientError` whose `code` is the failure's kind.
|
|
108
|
+
*/
|
|
109
|
+
function unwrap<T>(outcome: Result<T, ClientFailure>): T {
|
|
110
|
+
if (outcome.ok) return outcome.value;
|
|
111
|
+
//trust:accept public API contract: SqlegoClient methods reject with SqlegoClientError(code, message)
|
|
112
|
+
throw new SqlegoClientError(outcome.error.kind, outcome.error.message);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* `query<Row>` lets the caller name the shape of its own SQL's rows, as any
|
|
117
|
+
* typed SQL client does: sqlego checks that each row is an object (in
|
|
118
|
+
* `parseQueryResult`), and the column types are the caller's declaration.
|
|
119
|
+
*/
|
|
120
|
+
//trust:validator_function
|
|
121
|
+
function callerRows<Row extends SqlRow>(rows: SqlRow[]): Row[] {
|
|
122
|
+
return rows as Row[];
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export class SqlegoClient {
|
|
126
|
+
readonly paths: FilePaths;
|
|
127
|
+
private socket: net.Socket | null = null;
|
|
128
|
+
private buffer = '';
|
|
129
|
+
private nextId = 1;
|
|
130
|
+
private readonly pending = new Map<number, Waiter>();
|
|
131
|
+
private hello: HelloResult | null = null;
|
|
132
|
+
/** Why the server this client spawned did not come up, if it did not. */
|
|
133
|
+
private spawnFailure: string | null = null;
|
|
134
|
+
private readonly options: ClientOptions;
|
|
135
|
+
|
|
136
|
+
private constructor(paths: FilePaths, options: ClientOptions) {
|
|
137
|
+
this.paths = paths;
|
|
138
|
+
this.options = options;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
static async connect(file: string, options: ClientOptions = {}): Promise<SqlegoClient> {
|
|
142
|
+
const paths = resolvePaths(file);
|
|
143
|
+
if (!paths.ok) {
|
|
144
|
+
//trust:accept public API contract: an unusable path rejects with an Error, as pathsFor does
|
|
145
|
+
throw new Error(paths.error.message);
|
|
146
|
+
}
|
|
147
|
+
const client = new SqlegoClient(paths.value, options);
|
|
148
|
+
unwrap(await client.open());
|
|
149
|
+
return client;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
get server(): HelloResult {
|
|
153
|
+
if (this.hello) return this.hello;
|
|
154
|
+
return unwrap(Result.err({ kind: 'not-connected', message: 'client is not connected' }));
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async query<Row extends SqlRow = SqlRow>(sql: string, params?: SqlParams): Promise<Row[]> {
|
|
158
|
+
const result = unwrap(await this.call({ op: 'query', sql, params }, parseQueryResult));
|
|
159
|
+
return callerRows<Row>(result.rows);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
async run(sql: string, params?: SqlParams): Promise<RunResult> {
|
|
163
|
+
return unwrap(await this.call({ op: 'run', sql, params }, parseRunResult));
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** One transaction; the whole batch rolls back on the first failure. */
|
|
167
|
+
async batch(statements: readonly Statement[]): Promise<BatchResult['results']> {
|
|
168
|
+
const result = unwrap(await this.call({ op: 'batch', statements }, parseBatchResult));
|
|
169
|
+
return result.results;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Opens a transaction held across requests. It is bound to this connection
|
|
174
|
+
* and rolled back by the server if the connection drops, the lease runs out
|
|
175
|
+
* between requests, or the server's hard cap is reached; other clients'
|
|
176
|
+
* statements wait until it ends. End it with `commit` or `rollback`.
|
|
177
|
+
*/
|
|
178
|
+
async begin(options: BeginOptions = {}): Promise<SqlegoTransaction> {
|
|
179
|
+
const opened = unwrap(await this.call({ op: 'begin', mode: options.mode, leaseMs: options.leaseMs }, parseBeginResult));
|
|
180
|
+
return new SqlegoTransaction(this, opened);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Runs `work` in a transaction: commits when it resolves, rolls back when it rejects (and rethrows). */
|
|
184
|
+
async transaction<T>(work: (tx: SqlegoTransaction) => Promise<T>, options: BeginOptions = {}): Promise<T> {
|
|
185
|
+
const tx = await this.begin(options);
|
|
186
|
+
const outcome = await Trust.tryAsync(() => work(tx), (cause) => ({ kind: 'work-failed' as const, cause }));
|
|
187
|
+
if (outcome.ok) {
|
|
188
|
+
await tx.commit();
|
|
189
|
+
return outcome.value;
|
|
190
|
+
}
|
|
191
|
+
// The work's own error is what the caller must see; a rollback that
|
|
192
|
+
// fails (the server already rolled back an expired transaction) adds nothing.
|
|
193
|
+
await tx.rollback().catch(() => undefined);
|
|
194
|
+
//trust:accept public API contract: transaction(work) rethrows the work's own rejection after rolling back
|
|
195
|
+
throw outcome.error.cause;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** @internal Statements inside a transaction; `SqlegoTransaction` is the public face. */
|
|
199
|
+
async transactionQuery<Row extends SqlRow>(txId: number, sql: string, params?: SqlParams): Promise<Row[]> {
|
|
200
|
+
const result = unwrap(await this.call({ op: 'query', sql, params, txId }, parseQueryResult));
|
|
201
|
+
return callerRows<Row>(result.rows);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** @internal */
|
|
205
|
+
async transactionRun(txId: number, sql: string, params?: SqlParams): Promise<RunResult> {
|
|
206
|
+
return unwrap(await this.call({ op: 'run', sql, params, txId }, parseRunResult));
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** @internal */
|
|
210
|
+
async transactionEnd(txId: number, how: 'commit' | 'rollback'): Promise<void> {
|
|
211
|
+
unwrap(await this.call({ op: how, txId }, parseTransactionEndResult));
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
async status(): Promise<StatusResult> {
|
|
215
|
+
return unwrap(await this.call({ op: 'status' }, parseStatusResult));
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** Asks the server to shut down; the connection closes as a consequence. */
|
|
219
|
+
async stop(): Promise<void> {
|
|
220
|
+
unwrap(await this.stopServer());
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
async close(): Promise<void> {
|
|
224
|
+
const socket = this.socket;
|
|
225
|
+
this.socket = null;
|
|
226
|
+
if (!socket || socket.destroyed) return;
|
|
227
|
+
await new Promise<void>((resolve) => endSocket(socket, resolve));
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
private async stopServer() {
|
|
231
|
+
const stopped = await this.call({ op: 'stop' }, parseStopResult, STOP_TIMEOUT_MS);
|
|
232
|
+
if (!stopped.ok) {
|
|
233
|
+
switch (stopped.error.kind) {
|
|
234
|
+
// The server may drop the connection before the reply lands (another
|
|
235
|
+
// client stopped it first); that is the outcome we asked for.
|
|
236
|
+
case 'closed':
|
|
237
|
+
case 'not-connected':
|
|
238
|
+
case 'socket':
|
|
239
|
+
case 'request-timeout':
|
|
240
|
+
break;
|
|
241
|
+
default:
|
|
242
|
+
return stopped;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
await this.close();
|
|
246
|
+
return Result.ok(undefined);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
private async open() {
|
|
250
|
+
const deadline = Date.now() + (this.options.connectTimeoutMs ?? 10_000);
|
|
251
|
+
const socket = await this.connectOrSpawn(deadline);
|
|
252
|
+
if (!socket.ok) return socket;
|
|
253
|
+
const attached = this.attach(socket.value);
|
|
254
|
+
if (!attached.ok) return attached;
|
|
255
|
+
const hello = await this.call({ op: 'hello', clientVersion: VERSION, protocol: PROTOCOL_VERSION }, parseHelloResult);
|
|
256
|
+
if (!hello.ok) return hello;
|
|
257
|
+
if (hello.value.serverVersion === VERSION || this.options.spawn === false) {
|
|
258
|
+
this.hello = hello.value;
|
|
259
|
+
return Result.ok(undefined);
|
|
260
|
+
}
|
|
261
|
+
// Stale server from an older build: drain it and start a fresh one.
|
|
262
|
+
const stopped = await this.stopServer();
|
|
263
|
+
if (!stopped.ok) return stopped;
|
|
264
|
+
await this.waitForExit(hello.value.pid, deadline);
|
|
265
|
+
const fresh = await this.connectOrSpawn(deadline);
|
|
266
|
+
if (!fresh.ok) return fresh;
|
|
267
|
+
const reattached = this.attach(fresh.value);
|
|
268
|
+
if (!reattached.ok) return reattached;
|
|
269
|
+
const freshHello = await this.call({ op: 'hello', clientVersion: VERSION, protocol: PROTOCOL_VERSION }, parseHelloResult);
|
|
270
|
+
if (!freshHello.ok) return freshHello;
|
|
271
|
+
this.hello = freshHello.value;
|
|
272
|
+
return Result.ok(undefined);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
private async connectOrSpawn(deadline: number) {
|
|
276
|
+
const first = await tryConnect(this.paths.socket);
|
|
277
|
+
if (first) return Result.ok(first);
|
|
278
|
+
if (this.options.spawn === false) {
|
|
279
|
+
return Result.err({ kind: 'not-running', message: `no sqlego server for ${this.paths.file}` });
|
|
280
|
+
}
|
|
281
|
+
const claimed = this.claimLock();
|
|
282
|
+
if (!claimed.ok) return claimed;
|
|
283
|
+
if (claimed.value) {
|
|
284
|
+
const spawned = this.spawnServer();
|
|
285
|
+
if (!spawned.ok) return spawned;
|
|
286
|
+
}
|
|
287
|
+
// Claimer or not, the socket appears when the winner is listening.
|
|
288
|
+
while (Date.now() < deadline) {
|
|
289
|
+
const socket = await tryConnect(this.paths.socket);
|
|
290
|
+
if (socket) return Result.ok(socket);
|
|
291
|
+
await sleep(25);
|
|
292
|
+
}
|
|
293
|
+
const cause = this.spawnFailure ? ` (${this.spawnFailure})` : '';
|
|
294
|
+
return Result.err({ kind: 'connect-timeout', message: `no sqlego server became reachable for ${this.paths.file}${cause}` });
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** O_EXCL create; a lock left by a dead process (or unreadable) is reclaimed. */
|
|
298
|
+
private claimLock() {
|
|
299
|
+
const lock = this.paths.lock;
|
|
300
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
301
|
+
const created = Trust.try(
|
|
302
|
+
() => {
|
|
303
|
+
const fd = openSync(lock, 'wx');
|
|
304
|
+
writeSync(fd, String(process.pid));
|
|
305
|
+
closeSync(fd);
|
|
306
|
+
},
|
|
307
|
+
(cause) => (errnoCode(cause) === 'EEXIST'
|
|
308
|
+
? { kind: 'lock-held' as const, message: `${lock} exists` }
|
|
309
|
+
: { kind: 'lock-failed' as const, message: `cannot create ${lock}: ${errorMessage(cause)}` }),
|
|
310
|
+
);
|
|
311
|
+
if (created.ok) return Result.ok(true);
|
|
312
|
+
if (created.error.kind === 'lock-failed') return Result.err({ kind: 'lock-failed', message: created.error.message });
|
|
313
|
+
if (created.error.kind === 'lock-held') {
|
|
314
|
+
const holder = Trust.try(
|
|
315
|
+
() => Number(readFileSync(lock, 'utf8').trim()),
|
|
316
|
+
(cause) => ({ kind: 'lock-unreadable' as const, message: errorMessage(cause) }),
|
|
317
|
+
);
|
|
318
|
+
if (holder.ok) {
|
|
319
|
+
if (Number.isFinite(holder.value) && holder.value > 0 && isProcessAlive(holder.value)) return Result.ok(false);
|
|
320
|
+
// A dead (or unrecorded) holder: reclaim the lock below.
|
|
321
|
+
} else if (holder.error.kind === 'lock-unreadable') {
|
|
322
|
+
// The lock vanished between the create and the read: reclaim below and retry.
|
|
323
|
+
}
|
|
324
|
+
const removed = Trust.try(
|
|
325
|
+
() => rmSync(lock, { force: true }),
|
|
326
|
+
(cause) => ({ kind: 'lock-failed' as const, message: `cannot remove stale ${lock}: ${errorMessage(cause)}` }),
|
|
327
|
+
);
|
|
328
|
+
if (!removed.ok) return removed;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
return Result.ok(false);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
private spawnServer() {
|
|
335
|
+
const [command, ...args] = this.options.serverCommand ?? defaultServerCommand();
|
|
336
|
+
const pragmaArgs = (this.options.serverPragmas ?? []).flatMap((pragma) => ['--pragma', pragma]);
|
|
337
|
+
return Trust.try(
|
|
338
|
+
() => {
|
|
339
|
+
const child = spawn(command, [...args, 'serve', this.paths.file, '--idle-ms', String(this.options.idleTimeoutMs ?? 30_000), ...pragmaArgs], {
|
|
340
|
+
detached: true,
|
|
341
|
+
// stderr is captured (bounded) only to explain a failed start; it never
|
|
342
|
+
// keeps this process alive.
|
|
343
|
+
stdio: ['ignore', 'ignore', 'pipe'],
|
|
344
|
+
env: { ...process.env, SQLEGO_CLAIMED_BY: String(process.pid) },
|
|
345
|
+
});
|
|
346
|
+
let stderr = '';
|
|
347
|
+
child.stderr?.on('data', (chunk: Buffer) => { if (stderr.length < 2_000) stderr += chunk.toString(); });
|
|
348
|
+
// The stderr pipe is a net.Socket at runtime, but typed as a Readable,
|
|
349
|
+
// which declares no unref(); feature-test it on `unknown`.
|
|
350
|
+
const stderrPipe: unknown = child.stderr;
|
|
351
|
+
if (typeof stderrPipe === 'object' && stderrPipe !== null && 'unref' in stderrPipe && typeof stderrPipe.unref === 'function') {
|
|
352
|
+
stderrPipe.unref();
|
|
353
|
+
}
|
|
354
|
+
child.on('error', (error) => this.onSpawnError(command, error));
|
|
355
|
+
child.on('exit', (code, signal) => {
|
|
356
|
+
if (!this.hello) this.spawnFailure = `server exited before listening (code ${code}, signal ${signal})${stderr ? `: ${stderr.trim()}` : ''}`;
|
|
357
|
+
});
|
|
358
|
+
child.unref();
|
|
359
|
+
},
|
|
360
|
+
(cause) => ({ kind: 'spawn-failed' as const, message: `spawn ${command} failed: ${errorMessage(cause)}` }),
|
|
361
|
+
);
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** The spawn never started: record why, and release the lock so another claimer can try. */
|
|
365
|
+
private onSpawnError(command: string, error: Error): void {
|
|
366
|
+
this.spawnFailure = `spawn ${command} failed: ${error.message}`;
|
|
367
|
+
const released = Trust.try(
|
|
368
|
+
() => rmSync(this.paths.lock, { force: true }),
|
|
369
|
+
(cause) => ({ kind: 'lock-failed' as const, message: errorMessage(cause) }),
|
|
370
|
+
);
|
|
371
|
+
if (!released.ok && released.error.kind === 'lock-failed') this.spawnFailure += `; lock not released: ${released.error.message}`;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
private attach(socket: net.Socket) {
|
|
375
|
+
this.socket = socket;
|
|
376
|
+
this.buffer = '';
|
|
377
|
+
return Trust.try(
|
|
378
|
+
() => {
|
|
379
|
+
socket.setEncoding('utf8');
|
|
380
|
+
socket.on('data', (chunk: string) => this.onData(chunk));
|
|
381
|
+
// Peer FIN (server stopping): tear down now rather than lingering half-open.
|
|
382
|
+
socket.on('end', () => socket.destroy());
|
|
383
|
+
socket.on('close', () => this.onClose(socket));
|
|
384
|
+
socket.on('error', (error) => this.settleAll({ kind: 'socket', message: error.message }));
|
|
385
|
+
},
|
|
386
|
+
(cause) => ({ kind: 'socket' as const, message: errorMessage(cause) }),
|
|
387
|
+
);
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
private onClose(socket: net.Socket): void {
|
|
391
|
+
if (this.socket === socket) this.socket = null;
|
|
392
|
+
this.settleAll({ kind: 'closed', message: 'connection closed' });
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
private onData(chunk: string): void {
|
|
396
|
+
const { frames, rest } = splitFrames(this.buffer + chunk);
|
|
397
|
+
this.buffer = rest;
|
|
398
|
+
for (const frame of frames) {
|
|
399
|
+
const json = fromJson(frame);
|
|
400
|
+
const parsed = json.ok ? parseResponse(json.value) : json;
|
|
401
|
+
if (!parsed.ok) {
|
|
402
|
+
// A corrupt frame means the stream is unrecoverable; fail every waiter
|
|
403
|
+
// and drop the socket rather than throwing out of a 'data' handler.
|
|
404
|
+
if (parsed.error.kind === 'invalid') {
|
|
405
|
+
this.buffer = '';
|
|
406
|
+
this.settleAll({ kind: 'protocol', message: `malformed frame from server: ${parsed.error.message}` });
|
|
407
|
+
this.socket?.destroy();
|
|
408
|
+
}
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
const response = parsed.value;
|
|
412
|
+
const waiter = this.pending.get(response.id);
|
|
413
|
+
if (!waiter) continue;
|
|
414
|
+
this.pending.delete(response.id);
|
|
415
|
+
clearTimeout(waiter.timer);
|
|
416
|
+
waiter.settle(response.ok ? Result.ok(response.result) : Result.err({ kind: response.error.code, message: response.error.message }));
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* One request whose reply `parse` turns from `unknown` into its typed
|
|
422
|
+
* result; a reply that does not parse is a `protocol` failure.
|
|
423
|
+
*/
|
|
424
|
+
private async call<T>(body: RequestBody, parse: (input: unknown) => Result<T, Invalid>, timeoutMs?: number) {
|
|
425
|
+
const reply = await this.request(body, timeoutMs);
|
|
426
|
+
if (!reply.ok) return reply;
|
|
427
|
+
const parsed = parse(reply.value);
|
|
428
|
+
if (parsed.ok) return parsed;
|
|
429
|
+
if (parsed.error.kind === 'invalid') {
|
|
430
|
+
return Result.err<RequestFailure>({ kind: 'protocol', message: `unexpected ${body.op} reply: ${parsed.error.message}` });
|
|
431
|
+
}
|
|
432
|
+
const unhandled: never = parsed.error.kind;
|
|
433
|
+
return unhandled;
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/** Never rejects: every outcome, including transport failures, is a `Result`. The reply is `unknown` until parsed. */
|
|
437
|
+
private request(body: RequestBody, timeoutMs = this.options.requestTimeoutMs ?? 60_000): Promise<Result<unknown, RequestFailure>> {
|
|
438
|
+
const socket = this.socket;
|
|
439
|
+
if (!socket || socket.destroyed) {
|
|
440
|
+
return Promise.resolve(Result.err({ kind: 'not-connected', message: 'client is not connected' }));
|
|
441
|
+
}
|
|
442
|
+
const id = this.nextId++;
|
|
443
|
+
const frame = encodeFrame({ id, ...body } as Request);
|
|
444
|
+
if (!frame.ok) return Promise.resolve(frame);
|
|
445
|
+
return new Promise<Result<unknown, RequestFailure>>((settle) => {
|
|
446
|
+
const timer = setTimeout(() => {
|
|
447
|
+
this.pending.delete(id);
|
|
448
|
+
settle(Result.err({ kind: 'request-timeout', message: `request ${id} (${body.op}) timed out` }));
|
|
449
|
+
}, timeoutMs);
|
|
450
|
+
this.pending.set(id, { settle, timer });
|
|
451
|
+
const written = Trust.try(
|
|
452
|
+
() => socket.write(frame.value),
|
|
453
|
+
(cause) => ({ kind: 'socket' as const, message: errorMessage(cause) }),
|
|
454
|
+
);
|
|
455
|
+
if (!written.ok) {
|
|
456
|
+
this.pending.delete(id);
|
|
457
|
+
clearTimeout(timer);
|
|
458
|
+
settle(written);
|
|
459
|
+
}
|
|
460
|
+
});
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
private settleAll(failure: RequestFailure): void {
|
|
464
|
+
for (const waiter of this.pending.values()) {
|
|
465
|
+
clearTimeout(waiter.timer);
|
|
466
|
+
waiter.settle(Result.err(failure));
|
|
467
|
+
}
|
|
468
|
+
this.pending.clear();
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
private async waitForExit(pid: number, deadline: number): Promise<void> {
|
|
472
|
+
while (Date.now() < deadline && isProcessAlive(pid)) await sleep(25);
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/**
|
|
477
|
+
* One open transaction on a `SqlegoClient`. Every method rejects with a
|
|
478
|
+
* `SqlegoClientError` whose code is `tx-expired` once the server has rolled
|
|
479
|
+
* it back (lease, hard cap, disconnect) and `tx-invalid` after it ended.
|
|
480
|
+
*/
|
|
481
|
+
export class SqlegoTransaction {
|
|
482
|
+
readonly id: number;
|
|
483
|
+
/** The lease the server granted, which may be shorter than requested. */
|
|
484
|
+
readonly leaseMs: number;
|
|
485
|
+
/** The server's hard cap on this transaction's life. */
|
|
486
|
+
readonly maxDurationMs: number;
|
|
487
|
+
private readonly client: SqlegoClient;
|
|
488
|
+
private ended = false;
|
|
489
|
+
|
|
490
|
+
constructor(client: SqlegoClient, opened: BeginResult) {
|
|
491
|
+
this.client = client;
|
|
492
|
+
this.id = opened.txId;
|
|
493
|
+
this.leaseMs = opened.leaseMs;
|
|
494
|
+
this.maxDurationMs = opened.maxDurationMs;
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
/** True once `commit` or `rollback` has been sent; the server may also have ended it on its own. */
|
|
498
|
+
get closed(): boolean {
|
|
499
|
+
return this.ended;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
query<Row extends SqlRow = SqlRow>(sql: string, params?: SqlParams): Promise<Row[]> {
|
|
503
|
+
return this.client.transactionQuery<Row>(this.id, sql, params);
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
run(sql: string, params?: SqlParams): Promise<RunResult> {
|
|
507
|
+
return this.client.transactionRun(this.id, sql, params);
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/** `SAVEPOINT name`: a nested scope that `rollbackTo` can undo and `release` folds into the transaction. */
|
|
511
|
+
async savepoint(name: string): Promise<void> {
|
|
512
|
+
await this.run(`SAVEPOINT ${savepointName(name)}`);
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
async release(name: string): Promise<void> {
|
|
516
|
+
await this.run(`RELEASE SAVEPOINT ${savepointName(name)}`);
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/** Undoes everything since the savepoint; the savepoint itself stays until released. */
|
|
520
|
+
async rollbackTo(name: string): Promise<void> {
|
|
521
|
+
await this.run(`ROLLBACK TO SAVEPOINT ${savepointName(name)}`);
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
async commit(): Promise<void> {
|
|
525
|
+
this.ended = true;
|
|
526
|
+
await this.client.transactionEnd(this.id, 'commit');
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
async rollback(): Promise<void> {
|
|
530
|
+
this.ended = true;
|
|
531
|
+
await this.client.transactionEnd(this.id, 'rollback');
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/** A savepoint name is spliced into SQL, so only an identifier is accepted. */
|
|
536
|
+
function savepointName(name: string): string {
|
|
537
|
+
if (SAVEPOINT_NAME.test(name)) return name;
|
|
538
|
+
return unwrap(Result.err({ kind: 'bad-request', message: `savepoint name must be an identifier (letters, digits, _), not "${name}"` }));
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* How to start a server: SQLEGO_BIN if set; the compiled `sqlego` binary when
|
|
543
|
+
* running as one; the dev entry (`bun src/cli.ts`) when running from source
|
|
544
|
+
* under Bun; else `sqlego` on PATH.
|
|
545
|
+
*/
|
|
546
|
+
export function defaultServerCommand(): readonly string[] {
|
|
547
|
+
const configured = process.env.SQLEGO_BIN;
|
|
548
|
+
if (configured && configured.length > 0) return [configured];
|
|
549
|
+
const entry = process.argv[1] ?? '';
|
|
550
|
+
const located = Trust.try(
|
|
551
|
+
() => path.dirname(fileURLToPath(import.meta.url)),
|
|
552
|
+
(cause) => ({ kind: 'module-path' as const, message: errorMessage(cause) }),
|
|
553
|
+
);
|
|
554
|
+
// A module that cannot locate itself has no sibling cli.ts or bin/ to offer.
|
|
555
|
+
let here: string | null = null;
|
|
556
|
+
if (located.ok) here = located.value;
|
|
557
|
+
else if (located.error.kind === 'module-path') here = null;
|
|
558
|
+
if (process.versions.bun) {
|
|
559
|
+
if (entry.endsWith('cli.ts')) return [process.execPath, entry];
|
|
560
|
+
if (entry.endsWith('.ts') && here !== null) {
|
|
561
|
+
const cli = path.join(here, 'cli.ts');
|
|
562
|
+
if (existsSync(cli)) return [process.execPath, cli];
|
|
563
|
+
}
|
|
564
|
+
if (!entry.endsWith('.js') && !entry.endsWith('.ts')) return [process.execPath];
|
|
565
|
+
}
|
|
566
|
+
if (here !== null) {
|
|
567
|
+
const local = path.join(here, '..', 'bin', 'sqlego');
|
|
568
|
+
if (existsSync(local)) return [local];
|
|
569
|
+
}
|
|
570
|
+
return ['sqlego'];
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
/** Resolves the connected socket, or null when nothing is listening (or the attempt could not start). */
|
|
574
|
+
function tryConnect(socketPath: string): Promise<net.Socket | null> {
|
|
575
|
+
return new Promise((resolve) => {
|
|
576
|
+
// Listeners first: Bun's node:net can emit `error` synchronously from
|
|
577
|
+
// connect() when the socket file is absent.
|
|
578
|
+
const started = Trust.try(
|
|
579
|
+
() => {
|
|
580
|
+
const socket = new net.Socket();
|
|
581
|
+
socket.once('connect', () => resolve(connected(socket)));
|
|
582
|
+
socket.once('error', () => { socket.destroy(); resolve(null); });
|
|
583
|
+
socket.connect(socketPath);
|
|
584
|
+
},
|
|
585
|
+
(cause) => ({ kind: 'connect-failed' as const, message: errorMessage(cause) }),
|
|
586
|
+
);
|
|
587
|
+
if (!started.ok && started.error.kind === 'connect-failed') resolve(null);
|
|
588
|
+
});
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/** The connect-time error listener must go, or a later error would destroy a live connection. */
|
|
592
|
+
function connected(socket: net.Socket): net.Socket | null {
|
|
593
|
+
const detached = Trust.try(
|
|
594
|
+
() => socket.removeAllListeners('error'),
|
|
595
|
+
(cause) => ({ kind: 'listener-cleanup' as const, message: errorMessage(cause) }),
|
|
596
|
+
);
|
|
597
|
+
if (detached.ok) return socket;
|
|
598
|
+
if (detached.error.kind === 'listener-cleanup') socket.destroy();
|
|
599
|
+
return null;
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
/** Half-closes and resolves on 'close', or after 500 ms for a peer that went away without one. */
|
|
603
|
+
function endSocket(socket: net.Socket, resolve: () => void): void {
|
|
604
|
+
const ended = Trust.try(
|
|
605
|
+
() => {
|
|
606
|
+
const done = () => { clearTimeout(guard); resolve(); };
|
|
607
|
+
const guard = setTimeout(() => { socket.destroy(); done(); }, 500);
|
|
608
|
+
socket.once('close', done);
|
|
609
|
+
socket.end();
|
|
610
|
+
},
|
|
611
|
+
(cause) => ({ kind: 'end-failed' as const, message: errorMessage(cause) }),
|
|
612
|
+
);
|
|
613
|
+
if (!ended.ok && ended.error.kind === 'end-failed') {
|
|
614
|
+
socket.destroy();
|
|
615
|
+
resolve();
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
function sleep(ms: number): Promise<void> {
|
|
620
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
621
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export { SqlegoClient, SqlegoClientError, SqlegoTransaction, defaultServerCommand, type BeginOptions, 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 BeginResult,
|
|
13
|
+
type StatusResult,
|
|
14
|
+
type HelloResult,
|
|
15
|
+
type TransactionMode,
|
|
16
|
+
type TransactionStatus,
|
|
17
|
+
} from './protocol.ts';
|
|
18
|
+
export { VERSION } from './version.ts';
|