@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/client.ts CHANGED
@@ -1,16 +1,17 @@
1
1
  import { spawn } from 'node:child_process';
2
- import { closeSync, openSync, readdirSync, readFileSync, rmSync, writeSync, existsSync } from 'node:fs';
2
+ import { readdirSync, readFileSync, existsSync } from 'node:fs';
3
3
  import { createRequire } from 'node:module';
4
4
  import net from 'node:net';
5
5
  import path from 'node:path';
6
6
  import { fileURLToPath } from 'node:url';
7
7
  import { Result, Trust } from '@noego/trust';
8
8
  import { locateServerBinary, type BinaryMissing } from './binary.ts';
9
+ import { acquireLease, encodeLease, handOverLease, leaseHead, leaseHolder, releaseLease, spawnLeaseBase, type Lease } from './lease.ts';
10
+ import { dropLegacyLock, takeLegacyLock } from './legacy_lock.ts';
9
11
  import {
10
12
  FrameReader,
11
13
  PROTOCOL_VERSION,
12
14
  encodeRequestFrame,
13
- errnoCode,
14
15
  errorMessage,
15
16
  fromJson,
16
17
  parseBatchResult,
@@ -204,8 +205,10 @@ export class SqlegoClient {
204
205
  private mismatches: readonly OwnerMismatch[] = [];
205
206
  /** Why the server this client spawned did not come up, if it did not. */
206
207
  private spawnFailure: string | null = null;
207
- /** True while this client is the one spawning an owner process (see `placeFile`). */
208
- private holdsSpawnLock = false;
208
+ /** The file's claim while this client holds it (see `claimLock`); an owner that takes the file on takes it over. */
209
+ private claim: Lease | null = null;
210
+ /** The spawn reservation while this client holds it (see `placeFile`); the owner it spawns takes it over. */
211
+ private spawnLease: Lease | null = null;
209
212
  private readonly options: ClientOptions;
210
213
 
211
214
  private constructor(paths: FilePaths, options: ClientOptions) {
@@ -249,13 +252,14 @@ export class SqlegoClient {
249
252
  return this.hello.capabilities.includes('detached-plain');
250
253
  }
251
254
 
252
- async query<Row extends SqlRow = SqlRow>(sql: string, params?: SqlParams): Promise<Row[]> {
253
- const result = unwrap(await this.call({ op: 'query', sql, params }, parseQueryResult));
254
- return callerRows<Row>(result.rows);
255
+ // The request methods below are deliberately not `async`: a suspended async
256
+ // frame would keep `sql`/`params`/`statements` alive until the reply (#1178).
257
+ query<Row extends SqlRow = SqlRow>(sql: string, params?: SqlParams): Promise<Row[]> {
258
+ return this.call({ op: 'query', sql, params }, parseQueryResult).then((reply) => callerRows<Row>(unwrap(reply).rows));
255
259
  }
256
260
 
257
- async run(sql: string, params?: SqlParams): Promise<RunResult> {
258
- return unwrap(await this.call({ op: 'run', sql, params }, parseRunResult));
261
+ run(sql: string, params?: SqlParams): Promise<RunResult> {
262
+ return this.call({ op: 'run', sql, params }, parseRunResult).then((reply) => unwrap(reply));
259
263
  }
260
264
 
261
265
  /**
@@ -265,8 +269,8 @@ export class SqlegoClient {
265
269
  * changed (0 for a read). Integers beyond ±2^53-1 come back as `bigint`,
266
270
  * blobs as `Uint8Array`; `bigint` and `Uint8Array` parameters bind losslessly.
267
271
  */
268
- async statement<Row extends SqlRow = SqlRow>(sql: string, params?: SqlParams): Promise<StatementResult<Row>> {
269
- return callerStatement<Row>(unwrap(await this.call({ op: 'statement', sql, params }, parseStatementResult)));
272
+ statement<Row extends SqlRow = SqlRow>(sql: string, params?: SqlParams): Promise<StatementResult<Row>> {
273
+ return this.call({ op: 'statement', sql, params }, parseStatementResult).then((reply) => callerStatement<Row>(unwrap(reply)));
270
274
  }
271
275
 
272
276
  /**
@@ -275,14 +279,13 @@ export class SqlegoClient {
275
279
  * unless this runs inside a transaction that is then rolled back.
276
280
  * Transaction control anywhere in the text is refused, as with `run`.
277
281
  */
278
- async exec(sql: string): Promise<ExecResult> {
279
- return unwrap(await this.call({ op: 'exec', sql }, parseExecResult));
282
+ exec(sql: string): Promise<ExecResult> {
283
+ return this.call({ op: 'exec', sql }, parseExecResult).then((reply) => unwrap(reply));
280
284
  }
281
285
 
282
286
  /** One transaction; the whole batch rolls back on the first failure. */
283
- async batch(statements: readonly Statement[]): Promise<BatchResult['results']> {
284
- const result = unwrap(await this.call({ op: 'batch', statements }, parseBatchResult));
285
- return result.results;
287
+ batch(statements: readonly Statement[]): Promise<BatchResult['results']> {
288
+ return this.call({ op: 'batch', statements }, parseBatchResult).then((reply) => unwrap(reply).results);
286
289
  }
287
290
 
288
291
  /**
@@ -312,19 +315,18 @@ export class SqlegoClient {
312
315
  }
313
316
 
314
317
  /** @internal Statements inside a transaction; `SqlegoTransaction` is the public face. */
315
- async transactionQuery<Row extends SqlRow>(txId: number, sql: string, params?: SqlParams): Promise<Row[]> {
316
- const result = unwrap(await this.call({ op: 'query', sql, params, txId }, parseQueryResult));
317
- return callerRows<Row>(result.rows);
318
+ transactionQuery<Row extends SqlRow>(txId: number, sql: string, params?: SqlParams): Promise<Row[]> {
319
+ return this.call({ op: 'query', sql, params, txId }, parseQueryResult).then((reply) => callerRows<Row>(unwrap(reply).rows));
318
320
  }
319
321
 
320
322
  /** @internal */
321
- async transactionRun(txId: number, sql: string, params?: SqlParams): Promise<RunResult> {
322
- return unwrap(await this.call({ op: 'run', sql, params, txId }, parseRunResult));
323
+ transactionRun(txId: number, sql: string, params?: SqlParams): Promise<RunResult> {
324
+ return this.call({ op: 'run', sql, params, txId }, parseRunResult).then((reply) => unwrap(reply));
323
325
  }
324
326
 
325
327
  /** @internal */
326
- async transactionStatement<Row extends SqlRow>(txId: number, sql: string, params?: SqlParams): Promise<StatementResult<Row>> {
327
- return callerStatement<Row>(unwrap(await this.call({ op: 'statement', sql, params, txId }, parseStatementResult)));
328
+ transactionStatement<Row extends SqlRow>(txId: number, sql: string, params?: SqlParams): Promise<StatementResult<Row>> {
329
+ return this.call({ op: 'statement', sql, params, txId }, parseStatementResult).then((reply) => callerStatement<Row>(unwrap(reply)));
328
330
  }
329
331
 
330
332
  /** @internal */
@@ -511,34 +513,111 @@ export class SqlegoClient {
511
513
  if (this.options.spawn === false) {
512
514
  return Result.err({ kind: 'not-running', message: `no sqlego server for ${this.paths.file}` });
513
515
  }
514
- const claimed = this.claimLock();
515
- if (!claimed.ok) return claimed;
516
- if (claimed.value) {
517
- const placed = await this.placeFile(deadline);
518
- if (!placed.ok) {
519
- // Nothing will serve the file: the claim must go so the next client can try.
520
- const released = this.releaseLock();
521
- const suffix = !released.ok && released.error.kind === 'lock-failed' ? `; lock not released: ${released.error.message}` : '';
522
- return Result.err({ kind: placed.error.kind, message: `${placed.error.message}${suffix}` });
516
+ for (;;) {
517
+ const claimed = this.claimLock();
518
+ if (!claimed.ok) return claimed;
519
+ if (claimed.value) {
520
+ const placed = await this.placeFile(deadline);
521
+ if (!placed.ok) {
522
+ // Nothing will serve the file: the spawn lock (when this client took it) and the claim must go so the next client can try.
523
+ this.releaseSpawnLock();
524
+ const released = this.releaseLock();
525
+ const suffix = !released.ok && released.error.kind === 'lock-failed' ? `; lock not released: ${released.error.message}` : '';
526
+ return Result.err({ kind: placed.error.kind, message: `${placed.error.message}${suffix}` });
527
+ }
523
528
  }
529
+ // Claimer or not, the socket appears when the winner is listening.
530
+ const waited = await this.waitForSocket(deadline, !claimed.value);
531
+ if (!waited.ok) return waited;
532
+ if (waited.value) return Result.ok(waited.value);
533
+ // The claim it waited on was freed with nothing listening: place the file now.
524
534
  }
525
- // Claimer or not, the socket appears when the winner is listening.
535
+ }
536
+
537
+ /** How often a client waiting on another process's claim checks whether that claim was freed. */
538
+ private static readonly CLAIM_RECHECK_MS = 100;
539
+
540
+ /**
541
+ * Waits for the file's socket until `deadline`. A client that found the
542
+ * claim held by another process (`watchClaim`) also watches that claim:
543
+ * an owner that is stopping removes its socket and meta while it still
544
+ * holds the claim and frees it last, so once the claim is free nothing
545
+ * will listen unless this client places the file itself (ok, null).
546
+ */
547
+ private async waitForSocket(deadline: number, watchClaim: boolean) {
548
+ let rechecked = Date.now();
526
549
  for (let delayMs = 2; Date.now() < deadline; delayMs = Math.min(25, delayMs * 2)) {
527
550
  const socket = await tryConnect(this.paths.socket);
528
551
  if (socket) {
529
- this.releaseSpawnLock();
530
- return Result.ok(socket);
552
+ this.settleLeases();
553
+ return Result.ok<typeof socket | null>(socket);
554
+ }
555
+ if (watchClaim && Date.now() - rechecked >= SqlegoClient.CLAIM_RECHECK_MS) {
556
+ rechecked = Date.now();
557
+ // A claim that cannot be read is not known to be free.
558
+ if (Trust.decide(leaseHolder(this.paths.lease), { 'lease-failed': () => -1 }).value === null) return Result.ok(null);
531
559
  }
532
560
  await sleep(delayMs);
533
561
  }
534
- this.releaseSpawnLock();
562
+ this.settleLeases();
535
563
  const cause = this.spawnFailure ? ` (${this.spawnFailure})` : '';
536
- return Result.err({ kind: 'connect-timeout', message: `no sqlego server became reachable for ${this.paths.file}${cause}` });
564
+ return Result.err({ kind: 'connect-timeout' as const, message: `no sqlego server became reachable for ${this.paths.file}${cause}` });
537
565
  }
538
566
 
539
- /** The file's own claim lock: whoever holds it places the file with an owner. */
567
+ /**
568
+ * The file's claim: whoever holds it places the file with an owner, which
569
+ * then holds it while it serves the file. See `takeClaim`.
570
+ */
540
571
  private claimLock() {
541
- return claimLockAt(this.paths.lock);
572
+ const taken = this.takeClaim();
573
+ if (!taken.ok) return taken;
574
+ this.claim = taken.value;
575
+ return Result.ok(taken.value !== null);
576
+ }
577
+
578
+ /**
579
+ * Takes the file's claim lease and, with it, the claim lock older builds
580
+ * use (`<key>.lock`, see legacy_lock.ts) so that they see the file claimed
581
+ * too. Null when either is held: the lease by a process of this build, the
582
+ * lock by a live client of an older build placing the file.
583
+ */
584
+ private takeClaim(): Result<Lease | null, { readonly kind: 'lock-failed'; readonly message: string }> {
585
+ const acquired = acquireLease(this.paths.lease);
586
+ if (!acquired.ok) return Result.err({ kind: 'lock-failed', message: `cannot claim ${this.paths.file}: ${acquired.error.message}` });
587
+ const lease = acquired.value;
588
+ if (!lease) return Result.ok(null);
589
+ const legacy = takeLegacyLock(this.paths.lock, process.pid);
590
+ if (legacy.ok && legacy.value) return Result.ok(lease);
591
+ const released = releaseLease(lease);
592
+ if (!released.ok && released.error.kind === 'lease-failed') {
593
+ // It names this live process; it frees itself when the process exits.
594
+ }
595
+ if (!legacy.ok) return Result.err({ kind: 'lock-failed', message: `cannot claim ${this.paths.file}: ${legacy.error.message}` });
596
+ return Result.ok(null);
597
+ }
598
+
599
+ /**
600
+ * Where this client's claim stands. `own` while this client still holds
601
+ * it (or holds none); `placed` once a live process holds it instead — the
602
+ * owner that took the file on, or another client placing it. An owner that
603
+ * took the claim over and then could not serve the file (its open or bind
604
+ * failed) released it again: this client takes it back and keeps placing.
605
+ */
606
+ private followClaim(): Result<'own' | 'placed', { readonly kind: 'lock-failed'; readonly message: string }> {
607
+ const claim = this.claim;
608
+ if (!claim) return Result.ok('own');
609
+ // A lease that cannot be read is not known to have moved on.
610
+ if (Trust.decide(leaseHead(claim.base), { 'lease-failed': () => 0 }).value <= claim.generation) return Result.ok('own');
611
+ const holder = leaseHolder(claim.base);
612
+ if (!holder.ok) return Result.err({ kind: 'lock-failed', message: `cannot read the claim on ${this.paths.file}: ${holder.error.message}` });
613
+ if (holder.value !== null) {
614
+ this.claim = null;
615
+ return Result.ok('placed');
616
+ }
617
+ const again = this.takeClaim();
618
+ if (!again.ok) return Result.err({ kind: 'lock-failed', message: `cannot claim ${this.paths.file} again: ${again.error.message}` });
619
+ this.claim = again.value;
620
+ return Result.ok(again.value === null ? 'placed' : 'own');
542
621
  }
543
622
 
544
623
  /* ------------------------------------------------------------------ *
@@ -550,32 +629,45 @@ export class SqlegoClient {
550
629
  return Number.isFinite(configured) && configured >= 0 ? Math.floor(configured) : DEFAULT_MAX_OWNERS;
551
630
  }
552
631
 
553
- /** The runtime directory's spawn lock: at most one client spawns an owner process at a time. */
554
- private spawnLockPath(): string {
555
- return path.join(path.dirname(this.paths.lock), 'spawn.lock');
556
- }
557
-
558
632
  /**
559
- * Gets this client's file served, holding the file's claim lock: by the
633
+ * Gets this client's file served, holding the file's claim: by the
560
634
  * running owner process (of this build) serving the fewest files, or by a
561
635
  * new process while fewer than `maxOwners` are running. Spawning is
562
- * serialized through the spawn lock so many files opened at once share
636
+ * serialized through the spawn lease so many files opened at once share
563
637
  * one process instead of each starting their own; a client that loses
564
- * that lock waits for the new owner to appear and adopts into it.
638
+ * that lease waits for the new owner to appear and adopts into it. The
639
+ * owner a client spawns takes both leases over (see `serve` in cli.ts), so
640
+ * the reservation lasts until that owner is counted even if this client
641
+ * exits first.
565
642
  */
566
643
  private async placeFile(deadline: number) {
567
644
  const budget = this.ownerBudget();
568
645
  let lastRefusal: string | null = null;
646
+ const refusal = () => (lastRefusal ? `: ${lastRefusal}` : '');
569
647
  while (Date.now() < deadline) {
648
+ // An owner took the file on (an adopt that timed out here, say): it serves it.
649
+ const standing = this.followClaim();
650
+ if (!standing.ok) return Result.err({ kind: standing.error.kind, message: `${standing.error.message}${refusal()}` });
651
+ if (standing.value === 'placed') return Result.ok(undefined);
570
652
  const owners = this.currentOwners();
571
653
  if (!owners.ok) return owners;
572
654
  if (budget === 0 || owners.value.length < budget) {
573
655
  if (budget === 0) return this.spawnServer();
574
- const claimed = claimLockAt(this.spawnLockPath());
575
- if (!claimed.ok) return claimed;
656
+ const claimed = acquireLease(spawnLeaseBase(path.dirname(this.paths.lease)));
657
+ if (!claimed.ok) return Result.err({ kind: 'lock-failed' as const, message: `cannot reserve a spawn: ${claimed.error.message}` });
576
658
  if (claimed.value) {
577
- this.holdsSpawnLock = true;
578
- return this.spawnServer();
659
+ this.spawnLease = claimed.value;
660
+ // The count above was read before the lease was ours: the spawner
661
+ // that just released it may have published its owner since. Count
662
+ // again under the lease, and adopt instead if the budget is now met.
663
+ const settled = this.currentOwners();
664
+ if (!settled.ok) {
665
+ this.releaseSpawnLock();
666
+ return settled;
667
+ }
668
+ if (settled.value.length < budget) return this.spawnServer();
669
+ this.releaseSpawnLock();
670
+ continue;
579
671
  }
580
672
  // Another client is spawning an owner; it will be adoptable once up.
581
673
  await sleep(25);
@@ -586,15 +678,19 @@ export class SqlegoClient {
586
678
  if (remaining <= 0) break;
587
679
  const adopted = await oneShot(owner.socket, {
588
680
  op: 'adopt', file: this.paths.file, pragmas: this.options.serverPragmas, idleTimeoutMs: this.options.idleTimeoutMs ?? 30_000,
681
+ claim: this.claim ? encodeLease(this.claim) : undefined,
589
682
  }, parseAdoptResult, Math.min(ADOPT_TIMEOUT_MS, remaining));
590
683
  if (adopted.ok) return Result.ok(undefined);
591
684
  if (adopted.error.kind === 'probe-failed') lastRefusal = `owner ${owner.pid}: ${adopted.error.message}`;
685
+ // The owner may have taken the claim over and released it again (it could not serve the file): take it back for the next.
686
+ const after = this.followClaim();
687
+ if (!after.ok) return Result.err({ kind: after.error.kind, message: `${after.error.message}${refusal()}` });
688
+ if (after.value === 'placed') return Result.ok(undefined);
592
689
  }
593
690
  // Every owner went away or refused; the owner set may have changed.
594
691
  await sleep(25);
595
692
  }
596
- const why = lastRefusal ? `: ${lastRefusal}` : '';
597
- return Result.err({ kind: 'connect-timeout' as const, message: `no sqlego owner took on ${this.paths.file}${why}` });
693
+ return Result.err({ kind: 'connect-timeout' as const, message: `no sqlego owner took on ${this.paths.file}${refusal()}` });
598
694
  }
599
695
 
600
696
  /**
@@ -637,15 +733,24 @@ export class SqlegoClient {
637
733
  return Result.ok(owners);
638
734
  }
639
735
 
736
+ /**
737
+ * Releases the spawn reservation unless it has moved on: once the spawned
738
+ * owner has taken it over, this is a no-op and never frees the owner's.
739
+ */
640
740
  private releaseSpawnLock(): void {
641
- if (!this.holdsSpawnLock) return;
642
- this.holdsSpawnLock = false;
643
- const released = Trust.try(
644
- () => rmSync(this.spawnLockPath(), { force: true }),
645
- (cause) => ({ kind: 'lock-failed' as const, message: errorMessage(cause) }),
646
- );
647
- // A spawn lock that cannot be removed is reclaimed by the next client once this process is gone.
648
- if (!released.ok && released.error.kind === 'lock-failed') this.spawnFailure = `spawn lock not released: ${released.error.message}`;
741
+ const lease = this.spawnLease;
742
+ this.spawnLease = null;
743
+ if (!lease) return;
744
+ const released = releaseLease(lease);
745
+ // A reservation that cannot be released names this process; it frees itself when the process exits.
746
+ if (!released.ok && released.error.kind === 'lease-failed') this.spawnFailure = `spawn lock not released: ${released.error.message}`;
747
+ }
748
+
749
+ /** Connected or given up: whatever this client still holds goes (a no-op for anything an owner took over). */
750
+ private settleLeases(): void {
751
+ this.releaseSpawnLock();
752
+ const released = this.releaseLock();
753
+ if (!released.ok && released.error.kind === 'lock-failed') this.spawnFailure = `claim not released: ${released.error.message}`;
649
754
  }
650
755
 
651
756
  /** Waits until nothing answers on the file's socket (the old owner released it, its database closed first), or the deadline. */
@@ -663,7 +768,13 @@ export class SqlegoClient {
663
768
  if (!resolved.ok) return resolved;
664
769
  const [command, ...args] = resolved.value;
665
770
  const pragmaArgs = (this.options.serverPragmas ?? []).flatMap((pragma) => ['--pragma', pragma]);
666
- return Trust.try(
771
+ // The owner takes the claim and the spawn reservation over (see `serve` in cli.ts).
772
+ const env: Record<string, string | undefined> = { ...process.env };
773
+ delete env.SQLEGO_CLAIM_LEASE;
774
+ delete env.SQLEGO_SPAWN_LEASE;
775
+ if (this.claim) env.SQLEGO_CLAIM_LEASE = encodeLease(this.claim);
776
+ if (this.spawnLease) env.SQLEGO_SPAWN_LEASE = encodeLease(this.spawnLease);
777
+ const spawned = Trust.try(
667
778
  () => {
668
779
  const child = spawn(command, [...args, 'serve', this.paths.file, '--idle-ms', String(this.options.idleTimeoutMs ?? 30_000), ...pragmaArgs], {
669
780
  detached: true,
@@ -672,7 +783,7 @@ export class SqlegoClient {
672
783
  // stderr is captured (bounded) only to explain a failed start; it never
673
784
  // keeps this process alive.
674
785
  stdio: ['ignore', 'ignore', 'pipe'],
675
- env: { ...process.env, SQLEGO_CLAIMED_BY: String(process.pid) },
786
+ env,
676
787
  });
677
788
  let stderr = '';
678
789
  child.stderr?.on('data', (chunk: Buffer) => { if (stderr.length < 2_000) stderr += chunk.toString(); });
@@ -687,23 +798,50 @@ export class SqlegoClient {
687
798
  if (!this.hello) this.spawnFailure = `server exited before listening (code ${code}, signal ${signal})${stderr ? `: ${stderr.trim()}` : ''}`;
688
799
  });
689
800
  child.unref();
801
+ return child.pid;
690
802
  },
691
803
  (cause) => ({ kind: 'spawn-failed' as const, message: `spawn ${command} failed: ${errorMessage(cause)}` }),
692
804
  );
805
+ // The older builds' claim lock keeps naming this client until the owner
806
+ // moves it to itself with the claim (see `serve` in cli.ts). If this
807
+ // client dies first and an older client takes the lock, the owner finds
808
+ // it held by a live process other than its spawner and refuses the file.
809
+ if (!spawned.ok) return spawned;
810
+ return Result.ok(undefined);
693
811
  }
694
812
 
695
- /** The spawn never started: record why, and release the lock so another claimer can try. */
813
+ /** The spawn never started: record why, and release both locks so another claimer can try. */
696
814
  private onSpawnError(command: string, error: Error): void {
815
+ // First: a spawn lock that cannot be removed records that in `spawnFailure`, which the cause below must replace.
816
+ this.releaseSpawnLock();
697
817
  this.spawnFailure = `spawn ${command} failed: ${error.message}`;
698
818
  const released = this.releaseLock();
699
819
  if (!released.ok && released.error.kind === 'lock-failed') this.spawnFailure += `; lock not released: ${released.error.message}`;
700
820
  }
701
821
 
822
+ /**
823
+ * Releases this client's claim unless an owner has taken it over (then this
824
+ * is a no-op), or it was released already. First the claim moves to a new
825
+ * generation this client holds — one step that fails if an owner took it
826
+ * over meanwhile, in which case the older builds' claim lock is the
827
+ * owner's and stays. Holding that generation, no owner can take the claim
828
+ * over any more, so the lock (only if it names this client) goes before
829
+ * the claim is freed: freed first, a client taking it would find the lock
830
+ * still naming this live process, back off, and wait for a socket nobody
831
+ * starts.
832
+ */
702
833
  private releaseLock() {
703
- return Trust.try(
704
- () => rmSync(this.paths.lock, { force: true }),
705
- (cause) => ({ kind: 'lock-failed' as const, message: errorMessage(cause) }),
706
- );
834
+ const claim = this.claim;
835
+ this.claim = null;
836
+ if (!claim) return Result.ok(undefined);
837
+ const releasing = handOverLease(claim, process.pid);
838
+ if (!releasing.ok) return Result.err({ kind: 'lock-failed' as const, message: releasing.error.message });
839
+ if (!releasing.value) return Result.ok(undefined);
840
+ const dropped = dropLegacyLock(this.paths.lock, [process.pid]);
841
+ const released = releaseLease(releasing.value);
842
+ if (!dropped.ok) return Result.err({ kind: 'lock-failed' as const, message: dropped.error.message });
843
+ if (!released.ok) return Result.err({ kind: 'lock-failed' as const, message: released.error.message });
844
+ return Result.ok(undefined);
707
845
  }
708
846
 
709
847
  private attach(socket: net.Socket) {
@@ -754,13 +892,18 @@ export class SqlegoClient {
754
892
  * One request whose reply `parse` turns from `unknown` into its typed
755
893
  * result; a reply that does not parse is a `protocol` failure.
756
894
  */
757
- private async call<T>(body: RequestBody, parse: (input: unknown) => Result<T, Invalid>, timeoutMs?: number) {
758
- const reply = await this.request(body, timeoutMs);
895
+ private call<T>(body: RequestBody, parse: (input: unknown) => Result<T, Invalid>, timeoutMs?: number) {
896
+ // Not `async`: a suspended async frame would keep `body` (and its params) alive until the reply.
897
+ const op = body.op;
898
+ return this.request(body, timeoutMs).then((reply) => this.parseReply(op, reply, parse));
899
+ }
900
+
901
+ private parseReply<T>(op: string, reply: Result<unknown, RequestFailure>, parse: (input: unknown) => Result<T, Invalid>) {
759
902
  if (!reply.ok) return reply;
760
903
  const parsed = parse(reply.value);
761
904
  if (parsed.ok) return parsed;
762
905
  if (parsed.error.kind === 'invalid') {
763
- return Result.err<RequestFailure>({ kind: 'protocol', message: `unexpected ${body.op} reply: ${parsed.error.message}` });
906
+ return Result.err<RequestFailure>({ kind: 'protocol', message: `unexpected ${op} reply: ${parsed.error.message}` });
764
907
  }
765
908
  const unhandled: never = parsed.error.kind;
766
909
  return unhandled;
@@ -775,24 +918,40 @@ export class SqlegoClient {
775
918
  const id = this.nextId++;
776
919
  const frame = encodeRequestFrame({ id, ...body } as Request);
777
920
  if (!frame.ok) return Promise.resolve(frame);
921
+ const reply = this.register(id, body.op, timeoutMs);
922
+ const written = Trust.try(
923
+ () => socket.write(frame.value),
924
+ (cause) => ({ kind: 'socket' as const, message: errorMessage(cause) }),
925
+ );
926
+ if (!written.ok) {
927
+ this.forget(id);
928
+ return Promise.resolve(written);
929
+ }
930
+ return reply;
931
+ }
932
+
933
+ /**
934
+ * The pending waiter for `id`. Built outside `request` so the waiter and
935
+ * timer closures capture only `id`, `op` and `timeoutMs`: a pending reply
936
+ * must not keep the request body or its encoded frame alive after the write.
937
+ */
938
+ private register(id: number, op: string, timeoutMs: number): Promise<Result<unknown, RequestFailure>> {
778
939
  return new Promise<Result<unknown, RequestFailure>>((settle) => {
779
940
  const timer = setTimeout(() => {
780
941
  this.pending.delete(id);
781
- settle(Result.err({ kind: 'request-timeout', message: `request ${id} (${body.op}) timed out` }));
942
+ settle(Result.err({ kind: 'request-timeout', message: `request ${id} (${op}) timed out` }));
782
943
  }, timeoutMs);
783
944
  this.pending.set(id, { settle, timer });
784
- const written = Trust.try(
785
- () => socket.write(frame.value),
786
- (cause) => ({ kind: 'socket' as const, message: errorMessage(cause) }),
787
- );
788
- if (!written.ok) {
789
- this.pending.delete(id);
790
- clearTimeout(timer);
791
- settle(written);
792
- }
793
945
  });
794
946
  }
795
947
 
948
+ /** Drops the waiter for `id` and its timer; its promise is abandoned unsettled. */
949
+ private forget(id: number): void {
950
+ const waiter = this.pending.get(id);
951
+ if (waiter) clearTimeout(waiter.timer);
952
+ this.pending.delete(id);
953
+ }
954
+
796
955
  private settleAll(failure: RequestFailure): void {
797
956
  for (const waiter of this.pending.values()) {
798
957
  clearTimeout(waiter.timer);
@@ -803,42 +962,6 @@ export class SqlegoClient {
803
962
 
804
963
  }
805
964
 
806
- /** O_EXCL create of `lock` holding this pid; a lock left by a dead process (or unreadable) is reclaimed. */
807
- function claimLockAt(lock: string) {
808
- for (let attempt = 0; attempt < 2; attempt += 1) {
809
- const created = Trust.try(
810
- () => {
811
- const fd = openSync(lock, 'wx');
812
- writeSync(fd, String(process.pid));
813
- closeSync(fd);
814
- },
815
- (cause) => (errnoCode(cause) === 'EEXIST'
816
- ? { kind: 'lock-held' as const, message: `${lock} exists` }
817
- : { kind: 'lock-failed' as const, message: `cannot create ${lock}: ${errorMessage(cause)}` }),
818
- );
819
- if (created.ok) return Result.ok(true);
820
- if (created.error.kind === 'lock-failed') return Result.err({ kind: 'lock-failed', message: created.error.message });
821
- if (created.error.kind === 'lock-held') {
822
- const holder = Trust.try(
823
- () => Number(readFileSync(lock, 'utf8').trim()),
824
- (cause) => ({ kind: 'lock-unreadable' as const, message: errorMessage(cause) }),
825
- );
826
- if (holder.ok) {
827
- if (Number.isFinite(holder.value) && holder.value > 0 && isProcessAlive(holder.value)) return Result.ok(false);
828
- // A dead (or unrecorded) holder: reclaim the lock below.
829
- } else if (holder.error.kind === 'lock-unreadable') {
830
- // The lock vanished between the create and the read: reclaim below and retry.
831
- }
832
- const removed = Trust.try(
833
- () => rmSync(lock, { force: true }),
834
- (cause) => ({ kind: 'lock-failed' as const, message: `cannot remove stale ${lock}: ${errorMessage(cause)}` }),
835
- );
836
- if (!removed.ok) return removed;
837
- }
838
- }
839
- return Result.ok(false);
840
- }
841
-
842
965
  /**
843
966
  * One open transaction on a `SqlegoClient`. Every method rejects with a
844
967
  * `SqlegoClientError` whose code is `tx-expired` once the server has rolled