@noego/sqlego 0.1.2 → 0.1.3-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/src/server.ts CHANGED
@@ -1,17 +1,18 @@
1
1
  import { Database, type SQLQueryBindings, type Statement as SqliteStatement } from 'bun:sqlite';
2
- import { rmSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
2
+ import { rmSync, writeFileSync, existsSync, mkdirSync, statSync } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { Result, Trust } from '@noego/trust';
5
5
  import {
6
+ FrameReader,
6
7
  PROTOCOL_VERSION,
7
8
  encodeFrame,
8
9
  encodeResultRows,
9
10
  encodeWireInteger,
11
+ errnoCode,
10
12
  errorMessage,
11
13
  fromJson,
12
14
  parseRequest,
13
15
  parseRows,
14
- splitFrames,
15
16
  splitSqlStatements,
16
17
  toJson,
17
18
  transactionControl,
@@ -53,6 +54,12 @@ export type ServerOptions = Readonly<{
53
54
  txMaxDurationMs?: number;
54
55
  /** How long another client's request waits behind an open transaction before failing with `tx-busy`. Default 30 000. */
55
56
  txQueueTimeoutMs?: number;
57
+ /**
58
+ * How often the owner checks that the file is still where it opened it; a
59
+ * file deleted (or its directory), or replaced by another file, is
60
+ * released at once, clients or not. Default 5 000.
61
+ */
62
+ fileCheckMs?: number;
56
63
  }>;
57
64
 
58
65
  /**
@@ -68,6 +75,7 @@ export const DEFAULT_PRAGMAS: readonly string[] = ['auto_vacuum = INCREMENTAL',
68
75
  export const DEFAULT_TX_LEASE_MS = 10_000;
69
76
  export const DEFAULT_TX_MAX_DURATION_MS = 60_000;
70
77
  export const DEFAULT_TX_QUEUE_TIMEOUT_MS = 30_000;
78
+ export const DEFAULT_FILE_CHECK_MS = 5_000;
71
79
 
72
80
  type SqliteFailure = { readonly kind: 'sqlite'; readonly message: string; readonly code?: string };
73
81
  type BadRequest = { readonly kind: 'bad-request'; readonly message: string };
@@ -75,6 +83,12 @@ type TransactionFailure = { readonly kind: 'tx-expired' | 'tx-invalid'; readonly
75
83
  type CleanupFailure = { readonly kind: 'cleanup-failed'; readonly message: string };
76
84
  type WriteFailure = { readonly kind: 'write-failed'; readonly message: string };
77
85
  type EncodeFailure = { readonly kind: 'encode-failed'; readonly message: string };
86
+ type OwnerBusy = { readonly kind: 'owner-busy'; readonly message: string };
87
+
88
+ /** Which file the owner opened at its path: a different identity there means the path now leads elsewhere. */
89
+ type FileIdentity = Readonly<{ dev: bigint; ino: bigint }>;
90
+ /** Whether the file is still at its path: there, gone (deleted, or its directory), or replaced by another file. */
91
+ type FilePresence = 'present' | 'gone' | 'replaced';
78
92
 
79
93
  /** One statement as `executeOne` ran it: its raw rows and what it changed. */
80
94
  type Executed = { reader: boolean; rows: unknown; changes: number; lastInsertRowid: number | bigint };
@@ -91,7 +105,7 @@ const writeFailure = (cause: unknown): WriteFailure => ({ kind: 'write-failed',
91
105
  const badRequest = (message: string) => Result.err<BadRequest>({ kind: 'bad-request', message });
92
106
 
93
107
  /** Distinct statements each connection keeps prepared; past this, the least recently used is finalized. */
94
- const STATEMENT_CACHE_SIZE = 64;
108
+ const STATEMENT_CACHE_SIZE = 256;
95
109
 
96
110
  type PreparedStatement = SqliteStatement<unknown, SQLQueryBindings[]>;
97
111
 
@@ -104,19 +118,52 @@ type PreparedStatement = SqliteStatement<unknown, SQLQueryBindings[]>;
104
118
  * own `db.query()` cache cannot serve: it keeps its first 20 statements and
105
119
  * returns every later one uncached and unfinalized (2026-10-17: owners kept
106
120
  * thousands of descriptors on released, deleted files).
121
+ *
122
+ * SQL with a `*` anywhere is prepared for one use and finalized after it,
123
+ * never cached. Its result columns (`SELECT *`, `t.*`, `RETURNING *`) follow
124
+ * the schema, and a reused bun:sqlite statement keeps the column names it
125
+ * last read whenever the schema changes without bun:sqlite seeing it: on the
126
+ * reader after the writer's DDL, on the writer after a rollback undoes DDL
127
+ * (2026-10-18, Bun 1.3.6: a cached `SELECT *` on the reader left out a column
128
+ * the writer had just added). A column named in the SQL cannot change that
129
+ * way; one that no longer exists fails when SQLite prepares the statement again.
107
130
  */
108
131
  class StatementCache {
109
132
  private readonly statements = new Map<string, PreparedStatement>();
110
133
  private readonly db: Database;
111
134
  private readonly onFinalizeFailed: (message: string) => void;
135
+ private used = 0;
112
136
 
113
137
  constructor(db: Database, onFinalizeFailed: (message: string) => void) {
114
138
  this.db = db;
115
139
  this.onFinalizeFailed = onFinalizeFailed;
116
140
  }
117
141
 
118
- /** The prepared statement for `sql`; SQL that SQLite cannot prepare is a sqlite failure. */
119
- prepare(sql: string) {
142
+ /** How many statements `use` has run on this connection, failed ones included. */
143
+ get runs(): number {
144
+ return this.used;
145
+ }
146
+
147
+ /**
148
+ * Runs `work` on the prepared statement for `sql` and returns its outcome;
149
+ * SQL that SQLite cannot prepare is a sqlite failure.
150
+ */
151
+ use<T, E>(sql: string, work: (statement: PreparedStatement) => Result<T, E>) {
152
+ this.used += 1;
153
+ if (sql.includes('*')) return this.useOnce(sql, work);
154
+ const prepared = this.prepare(sql);
155
+ if (!prepared.ok) return prepared;
156
+ return work(prepared.value);
157
+ }
158
+
159
+ /** Finalizes every statement, so the connection can then close for real. */
160
+ clear(): void {
161
+ for (const statement of this.statements.values()) this.finalize(statement);
162
+ this.statements.clear();
163
+ }
164
+
165
+ /** The cached statement for `sql`, prepared on first use. */
166
+ private prepare(sql: string) {
120
167
  const cached = this.statements.get(sql);
121
168
  if (cached !== undefined) {
122
169
  // Re-inserted so the first key is always the least recently used.
@@ -131,10 +178,13 @@ class StatementCache {
131
178
  return prepared;
132
179
  }
133
180
 
134
- /** Finalizes every statement, so the connection can then close for real. */
135
- clear(): void {
136
- for (const statement of this.statements.values()) this.finalize(statement);
137
- this.statements.clear();
181
+ /** `use` for SQL that is never cached: prepared, run, finalized. */
182
+ private useOnce<T, E>(sql: string, work: (statement: PreparedStatement) => Result<T, E>) {
183
+ const prepared = Trust.try((): PreparedStatement => this.db.prepare<unknown, SQLQueryBindings[]>(sql), sqliteFailure);
184
+ if (!prepared.ok) return prepared;
185
+ const outcome = work(prepared.value);
186
+ this.finalize(prepared.value);
187
+ return outcome;
138
188
  }
139
189
 
140
190
  private evictLeastRecentlyUsed(): void {
@@ -152,12 +202,13 @@ class StatementCache {
152
202
  }
153
203
 
154
204
  /**
155
- * `outbound` holds bytes the kernel buffer refused (null when there are none).
156
- * Bun's `socket.write` returns the byte count it accepted and drops the rest,
157
- * so a large result followed by another frame corrupts the stream unless the
158
- * remainder is carried and flushed on `drain`.
205
+ * `frames` reads the request frames of this socket from its raw bytes (see
206
+ * `FrameReader.pushBytes`). `outbound` holds bytes the kernel buffer refused
207
+ * (null when there are none). Bun's `socket.write` returns the byte count it
208
+ * accepted and drops the rest, so a large result followed by another frame
209
+ * corrupts the stream unless the remainder is carried and flushed on `drain`.
159
210
  */
160
- type Connection = { id: number; buffer: string; outbound: Buffer | null; socket: ServerSocket; detachedPlain: boolean };
211
+ type Connection = { id: number; frames: FrameReader; outbound: Buffer | null; socket: ServerSocket; detachedPlain: boolean };
161
212
 
162
213
  /** Each socket carries its connection in Bun's typed `data` slot: null until `open` assigns it. */
163
214
  type ServerSocket = import('bun').Socket<Connection | null>;
@@ -222,6 +273,14 @@ export class SqlegoServer {
222
273
  private readonly reader: Database | null;
223
274
  private readonly statements: StatementCache;
224
275
  private readonly readerStatements: StatementCache | null;
276
+ /**
277
+ * The writer's `total_changes()` as the last `statement`/`exec` statement
278
+ * left it, and `statements.runs` then. While no statement has run since,
279
+ * it is the next one's "before" and costs no read; every statement that can
280
+ * change rows runs through `statements`, so a changed count means it may be
281
+ * stale. (BEGIN, COMMIT and ROLLBACK, run past the cache, never move it.)
282
+ */
283
+ private lastTotal: Readonly<{ total: number; runs: number }> | null = null;
225
284
 
226
285
  get capabilities(): readonly string[] {
227
286
  return this.reader ? ['detached-plain'] : [];
@@ -232,6 +291,9 @@ export class SqlegoServer {
232
291
  private listener: import('bun').UnixSocketListener<Connection | null> | null = null;
233
292
  private idleTimer: ReturnType<typeof setTimeout> | null = null;
234
293
  private idleSince: number | null = null;
294
+ /** The file as `listen` found it at its path (null when it could not be read then: only its presence is checked). */
295
+ private identity: FileIdentity | null = null;
296
+ private fileCheckTimer: ReturnType<typeof setTimeout> | null = null;
235
297
  private nextConnectionId = 1;
236
298
  private nextTransactionId = 1;
237
299
  private requestsServed = 0;
@@ -348,32 +410,43 @@ export class SqlegoServer {
348
410
  (cause) => ({ kind: 'listen-failed', message: `cannot listen on ${this.paths.socket}: ${errorMessage(cause)}` }),
349
411
  );
350
412
  if (!bound.ok) return bound;
413
+ this.identity = this.fileIdentity();
351
414
  this.armIdleTimer();
415
+ this.armFileCheck();
352
416
  this.log('listening', { file: this.paths.file, socket: this.paths.socket, pid: process.pid, idleTimeoutMs: this.options.idleTimeoutMs });
353
417
  return Result.ok(undefined);
354
418
  }
355
419
 
356
- /** Graceful stop: refuse new work, drop clients, release the file, remove socket/meta/lock. Every step is attempted. */
420
+ /**
421
+ * Graceful stop: refuse new work, drop clients, close the database, then
422
+ * remove lock, socket and meta and stop listening. Every step is attempted.
423
+ * The database closes before the socket stops answering: a client waiting
424
+ * for the file to be released (one retiring this owner) sees nothing answer
425
+ * only once the file is closed, so the owner it places the file with next
426
+ * never holds the file alongside this one. A client whose connect landed
427
+ * while this ran is dropped with the listener and connects again.
428
+ */
357
429
  stop(reason: string): void {
358
430
  if (this.stopping) return;
359
431
  this.stopping = true;
360
432
  this.log('stopping', { reason, clients: this.connections.size, requestsServed: this.requestsServed });
361
433
  if (this.idleTimer) clearTimeout(this.idleTimer);
434
+ if (this.fileCheckTimer) clearTimeout(this.fileCheckTimer);
362
435
  if (this.transaction) this.endTransaction('server stopping', 'tx-expired', true);
363
436
  for (const queued of this.queue.splice(0)) clearTimeout(queued.timer);
364
- // Socket file first: a client that connects after this point falls through
365
- // to claim-and-spawn instead of racing a closing server.
437
+ for (const connection of this.connections.values()) {
438
+ this.reportCleanup('end connection', Trust.try(() => connection.socket.end(), cleanupFailure));
439
+ }
440
+ this.closeConnections();
441
+ // The lock before the socket: once the socket is gone a client claims the
442
+ // lock to place the file anew, and that claim is not this owner's to remove.
443
+ this.reportCleanup('remove lock', Trust.try(() => rmSync(this.paths.lock, { force: true }), cleanupFailure));
366
444
  if (!isNamedPipe(this.paths.socket)) {
367
445
  this.reportCleanup('remove socket', Trust.try(() => rmSync(this.paths.socket, { force: true }), cleanupFailure));
368
446
  }
369
447
  this.reportCleanup('remove meta', Trust.try(() => rmSync(this.paths.meta, { force: true }), cleanupFailure));
370
- this.reportCleanup('remove lock', Trust.try(() => rmSync(this.paths.lock, { force: true }), cleanupFailure));
371
- for (const connection of this.connections.values()) {
372
- this.reportCleanup('end connection', Trust.try(() => connection.socket.end(), cleanupFailure));
373
- }
374
448
  const listener = this.listener;
375
449
  if (listener) this.reportCleanup('stop listener', Trust.try(() => listener.stop(true), cleanupFailure));
376
- this.closeConnections();
377
450
  }
378
451
 
379
452
  /**
@@ -470,7 +543,7 @@ export class SqlegoServer {
470
543
  return;
471
544
  }
472
545
  const id = this.nextConnectionId++;
473
- const connection: Connection = { id, buffer: '', outbound: null, socket, detachedPlain: false };
546
+ const connection: Connection = { id, frames: new FrameReader(), outbound: null, socket, detachedPlain: false };
474
547
  this.connections.set(id, connection);
475
548
  socket.data = connection;
476
549
  this.disarmIdleTimer();
@@ -499,9 +572,7 @@ export class SqlegoServer {
499
572
  private onData(socket: ServerSocket, data: Buffer): void {
500
573
  const connection = socket.data;
501
574
  if (!connection) return;
502
- const { frames, rest } = splitFrames(connection.buffer + data.toString('utf8'));
503
- connection.buffer = rest;
504
- for (const frame of frames) {
575
+ for (const frame of connection.frames.pushBytes(data)) {
505
576
  if (this.stopping) return;
506
577
  this.accept(connection, frame);
507
578
  }
@@ -616,6 +687,7 @@ export class SqlegoServer {
616
687
  case 'tx-invalid': return { id: request.id, ok: false, error: { code: 'tx-invalid', message: outcome.error.message } };
617
688
  case 'encode-failed': return { id: request.id, ok: false, error: { code: 'encode-failed', message: outcome.error.message } };
618
689
  case 'adopt-failed': return { id: request.id, ok: false, error: { code: 'adopt-failed', message: outcome.error.message } };
690
+ case 'owner-busy': return { id: request.id, ok: false, error: { code: 'owner-busy', message: outcome.error.message } };
619
691
  default: {
620
692
  const unhandled: never = outcome.error;
621
693
  return unhandled;
@@ -635,7 +707,7 @@ export class SqlegoServer {
635
707
  case 'commit': return this.finish(connection, request.txId, 'commit');
636
708
  case 'rollback': return this.finish(connection, request.txId, 'rollback');
637
709
  case 'status': return Result.ok(this.status());
638
- case 'stop': return Result.ok({ stopping: true });
710
+ case 'stop': return this.stopRequest(connection);
639
711
  case 'adopt': return this.adopt(request.file, request.pragmas, request.idleTimeoutMs);
640
712
  default: {
641
713
  const unhandled: never = request;
@@ -644,6 +716,25 @@ export class SqlegoServer {
644
716
  }
645
717
  }
646
718
 
719
+ /**
720
+ * A client's `stop`: granted only to the file's sole connection, then
721
+ * `serve` releases this file (and the process exits when it was the last).
722
+ * While other clients are connected, or another connection's transaction is
723
+ * open, it is refused with `owner-busy` and nothing is released: a client
724
+ * must never take a file away from the clients using it (2026-10-18: a CLI
725
+ * from another build stopped the running app's files, a 7-minute outage).
726
+ */
727
+ private stopRequest(connection: Connection) {
728
+ const others = this.connections.size - (this.connections.has(connection.id) ? 1 : 0);
729
+ const foreign = this.transaction !== null && this.transaction.connection !== connection;
730
+ if (others > 0 || foreign) {
731
+ const held = foreign && this.transaction ? `; transaction ${this.transaction.id} of another client is open` : '';
732
+ const clients = `${others} other client${others === 1 ? '' : 's'}`;
733
+ return Result.err<OwnerBusy>({ kind: 'owner-busy', message: `${this.paths.file} is in use by ${clients}${held}; nothing was released` });
734
+ }
735
+ return Result.ok({ stopping: true as const });
736
+ }
737
+
647
738
  /**
648
739
  * Serves one more file from this process, with this file's transaction
649
740
  * settings and log but its own pragmas and idle timeout. Only a standalone
@@ -751,12 +842,10 @@ export class SqlegoServer {
751
842
  }
752
843
 
753
844
  private query(sql: string, params?: SqlParams, db = this.db) {
754
- const statement = this.statementsOf(db).prepare(sql);
755
- if (!statement.ok) return statement;
756
- const fetched = Trust.try(
757
- (): unknown => (params === undefined ? statement.value.all() : statement.value.all(...bindings(params))),
845
+ const fetched = this.statementsOf(db).use(sql, (statement) => Trust.try(
846
+ (): unknown => (params === undefined ? statement.all() : statement.all(...bindings(params))),
758
847
  sqliteFailure,
759
- );
848
+ ));
760
849
  if (!fetched.ok) return fetched;
761
850
  const rows = parseRows(fetched.value);
762
851
  if (!rows.ok) return Result.err<SqliteFailure>({ kind: 'sqlite', message: `unexpected row shape: ${rows.error.message}` });
@@ -765,11 +854,9 @@ export class SqlegoServer {
765
854
  }
766
855
 
767
856
  private run(sql: string, params?: SqlParams, db = this.db) {
768
- const statement = this.statementsOf(db).prepare(sql);
769
- if (!statement.ok) return statement;
770
- return Trust.try(
857
+ return this.statementsOf(db).use(sql, (statement) => Trust.try(
771
858
  () => {
772
- const outcome = params === undefined ? statement.value.run() : statement.value.run(...bindings(params));
859
+ const outcome = params === undefined ? statement.run() : statement.run(...bindings(params));
773
860
  // safeIntegers may report either counter as bigint; `run` keeps answering with numbers.
774
861
  const result: RunResult = db === this.reader
775
862
  ? { changes: 0, lastInsertRowid: 0 }
@@ -777,7 +864,7 @@ export class SqlegoServer {
777
864
  return result;
778
865
  },
779
866
  sqliteFailure,
780
- );
867
+ ));
781
868
  }
782
869
 
783
870
  /** The statement cache of `db`, which is this file's writer or its reader. */
@@ -786,52 +873,75 @@ export class SqlegoServer {
786
873
  }
787
874
 
788
875
  /**
789
- * Prepares and steps one statement exactly once. A statement with result
790
- * columns (SELECT, PRAGMA, `INSERT … RETURNING`) is stepped through `all()`
791
- * and never re-run for its changes; one without is stepped through `run()`.
792
- * `changes` is SQLite's own count when the statement changed anything
793
- * (`total_changes()` moved), else 0 — `changes()` alone would repeat the
794
- * previous write's count after a read or DDL.
876
+ * Steps one statement exactly once (see `step`), prepared once per
877
+ * connection (see `StatementCache`). A statement with result columns
878
+ * (SELECT, PRAGMA, `INSERT … RETURNING`) is a reader and returns its rows;
879
+ * it is never re-run for its changes. `changes` is SQLite's own count when
880
+ * the statement changed anything (`total_changes()` moved), else 0 —
881
+ * `changes()` alone would repeat the previous write's count after a read or
882
+ * DDL. On the writer one counters read follows the statement; the total
883
+ * before it is the one the previous statement's read left (`lastTotal`),
884
+ * read afresh only when another statement ran in between. The reader cannot
885
+ * write: its statements report 0 and 0 and read no counters.
795
886
  */
796
887
  private executeOne(sql: string, params: SqlParams | undefined, db = this.db) {
797
- const before = this.counters(db);
798
- if (!before.ok) return before;
799
- const prepared = Trust.try(() => db.prepare(sql), sqliteFailure);
800
- if (!prepared.ok) return prepared;
801
- const statement = prepared.value;
802
888
  const args: SQLQueryBindings[] = params === undefined ? [] : bindings(params);
803
- const ran = Trust.try(
804
- () => {
805
- const columns: unknown = statement.columnNames;
806
- if (!Array.isArray(columns)) throw new Error('SQLite returned invalid column metadata');
807
- const reader = columns.length > 0;
808
- if (reader) {
809
- const rows: unknown = statement.all(...args);
810
- return { reader, rows };
811
- }
812
- statement.run(...args);
813
- return { reader, rows: [] };
814
- },
815
- sqliteFailure,
816
- );
817
- const finalized = Trust.try(() => statement.finalize(), sqliteFailure);
818
- if (!finalized.ok && finalized.error.kind === 'sqlite') this.log('finalize failed', { error: finalized.error.message });
889
+ if (db === this.reader) {
890
+ const ran = this.step(sql, args, db);
891
+ if (!ran.ok) return ran;
892
+ const executed: Executed = { reader: ran.value.reader, rows: ran.value.rows, changes: 0, lastInsertRowid: 0 };
893
+ return Result.ok(executed);
894
+ }
895
+ const before = this.writerTotal();
896
+ if (!before.ok) return before;
897
+ const ran = this.step(sql, args, db);
819
898
  if (!ran.ok) return ran;
820
899
  const after = this.counters(db);
821
900
  if (!after.ok) return after;
901
+ this.lastTotal = { total: after.value.total, runs: this.statements.runs };
822
902
  const executed: Executed = {
823
903
  reader: ran.value.reader,
824
904
  rows: ran.value.rows,
825
- changes: db === this.reader || after.value.total === before.value.total ? 0 : after.value.changes,
826
- lastInsertRowid: db === this.reader ? 0 : after.value.lastInsertRowid,
905
+ changes: after.value.total === before.value ? 0 : after.value.changes,
906
+ lastInsertRowid: after.value.lastInsertRowid,
827
907
  };
828
908
  return Result.ok(executed);
829
909
  }
830
910
 
911
+ /**
912
+ * Steps one statement on `db` through `all()`, then reads its columns: when
913
+ * another connection changed the schema, SQLite prepares the statement again
914
+ * as it steps, and only then do its columns match the rows. Read before the
915
+ * step they were the old ones, and `SELECT *` on the reader dropped the
916
+ * columns the writer had just added (2026-10-18). A statement without
917
+ * result columns steps to its end in `all()` just as in `run()`.
918
+ */
919
+ private step(sql: string, args: SQLQueryBindings[], db: Database) {
920
+ return this.statementsOf(db).use(sql, (statement) => Trust.try(
921
+ () => {
922
+ const rows: unknown = statement.all(...args);
923
+ const columns: unknown = statement.columnNames;
924
+ if (!Array.isArray(columns)) throw new Error('SQLite returned invalid column metadata');
925
+ return { reader: columns.length > 0, rows };
926
+ },
927
+ sqliteFailure,
928
+ ));
929
+ }
930
+
931
+ /** The writer's `total_changes()` now: `lastTotal` while no statement has run since, else read. */
932
+ private writerTotal() {
933
+ const last = this.lastTotal;
934
+ if (last !== null && last.runs === this.statements.runs) return Result.ok(last.total);
935
+ const read = this.counters();
936
+ if (!read.ok) return read;
937
+ return Result.ok(read.value.total);
938
+ }
939
+
831
940
  private counters(db = this.db) {
832
- const statement = this.statementsOf(db).prepare('SELECT changes() AS changes, total_changes() AS total, last_insert_rowid() AS rowid');
833
- if (!statement.ok) return statement;
834
- const read = Trust.try((): unknown => statement.value.get(), sqliteFailure);
941
+ const read = this.statementsOf(db).use(
942
+ 'SELECT changes() AS changes, total_changes() AS total, last_insert_rowid() AS rowid',
943
+ (statement) => Trust.try((): unknown => statement.get(), sqliteFailure),
944
+ );
835
945
  if (!read.ok) return read;
836
946
  return parseCounters(read.value);
837
947
  }
@@ -1105,6 +1215,85 @@ export class SqlegoServer {
1105
1215
  this.idleTimer = null;
1106
1216
  }
1107
1217
  }
1218
+
1219
+ /* ------------------------------------------------------------------ *
1220
+ * A file that left its path
1221
+ * ------------------------------------------------------------------ */
1222
+
1223
+ /**
1224
+ * Checks every `fileCheckMs` that the file is still at its path. One deleted
1225
+ * (or its directory), or replaced by another file, is released at once,
1226
+ * whoever is connected: nobody reaches that database by its path any more,
1227
+ * and an owner that kept it would hold a deleted file's space and
1228
+ * descriptors for as long as it lives (sqlego#8: owners still held test
1229
+ * fixtures deleted days before). The timer never keeps the process alive.
1230
+ */
1231
+ private armFileCheck(): void {
1232
+ if (this.fileCheckTimer) clearTimeout(this.fileCheckTimer);
1233
+ const timer = setTimeout(() => this.checkFile(), this.options.fileCheckMs ?? DEFAULT_FILE_CHECK_MS);
1234
+ timer.unref();
1235
+ this.fileCheckTimer = timer;
1236
+ }
1237
+
1238
+ private checkFile(): void {
1239
+ this.fileCheckTimer = null;
1240
+ if (this.stopping) return;
1241
+ const presence = this.filePresence();
1242
+ switch (presence) {
1243
+ case 'present':
1244
+ this.armFileCheck();
1245
+ return;
1246
+ case 'gone':
1247
+ case 'replaced':
1248
+ this.log('file left its path; releasing', { file: this.paths.file, presence, clients: this.connections.size });
1249
+ this.release(presence === 'gone' ? 'file gone' : 'file replaced');
1250
+ return;
1251
+ default: {
1252
+ const unhandled: never = presence;
1253
+ return unhandled;
1254
+ }
1255
+ }
1256
+ }
1257
+
1258
+ /**
1259
+ * Where the file stands at its path now. A path that cannot be read for
1260
+ * another reason (permissions, I/O) counts as present: only a file that is
1261
+ * known to be gone or different is released.
1262
+ */
1263
+ private filePresence(): FilePresence {
1264
+ const stat = Trust.try(
1265
+ () => statSync(this.paths.file, { bigint: true }),
1266
+ (cause) => {
1267
+ const code = errnoCode(cause);
1268
+ return code === 'ENOENT' || code === 'ENOTDIR' ? { kind: 'gone' as const } : { kind: 'unreadable' as const };
1269
+ },
1270
+ );
1271
+ if (!stat.ok) {
1272
+ switch (stat.error.kind) {
1273
+ case 'gone': return 'gone';
1274
+ case 'unreadable': return 'present';
1275
+ default: {
1276
+ const unhandled: never = stat.error;
1277
+ return unhandled;
1278
+ }
1279
+ }
1280
+ }
1281
+ const known = this.identity;
1282
+ if (known === null) return 'present';
1283
+ return stat.value.dev === known.dev && stat.value.ino === known.ino ? 'present' : 'replaced';
1284
+ }
1285
+
1286
+ /** The identity of the file at its path, or null when it cannot be read. */
1287
+ private fileIdentity(): FileIdentity | null {
1288
+ const stat = Trust.try(
1289
+ () => statSync(this.paths.file, { bigint: true }),
1290
+ (cause) => ({ kind: 'unreadable' as const, message: errorMessage(cause) }),
1291
+ );
1292
+ if (stat.ok) return { dev: stat.value.dev, ino: stat.value.ino };
1293
+ if (stat.error.kind === 'unreadable') return null;
1294
+ const unhandled: never = stat.error.kind;
1295
+ return unhandled;
1296
+ }
1108
1297
  }
1109
1298
 
1110
1299
  /**