@noego/sqlego 0.0.1 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/server.ts CHANGED
@@ -5,13 +5,19 @@ import { Result, Trust } from '@noego/trust';
5
5
  import {
6
6
  PROTOCOL_VERSION,
7
7
  encodeFrame,
8
+ encodeResultRows,
9
+ encodeWireInteger,
8
10
  errorMessage,
9
11
  fromJson,
10
12
  parseRequest,
11
13
  parseRows,
12
14
  splitFrames,
15
+ splitSqlStatements,
13
16
  toJson,
17
+ transactionControl,
14
18
  type BatchResult,
19
+ type BeginResult,
20
+ type ExecWireResult,
15
21
  type HelloResult,
16
22
  type QueryResult,
17
23
  type Request,
@@ -20,7 +26,11 @@ import {
20
26
  type SqlParams,
21
27
  type SqlValue,
22
28
  type Statement,
29
+ type StatementWireResult,
23
30
  type StatusResult,
31
+ type TransactionEndResult,
32
+ type TransactionMode,
33
+ type TransactionStatus,
24
34
  } from './protocol.ts';
25
35
  import { resolvePaths, type FilePaths, type ServerMeta } from './paths.ts';
26
36
  import { VERSION } from './version.ts';
@@ -32,6 +42,16 @@ export type ServerOptions = Readonly<{
32
42
  /** Pragmas applied on open, in order (e.g. `journal_mode = WAL`). */
33
43
  pragmas?: readonly string[];
34
44
  log?: (message: string, fields?: Record<string, unknown>) => void;
45
+ /**
46
+ * Default and ceiling for a client transaction's lease: the transaction is
47
+ * rolled back when no request for it arrives within this long. A client may
48
+ * ask for a shorter lease in `begin`, never a longer one. Default 10 000.
49
+ */
50
+ txLeaseMs?: number;
51
+ /** Hard cap on how long one transaction may stay open, renewed or not. Default 60 000. */
52
+ txMaxDurationMs?: number;
53
+ /** How long another client's request waits behind an open transaction before failing with `tx-busy`. Default 30 000. */
54
+ txQueueTimeoutMs?: number;
35
55
  }>;
36
56
 
37
57
  /**
@@ -42,13 +62,27 @@ export type ServerOptions = Readonly<{
42
62
  */
43
63
  export const DEFAULT_PRAGMAS: readonly string[] = ['auto_vacuum = INCREMENTAL', 'journal_mode = WAL', 'busy_timeout = 5000'];
44
64
 
65
+ export const DEFAULT_TX_LEASE_MS = 10_000;
66
+ export const DEFAULT_TX_MAX_DURATION_MS = 60_000;
67
+ export const DEFAULT_TX_QUEUE_TIMEOUT_MS = 30_000;
68
+
45
69
  type SqliteFailure = { readonly kind: 'sqlite'; readonly message: string };
70
+ type BadRequest = { readonly kind: 'bad-request'; readonly message: string };
71
+ type TransactionFailure = { readonly kind: 'tx-expired' | 'tx-invalid'; readonly message: string };
46
72
  type CleanupFailure = { readonly kind: 'cleanup-failed'; readonly message: string };
47
73
  type WriteFailure = { readonly kind: 'write-failed'; readonly message: string };
74
+ type EncodeFailure = { readonly kind: 'encode-failed'; readonly message: string };
75
+
76
+ /** One statement as `executeOne` ran it: its raw rows and what it changed. */
77
+ type Executed = { reader: boolean; rows: unknown; changes: number; lastInsertRowid: number | bigint };
78
+ /** The connection's counters around a statement (`changes()`, `total_changes()`, `last_insert_rowid()`). */
79
+ type Counters = { changes: number; total: number; lastInsertRowid: number | bigint };
80
+ type TxControl = ReturnType<typeof transactionControl>;
48
81
 
49
82
  const sqliteFailure = (cause: unknown): SqliteFailure => ({ kind: 'sqlite', message: errorMessage(cause) });
50
83
  const cleanupFailure = (cause: unknown): CleanupFailure => ({ kind: 'cleanup-failed', message: errorMessage(cause) });
51
84
  const writeFailure = (cause: unknown): WriteFailure => ({ kind: 'write-failed', message: errorMessage(cause) });
85
+ const badRequest = (message: string) => Result.err<BadRequest>({ kind: 'bad-request', message });
52
86
 
53
87
  /**
54
88
  * Carries one statement's failure out of a `db.transaction` callback: bun:sqlite
@@ -74,10 +108,33 @@ type Connection = { id: number; buffer: string; outbound: Buffer | null; socket:
74
108
  /** Each socket carries its connection in Bun's typed `data` slot: null until `open` assigns it. */
75
109
  type ServerSocket = import('bun').Socket<Connection | null>;
76
110
 
111
+ /** The one transaction a client may hold open; it lives and dies with `connection`. */
112
+ type OpenTransaction = {
113
+ id: number;
114
+ connection: Connection;
115
+ startedAt: number;
116
+ lastRequestAt: number;
117
+ leaseMs: number;
118
+ leaseTimer: ReturnType<typeof setTimeout>;
119
+ maxTimer: ReturnType<typeof setTimeout>;
120
+ };
121
+
122
+ /** A request from another client, held until the open transaction ends (or its wait runs out). */
123
+ type QueuedRequest = { connection: Connection; request: Request; timer: ReturnType<typeof setTimeout> };
124
+
125
+ /** How a transaction ended, kept so a late request for it gets a precise answer. */
126
+ type EndedTransaction = { code: 'tx-expired' | 'tx-invalid'; message: string };
127
+
128
+ const REMEMBERED_ENDINGS = 32;
129
+
77
130
  /**
78
131
  * The single owner of one SQLite file. Every request from every client runs,
79
132
  * in arrival order, on this process's one connection; SQLite's write lock is
80
133
  * therefore never contended from outside this process.
134
+ *
135
+ * While a client holds a transaction, that client's statements run at once
136
+ * and every other client's statements wait in arrival order; the transaction
137
+ * cannot outlive its socket, its lease, or the server's hard cap.
81
138
  */
82
139
  export class SqlegoServer {
83
140
  readonly paths: FilePaths;
@@ -89,9 +146,12 @@ export class SqlegoServer {
89
146
  private idleTimer: ReturnType<typeof setTimeout> | null = null;
90
147
  private idleSince: number | null = null;
91
148
  private nextConnectionId = 1;
149
+ private nextTransactionId = 1;
92
150
  private requestsServed = 0;
93
151
  private stopping = false;
94
- private lastOp: Request['op'] | null = null;
152
+ private transaction: OpenTransaction | null = null;
153
+ private readonly queue: QueuedRequest[] = [];
154
+ private readonly ended = new Map<number, EndedTransaction>();
95
155
  private readonly log: NonNullable<ServerOptions['log']>;
96
156
 
97
157
  private constructor(options: ServerOptions, paths: FilePaths, db: Database) {
@@ -108,7 +168,9 @@ export class SqlegoServer {
108
168
  const db = Trust.try(
109
169
  () => {
110
170
  mkdirSync(path.dirname(paths.value.file), { recursive: true });
111
- const opened = new Database(paths.value.file, { create: true, strict: false });
171
+ // safeIntegers: SQLite integers arrive as bigint so `statement`/`exec`
172
+ // can return all 64 bits; `query`/`run`/`batch` still send JSON numbers.
173
+ const opened = new Database(paths.value.file, { create: true, strict: false, safeIntegers: true });
112
174
  for (const pragma of options.pragmas ?? DEFAULT_PRAGMAS) opened.exec(`PRAGMA ${pragma}`);
113
175
  return opened;
114
176
  },
@@ -155,6 +217,8 @@ export class SqlegoServer {
155
217
  this.stopping = true;
156
218
  this.log('stopping', { reason, clients: this.connections.size, requestsServed: this.requestsServed });
157
219
  if (this.idleTimer) clearTimeout(this.idleTimer);
220
+ if (this.transaction) this.endTransaction('server stopping', 'tx-expired', true);
221
+ for (const queued of this.queue.splice(0)) clearTimeout(queued.timer);
158
222
  // Socket file first: a client that connects after this point falls through
159
223
  // to claim-and-spawn instead of racing a closing server.
160
224
  this.reportCleanup('remove socket', Trust.try(() => rmSync(this.paths.socket, { force: true }), cleanupFailure));
@@ -180,9 +244,36 @@ export class SqlegoServer {
180
244
  idleMs: this.idleSince === null ? null : Date.now() - this.idleSince,
181
245
  idleTimeoutMs: this.options.idleTimeoutMs,
182
246
  requestsServed: this.requestsServed,
247
+ transaction: this.transactionStatus(),
183
248
  };
184
249
  }
185
250
 
251
+ private transactionStatus(): TransactionStatus | null {
252
+ const open = this.transaction;
253
+ if (!open) return null;
254
+ const now = Date.now();
255
+ return {
256
+ txId: open.id,
257
+ ageMs: now - open.startedAt,
258
+ idleMs: now - open.lastRequestAt,
259
+ leaseMs: open.leaseMs,
260
+ maxDurationMs: this.txMaxDurationMs(),
261
+ queued: this.queue.length,
262
+ };
263
+ }
264
+
265
+ private txLeaseMs(): number {
266
+ return this.options.txLeaseMs ?? DEFAULT_TX_LEASE_MS;
267
+ }
268
+
269
+ private txMaxDurationMs(): number {
270
+ return this.options.txMaxDurationMs ?? DEFAULT_TX_MAX_DURATION_MS;
271
+ }
272
+
273
+ private txQueueTimeoutMs(): number {
274
+ return this.options.txQueueTimeoutMs ?? DEFAULT_TX_QUEUE_TIMEOUT_MS;
275
+ }
276
+
186
277
  /** Shutdown is best effort: a step that fails is logged and the rest still run. */
187
278
  private reportCleanup(step: string, outcome: Result<unknown, CleanupFailure>): void {
188
279
  if (!outcome.ok && outcome.error.kind === 'cleanup-failed') this.log('cleanup failed', { step, error: outcome.error.message });
@@ -204,6 +295,14 @@ export class SqlegoServer {
204
295
  const connection = socket.data;
205
296
  if (!connection) return;
206
297
  this.connections.delete(connection.id);
298
+ // A waiting request from a client that left has nobody to answer.
299
+ for (let index = this.queue.length - 1; index >= 0; index -= 1) {
300
+ if (this.queue[index].connection === connection) clearTimeout(this.queue.splice(index, 1)[0].timer);
301
+ }
302
+ if (this.transaction && this.transaction.connection === connection) {
303
+ this.endTransaction(`client ${connection.id} disconnected`, 'tx-expired', true);
304
+ this.drainQueue();
305
+ }
207
306
  if (this.connections.size === 0 && !this.stopping) this.armIdleTimer();
208
307
  }
209
308
 
@@ -218,87 +317,99 @@ export class SqlegoServer {
218
317
  const { frames, rest } = splitFrames(connection.buffer + data.toString('utf8'));
219
318
  connection.buffer = rest;
220
319
  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
- }
320
+ if (this.stopping) return;
321
+ this.accept(connection, frame);
228
322
  }
229
323
  }
230
324
 
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}`);
325
+ /** Parses one frame and either serves it now or holds it behind another client's transaction. */
326
+ private accept(connection: Connection, frame: string): void {
327
+ const parsed = this.parseFrame(frame);
328
+ if (!parsed.ok) return this.reply(connection, { id: parsed.error.id, ok: false, error: { code: 'bad-request', message: parsed.error.message } });
329
+ const request = parsed.value;
330
+ if (this.mustWait(connection, request)) {
331
+ const timer = setTimeout(() => this.expireQueued(connection, request), this.txQueueTimeoutMs());
332
+ this.queue.push({ connection, request, timer });
242
333
  return;
243
334
  }
244
- const sent = this.send(connection, frame.value);
245
- if (!sent.ok && sent.error.kind === 'write-failed') this.dropConnection(connection, sent.error.message);
335
+ this.serve(connection, request);
246
336
  }
247
337
 
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));
338
+ /** A frame's request; a malformed one is a bad request answered on the id it carried (-1 when it had none). */
339
+ private parseFrame(frame: string) {
340
+ const json = fromJson(frame);
341
+ if (!json.ok) return Result.err({ kind: 'bad-request' as const, id: -1, message: `malformed frame: ${json.error.message}` });
342
+ const parsed = parseRequest(json.value);
343
+ if (!parsed.ok) return Result.err({ kind: 'bad-request' as const, id: parsed.error.id, message: parsed.error.message });
344
+ return parsed;
252
345
  }
253
346
 
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);
347
+ /**
348
+ * Statements from a client other than the transaction's owner wait until it
349
+ * ends. Its own requests, and anything that is not a statement (`hello`,
350
+ * `status`, `stop`), go through at once; so does a statement naming a
351
+ * `txId`, which can only be answered with a transaction error.
352
+ */
353
+ private mustWait(connection: Connection, request: Request): boolean {
354
+ const open = this.transaction;
355
+ if (!open || open.connection === connection) return false;
356
+ switch (request.op) {
357
+ case 'query':
358
+ case 'run':
359
+ case 'statement':
360
+ case 'exec': return request.txId === undefined;
361
+ case 'batch':
362
+ case 'begin': return true;
363
+ default: return false;
364
+ }
265
365
  }
266
366
 
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);
367
+ private expireQueued(connection: Connection, request: Request): void {
368
+ const index = this.queue.findIndex((queued) => queued.request === request);
369
+ if (index < 0) return;
370
+ this.queue.splice(index, 1);
371
+ const waited = this.txQueueTimeoutMs();
372
+ this.reply(connection, {
373
+ id: request.id, ok: false,
374
+ error: { code: 'tx-busy', message: `another client's transaction kept this ${request.op} waiting for ${waited} ms` },
375
+ });
272
376
  }
273
377
 
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
- );
378
+ /** Serves held requests in arrival order until one of them opens a new transaction. */
379
+ private drainQueue(): void {
380
+ while (this.queue.length > 0 && this.transaction === null && !this.stopping) {
381
+ const next = this.queue.shift();
382
+ if (!next) return;
383
+ clearTimeout(next.timer);
384
+ this.serve(next.connection, next.request);
385
+ }
284
386
  }
285
387
 
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;
388
+ private serve(connection: Connection, request: Request): void {
294
389
  this.requestsServed += 1;
390
+ const response = this.respond(connection, request);
391
+ this.reply(connection, response);
392
+ if (response.ok && request.op === 'stop') {
393
+ this.stop('client request');
394
+ setTimeout(() => process.exit(0), 20);
395
+ return;
396
+ }
397
+ // A commit, rollback or expiry may have freed the file for whoever was waiting.
398
+ this.drainQueue();
399
+ }
400
+
401
+ /** Decides every failure of one request into a wire response. */
402
+ private respond(connection: Connection, request: Request): Response {
295
403
  if (this.stopping) return { id: request.id, ok: false, error: { code: 'shutting-down', message: 'server is shutting down' } };
296
- const outcome = this.execute(request);
404
+ const outcome = this.execute(connection, request);
297
405
  if (outcome.ok) return { id: request.id, ok: true, result: outcome.value };
298
406
  switch (outcome.error.kind) {
299
407
  case 'bad-request': return { id: request.id, ok: false, error: { code: 'bad-request', message: outcome.error.message } };
300
408
  case 'protocol-mismatch': return { id: request.id, ok: false, error: { code: 'protocol-mismatch', message: outcome.error.message } };
301
409
  case 'sqlite': return { id: request.id, ok: false, error: { code: 'sqlite', message: outcome.error.message } };
410
+ case 'tx-expired': return { id: request.id, ok: false, error: { code: 'tx-expired', message: outcome.error.message } };
411
+ case 'tx-invalid': return { id: request.id, ok: false, error: { code: 'tx-invalid', message: outcome.error.message } };
412
+ case 'encode-failed': return { id: request.id, ok: false, error: { code: 'encode-failed', message: outcome.error.message } };
302
413
  default: {
303
414
  const unhandled: never = outcome.error;
304
415
  return unhandled;
@@ -306,12 +417,17 @@ export class SqlegoServer {
306
417
  }
307
418
  }
308
419
 
309
- private execute(request: Request) {
420
+ private execute(connection: Connection, request: Request) {
310
421
  switch (request.op) {
311
422
  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);
423
+ case 'query':
424
+ case 'run': return this.statement(connection, request.op, request.sql, request.params, request.txId);
425
+ case 'statement': return this.unifiedStatement(connection, request.sql, request.params, request.txId);
426
+ case 'exec': return this.exec(connection, request.sql, request.txId);
427
+ case 'batch': return this.batch(connection, request.statements);
428
+ case 'begin': return this.begin(connection, request.mode ?? 'deferred', request.leaseMs);
429
+ case 'commit': return this.finish(connection, request.txId, 'commit');
430
+ case 'rollback': return this.finish(connection, request.txId, 'rollback');
315
431
  case 'status': return Result.ok(this.status());
316
432
  case 'stop': return Result.ok({ stopping: true });
317
433
  default: {
@@ -329,6 +445,82 @@ export class SqlegoServer {
329
445
  return Result.ok(hello);
330
446
  }
331
447
 
448
+ /**
449
+ * One `query` or `run`. Outside a transaction no transaction-control SQL is
450
+ * accepted at all: a stray `BEGIN` would silently wrap every client's later
451
+ * statements. Inside one, savepoints are SQL but the transaction itself ends
452
+ * only through `commit`/`rollback`, so the server always knows its state.
453
+ */
454
+ private statement(connection: Connection, op: 'query' | 'run', sql: string, params: SqlParams | undefined, txId: number | undefined) {
455
+ return this.scoped<QueryResult | RunResult, SqliteFailure>(connection, op, txId, [transactionControl(sql)], () => this.runStatement(op, sql, params));
456
+ }
457
+
458
+ /**
459
+ * One `statement`: exactly one SQL statement (a second one would otherwise
460
+ * be silently ignored by prepare), under the same transaction-control rules
461
+ * as `query`/`run`.
462
+ */
463
+ private unifiedStatement(connection: Connection, sql: string, params: SqlParams | undefined, txId: number | undefined) {
464
+ const pieces = splitSqlStatements(sql);
465
+ if (pieces.length === 0) return badRequest('statement needs one SQL statement; the text has none');
466
+ if (pieces.length > 1) return badRequest(`statement takes one SQL statement, the text has ${pieces.length}: use exec for several`);
467
+ const piece = pieces[0];
468
+ return this.scoped<StatementWireResult, SqliteFailure | EncodeFailure>(connection, 'statement', txId, [transactionControl(piece)], () => this.encodeExecuted(this.executeOne(piece, params)));
469
+ }
470
+
471
+ /**
472
+ * `exec`: every statement of the text, in order, stopping at the first
473
+ * failure (statements before it keep their effect, as with sqlite3_exec).
474
+ * Each statement is classified before any runs, so transaction control
475
+ * hidden after a harmless first statement is refused just like a leading one.
476
+ */
477
+ private exec(connection: Connection, sql: string, txId: number | undefined) {
478
+ const pieces = splitSqlStatements(sql);
479
+ return this.scoped(connection, 'exec', txId, pieces.map((piece) => transactionControl(piece)), () => this.runScript(pieces));
480
+ }
481
+
482
+ /**
483
+ * Runs `work` under the transaction rules shared by every statement op:
484
+ * outside a transaction no transaction-control SQL at all; inside the
485
+ * caller's own transaction, savepoints only, and its lease is renewed (or
486
+ * the transaction closed when SQLite aborted it). Outside a transaction,
487
+ * work that somehow left one open is rolled back and reported.
488
+ */
489
+ private scoped<T, E>(connection: Connection, op: string, txId: number | undefined, controls: readonly TxControl[], work: () => Result<T, E>) {
490
+ if (txId === undefined) {
491
+ const refused = refuseControl(controls, op, undefined);
492
+ if (!refused.ok) return refused;
493
+ const wasInTransaction = this.db.inTransaction;
494
+ const outcome = work();
495
+ if (!wasInTransaction && this.db.inTransaction) {
496
+ const rolledBack = Trust.try(() => this.db.exec('ROLLBACK'), sqliteFailure);
497
+ if (!rolledBack.ok && rolledBack.error.kind === 'sqlite') this.log('rollback failed', { op, error: rolledBack.error.message });
498
+ return Result.err<SqliteFailure>({ kind: 'sqlite', message: `${op} left a transaction open, which only begin may do; it was rolled back` });
499
+ }
500
+ return outcome;
501
+ }
502
+ const owned = this.ownedTransaction(connection, txId);
503
+ if (!owned.ok) return owned;
504
+ const refused = refuseControl(controls, op, txId);
505
+ if (!refused.ok) return refused;
506
+ const outcome = work();
507
+ this.afterTransactionStatement(owned.value);
508
+ return outcome;
509
+ }
510
+
511
+ private runStatement(op: 'query' | 'run', sql: string, params: SqlParams | undefined) {
512
+ return op === 'query' ? this.query(sql, params) : this.run(sql, params);
513
+ }
514
+
515
+ /** SQLite aborts a transaction by itself on some errors; the server must not believe it is still open. */
516
+ private afterTransactionStatement(open: OpenTransaction): void {
517
+ if (!this.db.inTransaction) {
518
+ this.endTransaction('SQLite aborted the transaction', 'tx-expired', false);
519
+ return;
520
+ }
521
+ this.renewLease(open);
522
+ }
523
+
332
524
  private query(sql: string, params?: SqlParams) {
333
525
  const fetched = Trust.try(
334
526
  (): unknown => {
@@ -349,17 +541,116 @@ export class SqlegoServer {
349
541
  () => {
350
542
  const statement = this.db.query(sql);
351
543
  const outcome = params === undefined ? statement.run() : statement.run(...bindings(params));
352
- const result: RunResult = { changes: outcome.changes, lastInsertRowid: outcome.lastInsertRowid };
544
+ // safeIntegers may report either counter as bigint; `run` keeps answering with numbers.
545
+ const result: RunResult = { changes: Number(outcome.changes), lastInsertRowid: outcome.lastInsertRowid };
353
546
  return result;
354
547
  },
355
548
  sqliteFailure,
356
549
  );
357
550
  }
358
551
 
552
+ /**
553
+ * Prepares and steps one statement exactly once. A statement with result
554
+ * columns (SELECT, PRAGMA, `INSERT … RETURNING`) is stepped through `all()`
555
+ * and never re-run for its changes; one without is stepped through `run()`.
556
+ * `changes` is SQLite's own count when the statement changed anything
557
+ * (`total_changes()` moved), else 0 — `changes()` alone would repeat the
558
+ * previous write's count after a read or DDL.
559
+ */
560
+ private executeOne(sql: string, params: SqlParams | undefined) {
561
+ const before = this.counters();
562
+ if (!before.ok) return before;
563
+ const prepared = Trust.try(() => this.db.prepare(sql), sqliteFailure);
564
+ if (!prepared.ok) return prepared;
565
+ const statement = prepared.value;
566
+ const args: SQLQueryBindings[] = params === undefined ? [] : bindings(params);
567
+ const ran = Trust.try(
568
+ () => {
569
+ const columns: unknown = statement.columnNames;
570
+ if (!Array.isArray(columns)) throw new Error('SQLite returned invalid column metadata');
571
+ const reader = columns.length > 0;
572
+ if (reader) {
573
+ const rows: unknown = statement.all(...args);
574
+ return { reader, rows };
575
+ }
576
+ statement.run(...args);
577
+ return { reader, rows: [] };
578
+ },
579
+ sqliteFailure,
580
+ );
581
+ const finalized = Trust.try(() => statement.finalize(), sqliteFailure);
582
+ if (!finalized.ok && finalized.error.kind === 'sqlite') this.log('finalize failed', { error: finalized.error.message });
583
+ if (!ran.ok) return ran;
584
+ const after = this.counters();
585
+ if (!after.ok) return after;
586
+ const executed: Executed = {
587
+ reader: ran.value.reader,
588
+ rows: ran.value.rows,
589
+ changes: after.value.total === before.value.total ? 0 : after.value.changes,
590
+ lastInsertRowid: after.value.lastInsertRowid,
591
+ };
592
+ return Result.ok(executed);
593
+ }
594
+
595
+ private counters() {
596
+ const read = Trust.try(
597
+ (): unknown => this.db.query('SELECT changes() AS changes, total_changes() AS total, last_insert_rowid() AS rowid').get(),
598
+ sqliteFailure,
599
+ );
600
+ if (!read.ok) return read;
601
+ return parseCounters(read.value);
602
+ }
603
+
604
+ /** A `statement` reply in wire form: lossless integers and blobs. */
605
+ private encodeExecuted(executed: Result<Executed, SqliteFailure>) {
606
+ if (!executed.ok) return executed;
607
+ const rows = encodeResultRows(executed.value.rows);
608
+ if (!rows.ok) return Result.err<EncodeFailure>({ kind: 'encode-failed', message: rows.error.message });
609
+ const result: StatementWireResult = {
610
+ reader: executed.value.reader,
611
+ rows: rows.value,
612
+ changes: executed.value.changes,
613
+ lastInsertRowid: encodeWireInteger(executed.value.lastInsertRowid),
614
+ };
615
+ return Result.ok(result);
616
+ }
617
+
618
+ /**
619
+ * The statements of one `exec`, in order. Stops at the first failure, and
620
+ * also when a statement changed whether the connection is inside a
621
+ * transaction (which only begin/commit/rollback may do) — `scoped` and
622
+ * `afterTransactionStatement` then settle the transaction itself.
623
+ */
624
+ private runScript(pieces: readonly string[]) {
625
+ const wasInTransaction = this.db.inTransaction;
626
+ let changes = 0;
627
+ for (const [index, piece] of pieces.entries()) {
628
+ const at = pieces.length > 1 ? `statement ${index + 1} of ${pieces.length}` : 'the statement';
629
+ const executed = this.executeOne(piece, undefined);
630
+ if (!executed.ok) {
631
+ const applied = index > 0 ? ' (the statements before it took effect)' : '';
632
+ return Result.err<SqliteFailure>({ kind: 'sqlite', message: `${at} failed${applied}: ${executed.error.message}` });
633
+ }
634
+ changes += executed.value.changes;
635
+ if (this.db.inTransaction !== wasInTransaction) {
636
+ return Result.err<SqliteFailure>({ kind: 'sqlite', message: `${at} changed the transaction state; exec stopped there` });
637
+ }
638
+ }
639
+ const counters = this.counters();
640
+ if (!counters.ok) return counters;
641
+ const result: ExecWireResult = { statements: pieces.length, changes, lastInsertRowid: encodeWireInteger(counters.value.lastInsertRowid) };
642
+ return Result.ok(result);
643
+ }
644
+
359
645
  /** 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' });
646
+ private batch(connection: Connection, statements: readonly Statement[]) {
647
+ if (statements.length === 0) return badRequest('batch requires a non-empty statements array');
648
+ if (this.transaction && this.transaction.connection === connection) {
649
+ return badRequest(`batch is not allowed while this connection holds transaction ${this.transaction.id}: run the statements in it instead`);
650
+ }
651
+ for (const [index, item] of statements.entries()) {
652
+ const control = transactionControl(item.sql);
653
+ if (control !== null) return badRequest(`statements[${index}]: ${control.toUpperCase()} is not allowed in a batch, which is already one transaction`);
363
654
  }
364
655
  return Trust.try(
365
656
  () => {
@@ -379,14 +670,185 @@ export class SqlegoServer {
379
670
  throw new BatchStatementFailed(outcome.error);
380
671
  }
381
672
 
673
+ /* ------------------------------------------------------------------ *
674
+ * Leased transactions
675
+ * ------------------------------------------------------------------ */
676
+
677
+ private begin(connection: Connection, mode: TransactionMode, requestedLeaseMs: number | undefined) {
678
+ const open = this.transaction;
679
+ if (open) {
680
+ // Any other owner's `begin` is queued in accept(); only the owner reaches here.
681
+ return Result.err<TransactionFailure>({ kind: 'tx-invalid', message: `transaction ${open.id} is already open on this connection` });
682
+ }
683
+ const started = Trust.try(() => this.db.exec(mode === 'immediate' ? 'BEGIN IMMEDIATE' : 'BEGIN'), sqliteFailure);
684
+ if (!started.ok) return started;
685
+ const leaseMs = Math.min(requestedLeaseMs ?? this.txLeaseMs(), this.txLeaseMs());
686
+ const maxDurationMs = this.txMaxDurationMs();
687
+ const id = this.nextTransactionId++;
688
+ const now = Date.now();
689
+ const transaction: OpenTransaction = {
690
+ id,
691
+ connection,
692
+ startedAt: now,
693
+ lastRequestAt: now,
694
+ leaseMs,
695
+ leaseTimer: setTimeout(() => this.onLeaseExpired(id), leaseMs),
696
+ maxTimer: setTimeout(() => this.onMaxDuration(id), maxDurationMs),
697
+ };
698
+ this.transaction = transaction;
699
+ this.log('transaction opened', { txId: id, connection: connection.id, mode, leaseMs, maxDurationMs });
700
+ const result: BeginResult = { txId: id, leaseMs, maxDurationMs };
701
+ return Result.ok(result);
702
+ }
703
+
704
+ private finish(connection: Connection, txId: number, how: 'commit' | 'rollback') {
705
+ const owned = this.ownedTransaction(connection, txId);
706
+ if (!owned.ok) return owned;
707
+ const result: TransactionEndResult = { txId };
708
+ if (how === 'rollback') {
709
+ this.endTransaction('rolled back by client', 'tx-invalid', true);
710
+ return Result.ok(result);
711
+ }
712
+ const committed = Trust.try(() => this.db.exec('COMMIT'), sqliteFailure);
713
+ // A COMMIT that fails leaves the transaction open in SQLite; the client
714
+ // asked for it to end, so it does — by rollback — and learns why.
715
+ this.endTransaction(committed.ok ? 'committed' : `commit failed: ${committed.error.message}`, 'tx-invalid', !committed.ok);
716
+ if (!committed.ok) return committed;
717
+ return Result.ok(result);
718
+ }
719
+
720
+ /** The open transaction `txId` held by `connection`, or the precise reason there is none. */
721
+ private ownedTransaction(connection: Connection, txId: number) {
722
+ const open = this.transaction;
723
+ if (open && open.id === txId && open.connection === connection) return Result.ok(open);
724
+ const ending = this.ended.get(txId);
725
+ if (ending) return Result.err<TransactionFailure>({ kind: ending.code, message: ending.message });
726
+ if (open && open.id === txId) {
727
+ return Result.err<TransactionFailure>({ kind: 'tx-invalid', message: `transaction ${txId} belongs to another connection` });
728
+ }
729
+ return Result.err<TransactionFailure>({ kind: 'tx-invalid', message: `no open transaction ${txId} on this connection` });
730
+ }
731
+
732
+ private renewLease(open: OpenTransaction): void {
733
+ open.lastRequestAt = Date.now();
734
+ clearTimeout(open.leaseTimer);
735
+ open.leaseTimer = setTimeout(() => this.onLeaseExpired(open.id), open.leaseMs);
736
+ }
737
+
738
+ private onLeaseExpired(txId: number): void {
739
+ const open = this.transaction;
740
+ if (!open || open.id !== txId) return;
741
+ this.endTransaction(`no request for ${open.leaseMs} ms (lease expired)`, 'tx-expired', true);
742
+ this.drainQueue();
743
+ }
744
+
745
+ private onMaxDuration(txId: number): void {
746
+ const open = this.transaction;
747
+ if (!open || open.id !== txId) return;
748
+ this.endTransaction(`open for ${this.txMaxDurationMs()} ms (max duration reached)`, 'tx-expired', true);
749
+ this.drainQueue();
750
+ }
751
+
752
+ /**
753
+ * Closes the open transaction: stops its timers, rolls SQLite back when
754
+ * asked (and still inside one), and remembers how it ended so a late request
755
+ * for its id gets `code`. Callers drain the queue afterwards.
756
+ */
757
+ private endTransaction(reason: string, code: EndedTransaction['code'], rollback: boolean): void {
758
+ const open = this.transaction;
759
+ if (!open) return;
760
+ this.transaction = null;
761
+ clearTimeout(open.leaseTimer);
762
+ clearTimeout(open.maxTimer);
763
+ if (rollback && this.db.inTransaction) {
764
+ const rolledBack = Trust.try(() => this.db.exec('ROLLBACK'), sqliteFailure);
765
+ if (!rolledBack.ok && rolledBack.error.kind === 'sqlite') this.log('rollback failed', { txId: open.id, error: rolledBack.error.message });
766
+ }
767
+ this.remember(open.id, { code, message: `transaction ${open.id} ended: ${reason}` });
768
+ this.log('transaction ended', { txId: open.id, connection: open.connection.id, reason, ageMs: Date.now() - open.startedAt });
769
+ }
770
+
771
+ private remember(txId: number, ending: EndedTransaction): void {
772
+ this.ended.set(txId, ending);
773
+ while (this.ended.size > REMEMBERED_ENDINGS) {
774
+ const oldest = this.ended.keys().next();
775
+ if (oldest.done) break;
776
+ this.ended.delete(oldest.value);
777
+ }
778
+ }
779
+
780
+ /* ------------------------------------------------------------------ *
781
+ * Replies
782
+ * ------------------------------------------------------------------ */
783
+
784
+ /**
785
+ * Sends one response. A response that cannot be encoded is answered with an
786
+ * error frame for the same id; a connection that cannot be written to is dropped.
787
+ */
788
+ private reply(connection: Connection, response: Response): void {
789
+ const encoded = encodeFrame(response);
790
+ const frame = encoded.ok
791
+ ? encoded
792
+ : encodeFrame({ id: response.id, ok: false, error: { code: 'encode-failed', message: encoded.error.message } });
793
+ if (!frame.ok) {
794
+ if (frame.error.kind === 'encode-failed') this.dropConnection(connection, `cannot encode response ${response.id}: ${frame.error.message}`);
795
+ return;
796
+ }
797
+ const sent = this.send(connection, frame.value);
798
+ if (!sent.ok && sent.error.kind === 'write-failed') this.dropConnection(connection, sent.error.message);
799
+ }
800
+
801
+ private dropConnection(connection: Connection, why: string): void {
802
+ this.log('dropping connection', { connection: connection.id, error: why });
803
+ connection.outbound = null;
804
+ this.reportCleanup('drop connection', Trust.try(() => connection.socket.end(), cleanupFailure));
805
+ }
806
+
807
+ /** Queues behind any unflushed bytes so frames never interleave. */
808
+ private send(connection: Connection, frame: string) {
809
+ const queued = Trust.try(
810
+ () => {
811
+ const bytes = Buffer.from(frame, 'utf8');
812
+ connection.outbound = connection.outbound === null ? bytes : Buffer.concat([connection.outbound, bytes]);
813
+ },
814
+ writeFailure,
815
+ );
816
+ if (!queued.ok) return queued;
817
+ return this.flush(connection);
818
+ }
819
+
820
+ private onDrain(socket: ServerSocket): void {
821
+ const connection = socket.data;
822
+ if (!connection) return;
823
+ const flushed = this.flush(connection);
824
+ if (!flushed.ok && flushed.error.kind === 'write-failed') this.dropConnection(connection, flushed.error.message);
825
+ }
826
+
827
+ private flush(connection: Connection) {
828
+ return Trust.try(
829
+ () => {
830
+ const pending = connection.outbound;
831
+ if (pending === null) return;
832
+ const written = connection.socket.write(pending);
833
+ connection.outbound = written >= pending.length ? null : pending.subarray(Math.max(written, 0));
834
+ },
835
+ writeFailure,
836
+ );
837
+ }
838
+
839
+ /* ------------------------------------------------------------------ *
840
+ * Idle exit
841
+ * ------------------------------------------------------------------ */
842
+
382
843
  private armIdleTimer(): void {
383
844
  this.idleSince = Date.now();
384
845
  if (this.idleTimer) clearTimeout(this.idleTimer);
385
846
  this.idleTimer = setTimeout(() => this.onIdle(), this.options.idleTimeoutMs);
386
847
  }
387
848
 
849
+ /** Never while a client is connected or a transaction is open (its owner is connected, but the guard is explicit). */
388
850
  private onIdle(): void {
389
- if (this.connections.size > 0) return;
851
+ if (this.connections.size > 0 || this.transaction !== null) return;
390
852
  this.stop('idle');
391
853
  process.exit(0);
392
854
  }
@@ -400,6 +862,44 @@ export class SqlegoServer {
400
862
  }
401
863
  }
402
864
 
865
+ /**
866
+ * Refuses transaction-control statements: all of them outside a transaction
867
+ * (a stray `BEGIN` or `SAVEPOINT` would wrap every client's later statements),
868
+ * and those that would end or nest the transaction inside one. With several
869
+ * statements (`exec`) the message names which one.
870
+ */
871
+ function refuseControl(controls: readonly TxControl[], op: string, txId: number | undefined) {
872
+ for (const [index, control] of controls.entries()) {
873
+ if (control === null) continue;
874
+ const at = controls.length > 1 ? `statement ${index + 1}: ` : '';
875
+ if (txId === undefined) {
876
+ return badRequest(`${at}${control.toUpperCase()} is not allowed as a plain ${op}: open a transaction with begin and end it with commit or rollback`);
877
+ }
878
+ if (control === 'begin' || control === 'commit' || control === 'rollback') {
879
+ return badRequest(`${at}${control.toUpperCase()} is not allowed inside transaction ${txId}: end it with commit or rollback`);
880
+ }
881
+ }
882
+ return Result.ok(undefined);
883
+ }
884
+
885
+ /** The counters row: each an integer, as a number or (safeIntegers) a bigint. */
886
+ //trust:validator_function
887
+ function parseCounters(input: unknown) {
888
+ const fields = typeof input === 'object' && input !== null ? (input as Readonly<Record<string, unknown>>) : null;
889
+ const changes = fields?.changes;
890
+ const total = fields?.total;
891
+ const rowid = fields?.rowid;
892
+ if (
893
+ (typeof changes !== 'number' && typeof changes !== 'bigint')
894
+ || (typeof total !== 'number' && typeof total !== 'bigint')
895
+ || (typeof rowid !== 'number' && typeof rowid !== 'bigint')
896
+ ) {
897
+ return Result.err<SqliteFailure>({ kind: 'sqlite', message: 'unexpected shape of changes()/total_changes()/last_insert_rowid()' });
898
+ }
899
+ const counters: Counters = { changes: Number(changes), total: Number(total), lastInsertRowid: rowid };
900
+ return Result.ok(counters);
901
+ }
902
+
403
903
  /**
404
904
  * bun:sqlite binds positional params from an array spread and named params
405
905
  * from one object argument. Every SqlValue is a binding bun:sqlite accepts;