@noego/sqlego 0.0.1-dev.0 → 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/src/server.ts CHANGED
@@ -11,7 +11,9 @@ import {
11
11
  parseRows,
12
12
  splitFrames,
13
13
  toJson,
14
+ transactionControl,
14
15
  type BatchResult,
16
+ type BeginResult,
15
17
  type HelloResult,
16
18
  type QueryResult,
17
19
  type Request,
@@ -21,6 +23,9 @@ import {
21
23
  type SqlValue,
22
24
  type Statement,
23
25
  type StatusResult,
26
+ type TransactionEndResult,
27
+ type TransactionMode,
28
+ type TransactionStatus,
24
29
  } from './protocol.ts';
25
30
  import { resolvePaths, type FilePaths, type ServerMeta } from './paths.ts';
26
31
  import { VERSION } from './version.ts';
@@ -32,6 +37,16 @@ export type ServerOptions = Readonly<{
32
37
  /** Pragmas applied on open, in order (e.g. `journal_mode = WAL`). */
33
38
  pragmas?: readonly string[];
34
39
  log?: (message: string, fields?: Record<string, unknown>) => void;
40
+ /**
41
+ * Default and ceiling for a client transaction's lease: the transaction is
42
+ * rolled back when no request for it arrives within this long. A client may
43
+ * ask for a shorter lease in `begin`, never a longer one. Default 10 000.
44
+ */
45
+ txLeaseMs?: number;
46
+ /** Hard cap on how long one transaction may stay open, renewed or not. Default 60 000. */
47
+ txMaxDurationMs?: number;
48
+ /** How long another client's request waits behind an open transaction before failing with `tx-busy`. Default 30 000. */
49
+ txQueueTimeoutMs?: number;
35
50
  }>;
36
51
 
37
52
  /**
@@ -42,13 +57,20 @@ export type ServerOptions = Readonly<{
42
57
  */
43
58
  export const DEFAULT_PRAGMAS: readonly string[] = ['auto_vacuum = INCREMENTAL', 'journal_mode = WAL', 'busy_timeout = 5000'];
44
59
 
60
+ export const DEFAULT_TX_LEASE_MS = 10_000;
61
+ export const DEFAULT_TX_MAX_DURATION_MS = 60_000;
62
+ export const DEFAULT_TX_QUEUE_TIMEOUT_MS = 30_000;
63
+
45
64
  type SqliteFailure = { readonly kind: 'sqlite'; readonly message: string };
65
+ type BadRequest = { readonly kind: 'bad-request'; readonly message: string };
66
+ type TransactionFailure = { readonly kind: 'tx-expired' | 'tx-invalid'; readonly message: string };
46
67
  type CleanupFailure = { readonly kind: 'cleanup-failed'; readonly message: string };
47
68
  type WriteFailure = { readonly kind: 'write-failed'; readonly message: string };
48
69
 
49
70
  const sqliteFailure = (cause: unknown): SqliteFailure => ({ kind: 'sqlite', message: errorMessage(cause) });
50
71
  const cleanupFailure = (cause: unknown): CleanupFailure => ({ kind: 'cleanup-failed', message: errorMessage(cause) });
51
72
  const writeFailure = (cause: unknown): WriteFailure => ({ kind: 'write-failed', message: errorMessage(cause) });
73
+ const badRequest = (message: string) => Result.err<BadRequest>({ kind: 'bad-request', message });
52
74
 
53
75
  /**
54
76
  * Carries one statement's failure out of a `db.transaction` callback: bun:sqlite
@@ -74,10 +96,33 @@ type Connection = { id: number; buffer: string; outbound: Buffer | null; socket:
74
96
  /** Each socket carries its connection in Bun's typed `data` slot: null until `open` assigns it. */
75
97
  type ServerSocket = import('bun').Socket<Connection | null>;
76
98
 
99
+ /** The one transaction a client may hold open; it lives and dies with `connection`. */
100
+ type OpenTransaction = {
101
+ id: number;
102
+ connection: Connection;
103
+ startedAt: number;
104
+ lastRequestAt: number;
105
+ leaseMs: number;
106
+ leaseTimer: ReturnType<typeof setTimeout>;
107
+ maxTimer: ReturnType<typeof setTimeout>;
108
+ };
109
+
110
+ /** A request from another client, held until the open transaction ends (or its wait runs out). */
111
+ type QueuedRequest = { connection: Connection; request: Request; timer: ReturnType<typeof setTimeout> };
112
+
113
+ /** How a transaction ended, kept so a late request for it gets a precise answer. */
114
+ type EndedTransaction = { code: 'tx-expired' | 'tx-invalid'; message: string };
115
+
116
+ const REMEMBERED_ENDINGS = 32;
117
+
77
118
  /**
78
119
  * The single owner of one SQLite file. Every request from every client runs,
79
120
  * in arrival order, on this process's one connection; SQLite's write lock is
80
121
  * therefore never contended from outside this process.
122
+ *
123
+ * While a client holds a transaction, that client's statements run at once
124
+ * and every other client's statements wait in arrival order; the transaction
125
+ * cannot outlive its socket, its lease, or the server's hard cap.
81
126
  */
82
127
  export class SqlegoServer {
83
128
  readonly paths: FilePaths;
@@ -89,9 +134,12 @@ export class SqlegoServer {
89
134
  private idleTimer: ReturnType<typeof setTimeout> | null = null;
90
135
  private idleSince: number | null = null;
91
136
  private nextConnectionId = 1;
137
+ private nextTransactionId = 1;
92
138
  private requestsServed = 0;
93
139
  private stopping = false;
94
- private lastOp: Request['op'] | null = null;
140
+ private transaction: OpenTransaction | null = null;
141
+ private readonly queue: QueuedRequest[] = [];
142
+ private readonly ended = new Map<number, EndedTransaction>();
95
143
  private readonly log: NonNullable<ServerOptions['log']>;
96
144
 
97
145
  private constructor(options: ServerOptions, paths: FilePaths, db: Database) {
@@ -155,6 +203,8 @@ export class SqlegoServer {
155
203
  this.stopping = true;
156
204
  this.log('stopping', { reason, clients: this.connections.size, requestsServed: this.requestsServed });
157
205
  if (this.idleTimer) clearTimeout(this.idleTimer);
206
+ if (this.transaction) this.endTransaction('server stopping', 'tx-expired', true);
207
+ for (const queued of this.queue.splice(0)) clearTimeout(queued.timer);
158
208
  // Socket file first: a client that connects after this point falls through
159
209
  // to claim-and-spawn instead of racing a closing server.
160
210
  this.reportCleanup('remove socket', Trust.try(() => rmSync(this.paths.socket, { force: true }), cleanupFailure));
@@ -180,9 +230,36 @@ export class SqlegoServer {
180
230
  idleMs: this.idleSince === null ? null : Date.now() - this.idleSince,
181
231
  idleTimeoutMs: this.options.idleTimeoutMs,
182
232
  requestsServed: this.requestsServed,
233
+ transaction: this.transactionStatus(),
234
+ };
235
+ }
236
+
237
+ private transactionStatus(): TransactionStatus | null {
238
+ const open = this.transaction;
239
+ if (!open) return null;
240
+ const now = Date.now();
241
+ return {
242
+ txId: open.id,
243
+ ageMs: now - open.startedAt,
244
+ idleMs: now - open.lastRequestAt,
245
+ leaseMs: open.leaseMs,
246
+ maxDurationMs: this.txMaxDurationMs(),
247
+ queued: this.queue.length,
183
248
  };
184
249
  }
185
250
 
251
+ private txLeaseMs(): number {
252
+ return this.options.txLeaseMs ?? DEFAULT_TX_LEASE_MS;
253
+ }
254
+
255
+ private txMaxDurationMs(): number {
256
+ return this.options.txMaxDurationMs ?? DEFAULT_TX_MAX_DURATION_MS;
257
+ }
258
+
259
+ private txQueueTimeoutMs(): number {
260
+ return this.options.txQueueTimeoutMs ?? DEFAULT_TX_QUEUE_TIMEOUT_MS;
261
+ }
262
+
186
263
  /** Shutdown is best effort: a step that fails is logged and the rest still run. */
187
264
  private reportCleanup(step: string, outcome: Result<unknown, CleanupFailure>): void {
188
265
  if (!outcome.ok && outcome.error.kind === 'cleanup-failed') this.log('cleanup failed', { step, error: outcome.error.message });
@@ -204,6 +281,14 @@ export class SqlegoServer {
204
281
  const connection = socket.data;
205
282
  if (!connection) return;
206
283
  this.connections.delete(connection.id);
284
+ // A waiting request from a client that left has nobody to answer.
285
+ for (let index = this.queue.length - 1; index >= 0; index -= 1) {
286
+ if (this.queue[index].connection === connection) clearTimeout(this.queue.splice(index, 1)[0].timer);
287
+ }
288
+ if (this.transaction && this.transaction.connection === connection) {
289
+ this.endTransaction(`client ${connection.id} disconnected`, 'tx-expired', true);
290
+ this.drainQueue();
291
+ }
207
292
  if (this.connections.size === 0 && !this.stopping) this.armIdleTimer();
208
293
  }
209
294
 
@@ -218,87 +303,96 @@ export class SqlegoServer {
218
303
  const { frames, rest } = splitFrames(connection.buffer + data.toString('utf8'));
219
304
  connection.buffer = rest;
220
305
  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
- }
306
+ if (this.stopping) return;
307
+ this.accept(connection, frame);
228
308
  }
229
309
  }
230
310
 
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}`);
311
+ /** Parses one frame and either serves it now or holds it behind another client's transaction. */
312
+ private accept(connection: Connection, frame: string): void {
313
+ const parsed = this.parseFrame(frame);
314
+ if (!parsed.ok) return this.reply(connection, { id: parsed.error.id, ok: false, error: { code: 'bad-request', message: parsed.error.message } });
315
+ const request = parsed.value;
316
+ if (this.mustWait(connection, request)) {
317
+ const timer = setTimeout(() => this.expireQueued(connection, request), this.txQueueTimeoutMs());
318
+ this.queue.push({ connection, request, timer });
242
319
  return;
243
320
  }
244
- const sent = this.send(connection, frame.value);
245
- if (!sent.ok && sent.error.kind === 'write-failed') this.dropConnection(connection, sent.error.message);
321
+ this.serve(connection, request);
246
322
  }
247
323
 
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));
324
+ /** A frame's request; a malformed one is a bad request answered on the id it carried (-1 when it had none). */
325
+ private parseFrame(frame: string) {
326
+ const json = fromJson(frame);
327
+ if (!json.ok) return Result.err({ kind: 'bad-request' as const, id: -1, message: `malformed frame: ${json.error.message}` });
328
+ const parsed = parseRequest(json.value);
329
+ if (!parsed.ok) return Result.err({ kind: 'bad-request' as const, id: parsed.error.id, message: parsed.error.message });
330
+ return parsed;
252
331
  }
253
332
 
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);
333
+ /**
334
+ * Statements from a client other than the transaction's owner wait until it
335
+ * ends. Its own requests, and anything that is not a statement (`hello`,
336
+ * `status`, `stop`), go through at once; so does a statement naming a
337
+ * `txId`, which can only be answered with a transaction error.
338
+ */
339
+ private mustWait(connection: Connection, request: Request): boolean {
340
+ const open = this.transaction;
341
+ if (!open || open.connection === connection) return false;
342
+ switch (request.op) {
343
+ case 'query':
344
+ case 'run': return request.txId === undefined;
345
+ case 'batch':
346
+ case 'begin': return true;
347
+ default: return false;
348
+ }
265
349
  }
266
350
 
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);
351
+ private expireQueued(connection: Connection, request: Request): void {
352
+ const index = this.queue.findIndex((queued) => queued.request === request);
353
+ if (index < 0) return;
354
+ this.queue.splice(index, 1);
355
+ const waited = this.txQueueTimeoutMs();
356
+ this.reply(connection, {
357
+ id: request.id, ok: false,
358
+ error: { code: 'tx-busy', message: `another client's transaction kept this ${request.op} waiting for ${waited} ms` },
359
+ });
272
360
  }
273
361
 
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
- );
362
+ /** Serves held requests in arrival order until one of them opens a new transaction. */
363
+ private drainQueue(): void {
364
+ while (this.queue.length > 0 && this.transaction === null && !this.stopping) {
365
+ const next = this.queue.shift();
366
+ if (!next) return;
367
+ clearTimeout(next.timer);
368
+ this.serve(next.connection, next.request);
369
+ }
284
370
  }
285
371
 
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;
372
+ private serve(connection: Connection, request: Request): void {
294
373
  this.requestsServed += 1;
374
+ const response = this.respond(connection, request);
375
+ this.reply(connection, response);
376
+ if (response.ok && request.op === 'stop') {
377
+ this.stop('client request');
378
+ setTimeout(() => process.exit(0), 20);
379
+ return;
380
+ }
381
+ // A commit, rollback or expiry may have freed the file for whoever was waiting.
382
+ this.drainQueue();
383
+ }
384
+
385
+ /** Decides every failure of one request into a wire response. */
386
+ private respond(connection: Connection, request: Request): Response {
295
387
  if (this.stopping) return { id: request.id, ok: false, error: { code: 'shutting-down', message: 'server is shutting down' } };
296
- const outcome = this.execute(request);
388
+ const outcome = this.execute(connection, request);
297
389
  if (outcome.ok) return { id: request.id, ok: true, result: outcome.value };
298
390
  switch (outcome.error.kind) {
299
391
  case 'bad-request': return { id: request.id, ok: false, error: { code: 'bad-request', message: outcome.error.message } };
300
392
  case 'protocol-mismatch': return { id: request.id, ok: false, error: { code: 'protocol-mismatch', message: outcome.error.message } };
301
393
  case 'sqlite': return { id: request.id, ok: false, error: { code: 'sqlite', message: outcome.error.message } };
394
+ case 'tx-expired': return { id: request.id, ok: false, error: { code: 'tx-expired', message: outcome.error.message } };
395
+ case 'tx-invalid': return { id: request.id, ok: false, error: { code: 'tx-invalid', message: outcome.error.message } };
302
396
  default: {
303
397
  const unhandled: never = outcome.error;
304
398
  return unhandled;
@@ -306,12 +400,15 @@ export class SqlegoServer {
306
400
  }
307
401
  }
308
402
 
309
- private execute(request: Request) {
403
+ private execute(connection: Connection, request: Request) {
310
404
  switch (request.op) {
311
405
  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);
406
+ case 'query':
407
+ case 'run': return this.statement(connection, request.op, request.sql, request.params, request.txId);
408
+ case 'batch': return this.batch(connection, request.statements);
409
+ case 'begin': return this.begin(connection, request.mode ?? 'deferred', request.leaseMs);
410
+ case 'commit': return this.finish(connection, request.txId, 'commit');
411
+ case 'rollback': return this.finish(connection, request.txId, 'rollback');
315
412
  case 'status': return Result.ok(this.status());
316
413
  case 'stop': return Result.ok({ stopping: true });
317
414
  default: {
@@ -329,6 +426,43 @@ export class SqlegoServer {
329
426
  return Result.ok(hello);
330
427
  }
331
428
 
429
+ /**
430
+ * One `query` or `run`. Outside a transaction no transaction-control SQL is
431
+ * accepted at all: a stray `BEGIN` would silently wrap every client's later
432
+ * statements. Inside one, savepoints are SQL but the transaction itself ends
433
+ * only through `commit`/`rollback`, so the server always knows its state.
434
+ */
435
+ private statement(connection: Connection, op: 'query' | 'run', sql: string, params: SqlParams | undefined, txId: number | undefined) {
436
+ const control = transactionControl(sql);
437
+ if (txId === undefined) {
438
+ if (control !== null) {
439
+ return badRequest(`${control.toUpperCase()} is not allowed as a plain ${op}: open a transaction with begin and end it with commit or rollback`);
440
+ }
441
+ return this.runStatement(op, sql, params);
442
+ }
443
+ const owned = this.ownedTransaction(connection, txId);
444
+ if (!owned.ok) return owned;
445
+ if (control === 'begin' || control === 'commit' || control === 'rollback') {
446
+ return badRequest(`${control.toUpperCase()} is not allowed inside transaction ${txId}: end it with commit or rollback`);
447
+ }
448
+ const outcome = this.runStatement(op, sql, params);
449
+ this.afterTransactionStatement(owned.value);
450
+ return outcome;
451
+ }
452
+
453
+ private runStatement(op: 'query' | 'run', sql: string, params: SqlParams | undefined) {
454
+ return op === 'query' ? this.query(sql, params) : this.run(sql, params);
455
+ }
456
+
457
+ /** SQLite aborts a transaction by itself on some errors; the server must not believe it is still open. */
458
+ private afterTransactionStatement(open: OpenTransaction): void {
459
+ if (!this.db.inTransaction) {
460
+ this.endTransaction('SQLite aborted the transaction', 'tx-expired', false);
461
+ return;
462
+ }
463
+ this.renewLease(open);
464
+ }
465
+
332
466
  private query(sql: string, params?: SqlParams) {
333
467
  const fetched = Trust.try(
334
468
  (): unknown => {
@@ -357,9 +491,14 @@ export class SqlegoServer {
357
491
  }
358
492
 
359
493
  /** 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' });
494
+ private batch(connection: Connection, statements: readonly Statement[]) {
495
+ if (statements.length === 0) return badRequest('batch requires a non-empty statements array');
496
+ if (this.transaction && this.transaction.connection === connection) {
497
+ return badRequest(`batch is not allowed while this connection holds transaction ${this.transaction.id}: run the statements in it instead`);
498
+ }
499
+ for (const [index, item] of statements.entries()) {
500
+ const control = transactionControl(item.sql);
501
+ if (control !== null) return badRequest(`statements[${index}]: ${control.toUpperCase()} is not allowed in a batch, which is already one transaction`);
363
502
  }
364
503
  return Trust.try(
365
504
  () => {
@@ -379,14 +518,185 @@ export class SqlegoServer {
379
518
  throw new BatchStatementFailed(outcome.error);
380
519
  }
381
520
 
521
+ /* ------------------------------------------------------------------ *
522
+ * Leased transactions
523
+ * ------------------------------------------------------------------ */
524
+
525
+ private begin(connection: Connection, mode: TransactionMode, requestedLeaseMs: number | undefined) {
526
+ const open = this.transaction;
527
+ if (open) {
528
+ // Any other owner's `begin` is queued in accept(); only the owner reaches here.
529
+ return Result.err<TransactionFailure>({ kind: 'tx-invalid', message: `transaction ${open.id} is already open on this connection` });
530
+ }
531
+ const started = Trust.try(() => this.db.exec(mode === 'immediate' ? 'BEGIN IMMEDIATE' : 'BEGIN'), sqliteFailure);
532
+ if (!started.ok) return started;
533
+ const leaseMs = Math.min(requestedLeaseMs ?? this.txLeaseMs(), this.txLeaseMs());
534
+ const maxDurationMs = this.txMaxDurationMs();
535
+ const id = this.nextTransactionId++;
536
+ const now = Date.now();
537
+ const transaction: OpenTransaction = {
538
+ id,
539
+ connection,
540
+ startedAt: now,
541
+ lastRequestAt: now,
542
+ leaseMs,
543
+ leaseTimer: setTimeout(() => this.onLeaseExpired(id), leaseMs),
544
+ maxTimer: setTimeout(() => this.onMaxDuration(id), maxDurationMs),
545
+ };
546
+ this.transaction = transaction;
547
+ this.log('transaction opened', { txId: id, connection: connection.id, mode, leaseMs, maxDurationMs });
548
+ const result: BeginResult = { txId: id, leaseMs, maxDurationMs };
549
+ return Result.ok(result);
550
+ }
551
+
552
+ private finish(connection: Connection, txId: number, how: 'commit' | 'rollback') {
553
+ const owned = this.ownedTransaction(connection, txId);
554
+ if (!owned.ok) return owned;
555
+ const result: TransactionEndResult = { txId };
556
+ if (how === 'rollback') {
557
+ this.endTransaction('rolled back by client', 'tx-invalid', true);
558
+ return Result.ok(result);
559
+ }
560
+ const committed = Trust.try(() => this.db.exec('COMMIT'), sqliteFailure);
561
+ // A COMMIT that fails leaves the transaction open in SQLite; the client
562
+ // asked for it to end, so it does — by rollback — and learns why.
563
+ this.endTransaction(committed.ok ? 'committed' : `commit failed: ${committed.error.message}`, 'tx-invalid', !committed.ok);
564
+ if (!committed.ok) return committed;
565
+ return Result.ok(result);
566
+ }
567
+
568
+ /** The open transaction `txId` held by `connection`, or the precise reason there is none. */
569
+ private ownedTransaction(connection: Connection, txId: number) {
570
+ const open = this.transaction;
571
+ if (open && open.id === txId && open.connection === connection) return Result.ok(open);
572
+ const ending = this.ended.get(txId);
573
+ if (ending) return Result.err<TransactionFailure>({ kind: ending.code, message: ending.message });
574
+ if (open && open.id === txId) {
575
+ return Result.err<TransactionFailure>({ kind: 'tx-invalid', message: `transaction ${txId} belongs to another connection` });
576
+ }
577
+ return Result.err<TransactionFailure>({ kind: 'tx-invalid', message: `no open transaction ${txId} on this connection` });
578
+ }
579
+
580
+ private renewLease(open: OpenTransaction): void {
581
+ open.lastRequestAt = Date.now();
582
+ clearTimeout(open.leaseTimer);
583
+ open.leaseTimer = setTimeout(() => this.onLeaseExpired(open.id), open.leaseMs);
584
+ }
585
+
586
+ private onLeaseExpired(txId: number): void {
587
+ const open = this.transaction;
588
+ if (!open || open.id !== txId) return;
589
+ this.endTransaction(`no request for ${open.leaseMs} ms (lease expired)`, 'tx-expired', true);
590
+ this.drainQueue();
591
+ }
592
+
593
+ private onMaxDuration(txId: number): void {
594
+ const open = this.transaction;
595
+ if (!open || open.id !== txId) return;
596
+ this.endTransaction(`open for ${this.txMaxDurationMs()} ms (max duration reached)`, 'tx-expired', true);
597
+ this.drainQueue();
598
+ }
599
+
600
+ /**
601
+ * Closes the open transaction: stops its timers, rolls SQLite back when
602
+ * asked (and still inside one), and remembers how it ended so a late request
603
+ * for its id gets `code`. Callers drain the queue afterwards.
604
+ */
605
+ private endTransaction(reason: string, code: EndedTransaction['code'], rollback: boolean): void {
606
+ const open = this.transaction;
607
+ if (!open) return;
608
+ this.transaction = null;
609
+ clearTimeout(open.leaseTimer);
610
+ clearTimeout(open.maxTimer);
611
+ if (rollback && this.db.inTransaction) {
612
+ const rolledBack = Trust.try(() => this.db.exec('ROLLBACK'), sqliteFailure);
613
+ if (!rolledBack.ok && rolledBack.error.kind === 'sqlite') this.log('rollback failed', { txId: open.id, error: rolledBack.error.message });
614
+ }
615
+ this.remember(open.id, { code, message: `transaction ${open.id} ended: ${reason}` });
616
+ this.log('transaction ended', { txId: open.id, connection: open.connection.id, reason, ageMs: Date.now() - open.startedAt });
617
+ }
618
+
619
+ private remember(txId: number, ending: EndedTransaction): void {
620
+ this.ended.set(txId, ending);
621
+ while (this.ended.size > REMEMBERED_ENDINGS) {
622
+ const oldest = this.ended.keys().next();
623
+ if (oldest.done) break;
624
+ this.ended.delete(oldest.value);
625
+ }
626
+ }
627
+
628
+ /* ------------------------------------------------------------------ *
629
+ * Replies
630
+ * ------------------------------------------------------------------ */
631
+
632
+ /**
633
+ * Sends one response. A response that cannot be encoded is answered with an
634
+ * error frame for the same id; a connection that cannot be written to is dropped.
635
+ */
636
+ private reply(connection: Connection, response: Response): void {
637
+ const encoded = encodeFrame(response);
638
+ const frame = encoded.ok
639
+ ? encoded
640
+ : encodeFrame({ id: response.id, ok: false, error: { code: 'encode-failed', message: encoded.error.message } });
641
+ if (!frame.ok) {
642
+ if (frame.error.kind === 'encode-failed') this.dropConnection(connection, `cannot encode response ${response.id}: ${frame.error.message}`);
643
+ return;
644
+ }
645
+ const sent = this.send(connection, frame.value);
646
+ if (!sent.ok && sent.error.kind === 'write-failed') this.dropConnection(connection, sent.error.message);
647
+ }
648
+
649
+ private dropConnection(connection: Connection, why: string): void {
650
+ this.log('dropping connection', { connection: connection.id, error: why });
651
+ connection.outbound = null;
652
+ this.reportCleanup('drop connection', Trust.try(() => connection.socket.end(), cleanupFailure));
653
+ }
654
+
655
+ /** Queues behind any unflushed bytes so frames never interleave. */
656
+ private send(connection: Connection, frame: string) {
657
+ const queued = Trust.try(
658
+ () => {
659
+ const bytes = Buffer.from(frame, 'utf8');
660
+ connection.outbound = connection.outbound === null ? bytes : Buffer.concat([connection.outbound, bytes]);
661
+ },
662
+ writeFailure,
663
+ );
664
+ if (!queued.ok) return queued;
665
+ return this.flush(connection);
666
+ }
667
+
668
+ private onDrain(socket: ServerSocket): void {
669
+ const connection = socket.data;
670
+ if (!connection) return;
671
+ const flushed = this.flush(connection);
672
+ if (!flushed.ok && flushed.error.kind === 'write-failed') this.dropConnection(connection, flushed.error.message);
673
+ }
674
+
675
+ private flush(connection: Connection) {
676
+ return Trust.try(
677
+ () => {
678
+ const pending = connection.outbound;
679
+ if (pending === null) return;
680
+ const written = connection.socket.write(pending);
681
+ connection.outbound = written >= pending.length ? null : pending.subarray(Math.max(written, 0));
682
+ },
683
+ writeFailure,
684
+ );
685
+ }
686
+
687
+ /* ------------------------------------------------------------------ *
688
+ * Idle exit
689
+ * ------------------------------------------------------------------ */
690
+
382
691
  private armIdleTimer(): void {
383
692
  this.idleSince = Date.now();
384
693
  if (this.idleTimer) clearTimeout(this.idleTimer);
385
694
  this.idleTimer = setTimeout(() => this.onIdle(), this.options.idleTimeoutMs);
386
695
  }
387
696
 
697
+ /** Never while a client is connected or a transaction is open (its owner is connected, but the guard is explicit). */
388
698
  private onIdle(): void {
389
- if (this.connections.size > 0) return;
699
+ if (this.connections.size > 0 || this.transaction !== null) return;
390
700
  this.stop('idle');
391
701
  process.exit(0);
392
702
  }