@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/README.md +81 -2
- package/bin/sqlego +4 -0
- package/dist/client.d.ts +75 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +751 -0
- package/dist/paths.d.ts +70 -0
- package/dist/protocol.d.ts +218 -0
- package/dist/version.d.ts +23 -0
- package/package.json +43 -4
- package/src/cli.ts +310 -0
- package/src/client.ts +497 -0
- package/src/index.ts +15 -0
- package/src/paths.ts +154 -0
- package/src/protocol.ts +370 -0
- package/src/server.ts +413 -0
- package/src/version.ts +78 -0
package/src/server.ts
ADDED
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
import { Database, type SQLQueryBindings } from 'bun:sqlite';
|
|
2
|
+
import { rmSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { Result, Trust } from '@noego/trust';
|
|
5
|
+
import {
|
|
6
|
+
PROTOCOL_VERSION,
|
|
7
|
+
encodeFrame,
|
|
8
|
+
errorMessage,
|
|
9
|
+
fromJson,
|
|
10
|
+
parseRequest,
|
|
11
|
+
parseRows,
|
|
12
|
+
splitFrames,
|
|
13
|
+
toJson,
|
|
14
|
+
type BatchResult,
|
|
15
|
+
type HelloResult,
|
|
16
|
+
type QueryResult,
|
|
17
|
+
type Request,
|
|
18
|
+
type Response,
|
|
19
|
+
type RunResult,
|
|
20
|
+
type SqlParams,
|
|
21
|
+
type SqlValue,
|
|
22
|
+
type Statement,
|
|
23
|
+
type StatusResult,
|
|
24
|
+
} from './protocol.ts';
|
|
25
|
+
import { resolvePaths, type FilePaths, type ServerMeta } from './paths.ts';
|
|
26
|
+
import { VERSION } from './version.ts';
|
|
27
|
+
|
|
28
|
+
export type ServerOptions = Readonly<{
|
|
29
|
+
file: string;
|
|
30
|
+
/** Exit this long after the last client disconnects. */
|
|
31
|
+
idleTimeoutMs: number;
|
|
32
|
+
/** Pragmas applied on open, in order (e.g. `journal_mode = WAL`). */
|
|
33
|
+
pragmas?: readonly string[];
|
|
34
|
+
log?: (message: string, fields?: Record<string, unknown>) => void;
|
|
35
|
+
}>;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Applied in order on open. `auto_vacuum` must precede anything that writes
|
|
39
|
+
* the first page (journal_mode = WAL does), and only binds on a file with no
|
|
40
|
+
* pages yet: a brand-new file gets incremental vacuum, an existing file keeps
|
|
41
|
+
* whatever it was created with. Callers override with `--pragma`.
|
|
42
|
+
*/
|
|
43
|
+
export const DEFAULT_PRAGMAS: readonly string[] = ['auto_vacuum = INCREMENTAL', 'journal_mode = WAL', 'busy_timeout = 5000'];
|
|
44
|
+
|
|
45
|
+
type SqliteFailure = { readonly kind: 'sqlite'; readonly message: string };
|
|
46
|
+
type CleanupFailure = { readonly kind: 'cleanup-failed'; readonly message: string };
|
|
47
|
+
type WriteFailure = { readonly kind: 'write-failed'; readonly message: string };
|
|
48
|
+
|
|
49
|
+
const sqliteFailure = (cause: unknown): SqliteFailure => ({ kind: 'sqlite', message: errorMessage(cause) });
|
|
50
|
+
const cleanupFailure = (cause: unknown): CleanupFailure => ({ kind: 'cleanup-failed', message: errorMessage(cause) });
|
|
51
|
+
const writeFailure = (cause: unknown): WriteFailure => ({ kind: 'write-failed', message: errorMessage(cause) });
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Carries one statement's failure out of a `db.transaction` callback: bun:sqlite
|
|
55
|
+
* rolls the transaction back only when that callback throws.
|
|
56
|
+
*/
|
|
57
|
+
class BatchStatementFailed extends Error {
|
|
58
|
+
readonly failure: SqliteFailure;
|
|
59
|
+
|
|
60
|
+
constructor(failure: SqliteFailure) {
|
|
61
|
+
super(failure.message);
|
|
62
|
+
this.failure = failure;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* `outbound` holds bytes the kernel buffer refused (null when there are none).
|
|
68
|
+
* Bun's `socket.write` returns the byte count it accepted and drops the rest,
|
|
69
|
+
* so a large result followed by another frame corrupts the stream unless the
|
|
70
|
+
* remainder is carried and flushed on `drain`.
|
|
71
|
+
*/
|
|
72
|
+
type Connection = { id: number; buffer: string; outbound: Buffer | null; socket: ServerSocket };
|
|
73
|
+
|
|
74
|
+
/** Each socket carries its connection in Bun's typed `data` slot: null until `open` assigns it. */
|
|
75
|
+
type ServerSocket = import('bun').Socket<Connection | null>;
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* The single owner of one SQLite file. Every request from every client runs,
|
|
79
|
+
* in arrival order, on this process's one connection; SQLite's write lock is
|
|
80
|
+
* therefore never contended from outside this process.
|
|
81
|
+
*/
|
|
82
|
+
export class SqlegoServer {
|
|
83
|
+
readonly paths: FilePaths;
|
|
84
|
+
private readonly db: Database;
|
|
85
|
+
private readonly options: ServerOptions;
|
|
86
|
+
private readonly startedAt = Date.now();
|
|
87
|
+
private readonly connections = new Map<number, Connection>();
|
|
88
|
+
private listener: import('bun').UnixSocketListener<Connection | null> | null = null;
|
|
89
|
+
private idleTimer: ReturnType<typeof setTimeout> | null = null;
|
|
90
|
+
private idleSince: number | null = null;
|
|
91
|
+
private nextConnectionId = 1;
|
|
92
|
+
private requestsServed = 0;
|
|
93
|
+
private stopping = false;
|
|
94
|
+
private lastOp: Request['op'] | null = null;
|
|
95
|
+
private readonly log: NonNullable<ServerOptions['log']>;
|
|
96
|
+
|
|
97
|
+
private constructor(options: ServerOptions, paths: FilePaths, db: Database) {
|
|
98
|
+
this.options = options;
|
|
99
|
+
this.paths = paths;
|
|
100
|
+
this.db = db;
|
|
101
|
+
this.log = options.log ?? (() => undefined);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Opens (creating if needed) the database file and applies the pragmas. */
|
|
105
|
+
static open(options: ServerOptions) {
|
|
106
|
+
const paths = resolvePaths(options.file);
|
|
107
|
+
if (!paths.ok) return paths;
|
|
108
|
+
const db = Trust.try(
|
|
109
|
+
() => {
|
|
110
|
+
mkdirSync(path.dirname(paths.value.file), { recursive: true });
|
|
111
|
+
const opened = new Database(paths.value.file, { create: true, strict: false });
|
|
112
|
+
for (const pragma of options.pragmas ?? DEFAULT_PRAGMAS) opened.exec(`PRAGMA ${pragma}`);
|
|
113
|
+
return opened;
|
|
114
|
+
},
|
|
115
|
+
(cause) => ({ kind: 'open-failed', message: `cannot open ${paths.value.file}: ${errorMessage(cause)}` }),
|
|
116
|
+
);
|
|
117
|
+
if (!db.ok) return db;
|
|
118
|
+
return Result.ok(new SqlegoServer(options, paths.value, db.value));
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Binds the socket and publishes meta. Clients can connect once this returns ok. */
|
|
122
|
+
listen() {
|
|
123
|
+
const meta: ServerMeta = {
|
|
124
|
+
file: this.paths.file, socket: this.paths.socket, pid: process.pid, serverVersion: VERSION, startedAt: this.startedAt,
|
|
125
|
+
};
|
|
126
|
+
const metaJson = toJson(meta);
|
|
127
|
+
if (!metaJson.ok) return Result.err({ kind: 'listen-failed', message: `cannot encode server meta: ${metaJson.error.message}` });
|
|
128
|
+
const bound = Trust.try(
|
|
129
|
+
() => {
|
|
130
|
+
if (existsSync(this.paths.socket)) rmSync(this.paths.socket, { force: true });
|
|
131
|
+
this.listener = Bun.listen<Connection | null>({
|
|
132
|
+
unix: this.paths.socket,
|
|
133
|
+
data: null,
|
|
134
|
+
socket: {
|
|
135
|
+
open: (socket) => this.onOpen(socket),
|
|
136
|
+
data: (socket, data) => this.onData(socket, data),
|
|
137
|
+
close: (socket) => this.onClose(socket),
|
|
138
|
+
drain: (socket) => this.onDrain(socket),
|
|
139
|
+
error: (socket, error) => this.onSocketError(socket, error),
|
|
140
|
+
},
|
|
141
|
+
});
|
|
142
|
+
writeFileSync(this.paths.meta, metaJson.value);
|
|
143
|
+
},
|
|
144
|
+
(cause) => ({ kind: 'listen-failed', message: `cannot listen on ${this.paths.socket}: ${errorMessage(cause)}` }),
|
|
145
|
+
);
|
|
146
|
+
if (!bound.ok) return bound;
|
|
147
|
+
this.armIdleTimer();
|
|
148
|
+
this.log('listening', { file: this.paths.file, socket: this.paths.socket, pid: process.pid, idleTimeoutMs: this.options.idleTimeoutMs });
|
|
149
|
+
return Result.ok(undefined);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Graceful stop: refuse new work, drop clients, release the file, remove socket/meta/lock. Every step is attempted. */
|
|
153
|
+
stop(reason: string): void {
|
|
154
|
+
if (this.stopping) return;
|
|
155
|
+
this.stopping = true;
|
|
156
|
+
this.log('stopping', { reason, clients: this.connections.size, requestsServed: this.requestsServed });
|
|
157
|
+
if (this.idleTimer) clearTimeout(this.idleTimer);
|
|
158
|
+
// Socket file first: a client that connects after this point falls through
|
|
159
|
+
// to claim-and-spawn instead of racing a closing server.
|
|
160
|
+
this.reportCleanup('remove socket', Trust.try(() => rmSync(this.paths.socket, { force: true }), cleanupFailure));
|
|
161
|
+
this.reportCleanup('remove meta', Trust.try(() => rmSync(this.paths.meta, { force: true }), cleanupFailure));
|
|
162
|
+
this.reportCleanup('remove lock', Trust.try(() => rmSync(this.paths.lock, { force: true }), cleanupFailure));
|
|
163
|
+
for (const connection of this.connections.values()) {
|
|
164
|
+
this.reportCleanup('end connection', Trust.try(() => connection.socket.end(), cleanupFailure));
|
|
165
|
+
}
|
|
166
|
+
const listener = this.listener;
|
|
167
|
+
if (listener) this.reportCleanup('stop listener', Trust.try(() => listener.stop(true), cleanupFailure));
|
|
168
|
+
this.reportCleanup('close database', Trust.try(() => this.db.close(), cleanupFailure));
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
status(): StatusResult {
|
|
172
|
+
return {
|
|
173
|
+
file: this.paths.file,
|
|
174
|
+
socket: this.paths.socket,
|
|
175
|
+
pid: process.pid,
|
|
176
|
+
serverVersion: VERSION,
|
|
177
|
+
protocol: PROTOCOL_VERSION,
|
|
178
|
+
clients: this.connections.size,
|
|
179
|
+
uptimeMs: Date.now() - this.startedAt,
|
|
180
|
+
idleMs: this.idleSince === null ? null : Date.now() - this.idleSince,
|
|
181
|
+
idleTimeoutMs: this.options.idleTimeoutMs,
|
|
182
|
+
requestsServed: this.requestsServed,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Shutdown is best effort: a step that fails is logged and the rest still run. */
|
|
187
|
+
private reportCleanup(step: string, outcome: Result<unknown, CleanupFailure>): void {
|
|
188
|
+
if (!outcome.ok && outcome.error.kind === 'cleanup-failed') this.log('cleanup failed', { step, error: outcome.error.message });
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
private onOpen(socket: ServerSocket): void {
|
|
192
|
+
if (this.stopping) {
|
|
193
|
+
this.reportCleanup('refuse connection', Trust.try(() => socket.end(), cleanupFailure));
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
const id = this.nextConnectionId++;
|
|
197
|
+
const connection: Connection = { id, buffer: '', outbound: null, socket };
|
|
198
|
+
this.connections.set(id, connection);
|
|
199
|
+
socket.data = connection;
|
|
200
|
+
this.disarmIdleTimer();
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
private onClose(socket: ServerSocket): void {
|
|
204
|
+
const connection = socket.data;
|
|
205
|
+
if (!connection) return;
|
|
206
|
+
this.connections.delete(connection.id);
|
|
207
|
+
if (this.connections.size === 0 && !this.stopping) this.armIdleTimer();
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
private onSocketError(socket: ServerSocket, error: Error): void {
|
|
211
|
+
this.log('socket error', { error: error.message });
|
|
212
|
+
this.onClose(socket);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
private onData(socket: ServerSocket, data: Buffer): void {
|
|
216
|
+
const connection = socket.data;
|
|
217
|
+
if (!connection) return;
|
|
218
|
+
const { frames, rest } = splitFrames(connection.buffer + data.toString('utf8'));
|
|
219
|
+
connection.buffer = rest;
|
|
220
|
+
for (const frame of frames) {
|
|
221
|
+
const response = this.handleFrame(frame);
|
|
222
|
+
this.reply(connection, response);
|
|
223
|
+
if (response.ok && this.lastOp === 'stop') {
|
|
224
|
+
this.stop('client request');
|
|
225
|
+
setTimeout(() => process.exit(0), 20);
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Sends one response. A response that cannot be encoded is answered with an
|
|
233
|
+
* error frame for the same id; a connection that cannot be written to is dropped.
|
|
234
|
+
*/
|
|
235
|
+
private reply(connection: Connection, response: Response): void {
|
|
236
|
+
const encoded = encodeFrame(response);
|
|
237
|
+
const frame = encoded.ok
|
|
238
|
+
? encoded
|
|
239
|
+
: encodeFrame({ id: response.id, ok: false, error: { code: 'encode-failed', message: encoded.error.message } });
|
|
240
|
+
if (!frame.ok) {
|
|
241
|
+
if (frame.error.kind === 'encode-failed') this.dropConnection(connection, `cannot encode response ${response.id}: ${frame.error.message}`);
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
const sent = this.send(connection, frame.value);
|
|
245
|
+
if (!sent.ok && sent.error.kind === 'write-failed') this.dropConnection(connection, sent.error.message);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
private dropConnection(connection: Connection, why: string): void {
|
|
249
|
+
this.log('dropping connection', { connection: connection.id, error: why });
|
|
250
|
+
connection.outbound = null;
|
|
251
|
+
this.reportCleanup('drop connection', Trust.try(() => connection.socket.end(), cleanupFailure));
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** Queues behind any unflushed bytes so frames never interleave. */
|
|
255
|
+
private send(connection: Connection, frame: string) {
|
|
256
|
+
const queued = Trust.try(
|
|
257
|
+
() => {
|
|
258
|
+
const bytes = Buffer.from(frame, 'utf8');
|
|
259
|
+
connection.outbound = connection.outbound === null ? bytes : Buffer.concat([connection.outbound, bytes]);
|
|
260
|
+
},
|
|
261
|
+
writeFailure,
|
|
262
|
+
);
|
|
263
|
+
if (!queued.ok) return queued;
|
|
264
|
+
return this.flush(connection);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
private onDrain(socket: ServerSocket): void {
|
|
268
|
+
const connection = socket.data;
|
|
269
|
+
if (!connection) return;
|
|
270
|
+
const flushed = this.flush(connection);
|
|
271
|
+
if (!flushed.ok && flushed.error.kind === 'write-failed') this.dropConnection(connection, flushed.error.message);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
private flush(connection: Connection) {
|
|
275
|
+
return Trust.try(
|
|
276
|
+
() => {
|
|
277
|
+
const pending = connection.outbound;
|
|
278
|
+
if (pending === null) return;
|
|
279
|
+
const written = connection.socket.write(pending);
|
|
280
|
+
connection.outbound = written >= pending.length ? null : pending.subarray(Math.max(written, 0));
|
|
281
|
+
},
|
|
282
|
+
writeFailure,
|
|
283
|
+
);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** Decides every failure of one request into a wire response. */
|
|
287
|
+
private handleFrame(frame: string): Response {
|
|
288
|
+
const json = fromJson(frame);
|
|
289
|
+
if (!json.ok) return { id: -1, ok: false, error: { code: 'bad-request', message: `malformed frame: ${json.error.message}` } };
|
|
290
|
+
const parsed = parseRequest(json.value);
|
|
291
|
+
if (!parsed.ok) return { id: parsed.error.id, ok: false, error: { code: 'bad-request', message: parsed.error.message } };
|
|
292
|
+
const request = parsed.value;
|
|
293
|
+
this.lastOp = request.op;
|
|
294
|
+
this.requestsServed += 1;
|
|
295
|
+
if (this.stopping) return { id: request.id, ok: false, error: { code: 'shutting-down', message: 'server is shutting down' } };
|
|
296
|
+
const outcome = this.execute(request);
|
|
297
|
+
if (outcome.ok) return { id: request.id, ok: true, result: outcome.value };
|
|
298
|
+
switch (outcome.error.kind) {
|
|
299
|
+
case 'bad-request': return { id: request.id, ok: false, error: { code: 'bad-request', message: outcome.error.message } };
|
|
300
|
+
case 'protocol-mismatch': return { id: request.id, ok: false, error: { code: 'protocol-mismatch', message: outcome.error.message } };
|
|
301
|
+
case 'sqlite': return { id: request.id, ok: false, error: { code: 'sqlite', message: outcome.error.message } };
|
|
302
|
+
default: {
|
|
303
|
+
const unhandled: never = outcome.error;
|
|
304
|
+
return unhandled;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
private execute(request: Request) {
|
|
310
|
+
switch (request.op) {
|
|
311
|
+
case 'hello': return this.hello(request.protocol);
|
|
312
|
+
case 'query': return this.query(request.sql, request.params);
|
|
313
|
+
case 'run': return this.run(request.sql, request.params);
|
|
314
|
+
case 'batch': return this.batch(request.statements);
|
|
315
|
+
case 'status': return Result.ok(this.status());
|
|
316
|
+
case 'stop': return Result.ok({ stopping: true });
|
|
317
|
+
default: {
|
|
318
|
+
const unhandled: never = request;
|
|
319
|
+
return unhandled;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
private hello(protocol: number) {
|
|
325
|
+
if (protocol !== PROTOCOL_VERSION) {
|
|
326
|
+
return Result.err({ kind: 'protocol-mismatch', message: `server speaks protocol ${PROTOCOL_VERSION}, client sent ${protocol}` });
|
|
327
|
+
}
|
|
328
|
+
const hello: HelloResult = { serverVersion: VERSION, protocol: PROTOCOL_VERSION, file: this.paths.file, pid: process.pid };
|
|
329
|
+
return Result.ok(hello);
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
private query(sql: string, params?: SqlParams) {
|
|
333
|
+
const fetched = Trust.try(
|
|
334
|
+
(): unknown => {
|
|
335
|
+
const statement = this.db.query(sql);
|
|
336
|
+
return params === undefined ? statement.all() : statement.all(...bindings(params));
|
|
337
|
+
},
|
|
338
|
+
sqliteFailure,
|
|
339
|
+
);
|
|
340
|
+
if (!fetched.ok) return fetched;
|
|
341
|
+
const rows = parseRows(fetched.value);
|
|
342
|
+
if (!rows.ok) return Result.err<SqliteFailure>({ kind: 'sqlite', message: `unexpected row shape: ${rows.error.message}` });
|
|
343
|
+
const result: QueryResult = { rows: rows.value };
|
|
344
|
+
return Result.ok(result);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
private run(sql: string, params?: SqlParams) {
|
|
348
|
+
return Trust.try(
|
|
349
|
+
() => {
|
|
350
|
+
const statement = this.db.query(sql);
|
|
351
|
+
const outcome = params === undefined ? statement.run() : statement.run(...bindings(params));
|
|
352
|
+
const result: RunResult = { changes: outcome.changes, lastInsertRowid: outcome.lastInsertRowid };
|
|
353
|
+
return result;
|
|
354
|
+
},
|
|
355
|
+
sqliteFailure,
|
|
356
|
+
);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/** All statements in one transaction; any failure rolls the whole batch back. */
|
|
360
|
+
private batch(statements: readonly Statement[]) {
|
|
361
|
+
if (statements.length === 0) {
|
|
362
|
+
return Result.err({ kind: 'bad-request', message: 'batch requires a non-empty statements array' });
|
|
363
|
+
}
|
|
364
|
+
return Trust.try(
|
|
365
|
+
() => {
|
|
366
|
+
const transaction = this.db.transaction((items: readonly Statement[]) => items.map((item) => this.batchItem(item)));
|
|
367
|
+
const result: BatchResult = { results: transaction(statements) };
|
|
368
|
+
return result;
|
|
369
|
+
},
|
|
370
|
+
(cause) => (cause instanceof BatchStatementFailed ? cause.failure : sqliteFailure(cause)),
|
|
371
|
+
);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** One statement of a batch, inside its transaction: a failure must throw so bun:sqlite rolls back. */
|
|
375
|
+
private batchItem(item: Statement): RunResult | QueryResult {
|
|
376
|
+
const outcome = item.mode === 'query' ? this.query(item.sql, item.params) : this.run(item.sql, item.params);
|
|
377
|
+
if (outcome.ok) return outcome.value;
|
|
378
|
+
//trust:accept bun:sqlite rolls a transaction back only when its callback throws; batch() turns this back into a Result
|
|
379
|
+
throw new BatchStatementFailed(outcome.error);
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
private armIdleTimer(): void {
|
|
383
|
+
this.idleSince = Date.now();
|
|
384
|
+
if (this.idleTimer) clearTimeout(this.idleTimer);
|
|
385
|
+
this.idleTimer = setTimeout(() => this.onIdle(), this.options.idleTimeoutMs);
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
private onIdle(): void {
|
|
389
|
+
if (this.connections.size > 0) return;
|
|
390
|
+
this.stop('idle');
|
|
391
|
+
process.exit(0);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
private disarmIdleTimer(): void {
|
|
395
|
+
this.idleSince = null;
|
|
396
|
+
if (this.idleTimer) {
|
|
397
|
+
clearTimeout(this.idleTimer);
|
|
398
|
+
this.idleTimer = null;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* bun:sqlite binds positional params from an array spread and named params
|
|
405
|
+
* from one object argument. Every SqlValue is a binding bun:sqlite accepts;
|
|
406
|
+
* `params` itself was checked by `parseSqlParams` when the frame arrived. This
|
|
407
|
+
* only tells the array form from the object form, which `Array.isArray`
|
|
408
|
+
* cannot narrow on a readonly array without widening it to `any[]`.
|
|
409
|
+
*/
|
|
410
|
+
//trust:validator_function
|
|
411
|
+
function bindings(params: SqlParams): SQLQueryBindings[] {
|
|
412
|
+
return Array.isArray(params) ? (params as SqlValue[]) : [params as Record<string, SqlValue>];
|
|
413
|
+
}
|
package/src/version.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { Result, Trust } from '@noego/trust';
|
|
6
|
+
import { errorMessage } from './protocol.ts';
|
|
7
|
+
import pkg from '../package.json' with { type: 'json' };
|
|
8
|
+
|
|
9
|
+
/** Stamped by `scripts/build.ts` (`--define`) into dist and the compiled binary; absent when running from source. */
|
|
10
|
+
declare const __SQLEGO_BUILD__: string | undefined;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Hash of every `src/*.ts` file, so the two artifacts built from one tree
|
|
14
|
+
* (Node client in dist/, Bun server in bin/) and a source run agree, while any
|
|
15
|
+
* edit yields a new id. `source` when the tree is not there.
|
|
16
|
+
*/
|
|
17
|
+
export function sourceBuildId(sourceDirectory: string) {
|
|
18
|
+
if (!existsSync(sourceDirectory)) return Result.ok('source');
|
|
19
|
+
return Trust.try(
|
|
20
|
+
() => {
|
|
21
|
+
const hash = createHash('sha1');
|
|
22
|
+
for (const name of readdirSync(sourceDirectory).filter((entry) => entry.endsWith('.ts')).sort()) {
|
|
23
|
+
hash.update(name);
|
|
24
|
+
hash.update(readFileSync(path.join(sourceDirectory, name)));
|
|
25
|
+
}
|
|
26
|
+
return hash.digest('hex').slice(0, 12);
|
|
27
|
+
},
|
|
28
|
+
(cause) => ({ kind: 'source-unreadable', message: `cannot hash sources in ${sourceDirectory}: ${errorMessage(cause)}` }),
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Exception-based form of `sourceBuildId` for the build script, which must stop on an unreadable tree. */
|
|
33
|
+
export function computeSourceBuildId(sourceDirectory: string): string {
|
|
34
|
+
const id = sourceBuildId(sourceDirectory);
|
|
35
|
+
if (id.ok) return id.value;
|
|
36
|
+
//trust:accept build script contract: an unhashable source tree must fail the build
|
|
37
|
+
throw new Error(id.error.message);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function resolveBuildId() {
|
|
41
|
+
if (typeof __SQLEGO_BUILD__ === 'string' && __SQLEGO_BUILD__.length > 0) return __SQLEGO_BUILD__;
|
|
42
|
+
const directory = Trust.try(
|
|
43
|
+
() => path.dirname(fileURLToPath(import.meta.url)),
|
|
44
|
+
(cause) => ({ kind: 'module-path', message: errorMessage(cause) }),
|
|
45
|
+
);
|
|
46
|
+
if (!directory.ok) return decideUnknownBuild(directory.error.kind);
|
|
47
|
+
const id = sourceBuildId(directory.value);
|
|
48
|
+
if (!id.ok) return decideUnknownBuild(id.error.kind);
|
|
49
|
+
return id.value;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* A source run whose tree cannot be located or read has no build id; it
|
|
54
|
+
* identifies as `source`, the same as a run with no tree at all.
|
|
55
|
+
*/
|
|
56
|
+
function decideUnknownBuild(kind: 'module-path' | 'source-unreadable') {
|
|
57
|
+
switch (kind) {
|
|
58
|
+
case 'module-path': return 'source';
|
|
59
|
+
case 'source-unreadable': return 'source';
|
|
60
|
+
default: {
|
|
61
|
+
const unhandled: never = kind;
|
|
62
|
+
return unhandled;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Build identity of this artifact: the source hash it was built from. */
|
|
68
|
+
export const BUILD_ID: string = resolveBuildId();
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* What the client/server handshake compares: `<package version>+<build id>`.
|
|
72
|
+
* A rebuilt binary or dist — even at an unchanged package version — therefore
|
|
73
|
+
* retires owners started from the previous build instead of leaving stale
|
|
74
|
+
* code serving (2026-09-04: a framing fix shipped under the same version and
|
|
75
|
+
* the old owners kept running until stopped by hand).
|
|
76
|
+
* `SQLEGO_VERSION_OVERRIDE` lets a test start a deliberately stale server.
|
|
77
|
+
*/
|
|
78
|
+
export const VERSION: string = process.env.SQLEGO_VERSION_OVERRIDE || `${pkg.version}+${BUILD_ID}`;
|