@noego/sqlego 0.1.6-dev.1 → 0.1.6-dev.11

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,5 +1,5 @@
1
1
  import { Database, type SQLQueryBindings } from 'bun:sqlite';
2
- import { rmSync, writeFileSync, existsSync, mkdirSync, statSync } from 'node:fs';
2
+ import { renameSync, rmSync, writeFileSync, existsSync, mkdirSync, statSync, utimesSync } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { Result, Trust } from '@noego/trust';
5
5
  import { ReaderPool, sharedReaderPool, type ReaderOutcome, type ReaderRows } from './reader_pool.ts';
@@ -7,6 +7,7 @@ import { ReaderPool, sharedReaderPool, type ReaderOutcome, type ReaderRows } fro
7
7
  export { ReaderPool, DEFAULT_READERS, DEFAULT_READER_QUEUE_LIMIT, type ReaderPoolOptions } from './reader_pool.ts';
8
8
  import { StatementCache, sqliteFailure, stepStatement, type SqliteFailure } from './statement_cache.ts';
9
9
  import {
10
+ DEFAULT_MAX_FRAME_LENGTH,
10
11
  FrameReader,
11
12
  PROTOCOL_VERSION,
12
13
  encodeFrame,
@@ -38,6 +39,8 @@ import {
38
39
  type TransactionMode,
39
40
  type TransactionStatus,
40
41
  } from './protocol.ts';
42
+ import { decodeLease, handOverLease, leaseFile, recordedHolder, releaseLease, type Lease } from './lease.ts';
43
+ import { dropLegacyLock, passLegacyLock } from './legacy_lock.ts';
41
44
  import { isNamedPipe, resolvePaths, type FilePaths, type ServerMeta } from './paths.ts';
42
45
  import { VERSION } from './version.ts';
43
46
 
@@ -64,6 +67,15 @@ export type ServerOptions = Readonly<{
64
67
  * released at once, clients or not. Default 5 000.
65
68
  */
66
69
  fileCheckMs?: number;
70
+ /**
71
+ * How often (checked on the `fileCheckMs` timer) the owner sets the access
72
+ * and modification times of the runtime files it holds — its meta, its
73
+ * socket file, and its claim's lease generation — to now, so age-based
74
+ * temp-directory cleaners (macOS's, systemd-tmpfiles) never take them
75
+ * while it lives. Deleting them by other means while sqlego runs is not
76
+ * supported. Default `DEFAULT_RUNTIME_REFRESH_MS` (one hour).
77
+ */
78
+ runtimeRefreshMs?: number;
67
79
  /**
68
80
  * The reader workers opted-in plain reads of a WAL file run on (see
69
81
  * `reader_pool.ts`). Default: the process's shared pool, sized by
@@ -71,6 +83,23 @@ export type ServerOptions = Readonly<{
71
83
  * read on the owner thread's readonly connection.
72
84
  */
73
85
  readerPool?: ReaderPool;
86
+ /** The longest request frame read, in characters; a connection sending a longer one is dropped. Default `DEFAULT_MAX_FRAME_LENGTH` (64 MiB). */
87
+ maxFrameLength?: number;
88
+ /**
89
+ * A connection's unsent replies past this many bytes stop the owner reading
90
+ * its requests; it reads again once they fall to half. Default 1 MiB.
91
+ */
92
+ outboundHighWaterBytes?: number;
93
+ /** Unsent replies past this many bytes when another reply comes drop the connection. Default 64 MiB. */
94
+ outboundMaxBytes?: number;
95
+ /** A connection with unsent replies whose client reads none of them for this long is dropped. Default 30 000. */
96
+ outboundStallMs?: number;
97
+ /**
98
+ * The file's claim lease (`lease.ts`), already handed over to this process
99
+ * (`start` only). It is held while the file is served, so no client places
100
+ * the file anew while this owner lives, and released when the file stops.
101
+ */
102
+ claim?: Lease;
74
103
  }>;
75
104
 
76
105
  /**
@@ -87,6 +116,11 @@ export const DEFAULT_TX_LEASE_MS = 10_000;
87
116
  export const DEFAULT_TX_MAX_DURATION_MS = 60_000;
88
117
  export const DEFAULT_TX_QUEUE_TIMEOUT_MS = 30_000;
89
118
  export const DEFAULT_FILE_CHECK_MS = 5_000;
119
+ /** How often an owner refreshes the runtime files it holds (see `ServerOptions.runtimeRefreshMs`). */
120
+ export const DEFAULT_RUNTIME_REFRESH_MS = 60 * 60 * 1000;
121
+ export const DEFAULT_OUTBOUND_HIGH_WATER_BYTES = 1024 * 1024;
122
+ export const DEFAULT_OUTBOUND_MAX_BYTES = 64 * 1024 * 1024;
123
+ export const DEFAULT_OUTBOUND_STALL_MS = 30_000;
90
124
 
91
125
  type BadRequest = { readonly kind: 'bad-request'; readonly message: string };
92
126
  type TransactionFailure = { readonly kind: 'tx-expired' | 'tx-invalid'; readonly message: string };
@@ -107,6 +141,34 @@ type Counters = { changes: number; total: number; lastInsertRowid: number | bigi
107
141
  type TxControl = ReturnType<typeof transactionControl>;
108
142
 
109
143
  const cleanupFailure = (cause: unknown): CleanupFailure => ({ kind: 'cleanup-failed', message: errorMessage(cause) });
144
+
145
+ /** The older builds' claim lock (`<key>.lock`) beside a file's claim lease (`<key>.lease`). */
146
+ function legacyLockOf(claim: Lease): string {
147
+ return claim.base.replace(/\.lease$/, '.lock');
148
+ }
149
+
150
+ /**
151
+ * Frees a claim this process holds, and the older builds' claim lock with it
152
+ * — the lock first, so that a client of this build never finds the lease
153
+ * free while the lock still names this process.
154
+ */
155
+ function freeClaim(claim: Lease) {
156
+ const dropped = dropLegacyLock(legacyLockOf(claim), [process.pid]);
157
+ const released = releaseLease(claim);
158
+ if (!dropped.ok) return Result.err<CleanupFailure>({ kind: 'cleanup-failed', message: dropped.error.message });
159
+ if (!released.ok) return Result.err<CleanupFailure>({ kind: 'cleanup-failed', message: released.error.message });
160
+ return Result.ok(undefined);
161
+ }
162
+
163
+ /** Frees a claim handed to this process for a file it will not serve. */
164
+ function releaseUnserved(claim: Lease | undefined): void {
165
+ if (!claim) return;
166
+ const freed = freeClaim(claim);
167
+ if (!freed.ok && freed.error.kind === 'cleanup-failed') {
168
+ // It names this process, so it frees itself when the process exits.
169
+ }
170
+ }
171
+
110
172
  const writeFailure = (cause: unknown): WriteFailure => ({ kind: 'write-failed', message: errorMessage(cause) });
111
173
  const badRequest = (message: string) => Result.err<BadRequest>({ kind: 'bad-request', message });
112
174
 
@@ -131,18 +193,38 @@ type DetachedRequest = Extract<Request, { op: 'query' | 'run' | 'statement' }>;
131
193
  * a client that stopped reading while thousands of replies went out (a
132
194
  * mass `tx-busy` expiry) made every reply re-copy the whole backlog, and
133
195
  * the owner stalled for seconds.
196
+ *
197
+ * The backlog (`pendingBytes` + `outboundBytes`, both UTF-8 bytes) is bounded: past
198
+ * `outboundHighWaterBytes` the owner stops accepting this socket's requests
199
+ * (they wait in `inbox`, and the socket is paused so no more arrive) until
200
+ * it falls to half; past `outboundMaxBytes`, or with no byte taken by the
201
+ * client for `outboundStallMs`, the connection is dropped.
134
202
  */
135
203
  type Connection = {
136
204
  id: number;
137
205
  frames: FrameReader;
138
206
  outbound: Buffer[];
207
+ /** Bytes held in `outbound`. */
208
+ outboundBytes: number;
139
209
  /**
140
210
  * Reply frames not yet handed to the socket. Replies produced in one turn
141
211
  * (every request of a pipelined burst, a drained queue) are joined and
142
212
  * written once, from a microtask, instead of one write per reply.
143
213
  */
144
214
  pending: string[];
215
+ /** UTF-8 bytes of the frames held in `pending`, as `outboundBytes` counts them. */
216
+ pendingBytes: number;
145
217
  flushScheduled: boolean;
218
+ /** Request frames read but not yet accepted: held while the reply backlog is over the high-water mark. */
219
+ inbox: string[];
220
+ /** Whether the socket is paused (no `data` delivered) by `regulate`. */
221
+ paused: boolean;
222
+ /** Set by `dropConnection`: nothing more is read, served or sent. */
223
+ dropped: boolean;
224
+ /** Armed while `outbound` holds bytes: drops a client that takes none of them for `outboundStallMs`. */
225
+ stallTimer: ReturnType<typeof setTimeout> | null;
226
+ /** When the kernel last took bytes of `outbound` (or when it last began to refuse them). */
227
+ progressAt: number;
146
228
  socket: ServerSocket;
147
229
  detachedPlain: boolean;
148
230
  };
@@ -252,10 +334,14 @@ export class SqlegoServer {
252
334
  /** The file as `listen` found it at its path (null when it could not be read then: only its presence is checked). */
253
335
  private identity: FileIdentity | null = null;
254
336
  private fileCheckTimer: ReturnType<typeof setTimeout> | null = null;
337
+ /** When the runtime files this owner holds were last refreshed (created, at first). */
338
+ private runtimeRefreshedAt = Date.now();
255
339
  private nextConnectionId = 1;
256
340
  private nextTransactionId = 1;
257
341
  private requestsServed = 0;
258
342
  private stopping = false;
343
+ /** The file's claim while this owner holds it (see `ServerOptions.claim`). */
344
+ private claim: Lease | null;
259
345
  private transaction: OpenTransaction | null = null;
260
346
  /**
261
347
  * Held requests in arrival order, settled ones included until the drain
@@ -274,6 +360,7 @@ export class SqlegoServer {
274
360
  private constructor(options: ServerOptions, paths: FilePaths, db: Database, pragmas: readonly string[], reader: Database | null, busyTimeoutMs: number, readers: ReaderPool) {
275
361
  this.options = options;
276
362
  this.paths = paths;
363
+ this.claim = options.claim ?? null;
277
364
  this.db = db;
278
365
  this.reader = reader;
279
366
  this.pragmas = pragmas;
@@ -324,40 +411,74 @@ export class SqlegoServer {
324
411
 
325
412
  /**
326
413
  * Serves one file as (part of) a standalone owner process: opens it,
327
- * listens, releases the claimer's lock now that the socket is live, and
328
- * registers the file so the process exits when its last file is released.
329
- * A file this process already serves is returned as is.
414
+ * listens, and registers the file so the process exits when its last file
415
+ * is released. The file's claim (`options.claim`, when a client placed the
416
+ * file) stays held while the file is served and goes when it stops, or now
417
+ * if the file cannot be served. A file this process already serves is
418
+ * returned as is.
330
419
  */
331
420
  static start(options: ServerOptions) {
332
421
  const paths = resolvePaths(options.file);
333
- if (!paths.ok) return paths;
422
+ if (!paths.ok) {
423
+ releaseUnserved(options.claim);
424
+ return paths;
425
+ }
334
426
  for (const server of owned) {
335
- if (server.paths.file === paths.value.file) return Result.ok(server);
427
+ if (server.paths.file !== paths.value.file) continue;
428
+ // Served without a claim so far (started by hand): it holds this one from now on.
429
+ if (options.claim && server.claim === null) server.claim = options.claim;
430
+ else releaseUnserved(options.claim);
431
+ return Result.ok(server);
336
432
  }
337
433
  const opened = SqlegoServer.open(options);
338
- if (!opened.ok) return opened;
434
+ if (!opened.ok) {
435
+ releaseUnserved(options.claim);
436
+ return opened;
437
+ }
339
438
  const server = opened.value;
340
439
  const listening = server.listen();
341
440
  if (!listening.ok) {
342
441
  server.stop('listen failed');
343
442
  return listening;
344
443
  }
345
- const released = Trust.try(
346
- () => rmSync(server.paths.lock, { force: true }),
347
- (cause) => ({ kind: 'cleanup-failed' as const, message: errorMessage(cause) }),
348
- );
349
- server.reportCleanup('release claim lock', released);
350
444
  owned.add(server);
351
445
  return Result.ok(server);
352
446
  }
353
447
 
354
- /** Binds the socket and publishes meta. Clients can connect once this returns ok. */
448
+ /** Frees the file's claim (and the older builds' claim lock) if this owner still holds it; once only. */
449
+ private releaseClaim(): void {
450
+ const claim = this.claim;
451
+ this.claim = null;
452
+ if (!claim) return;
453
+ this.reportCleanup('release claim', freeClaim(claim));
454
+ }
455
+
456
+ /**
457
+ * Publishes meta, then binds the socket. Clients can connect once this
458
+ * returns ok. Meta comes first: a client that reaches the socket releases
459
+ * the spawn lock, and the next spawner counts owners from the meta files,
460
+ * so an owner that answers must already be among them. Meta is staged under
461
+ * a temporary name and renamed into place so no reader sees it half-written,
462
+ * and it is removed again if the bind fails.
463
+ */
355
464
  listen() {
356
465
  const meta: ServerMeta = {
357
466
  file: this.paths.file, socket: this.paths.socket, pid: process.pid, serverVersion: VERSION, startedAt: this.startedAt,
358
467
  };
359
468
  const metaJson = toJson(meta);
360
469
  if (!metaJson.ok) return Result.err({ kind: 'listen-failed', message: `cannot encode server meta: ${metaJson.error.message}` });
470
+ const staged = `${this.paths.meta}.${process.pid}.tmp`;
471
+ const published = Trust.try(
472
+ () => {
473
+ writeFileSync(staged, metaJson.value);
474
+ renameSync(staged, this.paths.meta);
475
+ },
476
+ (cause) => ({ kind: 'listen-failed', message: `cannot publish server meta ${this.paths.meta}: ${errorMessage(cause)}` }),
477
+ );
478
+ if (!published.ok) {
479
+ this.reportCleanup('remove staged meta', Trust.try(() => rmSync(staged, { force: true }), cleanupFailure));
480
+ return published;
481
+ }
361
482
  const bound = Trust.try(
362
483
  () => {
363
484
  // A socket file left by a dead owner must go before bind; a named pipe has no file.
@@ -373,11 +494,14 @@ export class SqlegoServer {
373
494
  error: (socket, error) => this.onSocketError(socket, error),
374
495
  },
375
496
  });
376
- writeFileSync(this.paths.meta, metaJson.value);
377
497
  },
378
498
  (cause) => ({ kind: 'listen-failed', message: `cannot listen on ${this.paths.socket}: ${errorMessage(cause)}` }),
379
499
  );
380
- if (!bound.ok) return bound;
500
+ if (!bound.ok) {
501
+ // Nothing answers for this owner, so it must not be counted as one.
502
+ this.reportCleanup('remove meta', Trust.try(() => rmSync(this.paths.meta, { force: true }), cleanupFailure));
503
+ return bound;
504
+ }
381
505
  this.identity = this.fileIdentity();
382
506
  this.armIdleTimer();
383
507
  this.armFileCheck();
@@ -411,12 +535,15 @@ export class SqlegoServer {
411
535
  const queued = this.flushPending(connection);
412
536
  const flushed = queued.ok ? this.flush(connection) : queued;
413
537
  if (!flushed.ok && flushed.error.kind === 'write-failed') this.log('flush before stop failed', { connection: connection.id, error: flushed.error.message });
538
+ connection.inbox = [];
539
+ this.clearStallTimer(connection);
414
540
  this.reportCleanup('end connection', Trust.try(() => connection.socket.end(), cleanupFailure));
415
541
  }
416
542
  this.closeConnections();
417
- // The lock before the socket: once the socket is gone a client claims the
418
- // lock to place the file anew, and that claim is not this owner's to remove.
419
- this.reportCleanup('remove lock', Trust.try(() => rmSync(this.paths.lock, { force: true }), cleanupFailure));
543
+ // The claim before the socket: once the socket is gone a client claims the
544
+ // file to place it anew, and that claim is not this owner's to release
545
+ // (a release once the claim has moved on changes nothing anyway).
546
+ this.releaseClaim();
420
547
  if (!isNamedPipe(this.paths.socket)) {
421
548
  this.reportCleanup('remove socket', Trust.try(() => rmSync(this.paths.socket, { force: true }), cleanupFailure));
422
549
  }
@@ -541,6 +668,22 @@ export class SqlegoServer {
541
668
  return this.options.txQueueTimeoutMs ?? DEFAULT_TX_QUEUE_TIMEOUT_MS;
542
669
  }
543
670
 
671
+ private maxFrameLength(): number {
672
+ return this.options.maxFrameLength ?? DEFAULT_MAX_FRAME_LENGTH;
673
+ }
674
+
675
+ private outboundHighWaterBytes(): number {
676
+ return this.options.outboundHighWaterBytes ?? DEFAULT_OUTBOUND_HIGH_WATER_BYTES;
677
+ }
678
+
679
+ private outboundMaxBytes(): number {
680
+ return this.options.outboundMaxBytes ?? DEFAULT_OUTBOUND_MAX_BYTES;
681
+ }
682
+
683
+ private outboundStallMs(): number {
684
+ return this.options.outboundStallMs ?? DEFAULT_OUTBOUND_STALL_MS;
685
+ }
686
+
544
687
  /** Shutdown is best effort: a step that fails is logged and the rest still run. */
545
688
  private reportCleanup(step: string, outcome: Result<unknown, CleanupFailure>): void {
546
689
  if (!outcome.ok && outcome.error.kind === 'cleanup-failed') this.log('cleanup failed', { step, error: outcome.error.message });
@@ -552,7 +695,10 @@ export class SqlegoServer {
552
695
  return;
553
696
  }
554
697
  const id = this.nextConnectionId++;
555
- const connection: Connection = { id, frames: new FrameReader(), outbound: [], pending: [], flushScheduled: false, socket, detachedPlain: false };
698
+ const connection: Connection = {
699
+ id, frames: new FrameReader(this.maxFrameLength()), outbound: [], outboundBytes: 0, pending: [], pendingBytes: 0, flushScheduled: false,
700
+ inbox: [], paused: false, dropped: false, stallTimer: null, progressAt: 0, socket, detachedPlain: false,
701
+ };
556
702
  this.connections.set(id, connection);
557
703
  socket.data = connection;
558
704
  this.disarmIdleTimer();
@@ -562,6 +708,8 @@ export class SqlegoServer {
562
708
  const connection = socket.data;
563
709
  if (!connection) return;
564
710
  this.connections.delete(connection.id);
711
+ connection.inbox = [];
712
+ this.clearStallTimer(connection);
565
713
  // A waiting request from a client that left has nobody to answer.
566
714
  if (this.waiting > 0) {
567
715
  for (const queued of this.queue) {
@@ -580,13 +728,80 @@ export class SqlegoServer {
580
728
  this.onClose(socket);
581
729
  }
582
730
 
731
+ /**
732
+ * Reads the frames of `data` into the connection's inbox and accepts as
733
+ * many as the reply backlog allows; the rest wait, with the socket paused,
734
+ * until the client has read enough of its replies (`regulate`).
735
+ */
583
736
  private onData(socket: ServerSocket, data: Buffer): void {
584
737
  const connection = socket.data;
585
- if (!connection) return;
586
- for (const frame of connection.frames.pushBytes(data)) {
587
- if (this.stopping) return;
588
- this.accept(connection, frame);
738
+ if (!connection || connection.dropped) return;
739
+ for (const frame of connection.frames.pushBytes(data)) connection.inbox.push(frame);
740
+ if (connection.frames.oversized) {
741
+ this.dropConnection(connection, `request frame exceeds ${this.maxFrameLength()} characters`);
742
+ return;
743
+ }
744
+ this.pump(connection);
745
+ this.regulate(connection);
746
+ }
747
+
748
+ /** Unsent reply bytes of one connection: not yet written plus refused by the kernel. */
749
+ private backlog(connection: Connection): number {
750
+ return connection.pendingBytes + connection.outboundBytes;
751
+ }
752
+
753
+ /** Accepts inbox frames in order while the reply backlog is within the high-water mark. */
754
+ private pump(connection: Connection): void {
755
+ const highWater = this.outboundHighWaterBytes();
756
+ let next = 0;
757
+ // `inbox` is read afresh each step: a request can drop the connection, which empties it.
758
+ while (next < connection.inbox.length && !connection.dropped && !this.stopping && this.backlog(connection) <= highWater) {
759
+ this.accept(connection, connection.inbox[next++]);
760
+ }
761
+ connection.inbox.splice(0, next);
762
+ }
763
+
764
+ /**
765
+ * Resumes accepting once the backlog is down to half the high-water mark,
766
+ * pauses the socket while requests wait or the backlog is over it, and
767
+ * keeps the stall watch in step with `outbound`.
768
+ */
769
+ private regulate(connection: Connection): void {
770
+ if (connection.dropped || !this.connections.has(connection.id)) return;
771
+ const highWater = this.outboundHighWaterBytes();
772
+ if (connection.inbox.length > 0 && this.backlog(connection) <= highWater / 2) this.pump(connection);
773
+ if (connection.dropped || !this.connections.has(connection.id)) return;
774
+ const hold = connection.inbox.length > 0 || this.backlog(connection) > highWater;
775
+ if (hold !== connection.paused) {
776
+ const switched = Trust.try(() => (hold ? connection.socket.pause() : connection.socket.resume()), cleanupFailure);
777
+ if (switched.ok) connection.paused = hold;
778
+ this.reportCleanup(hold ? 'pause connection' : 'resume connection', switched);
589
779
  }
780
+ this.watchStall(connection);
781
+ }
782
+
783
+ /** Drops the connection when its client has taken none of its unsent bytes for `outboundStallMs`. */
784
+ private watchStall(connection: Connection): void {
785
+ if (connection.outboundBytes === 0) {
786
+ this.clearStallTimer(connection);
787
+ return;
788
+ }
789
+ if (connection.stallTimer) return;
790
+ const stallMs = this.outboundStallMs();
791
+ connection.stallTimer = setTimeout(() => {
792
+ connection.stallTimer = null;
793
+ if (connection.dropped || !this.connections.has(connection.id) || connection.outboundBytes === 0) return;
794
+ if (Date.now() - connection.progressAt >= stallMs) {
795
+ this.dropConnection(connection, `client read nothing for ${stallMs} ms with ${connection.outboundBytes} bytes unsent`);
796
+ return;
797
+ }
798
+ this.watchStall(connection);
799
+ }, Math.max(0, connection.progressAt + stallMs - Date.now()));
800
+ }
801
+
802
+ private clearStallTimer(connection: Connection): void {
803
+ if (connection.stallTimer) clearTimeout(connection.stallTimer);
804
+ connection.stallTimer = null;
590
805
  }
591
806
 
592
807
  /** Parses one frame and either serves it now or holds it behind another client's transaction. */
@@ -692,8 +907,8 @@ export class SqlegoServer {
692
907
  'worker-failed': (error) => ({ retry: error.message }),
693
908
  sqlite: (error) => ({ failure: error }),
694
909
  }).value;
695
- // A departed client's request must not run again, least of all as a write.
696
- if (!this.connections.has(connection.id)) return;
910
+ // A departed (or dropped) client's request must not run again, least of all as a write.
911
+ if (connection.dropped || !this.connections.has(connection.id)) return;
697
912
  if ('retry' in settled) {
698
913
  this.log('detached read fell back in-thread', { connection: connection.id, error: settled.retry });
699
914
  if (this.stopping || !this.reader) {
@@ -775,6 +990,14 @@ export class SqlegoServer {
775
990
  else if (this.queue.length > 1_024 && this.waiting * 2 < this.queue.length) this.queue = this.queue.filter((entry) => !entry.settled);
776
991
  }
777
992
 
993
+ /** Abandons every request `connection` still has held behind a transaction: nobody will read its answer. */
994
+ private abandonQueued(connection: Connection): void {
995
+ if (this.waiting === 0) return;
996
+ for (const queued of this.queue) {
997
+ if (queued.connection === connection) this.settleQueued(queued);
998
+ }
999
+ }
1000
+
778
1001
  /**
779
1002
  * Serves held requests in arrival order until one of them opens a new
780
1003
  * transaction. Not re-entrant: `serve` drains after every request, and
@@ -799,7 +1022,23 @@ export class SqlegoServer {
799
1022
  }
800
1023
  }
801
1024
 
1025
+ /**
1026
+ * Runs one request and answers it. Nothing runs for a dropped connection,
1027
+ * nor for one whose unsent replies are already past `outboundMaxBytes`
1028
+ * (that drops it first): a write whose answer cannot be delivered must
1029
+ * not happen.
1030
+ */
802
1031
  private serve(connection: Connection, request: Request, outcome?: ReturnType<SqlegoServer['execute']>): void {
1032
+ if (!connection.dropped && this.backlog(connection) > this.outboundMaxBytes()) {
1033
+ this.dropConnection(connection, `reply backlog exceeds ${this.outboundMaxBytes()} bytes`);
1034
+ }
1035
+ if (connection.dropped) {
1036
+ // A detached read that already ran has nobody to answer; its failure is only logged.
1037
+ const discarded = outcome ? this.respond(connection, request, outcome) : null;
1038
+ if (discarded && !discarded.ok) this.log('answer for dropped connection discarded', { connection: connection.id, error: discarded.error.message });
1039
+ this.drainQueue();
1040
+ return;
1041
+ }
803
1042
  this.requestsServed += 1;
804
1043
  const response = this.respond(connection, request, outcome);
805
1044
  this.reply(connection, response);
@@ -847,7 +1086,7 @@ export class SqlegoServer {
847
1086
  case 'rollback': return this.finish(connection, request.txId, 'rollback');
848
1087
  case 'status': return Result.ok(this.status());
849
1088
  case 'stop': return this.stopRequest(connection);
850
- case 'adopt': return this.adopt(request.file, request.pragmas, request.idleTimeoutMs);
1089
+ case 'adopt': return this.adopt(request.file, request.pragmas, request.idleTimeoutMs, request.claim);
851
1090
  default: {
852
1091
  const unhandled: never = request;
853
1092
  return unhandled;
@@ -878,14 +1117,37 @@ export class SqlegoServer {
878
1117
  * Serves one more file from this process, with this file's transaction
879
1118
  * settings and log but its own pragmas and idle timeout. Only a standalone
880
1119
  * owner (`start`) may adopt: an embedded server has no process to lend.
1120
+ * The asking client's claim on the file (`claim`, an encoded lease) is
1121
+ * handed over to this process first, in one step that fails if anyone else
1122
+ * acted on that claim since; then the file is refused.
881
1123
  */
882
- private adopt(file: string, pragmas: readonly string[] | undefined, idleTimeoutMs: number | undefined) {
1124
+ private adopt(file: string, pragmas: readonly string[] | undefined, idleTimeoutMs: number | undefined, encodedClaim: string | undefined) {
883
1125
  if (!owned.has(this)) return badRequest('this owner is embedded in another process and cannot adopt files');
1126
+ let claim: Lease | undefined;
1127
+ if (encodedClaim !== undefined) {
1128
+ const paths = resolvePaths(file);
1129
+ if (!paths.ok) return Result.err({ kind: 'adopt-failed' as const, message: `cannot adopt ${file}: ${paths.error.message}` });
1130
+ const asked = decodeLease(paths.value.lease, encodedClaim);
1131
+ if (!asked) return badRequest(`adopt claim is not a lease: ${encodedClaim}`);
1132
+ const asker = recordedHolder(asked);
1133
+ const handed = handOverLease(asked, process.pid);
1134
+ if (!handed.ok) return Result.err({ kind: 'adopt-failed' as const, message: `cannot adopt ${file}: cannot take its claim over: ${handed.error.message}` });
1135
+ if (!handed.value) return Result.err({ kind: 'adopt-failed' as const, message: `cannot adopt ${file}: its claim was taken by another process since it was asked` });
1136
+ // The older builds' claim lock moves from the asking client to this owner with the claim.
1137
+ const legacy = passLegacyLock(paths.value.lock, asker, process.pid);
1138
+ if (!legacy.ok || !legacy.value) {
1139
+ releaseUnserved(handed.value);
1140
+ const why = legacy.ok ? 'a client of an older build holds its claim lock' : `cannot take its claim lock over: ${legacy.error.message}`;
1141
+ return Result.err({ kind: 'adopt-failed' as const, message: `cannot adopt ${file}: ${why}` });
1142
+ }
1143
+ claim = handed.value;
1144
+ }
884
1145
  const started = SqlegoServer.start({
885
1146
  ...this.options,
886
1147
  file,
887
1148
  pragmas: pragmas ?? DEFAULT_PRAGMAS,
888
1149
  idleTimeoutMs: idleTimeoutMs ?? this.options.idleTimeoutMs,
1150
+ claim,
889
1151
  });
890
1152
  if (!started.ok) {
891
1153
  return Result.err({ kind: 'adopt-failed' as const, message: `cannot adopt ${file}: ${started.error.message}` });
@@ -1287,24 +1549,50 @@ export class SqlegoServer {
1287
1549
  this.send(connection, frame.value);
1288
1550
  }
1289
1551
 
1552
+ /**
1553
+ * Gives up a connection at once: its unsent replies, its unread requests
1554
+ * and its requests held behind a transaction all go now, synchronously, so
1555
+ * none of them runs after this. The socket's `close` follows later.
1556
+ */
1290
1557
  private dropConnection(connection: Connection, why: string): void {
1291
1558
  this.log('dropping connection', { connection: connection.id, error: why });
1559
+ connection.dropped = true;
1292
1560
  connection.outbound = [];
1561
+ connection.outboundBytes = 0;
1293
1562
  connection.pending = [];
1563
+ connection.pendingBytes = 0;
1564
+ connection.inbox = [];
1565
+ this.abandonQueued(connection);
1566
+ this.clearStallTimer(connection);
1294
1567
  this.reportCleanup('drop connection', Trust.try(() => connection.socket.end(), cleanupFailure));
1295
1568
  }
1296
1569
 
1297
1570
  /**
1298
1571
  * Queues one frame behind every frame before it, so frames never
1299
1572
  * interleave, and schedules one write for everything queued this turn.
1573
+ * A connection whose unsent replies are already past `outboundMaxBytes`
1574
+ * is dropped instead: its client is not reading them.
1300
1575
  */
1301
1576
  private send(connection: Connection, frame: string): void {
1577
+ if (connection.dropped) return;
1578
+ const limit = this.outboundMaxBytes();
1579
+ if (this.backlog(connection) > limit) {
1580
+ this.dropConnection(connection, `reply backlog exceeds ${limit} bytes`);
1581
+ return;
1582
+ }
1583
+ const size = Trust.try(() => Buffer.byteLength(frame, 'utf8'), writeFailure);
1584
+ if (!size.ok) {
1585
+ if (size.error.kind === 'write-failed') this.dropConnection(connection, size.error.message);
1586
+ return;
1587
+ }
1302
1588
  connection.pending.push(frame);
1589
+ connection.pendingBytes += size.value;
1303
1590
  if (connection.flushScheduled) return;
1304
1591
  connection.flushScheduled = true;
1305
1592
  queueMicrotask(() => {
1306
1593
  const flushed = this.flushPending(connection);
1307
1594
  if (!flushed.ok && flushed.error.kind === 'write-failed') this.dropConnection(connection, flushed.error.message);
1595
+ else this.regulate(connection);
1308
1596
  });
1309
1597
  }
1310
1598
 
@@ -1318,16 +1606,25 @@ export class SqlegoServer {
1318
1606
  if (connection.pending.length === 0) return Result.ok(undefined);
1319
1607
  const text = connection.pending.length === 1 ? connection.pending[0] : connection.pending.join('');
1320
1608
  connection.pending = [];
1609
+ connection.pendingBytes = 0;
1321
1610
  if (!this.connections.has(connection.id)) return Result.ok(undefined);
1322
1611
  return Trust.try(
1323
1612
  () => {
1324
1613
  if (connection.outbound.length > 0) {
1325
- connection.outbound.push(Buffer.from(text, 'utf8'));
1614
+ const bytes = Buffer.from(text, 'utf8');
1615
+ connection.outbound.push(bytes);
1616
+ connection.outboundBytes += bytes.length;
1326
1617
  return;
1327
1618
  }
1328
1619
  const written = connection.socket.write(text);
1329
1620
  const length = Buffer.byteLength(text, 'utf8');
1330
- if (written < length) connection.outbound.push(Buffer.from(text, 'utf8').subarray(Math.max(written, 0)));
1621
+ if (written < length) {
1622
+ const rest = Buffer.from(text, 'utf8').subarray(Math.max(written, 0));
1623
+ connection.outbound.push(rest);
1624
+ connection.outboundBytes += rest.length;
1625
+ // The stall clock starts when bytes begin to wait.
1626
+ connection.progressAt = Date.now();
1627
+ }
1331
1628
  },
1332
1629
  writeFailure,
1333
1630
  );
@@ -1338,12 +1635,15 @@ export class SqlegoServer {
1338
1635
  if (!connection) return;
1339
1636
  const flushed = this.flush(connection);
1340
1637
  if (!flushed.ok && flushed.error.kind === 'write-failed') this.dropConnection(connection, flushed.error.message);
1638
+ else this.regulate(connection);
1341
1639
  }
1342
1640
 
1343
1641
  /**
1344
1642
  * Writes the unflushed bytes in order until the kernel refuses some. Small
1345
1643
  * chunks are joined up to `FLUSH_JOIN_BYTES` per write, so each byte is
1346
- * copied a bounded number of times however long the backlog grew.
1644
+ * copied a bounded number of times however long the backlog grew. Only
1645
+ * bytes the kernel took count as progress: `drain` also fires for a
1646
+ * client that reads nothing.
1347
1647
  */
1348
1648
  private flush(connection: Connection) {
1349
1649
  return Trust.try(
@@ -1355,6 +1655,8 @@ export class SqlegoServer {
1355
1655
  while (take < chunks.length && size + chunks[take].length <= FLUSH_JOIN_BYTES) size += chunks[take++].length;
1356
1656
  const bytes = take === 1 ? chunks[0] : Buffer.concat(chunks.slice(0, take), size);
1357
1657
  const written = Math.max(connection.socket.write(bytes), 0);
1658
+ connection.outboundBytes -= written;
1659
+ if (written > 0) connection.progressAt = Date.now();
1358
1660
  chunks.splice(0, take);
1359
1661
  if (written < bytes.length) {
1360
1662
  chunks.unshift(bytes.subarray(written));
@@ -1415,6 +1717,7 @@ export class SqlegoServer {
1415
1717
  const presence = this.filePresence();
1416
1718
  switch (presence) {
1417
1719
  case 'present':
1720
+ this.refreshRuntimeFiles();
1418
1721
  this.armFileCheck();
1419
1722
  return;
1420
1723
  case 'gone':
@@ -1429,6 +1732,28 @@ export class SqlegoServer {
1429
1732
  }
1430
1733
  }
1431
1734
 
1735
+ /**
1736
+ * Once every `runtimeRefreshMs` (on the file-check timer), sets the access
1737
+ * and modification times of the runtime files this owner holds — meta,
1738
+ * socket file (a named pipe has none), and while it holds the claim, the
1739
+ * claim's lease generation and the older builds' claim lock `<key>.lock` —
1740
+ * to now, so age-based temp cleaners never see them as stale while this
1741
+ * owner lives. One that is gone anyway is reported, not recreated:
1742
+ * deleting live runtime files is not supported.
1743
+ */
1744
+ private refreshRuntimeFiles(): void {
1745
+ const now = Date.now();
1746
+ if (now - this.runtimeRefreshedAt < (this.options.runtimeRefreshMs ?? DEFAULT_RUNTIME_REFRESH_MS)) return;
1747
+ this.runtimeRefreshedAt = now;
1748
+ const files = [this.paths.meta];
1749
+ if (!isNamedPipe(this.paths.socket)) files.push(this.paths.socket);
1750
+ if (this.claim) files.push(leaseFile(this.claim), this.paths.lock);
1751
+ const at = now / 1000;
1752
+ for (const file of files) {
1753
+ this.reportCleanup(`refresh ${path.basename(file)}`, Trust.try(() => utimesSync(file, at, at), cleanupFailure));
1754
+ }
1755
+ }
1756
+
1432
1757
  /**
1433
1758
  * Where the file stands at its path now. A path that cannot be read for
1434
1759
  * another reason (permissions, I/O) counts as present: only a file that is