@noego/sqlego 0.1.6-dev.6 → 0.1.6-dev.7

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 { renameSync, rmSync, writeFileSync, existsSync, mkdirSync, statSync, utimesSync } 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 { ReaderPool, sharedReaderPool, type ReaderOutcome, type ReaderRows } from './reader_pool.ts';
@@ -7,7 +7,6 @@ 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,
11
10
  FrameReader,
12
11
  PROTOCOL_VERSION,
13
12
  encodeFrame,
@@ -39,8 +38,6 @@ import {
39
38
  type TransactionMode,
40
39
  type TransactionStatus,
41
40
  } from './protocol.ts';
42
- import { decodeLease, handOverLease, leaseFile, recordedHolder, releaseLease, type Lease } from './lease.ts';
43
- import { dropLegacyLock, passLegacyLock } from './legacy_lock.ts';
44
41
  import { isNamedPipe, resolvePaths, type FilePaths, type ServerMeta } from './paths.ts';
45
42
  import { VERSION } from './version.ts';
46
43
 
@@ -67,15 +64,6 @@ export type ServerOptions = Readonly<{
67
64
  * released at once, clients or not. Default 5 000.
68
65
  */
69
66
  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;
79
67
  /**
80
68
  * The reader workers opted-in plain reads of a WAL file run on (see
81
69
  * `reader_pool.ts`). Default: the process's shared pool, sized by
@@ -83,23 +71,6 @@ export type ServerOptions = Readonly<{
83
71
  * read on the owner thread's readonly connection.
84
72
  */
85
73
  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;
103
74
  }>;
104
75
 
105
76
  /**
@@ -116,11 +87,6 @@ export const DEFAULT_TX_LEASE_MS = 10_000;
116
87
  export const DEFAULT_TX_MAX_DURATION_MS = 60_000;
117
88
  export const DEFAULT_TX_QUEUE_TIMEOUT_MS = 30_000;
118
89
  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;
124
90
 
125
91
  type BadRequest = { readonly kind: 'bad-request'; readonly message: string };
126
92
  type TransactionFailure = { readonly kind: 'tx-expired' | 'tx-invalid'; readonly message: string };
@@ -141,34 +107,6 @@ type Counters = { changes: number; total: number; lastInsertRowid: number | bigi
141
107
  type TxControl = ReturnType<typeof transactionControl>;
142
108
 
143
109
  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
-
172
110
  const writeFailure = (cause: unknown): WriteFailure => ({ kind: 'write-failed', message: errorMessage(cause) });
173
111
  const badRequest = (message: string) => Result.err<BadRequest>({ kind: 'bad-request', message });
174
112
 
@@ -193,38 +131,18 @@ type DetachedRequest = Extract<Request, { op: 'query' | 'run' | 'statement' }>;
193
131
  * a client that stopped reading while thousands of replies went out (a
194
132
  * mass `tx-busy` expiry) made every reply re-copy the whole backlog, and
195
133
  * 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.
202
134
  */
203
135
  type Connection = {
204
136
  id: number;
205
137
  frames: FrameReader;
206
138
  outbound: Buffer[];
207
- /** Bytes held in `outbound`. */
208
- outboundBytes: number;
209
139
  /**
210
140
  * Reply frames not yet handed to the socket. Replies produced in one turn
211
141
  * (every request of a pipelined burst, a drained queue) are joined and
212
142
  * written once, from a microtask, instead of one write per reply.
213
143
  */
214
144
  pending: string[];
215
- /** UTF-8 bytes of the frames held in `pending`, as `outboundBytes` counts them. */
216
- pendingBytes: number;
217
145
  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;
228
146
  socket: ServerSocket;
229
147
  detachedPlain: boolean;
230
148
  };
@@ -334,14 +252,10 @@ export class SqlegoServer {
334
252
  /** The file as `listen` found it at its path (null when it could not be read then: only its presence is checked). */
335
253
  private identity: FileIdentity | null = null;
336
254
  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();
339
255
  private nextConnectionId = 1;
340
256
  private nextTransactionId = 1;
341
257
  private requestsServed = 0;
342
258
  private stopping = false;
343
- /** The file's claim while this owner holds it (see `ServerOptions.claim`). */
344
- private claim: Lease | null;
345
259
  private transaction: OpenTransaction | null = null;
346
260
  /**
347
261
  * Held requests in arrival order, settled ones included until the drain
@@ -360,7 +274,6 @@ export class SqlegoServer {
360
274
  private constructor(options: ServerOptions, paths: FilePaths, db: Database, pragmas: readonly string[], reader: Database | null, busyTimeoutMs: number, readers: ReaderPool) {
361
275
  this.options = options;
362
276
  this.paths = paths;
363
- this.claim = options.claim ?? null;
364
277
  this.db = db;
365
278
  this.reader = reader;
366
279
  this.pragmas = pragmas;
@@ -411,74 +324,40 @@ export class SqlegoServer {
411
324
 
412
325
  /**
413
326
  * Serves one file as (part of) a standalone owner process: opens it,
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.
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.
419
330
  */
420
331
  static start(options: ServerOptions) {
421
332
  const paths = resolvePaths(options.file);
422
- if (!paths.ok) {
423
- releaseUnserved(options.claim);
424
- return paths;
425
- }
333
+ if (!paths.ok) return paths;
426
334
  for (const server of owned) {
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);
335
+ if (server.paths.file === paths.value.file) return Result.ok(server);
432
336
  }
433
337
  const opened = SqlegoServer.open(options);
434
- if (!opened.ok) {
435
- releaseUnserved(options.claim);
436
- return opened;
437
- }
338
+ if (!opened.ok) return opened;
438
339
  const server = opened.value;
439
340
  const listening = server.listen();
440
341
  if (!listening.ok) {
441
342
  server.stop('listen failed');
442
343
  return listening;
443
344
  }
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);
444
350
  owned.add(server);
445
351
  return Result.ok(server);
446
352
  }
447
353
 
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
- */
354
+ /** Binds the socket and publishes meta. Clients can connect once this returns ok. */
464
355
  listen() {
465
356
  const meta: ServerMeta = {
466
357
  file: this.paths.file, socket: this.paths.socket, pid: process.pid, serverVersion: VERSION, startedAt: this.startedAt,
467
358
  };
468
359
  const metaJson = toJson(meta);
469
360
  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
- }
482
361
  const bound = Trust.try(
483
362
  () => {
484
363
  // A socket file left by a dead owner must go before bind; a named pipe has no file.
@@ -494,14 +373,11 @@ export class SqlegoServer {
494
373
  error: (socket, error) => this.onSocketError(socket, error),
495
374
  },
496
375
  });
376
+ writeFileSync(this.paths.meta, metaJson.value);
497
377
  },
498
378
  (cause) => ({ kind: 'listen-failed', message: `cannot listen on ${this.paths.socket}: ${errorMessage(cause)}` }),
499
379
  );
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
- }
380
+ if (!bound.ok) return bound;
505
381
  this.identity = this.fileIdentity();
506
382
  this.armIdleTimer();
507
383
  this.armFileCheck();
@@ -535,15 +411,12 @@ export class SqlegoServer {
535
411
  const queued = this.flushPending(connection);
536
412
  const flushed = queued.ok ? this.flush(connection) : queued;
537
413
  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);
540
414
  this.reportCleanup('end connection', Trust.try(() => connection.socket.end(), cleanupFailure));
541
415
  }
542
416
  this.closeConnections();
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();
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));
547
420
  if (!isNamedPipe(this.paths.socket)) {
548
421
  this.reportCleanup('remove socket', Trust.try(() => rmSync(this.paths.socket, { force: true }), cleanupFailure));
549
422
  }
@@ -668,22 +541,6 @@ export class SqlegoServer {
668
541
  return this.options.txQueueTimeoutMs ?? DEFAULT_TX_QUEUE_TIMEOUT_MS;
669
542
  }
670
543
 
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
-
687
544
  /** Shutdown is best effort: a step that fails is logged and the rest still run. */
688
545
  private reportCleanup(step: string, outcome: Result<unknown, CleanupFailure>): void {
689
546
  if (!outcome.ok && outcome.error.kind === 'cleanup-failed') this.log('cleanup failed', { step, error: outcome.error.message });
@@ -695,10 +552,7 @@ export class SqlegoServer {
695
552
  return;
696
553
  }
697
554
  const id = this.nextConnectionId++;
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
- };
555
+ const connection: Connection = { id, frames: new FrameReader(), outbound: [], pending: [], flushScheduled: false, socket, detachedPlain: false };
702
556
  this.connections.set(id, connection);
703
557
  socket.data = connection;
704
558
  this.disarmIdleTimer();
@@ -708,8 +562,6 @@ export class SqlegoServer {
708
562
  const connection = socket.data;
709
563
  if (!connection) return;
710
564
  this.connections.delete(connection.id);
711
- connection.inbox = [];
712
- this.clearStallTimer(connection);
713
565
  // A waiting request from a client that left has nobody to answer.
714
566
  if (this.waiting > 0) {
715
567
  for (const queued of this.queue) {
@@ -728,80 +580,13 @@ export class SqlegoServer {
728
580
  this.onClose(socket);
729
581
  }
730
582
 
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
- */
736
583
  private onData(socket: ServerSocket, data: Buffer): void {
737
584
  const connection = socket.data;
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);
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;
585
+ if (!connection) return;
586
+ for (const frame of connection.frames.pushBytes(data)) {
587
+ if (this.stopping) return;
588
+ this.accept(connection, frame);
788
589
  }
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;
805
590
  }
806
591
 
807
592
  /** Parses one frame and either serves it now or holds it behind another client's transaction. */
@@ -907,8 +692,8 @@ export class SqlegoServer {
907
692
  'worker-failed': (error) => ({ retry: error.message }),
908
693
  sqlite: (error) => ({ failure: error }),
909
694
  }).value;
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;
695
+ // A departed client's request must not run again, least of all as a write.
696
+ if (!this.connections.has(connection.id)) return;
912
697
  if ('retry' in settled) {
913
698
  this.log('detached read fell back in-thread', { connection: connection.id, error: settled.retry });
914
699
  if (this.stopping || !this.reader) {
@@ -990,14 +775,6 @@ export class SqlegoServer {
990
775
  else if (this.queue.length > 1_024 && this.waiting * 2 < this.queue.length) this.queue = this.queue.filter((entry) => !entry.settled);
991
776
  }
992
777
 
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
-
1001
778
  /**
1002
779
  * Serves held requests in arrival order until one of them opens a new
1003
780
  * transaction. Not re-entrant: `serve` drains after every request, and
@@ -1022,23 +799,7 @@ export class SqlegoServer {
1022
799
  }
1023
800
  }
1024
801
 
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
- */
1031
802
  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
- }
1042
803
  this.requestsServed += 1;
1043
804
  const response = this.respond(connection, request, outcome);
1044
805
  this.reply(connection, response);
@@ -1086,7 +847,7 @@ export class SqlegoServer {
1086
847
  case 'rollback': return this.finish(connection, request.txId, 'rollback');
1087
848
  case 'status': return Result.ok(this.status());
1088
849
  case 'stop': return this.stopRequest(connection);
1089
- case 'adopt': return this.adopt(request.file, request.pragmas, request.idleTimeoutMs, request.claim);
850
+ case 'adopt': return this.adopt(request.file, request.pragmas, request.idleTimeoutMs);
1090
851
  default: {
1091
852
  const unhandled: never = request;
1092
853
  return unhandled;
@@ -1117,37 +878,14 @@ export class SqlegoServer {
1117
878
  * Serves one more file from this process, with this file's transaction
1118
879
  * settings and log but its own pragmas and idle timeout. Only a standalone
1119
880
  * 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.
1123
881
  */
1124
- private adopt(file: string, pragmas: readonly string[] | undefined, idleTimeoutMs: number | undefined, encodedClaim: string | undefined) {
882
+ private adopt(file: string, pragmas: readonly string[] | undefined, idleTimeoutMs: number | undefined) {
1125
883
  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
- }
1145
884
  const started = SqlegoServer.start({
1146
885
  ...this.options,
1147
886
  file,
1148
887
  pragmas: pragmas ?? DEFAULT_PRAGMAS,
1149
888
  idleTimeoutMs: idleTimeoutMs ?? this.options.idleTimeoutMs,
1150
- claim,
1151
889
  });
1152
890
  if (!started.ok) {
1153
891
  return Result.err({ kind: 'adopt-failed' as const, message: `cannot adopt ${file}: ${started.error.message}` });
@@ -1549,50 +1287,24 @@ export class SqlegoServer {
1549
1287
  this.send(connection, frame.value);
1550
1288
  }
1551
1289
 
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
- */
1557
1290
  private dropConnection(connection: Connection, why: string): void {
1558
1291
  this.log('dropping connection', { connection: connection.id, error: why });
1559
- connection.dropped = true;
1560
1292
  connection.outbound = [];
1561
- connection.outboundBytes = 0;
1562
1293
  connection.pending = [];
1563
- connection.pendingBytes = 0;
1564
- connection.inbox = [];
1565
- this.abandonQueued(connection);
1566
- this.clearStallTimer(connection);
1567
1294
  this.reportCleanup('drop connection', Trust.try(() => connection.socket.end(), cleanupFailure));
1568
1295
  }
1569
1296
 
1570
1297
  /**
1571
1298
  * Queues one frame behind every frame before it, so frames never
1572
1299
  * 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.
1575
1300
  */
1576
1301
  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
- }
1588
1302
  connection.pending.push(frame);
1589
- connection.pendingBytes += size.value;
1590
1303
  if (connection.flushScheduled) return;
1591
1304
  connection.flushScheduled = true;
1592
1305
  queueMicrotask(() => {
1593
1306
  const flushed = this.flushPending(connection);
1594
1307
  if (!flushed.ok && flushed.error.kind === 'write-failed') this.dropConnection(connection, flushed.error.message);
1595
- else this.regulate(connection);
1596
1308
  });
1597
1309
  }
1598
1310
 
@@ -1606,25 +1318,16 @@ export class SqlegoServer {
1606
1318
  if (connection.pending.length === 0) return Result.ok(undefined);
1607
1319
  const text = connection.pending.length === 1 ? connection.pending[0] : connection.pending.join('');
1608
1320
  connection.pending = [];
1609
- connection.pendingBytes = 0;
1610
1321
  if (!this.connections.has(connection.id)) return Result.ok(undefined);
1611
1322
  return Trust.try(
1612
1323
  () => {
1613
1324
  if (connection.outbound.length > 0) {
1614
- const bytes = Buffer.from(text, 'utf8');
1615
- connection.outbound.push(bytes);
1616
- connection.outboundBytes += bytes.length;
1325
+ connection.outbound.push(Buffer.from(text, 'utf8'));
1617
1326
  return;
1618
1327
  }
1619
1328
  const written = connection.socket.write(text);
1620
1329
  const length = Buffer.byteLength(text, 'utf8');
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
- }
1330
+ if (written < length) connection.outbound.push(Buffer.from(text, 'utf8').subarray(Math.max(written, 0)));
1628
1331
  },
1629
1332
  writeFailure,
1630
1333
  );
@@ -1635,15 +1338,12 @@ export class SqlegoServer {
1635
1338
  if (!connection) return;
1636
1339
  const flushed = this.flush(connection);
1637
1340
  if (!flushed.ok && flushed.error.kind === 'write-failed') this.dropConnection(connection, flushed.error.message);
1638
- else this.regulate(connection);
1639
1341
  }
1640
1342
 
1641
1343
  /**
1642
1344
  * Writes the unflushed bytes in order until the kernel refuses some. Small
1643
1345
  * chunks are joined up to `FLUSH_JOIN_BYTES` per write, so each byte is
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.
1346
+ * copied a bounded number of times however long the backlog grew.
1647
1347
  */
1648
1348
  private flush(connection: Connection) {
1649
1349
  return Trust.try(
@@ -1655,8 +1355,6 @@ export class SqlegoServer {
1655
1355
  while (take < chunks.length && size + chunks[take].length <= FLUSH_JOIN_BYTES) size += chunks[take++].length;
1656
1356
  const bytes = take === 1 ? chunks[0] : Buffer.concat(chunks.slice(0, take), size);
1657
1357
  const written = Math.max(connection.socket.write(bytes), 0);
1658
- connection.outboundBytes -= written;
1659
- if (written > 0) connection.progressAt = Date.now();
1660
1358
  chunks.splice(0, take);
1661
1359
  if (written < bytes.length) {
1662
1360
  chunks.unshift(bytes.subarray(written));
@@ -1717,7 +1415,6 @@ export class SqlegoServer {
1717
1415
  const presence = this.filePresence();
1718
1416
  switch (presence) {
1719
1417
  case 'present':
1720
- this.refreshRuntimeFiles();
1721
1418
  this.armFileCheck();
1722
1419
  return;
1723
1420
  case 'gone':
@@ -1732,28 +1429,6 @@ export class SqlegoServer {
1732
1429
  }
1733
1430
  }
1734
1431
 
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
-
1757
1432
  /**
1758
1433
  * Where the file stands at its path now. A path that cannot be read for
1759
1434
  * another reason (permissions, I/O) counts as present: only a file that is