@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.
@@ -0,0 +1,370 @@
1
+ /**
2
+ * sqlego wire protocol: newline-delimited JSON over a local socket.
3
+ *
4
+ * One request per line, one response per line, correlated by `id`. The server
5
+ * executes requests in arrival order on its single connection to the file, so
6
+ * two clients' statements interleave at statement (or batch) granularity and
7
+ * never contend for SQLite's write lock.
8
+ *
9
+ * There is deliberately no BEGIN/COMMIT over the wire: a client-held
10
+ * transaction would hold the file's only writer hostage to that client's
11
+ * liveness. `batch` is the transactional unit.
12
+ */
13
+
14
+ import { Result, Trust } from '@noego/trust';
15
+
16
+ export const PROTOCOL_VERSION = 1;
17
+
18
+ export type SqlParams = ReadonlyArray<SqlValue> | Readonly<Record<string, SqlValue>>;
19
+ export type SqlValue = string | number | bigint | boolean | null | Uint8Array;
20
+ export type SqlRow = Record<string, unknown>;
21
+
22
+ export type Statement = Readonly<{
23
+ sql: string;
24
+ params?: SqlParams;
25
+ /** `query` returns rows; `run` returns the change count. Default `run`. */
26
+ mode?: 'query' | 'run';
27
+ }>;
28
+
29
+ export type Request =
30
+ | { id: number; op: 'hello'; clientVersion: string; protocol: number }
31
+ | { id: number; op: 'query'; sql: string; params?: SqlParams }
32
+ | { id: number; op: 'run'; sql: string; params?: SqlParams }
33
+ | { id: number; op: 'batch'; statements: readonly Statement[] }
34
+ | { id: number; op: 'status' }
35
+ | { id: number; op: 'stop' };
36
+
37
+ export type RunResult = Readonly<{ changes: number; lastInsertRowid: number | bigint }>;
38
+ export type QueryResult = Readonly<{ rows: SqlRow[] }>;
39
+ export type BatchResult = Readonly<{ results: ReadonlyArray<RunResult | QueryResult> }>;
40
+
41
+ export type HelloResult = Readonly<{
42
+ serverVersion: string;
43
+ protocol: number;
44
+ file: string;
45
+ pid: number;
46
+ }>;
47
+
48
+ export type StatusResult = Readonly<{
49
+ file: string;
50
+ socket: string;
51
+ pid: number;
52
+ serverVersion: string;
53
+ protocol: number;
54
+ clients: number;
55
+ uptimeMs: number;
56
+ idleMs: number | null;
57
+ idleTimeoutMs: number;
58
+ requestsServed: number;
59
+ }>;
60
+
61
+ export type ErrorCode =
62
+ | 'sqlite'
63
+ | 'bad-request'
64
+ | 'protocol-mismatch'
65
+ | 'shutting-down'
66
+ /** The server could not serialize a result (a value JSON cannot hold). */
67
+ | 'encode-failed';
68
+
69
+ export type Response =
70
+ | { id: number; ok: true; result: unknown }
71
+ | { id: number; ok: false; error: { code: ErrorCode; message: string } };
72
+
73
+ /**
74
+ * JSON text of a value. `JSON.stringify` is declared `string` but returns
75
+ * `undefined` for `undefined`, a function or a symbol, and throws on a cycle
76
+ * or a `toJSON` that throws; both are this one failure.
77
+ */
78
+ export function toJson(value: unknown, indent?: number) {
79
+ const encoded = Trust.try(
80
+ (): unknown => JSON.stringify(value, replaceBigInt, indent),
81
+ (cause) => ({ kind: 'encode-failed' as const, message: errorMessage(cause) }),
82
+ );
83
+ if (!encoded.ok) return encoded;
84
+ if (typeof encoded.value !== 'string') return Result.err({ kind: 'encode-failed', message: `${typeof value} has no JSON form` });
85
+ return Result.ok(encoded.value);
86
+ }
87
+
88
+ /** One frame: the message's JSON and the newline that ends it. */
89
+ export function encodeFrame(message: Request | Response) {
90
+ const json = toJson(message);
91
+ if (!json.ok) return json;
92
+ return Result.ok(`${json.value}\n`);
93
+ }
94
+
95
+ /** Parses JSON text into `unknown`; what it holds is for a validator to decide. */
96
+ export function fromJson(text: string) {
97
+ return Trust.try(
98
+ (): unknown => JSON.parse(text),
99
+ (cause) => ({ kind: 'invalid' as const, message: `not JSON: ${errorMessage(cause)}` }),
100
+ );
101
+ }
102
+
103
+ /* ------------------------------------------------------------------------ *
104
+ * Validators. Everything that crosses a process boundary (a frame, a file,
105
+ * a command-line argument) arrives as `unknown` and becomes typed only here.
106
+ * Each returns Err<{ kind: 'invalid' }> naming the first thing that is wrong;
107
+ * callers translate that into their own failure (bad-request, protocol, ...).
108
+ * ------------------------------------------------------------------------ */
109
+
110
+ type Fields = Readonly<Record<string, unknown>>;
111
+ type Invalid = Readonly<{ kind: 'invalid'; message: string }>;
112
+
113
+ const invalid = (message: string) => Result.err<Invalid>({ kind: 'invalid', message });
114
+
115
+ /** The own fields of a plain JSON object, each still `unknown`; null for anything else. */
116
+ //trust:validator_function
117
+ function fieldsOf(input: unknown): Fields | null {
118
+ return typeof input === 'object' && input !== null && !Array.isArray(input) ? (input as Fields) : null;
119
+ }
120
+
121
+ /** A value that survives JSON and SQLite binding: string, number, boolean or null. */
122
+ //trust:validator_function
123
+ export function parseSqlValue(input: unknown) {
124
+ if (input === null || typeof input === 'string' || typeof input === 'number' || typeof input === 'boolean') {
125
+ return Result.ok<SqlValue>(input);
126
+ }
127
+ return invalid(`a SQL value must be a string, number, boolean or null, not ${Array.isArray(input) ? 'an array' : typeof input}`);
128
+ }
129
+
130
+ /** Positional (`[...]`) or named (`{ name: value }`) parameters. */
131
+ //trust:validator_function
132
+ export function parseSqlParams(input: unknown) {
133
+ if (Array.isArray(input)) {
134
+ const values: SqlValue[] = [];
135
+ for (const [index, item] of input.entries()) {
136
+ const value = parseSqlValue(item);
137
+ if (!value.ok) return invalid(`params[${index}]: ${value.error.message}`);
138
+ values.push(value.value);
139
+ }
140
+ return Result.ok<SqlParams>(values);
141
+ }
142
+ const fields = fieldsOf(input);
143
+ if (!fields) return invalid('params must be an array or an object');
144
+ const named: Record<string, SqlValue> = {};
145
+ for (const [name, item] of Object.entries(fields)) {
146
+ const value = parseSqlValue(item);
147
+ if (!value.ok) return invalid(`params.${name}: ${value.error.message}`);
148
+ named[name] = value.value;
149
+ }
150
+ return Result.ok<SqlParams>(named);
151
+ }
152
+
153
+ /** `params` when present; absent (`undefined`) is allowed. */
154
+ //trust:validator_function
155
+ function parseOptionalParams(input: unknown) {
156
+ if (input === undefined) return Result.ok<SqlParams | undefined>(undefined);
157
+ return parseSqlParams(input);
158
+ }
159
+
160
+ //trust:validator_function
161
+ function parseStatement(input: unknown, at: string) {
162
+ const fields = fieldsOf(input);
163
+ if (!fields) return invalid(`${at} must be an object`);
164
+ if (typeof fields.sql !== 'string') return invalid(`${at}.sql must be a string`);
165
+ const mode = fields.mode;
166
+ if (mode !== undefined && mode !== 'query' && mode !== 'run') return invalid(`${at}.mode must be "query" or "run"`);
167
+ const params = parseOptionalParams(fields.params);
168
+ if (!params.ok) return invalid(`${at}.${params.error.message}`);
169
+ const statement: Statement = { sql: fields.sql, params: params.value, mode };
170
+ return Result.ok(statement);
171
+ }
172
+
173
+ /**
174
+ * A request frame. The failure carries the request's `id` when it had a
175
+ * numeric one, so the server can answer the request that was malformed.
176
+ */
177
+ //trust:validator_function
178
+ export function parseRequest(input: unknown) {
179
+ const reject = (id: number, message: string) => Result.err({ kind: 'invalid' as const, id, message });
180
+ const fields = fieldsOf(input);
181
+ if (!fields) return reject(-1, 'a request must be a JSON object');
182
+ const id = fields.id;
183
+ if (typeof id !== 'number') return reject(-1, 'a request needs a numeric id');
184
+ switch (fields.op) {
185
+ case 'hello': {
186
+ if (typeof fields.clientVersion !== 'string' || typeof fields.protocol !== 'number') {
187
+ return reject(id, 'hello needs clientVersion (string) and protocol (number)');
188
+ }
189
+ const request: Request = { id, op: 'hello', clientVersion: fields.clientVersion, protocol: fields.protocol };
190
+ return Result.ok(request);
191
+ }
192
+ case 'query':
193
+ case 'run': {
194
+ if (typeof fields.sql !== 'string') return reject(id, `${fields.op} needs sql (string)`);
195
+ const params = parseOptionalParams(fields.params);
196
+ if (!params.ok) return reject(id, params.error.message);
197
+ const request: Request = { id, op: fields.op, sql: fields.sql, params: params.value };
198
+ return Result.ok(request);
199
+ }
200
+ case 'batch': {
201
+ if (!Array.isArray(fields.statements)) return reject(id, 'batch needs a statements array');
202
+ const statements: Statement[] = [];
203
+ for (const [index, item] of fields.statements.entries()) {
204
+ const statement = parseStatement(item, `statements[${index}]`);
205
+ if (!statement.ok) return reject(id, statement.error.message);
206
+ statements.push(statement.value);
207
+ }
208
+ const request: Request = { id, op: 'batch', statements };
209
+ return Result.ok(request);
210
+ }
211
+ case 'status':
212
+ case 'stop': {
213
+ const request: Request = { id, op: fields.op };
214
+ return Result.ok(request);
215
+ }
216
+ default:
217
+ return reject(id, `unknown op ${String(fields.op)}`);
218
+ }
219
+ }
220
+
221
+ const ERROR_CODES: readonly ErrorCode[] = ['sqlite', 'bad-request', 'protocol-mismatch', 'shutting-down', 'encode-failed'];
222
+
223
+ //trust:validator_function
224
+ function parseErrorCode(input: unknown) {
225
+ const code = ERROR_CODES.find((known) => known === input);
226
+ return code === undefined ? invalid(`unknown error code ${String(input)}`) : Result.ok(code);
227
+ }
228
+
229
+ /** A response frame; `result` stays `unknown` until the parser for its op has seen it. */
230
+ //trust:validator_function
231
+ export function parseResponse(input: unknown) {
232
+ const fields = fieldsOf(input);
233
+ if (!fields) return invalid('a response must be a JSON object');
234
+ const id = fields.id;
235
+ if (typeof id !== 'number') return invalid('a response needs a numeric id');
236
+ if (fields.ok === true) {
237
+ const response: Response = { id, ok: true, result: fields.result };
238
+ return Result.ok(response);
239
+ }
240
+ if (fields.ok !== false) return invalid('a response needs ok: true or false');
241
+ const error = fieldsOf(fields.error);
242
+ if (!error || typeof error.message !== 'string') return invalid('a failed response needs error.code and error.message');
243
+ const code = parseErrorCode(error.code);
244
+ if (!code.ok) return code;
245
+ const response: Response = { id, ok: false, error: { code: code.value, message: error.message } };
246
+ return Result.ok(response);
247
+ }
248
+
249
+ //trust:validator_function
250
+ export function parseRow(input: unknown) {
251
+ const fields = fieldsOf(input);
252
+ if (!fields) return invalid('a row must be an object');
253
+ const row: SqlRow = { ...fields };
254
+ return Result.ok(row);
255
+ }
256
+
257
+ //trust:validator_function
258
+ export function parseRows(input: unknown) {
259
+ if (!Array.isArray(input)) return invalid('rows must be an array');
260
+ const rows: SqlRow[] = [];
261
+ for (const [index, item] of input.entries()) {
262
+ const row = parseRow(item);
263
+ if (!row.ok) return invalid(`rows[${index}]: ${row.error.message}`);
264
+ rows.push(row.value);
265
+ }
266
+ return Result.ok(rows);
267
+ }
268
+
269
+ //trust:validator_function
270
+ export function parseQueryResult(input: unknown) {
271
+ const fields = fieldsOf(input);
272
+ if (!fields) return invalid('a query result must be an object');
273
+ const rows = parseRows(fields.rows);
274
+ if (!rows.ok) return rows;
275
+ const result: QueryResult = { rows: rows.value };
276
+ return Result.ok(result);
277
+ }
278
+
279
+ //trust:validator_function
280
+ export function parseRunResult(input: unknown) {
281
+ const fields = fieldsOf(input);
282
+ if (!fields || typeof fields.changes !== 'number') return invalid('a run result needs changes (number)');
283
+ const rowid = fields.lastInsertRowid;
284
+ if (typeof rowid !== 'number' && typeof rowid !== 'bigint') return invalid('a run result needs lastInsertRowid (number)');
285
+ const result: RunResult = { changes: fields.changes, lastInsertRowid: rowid };
286
+ return Result.ok(result);
287
+ }
288
+
289
+ //trust:validator_function
290
+ export function parseBatchResult(input: unknown) {
291
+ const fields = fieldsOf(input);
292
+ if (!fields || !Array.isArray(fields.results)) return invalid('a batch result needs a results array');
293
+ const results: Array<RunResult | QueryResult> = [];
294
+ for (const [index, item] of fields.results.entries()) {
295
+ const shaped = fieldsOf(item);
296
+ const parsed = shaped && 'rows' in shaped ? parseQueryResult(item) : parseRunResult(item);
297
+ if (!parsed.ok) return invalid(`results[${index}]: ${parsed.error.message}`);
298
+ results.push(parsed.value);
299
+ }
300
+ const result: BatchResult = { results };
301
+ return Result.ok(result);
302
+ }
303
+
304
+ //trust:validator_function
305
+ export function parseHelloResult(input: unknown) {
306
+ const fields = fieldsOf(input);
307
+ if (
308
+ !fields
309
+ || typeof fields.serverVersion !== 'string' || typeof fields.protocol !== 'number'
310
+ || typeof fields.file !== 'string' || typeof fields.pid !== 'number'
311
+ ) {
312
+ return invalid('a hello result needs serverVersion, protocol, file and pid');
313
+ }
314
+ const result: HelloResult = { serverVersion: fields.serverVersion, protocol: fields.protocol, file: fields.file, pid: fields.pid };
315
+ return Result.ok(result);
316
+ }
317
+
318
+ //trust:validator_function
319
+ export function parseStatusResult(input: unknown) {
320
+ const f = fieldsOf(input);
321
+ if (
322
+ !f
323
+ || typeof f.file !== 'string' || typeof f.socket !== 'string' || typeof f.pid !== 'number'
324
+ || typeof f.serverVersion !== 'string' || typeof f.protocol !== 'number' || typeof f.clients !== 'number'
325
+ || typeof f.uptimeMs !== 'number' || (f.idleMs !== null && typeof f.idleMs !== 'number')
326
+ || typeof f.idleTimeoutMs !== 'number' || typeof f.requestsServed !== 'number'
327
+ ) {
328
+ return invalid('a status result is missing a field or has one of the wrong type');
329
+ }
330
+ const result: StatusResult = {
331
+ file: f.file, socket: f.socket, pid: f.pid, serverVersion: f.serverVersion, protocol: f.protocol,
332
+ clients: f.clients, uptimeMs: f.uptimeMs, idleMs: f.idleMs, idleTimeoutMs: f.idleTimeoutMs, requestsServed: f.requestsServed,
333
+ };
334
+ return Result.ok(result);
335
+ }
336
+
337
+ //trust:validator_function
338
+ export function parseStopResult(input: unknown) {
339
+ const fields = fieldsOf(input);
340
+ if (!fields || fields.stopping !== true) return invalid('a stop result needs stopping: true');
341
+ return Result.ok({ stopping: true as const });
342
+ }
343
+
344
+ /**
345
+ * The `code` of a thrown Node error (`EEXIST`, `EPERM`, ...), or undefined.
346
+ * Read through `in` on `unknown`, so nothing about the error is assumed.
347
+ */
348
+ export function errnoCode(cause: unknown): unknown {
349
+ if (typeof cause === 'object' && cause !== null && 'code' in cause) return cause.code;
350
+ return undefined;
351
+ }
352
+
353
+ /** The message of a caught value, whatever was thrown. */
354
+ export function errorMessage(cause: unknown): string {
355
+ return cause instanceof Error ? cause.message : String(cause);
356
+ }
357
+
358
+ /**
359
+ * Splits accumulated socket bytes into complete frames; returns the frames
360
+ * and the unterminated remainder to carry into the next chunk.
361
+ */
362
+ export function splitFrames(buffer: string): { frames: string[]; rest: string } {
363
+ const lines = buffer.split('\n');
364
+ const rest = lines.pop() ?? '';
365
+ return { frames: lines.filter((line) => line.length > 0), rest };
366
+ }
367
+
368
+ function replaceBigInt(_key: string, value: unknown): unknown {
369
+ return typeof value === 'bigint' ? Number(value) : value;
370
+ }