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

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) {
@@ -516,7 +519,8 @@ export class SqlegoClient {
516
519
  if (claimed.value) {
517
520
  const placed = await this.placeFile(deadline);
518
521
  if (!placed.ok) {
519
- // Nothing will serve the file: the claim must go so the next client can try.
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();
520
524
  const released = this.releaseLock();
521
525
  const suffix = !released.ok && released.error.kind === 'lock-failed' ? `; lock not released: ${released.error.message}` : '';
522
526
  return Result.err({ kind: placed.error.kind, message: `${placed.error.message}${suffix}` });
@@ -526,19 +530,70 @@ export class SqlegoClient {
526
530
  for (let delayMs = 2; Date.now() < deadline; delayMs = Math.min(25, delayMs * 2)) {
527
531
  const socket = await tryConnect(this.paths.socket);
528
532
  if (socket) {
529
- this.releaseSpawnLock();
533
+ this.settleLeases();
530
534
  return Result.ok(socket);
531
535
  }
532
536
  await sleep(delayMs);
533
537
  }
534
- this.releaseSpawnLock();
538
+ this.settleLeases();
535
539
  const cause = this.spawnFailure ? ` (${this.spawnFailure})` : '';
536
540
  return Result.err({ kind: 'connect-timeout', message: `no sqlego server became reachable for ${this.paths.file}${cause}` });
537
541
  }
538
542
 
539
- /** The file's own claim lock: whoever holds it places the file with an owner. */
543
+ /**
544
+ * The file's claim: whoever holds it places the file with an owner, which
545
+ * then holds it while it serves the file. See `takeClaim`.
546
+ */
540
547
  private claimLock() {
541
- return claimLockAt(this.paths.lock);
548
+ const taken = this.takeClaim();
549
+ if (!taken.ok) return taken;
550
+ this.claim = taken.value;
551
+ return Result.ok(taken.value !== null);
552
+ }
553
+
554
+ /**
555
+ * Takes the file's claim lease and, with it, the claim lock older builds
556
+ * use (`<key>.lock`, see legacy_lock.ts) so that they see the file claimed
557
+ * too. Null when either is held: the lease by a process of this build, the
558
+ * lock by a live client of an older build placing the file.
559
+ */
560
+ private takeClaim(): Result<Lease | null, { readonly kind: 'lock-failed'; readonly message: string }> {
561
+ const acquired = acquireLease(this.paths.lease);
562
+ if (!acquired.ok) return Result.err({ kind: 'lock-failed', message: `cannot claim ${this.paths.file}: ${acquired.error.message}` });
563
+ const lease = acquired.value;
564
+ if (!lease) return Result.ok(null);
565
+ const legacy = takeLegacyLock(this.paths.lock, process.pid);
566
+ if (legacy.ok && legacy.value) return Result.ok(lease);
567
+ const released = releaseLease(lease);
568
+ if (!released.ok && released.error.kind === 'lease-failed') {
569
+ // It names this live process; it frees itself when the process exits.
570
+ }
571
+ if (!legacy.ok) return Result.err({ kind: 'lock-failed', message: `cannot claim ${this.paths.file}: ${legacy.error.message}` });
572
+ return Result.ok(null);
573
+ }
574
+
575
+ /**
576
+ * Where this client's claim stands. `own` while this client still holds
577
+ * it (or holds none); `placed` once a live process holds it instead — the
578
+ * owner that took the file on, or another client placing it. An owner that
579
+ * took the claim over and then could not serve the file (its open or bind
580
+ * failed) released it again: this client takes it back and keeps placing.
581
+ */
582
+ private followClaim(): Result<'own' | 'placed', { readonly kind: 'lock-failed'; readonly message: string }> {
583
+ const claim = this.claim;
584
+ if (!claim) return Result.ok('own');
585
+ // A lease that cannot be read is not known to have moved on.
586
+ if (Trust.decide(leaseHead(claim.base), { 'lease-failed': () => 0 }).value <= claim.generation) return Result.ok('own');
587
+ const holder = leaseHolder(claim.base);
588
+ if (!holder.ok) return Result.err({ kind: 'lock-failed', message: `cannot read the claim on ${this.paths.file}: ${holder.error.message}` });
589
+ if (holder.value !== null) {
590
+ this.claim = null;
591
+ return Result.ok('placed');
592
+ }
593
+ const again = this.takeClaim();
594
+ if (!again.ok) return Result.err({ kind: 'lock-failed', message: `cannot claim ${this.paths.file} again: ${again.error.message}` });
595
+ this.claim = again.value;
596
+ return Result.ok(again.value === null ? 'placed' : 'own');
542
597
  }
543
598
 
544
599
  /* ------------------------------------------------------------------ *
@@ -550,32 +605,45 @@ export class SqlegoClient {
550
605
  return Number.isFinite(configured) && configured >= 0 ? Math.floor(configured) : DEFAULT_MAX_OWNERS;
551
606
  }
552
607
 
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
608
  /**
559
- * Gets this client's file served, holding the file's claim lock: by the
609
+ * Gets this client's file served, holding the file's claim: by the
560
610
  * running owner process (of this build) serving the fewest files, or by a
561
611
  * new process while fewer than `maxOwners` are running. Spawning is
562
- * serialized through the spawn lock so many files opened at once share
612
+ * serialized through the spawn lease so many files opened at once share
563
613
  * 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.
614
+ * that lease waits for the new owner to appear and adopts into it. The
615
+ * owner a client spawns takes both leases over (see `serve` in cli.ts), so
616
+ * the reservation lasts until that owner is counted even if this client
617
+ * exits first.
565
618
  */
566
619
  private async placeFile(deadline: number) {
567
620
  const budget = this.ownerBudget();
568
621
  let lastRefusal: string | null = null;
622
+ const refusal = () => (lastRefusal ? `: ${lastRefusal}` : '');
569
623
  while (Date.now() < deadline) {
624
+ // An owner took the file on (an adopt that timed out here, say): it serves it.
625
+ const standing = this.followClaim();
626
+ if (!standing.ok) return Result.err({ kind: standing.error.kind, message: `${standing.error.message}${refusal()}` });
627
+ if (standing.value === 'placed') return Result.ok(undefined);
570
628
  const owners = this.currentOwners();
571
629
  if (!owners.ok) return owners;
572
630
  if (budget === 0 || owners.value.length < budget) {
573
631
  if (budget === 0) return this.spawnServer();
574
- const claimed = claimLockAt(this.spawnLockPath());
575
- if (!claimed.ok) return claimed;
632
+ const claimed = acquireLease(spawnLeaseBase(path.dirname(this.paths.lease)));
633
+ if (!claimed.ok) return Result.err({ kind: 'lock-failed' as const, message: `cannot reserve a spawn: ${claimed.error.message}` });
576
634
  if (claimed.value) {
577
- this.holdsSpawnLock = true;
578
- return this.spawnServer();
635
+ this.spawnLease = claimed.value;
636
+ // The count above was read before the lease was ours: the spawner
637
+ // that just released it may have published its owner since. Count
638
+ // again under the lease, and adopt instead if the budget is now met.
639
+ const settled = this.currentOwners();
640
+ if (!settled.ok) {
641
+ this.releaseSpawnLock();
642
+ return settled;
643
+ }
644
+ if (settled.value.length < budget) return this.spawnServer();
645
+ this.releaseSpawnLock();
646
+ continue;
579
647
  }
580
648
  // Another client is spawning an owner; it will be adoptable once up.
581
649
  await sleep(25);
@@ -586,15 +654,19 @@ export class SqlegoClient {
586
654
  if (remaining <= 0) break;
587
655
  const adopted = await oneShot(owner.socket, {
588
656
  op: 'adopt', file: this.paths.file, pragmas: this.options.serverPragmas, idleTimeoutMs: this.options.idleTimeoutMs ?? 30_000,
657
+ claim: this.claim ? encodeLease(this.claim) : undefined,
589
658
  }, parseAdoptResult, Math.min(ADOPT_TIMEOUT_MS, remaining));
590
659
  if (adopted.ok) return Result.ok(undefined);
591
660
  if (adopted.error.kind === 'probe-failed') lastRefusal = `owner ${owner.pid}: ${adopted.error.message}`;
661
+ // The owner may have taken the claim over and released it again (it could not serve the file): take it back for the next.
662
+ const after = this.followClaim();
663
+ if (!after.ok) return Result.err({ kind: after.error.kind, message: `${after.error.message}${refusal()}` });
664
+ if (after.value === 'placed') return Result.ok(undefined);
592
665
  }
593
666
  // Every owner went away or refused; the owner set may have changed.
594
667
  await sleep(25);
595
668
  }
596
- const why = lastRefusal ? `: ${lastRefusal}` : '';
597
- return Result.err({ kind: 'connect-timeout' as const, message: `no sqlego owner took on ${this.paths.file}${why}` });
669
+ return Result.err({ kind: 'connect-timeout' as const, message: `no sqlego owner took on ${this.paths.file}${refusal()}` });
598
670
  }
599
671
 
600
672
  /**
@@ -637,15 +709,24 @@ export class SqlegoClient {
637
709
  return Result.ok(owners);
638
710
  }
639
711
 
712
+ /**
713
+ * Releases the spawn reservation unless it has moved on: once the spawned
714
+ * owner has taken it over, this is a no-op and never frees the owner's.
715
+ */
640
716
  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}`;
717
+ const lease = this.spawnLease;
718
+ this.spawnLease = null;
719
+ if (!lease) return;
720
+ const released = releaseLease(lease);
721
+ // A reservation that cannot be released names this process; it frees itself when the process exits.
722
+ if (!released.ok && released.error.kind === 'lease-failed') this.spawnFailure = `spawn lock not released: ${released.error.message}`;
723
+ }
724
+
725
+ /** Connected or given up: whatever this client still holds goes (a no-op for anything an owner took over). */
726
+ private settleLeases(): void {
727
+ this.releaseSpawnLock();
728
+ const released = this.releaseLock();
729
+ if (!released.ok && released.error.kind === 'lock-failed') this.spawnFailure = `claim not released: ${released.error.message}`;
649
730
  }
650
731
 
651
732
  /** Waits until nothing answers on the file's socket (the old owner released it, its database closed first), or the deadline. */
@@ -663,7 +744,13 @@ export class SqlegoClient {
663
744
  if (!resolved.ok) return resolved;
664
745
  const [command, ...args] = resolved.value;
665
746
  const pragmaArgs = (this.options.serverPragmas ?? []).flatMap((pragma) => ['--pragma', pragma]);
666
- return Trust.try(
747
+ // The owner takes the claim and the spawn reservation over (see `serve` in cli.ts).
748
+ const env: Record<string, string | undefined> = { ...process.env };
749
+ delete env.SQLEGO_CLAIM_LEASE;
750
+ delete env.SQLEGO_SPAWN_LEASE;
751
+ if (this.claim) env.SQLEGO_CLAIM_LEASE = encodeLease(this.claim);
752
+ if (this.spawnLease) env.SQLEGO_SPAWN_LEASE = encodeLease(this.spawnLease);
753
+ const spawned = Trust.try(
667
754
  () => {
668
755
  const child = spawn(command, [...args, 'serve', this.paths.file, '--idle-ms', String(this.options.idleTimeoutMs ?? 30_000), ...pragmaArgs], {
669
756
  detached: true,
@@ -672,7 +759,7 @@ export class SqlegoClient {
672
759
  // stderr is captured (bounded) only to explain a failed start; it never
673
760
  // keeps this process alive.
674
761
  stdio: ['ignore', 'ignore', 'pipe'],
675
- env: { ...process.env, SQLEGO_CLAIMED_BY: String(process.pid) },
762
+ env,
676
763
  });
677
764
  let stderr = '';
678
765
  child.stderr?.on('data', (chunk: Buffer) => { if (stderr.length < 2_000) stderr += chunk.toString(); });
@@ -687,23 +774,50 @@ export class SqlegoClient {
687
774
  if (!this.hello) this.spawnFailure = `server exited before listening (code ${code}, signal ${signal})${stderr ? `: ${stderr.trim()}` : ''}`;
688
775
  });
689
776
  child.unref();
777
+ return child.pid;
690
778
  },
691
779
  (cause) => ({ kind: 'spawn-failed' as const, message: `spawn ${command} failed: ${errorMessage(cause)}` }),
692
780
  );
781
+ // The older builds' claim lock keeps naming this client until the owner
782
+ // moves it to itself with the claim (see `serve` in cli.ts). If this
783
+ // client dies first and an older client takes the lock, the owner finds
784
+ // it held by a live process other than its spawner and refuses the file.
785
+ if (!spawned.ok) return spawned;
786
+ return Result.ok(undefined);
693
787
  }
694
788
 
695
- /** The spawn never started: record why, and release the lock so another claimer can try. */
789
+ /** The spawn never started: record why, and release both locks so another claimer can try. */
696
790
  private onSpawnError(command: string, error: Error): void {
791
+ // First: a spawn lock that cannot be removed records that in `spawnFailure`, which the cause below must replace.
792
+ this.releaseSpawnLock();
697
793
  this.spawnFailure = `spawn ${command} failed: ${error.message}`;
698
794
  const released = this.releaseLock();
699
795
  if (!released.ok && released.error.kind === 'lock-failed') this.spawnFailure += `; lock not released: ${released.error.message}`;
700
796
  }
701
797
 
798
+ /**
799
+ * Releases this client's claim unless an owner has taken it over (then this
800
+ * is a no-op), or it was released already. First the claim moves to a new
801
+ * generation this client holds — one step that fails if an owner took it
802
+ * over meanwhile, in which case the older builds' claim lock is the
803
+ * owner's and stays. Holding that generation, no owner can take the claim
804
+ * over any more, so the lock (only if it names this client) goes before
805
+ * the claim is freed: freed first, a client taking it would find the lock
806
+ * still naming this live process, back off, and wait for a socket nobody
807
+ * starts.
808
+ */
702
809
  private releaseLock() {
703
- return Trust.try(
704
- () => rmSync(this.paths.lock, { force: true }),
705
- (cause) => ({ kind: 'lock-failed' as const, message: errorMessage(cause) }),
706
- );
810
+ const claim = this.claim;
811
+ this.claim = null;
812
+ if (!claim) return Result.ok(undefined);
813
+ const releasing = handOverLease(claim, process.pid);
814
+ if (!releasing.ok) return Result.err({ kind: 'lock-failed' as const, message: releasing.error.message });
815
+ if (!releasing.value) return Result.ok(undefined);
816
+ const dropped = dropLegacyLock(this.paths.lock, [process.pid]);
817
+ const released = releaseLease(releasing.value);
818
+ if (!dropped.ok) return Result.err({ kind: 'lock-failed' as const, message: dropped.error.message });
819
+ if (!released.ok) return Result.err({ kind: 'lock-failed' as const, message: released.error.message });
820
+ return Result.ok(undefined);
707
821
  }
708
822
 
709
823
  private attach(socket: net.Socket) {
@@ -803,42 +917,6 @@ export class SqlegoClient {
803
917
 
804
918
  }
805
919
 
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
920
  /**
843
921
  * One open transaction on a `SqlegoClient`. Every method rejects with a
844
922
  * `SqlegoClientError` whose code is `tx-expired` once the server has rolled
package/src/lease.ts ADDED
@@ -0,0 +1,265 @@
1
+ /**
2
+ * Leases: the runtime directory's mutual exclusion between processes — a
3
+ * file's claim (who places it with an owner, then which owner serves it) and
4
+ * the spawn reservation (who is starting an owner process).
5
+ *
6
+ * A lease at `base` is a chain of generation files `<base>.<g>` (g = 1, 2,
7
+ * …), each created once and never rewritten. The highest generation is the
8
+ * lease's state: `{"holder":<pid>,"token":…}` (held while that process
9
+ * lives) or `{"free":true,"token":…}`. Every change — taking a free lease,
10
+ * reclaiming one whose holder died, handing one to another process,
11
+ * releasing it — creates generation g+1 by `link()`ing a fully written file
12
+ * into place, which fails if g+1 exists. So of all the processes acting on
13
+ * generation g exactly one succeeds: a reclaimer and a handover can never
14
+ * both win, and a release by a process the lease has since moved on from
15
+ * does nothing rather than removing its successor's lease. A generation is
16
+ * never read half-written.
17
+ *
18
+ * Each generation carries a token no other generation shares, and a change
19
+ * names the token of the generation it acts on, checked before and after the
20
+ * link. Generation numbers alone are not enough: if the newest generation
21
+ * file is lost (a temp-directory cleaner, say) the chain starts again at 1,
22
+ * and a process still holding an old generation would otherwise act on the
23
+ * new chain's generation of the same number.
24
+ *
25
+ * Older generations are pruned; the newest never is. An actor that recreates
26
+ * a pruned generation finds a newer one after its link and counts as having
27
+ * lost.
28
+ */
29
+ import { linkSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
30
+ import path from 'node:path';
31
+ import { Result, Trust } from '@noego/trust';
32
+ import { isProcessAlive } from './paths.ts';
33
+ import { errnoCode, errorMessage, fromJson } from './protocol.ts';
34
+
35
+ /** A lease this process holds: generation `generation` (whose token is `token`) of the lease at `base`. */
36
+ export type Lease = Readonly<{ base: string; generation: number; token: string }>;
37
+
38
+ type LeaseFailure = { readonly kind: 'lease-failed'; readonly message: string };
39
+
40
+ const leaseFailure = (cause: unknown): LeaseFailure => ({ kind: 'lease-failed', message: errorMessage(cause) });
41
+
42
+ /** How many times `acquireLease` retries after losing a race on a free or dead lease before reporting it held. */
43
+ const ACQUIRE_ATTEMPTS = 8;
44
+
45
+ /** The runtime directory's spawn reservation: at most one owner process is being started at a time. */
46
+ export function spawnLeaseBase(runtimeDirectory: string): string {
47
+ return path.join(runtimeDirectory, 'spawn.lease');
48
+ }
49
+
50
+ function generationFile(base: string, generation: number): string {
51
+ return `${base}.${generation}`;
52
+ }
53
+
54
+ /** The generation file `lease` names (what a long-lived holder keeps fresh against temp cleaners). */
55
+ export function leaseFile(lease: Lease): string {
56
+ return generationFile(lease.base, lease.generation);
57
+ }
58
+
59
+ /** Tells this process's generations apart from each other's (and its staged files). */
60
+ let created = 0;
61
+
62
+ /** A token no other generation has: this pid, the time, and a count within this process. */
63
+ function newToken(): string {
64
+ created += 1;
65
+ return `${process.pid}.${Date.now().toString(36)}.${created}`;
66
+ }
67
+
68
+ /** `<generation>:<token>`, the form a lease travels in to another process (an environment variable, an `adopt`). */
69
+ export function encodeLease(lease: Lease): string {
70
+ return `${lease.generation}:${lease.token}`;
71
+ }
72
+
73
+ /** The lease `encodeLease` wrote, at `base`; null for anything else. */
74
+ export function decodeLease(base: string, encoded: string | undefined): Lease | null {
75
+ const match = encoded === undefined ? null : /^(\d+):([0-9a-z.]+)$/.exec(encoded);
76
+ if (!match) return null;
77
+ const generation = Number(match[1]);
78
+ return generation > 0 ? { base, generation, token: match[2] } : null;
79
+ }
80
+
81
+ /** The lease's generations present on disk, in no particular order. */
82
+ function generations(base: string) {
83
+ const prefix = `${path.basename(base)}.`;
84
+ const names = Trust.try(() => readdirSync(path.dirname(base)), leaseFailure);
85
+ if (!names.ok) return names;
86
+ const found: number[] = [];
87
+ for (const name of names.value) {
88
+ if (!name.startsWith(prefix)) continue;
89
+ const suffix = name.slice(prefix.length);
90
+ if (/^\d+$/.test(suffix)) found.push(Number(suffix));
91
+ }
92
+ return Result.ok(found);
93
+ }
94
+
95
+ /** The lease's newest generation; 0 when it was never taken. */
96
+ export function leaseHead(base: string) {
97
+ const found = generations(base);
98
+ if (!found.ok) return found;
99
+ return Result.ok(Math.max(0, ...found.value));
100
+ }
101
+
102
+ /**
103
+ * What generation `generation` records: its token and its live holder (null
104
+ * when it is free, its holder is dead, or it is not one of ours). `gone` when
105
+ * the generation file is not there (pruned, or lost).
106
+ */
107
+ function readGeneration(base: string, generation: number) {
108
+ const text = Trust.try(
109
+ () => readFileSync(generationFile(base, generation), 'utf8'),
110
+ (cause) => (errnoCode(cause) === 'ENOENT' ? { kind: 'gone' as const } : leaseFailure(cause)),
111
+ );
112
+ if (!text.ok) return text;
113
+ // A generation that is not JSON is not one of ours (ours are never read half-written): no holder, no token.
114
+ const state = Trust.decide(fromJson(text.value), { invalid: () => null }).value;
115
+ if (typeof state !== 'object' || state === null) return Result.ok({ holder: null, token: null });
116
+ const token = 'token' in state && typeof state.token === 'string' ? state.token : null;
117
+ const holder = 'holder' in state ? state.holder : null;
118
+ const live = typeof holder === 'number' && Number.isInteger(holder) && holder > 0 && isProcessAlive(holder) ? holder : null;
119
+ return Result.ok({ holder: live, token });
120
+ }
121
+
122
+ /** Whether generation `generation` is there and has `token`. */
123
+ function generationIs(base: string, generation: number, token: string | null): Result<boolean, LeaseFailure> {
124
+ if (generation === 0) return Result.ok(true);
125
+ const state = readGeneration(base, generation);
126
+ if (state.ok) return Result.ok(state.value.token === token);
127
+ const failure = state.error;
128
+ if (failure.kind === 'gone') return Result.ok(false);
129
+ return Result.err(failure);
130
+ }
131
+
132
+ /**
133
+ * Creates generation `from + 1` recording `holder` (null: free), acting on
134
+ * generation `from` whose token is `fromToken`. The new generation's token
135
+ * when this call made it and it is the newest generation; null when another
136
+ * process acted on generation `from` first, or `from` is no longer that
137
+ * generation (the chain was lost and started again).
138
+ */
139
+ function advance(base: string, from: number, fromToken: string | null, holder: number | null): Result<string | null, LeaseFailure> {
140
+ const before = generationIs(base, from, fromToken);
141
+ if (!before.ok) return before;
142
+ if (!before.value) return Result.ok(null);
143
+ const next = generationFile(base, from + 1);
144
+ const token = newToken();
145
+ const staged = `${next}.${token}.tmp`;
146
+ const linked = Trust.try(
147
+ () => {
148
+ writeFileSync(staged, holder === null ? `{"free":true,"token":"${token}"}` : `{"holder":${holder},"token":"${token}"}`);
149
+ linkSync(staged, next);
150
+ },
151
+ (cause) => (errnoCode(cause) === 'EEXIST' ? { kind: 'lost' as const } : leaseFailure(cause)),
152
+ );
153
+ const unstaged = Trust.try(() => rmSync(staged, { force: true }), leaseFailure);
154
+ if (!unstaged.ok && unstaged.error.kind === 'lease-failed') {
155
+ // A staged copy left behind is never read: its name is not a generation.
156
+ }
157
+ if (!linked.ok) {
158
+ const failure = linked.error;
159
+ if (failure.kind === 'lost') return Result.ok(null);
160
+ return Result.err(failure);
161
+ }
162
+ const found = generations(base);
163
+ if (!found.ok) return found;
164
+ // A newer generation means `next` had been pruned and this link recreated it: the lease had moved on.
165
+ if (found.value.some((generation) => generation > from + 1)) return Result.ok(null);
166
+ // `from` replaced while this linked (lost and started again): this generation belongs to no chain.
167
+ const after = generationIs(base, from, fromToken);
168
+ if (!after.ok || !after.value) {
169
+ withdraw(base, from + 1, token);
170
+ if (!after.ok) return after;
171
+ return Result.ok(null);
172
+ }
173
+ prune(base, found.value.filter((generation) => generation <= from));
174
+ return Result.ok(token);
175
+ }
176
+
177
+ /** Removes generation `generation` again if it is still this call's own (token `token`). */
178
+ function withdraw(base: string, generation: number, token: string): void {
179
+ // One that cannot be read is left: it names this process or a free lease, and either frees itself.
180
+ if (!Trust.decide(generationIs(base, generation, token), { 'lease-failed': () => false }).value) return;
181
+ const removed = Trust.try(() => rmSync(generationFile(base, generation), { force: true }), leaseFailure);
182
+ if (!removed.ok && removed.error.kind === 'lease-failed') {
183
+ // Left in place it names this process or a free lease: either frees itself.
184
+ }
185
+ }
186
+
187
+ /** Removes superseded generations; one that cannot be removed now is removed by a later change. */
188
+ function prune(base: string, superseded: readonly number[]): void {
189
+ for (const generation of superseded) {
190
+ const removed = Trust.try(() => rmSync(generationFile(base, generation), { force: true }), leaseFailure);
191
+ if (!removed.ok && removed.error.kind === 'lease-failed') {
192
+ // Left for the next change to remove; an old generation is never read as the lease's state.
193
+ }
194
+ }
195
+ }
196
+
197
+ /**
198
+ * Takes the lease for this process if it is free or its holder is dead. Null
199
+ * when a live process holds it (this one included: a lease is not re-entrant).
200
+ */
201
+ export function acquireLease(base: string): Result<Lease | null, LeaseFailure> {
202
+ for (let attempt = 0; attempt < ACQUIRE_ATTEMPTS; attempt += 1) {
203
+ const head = leaseHead(base);
204
+ if (!head.ok) return head;
205
+ let headToken: string | null = null;
206
+ if (head.value > 0) {
207
+ const state = readGeneration(base, head.value);
208
+ if (!state.ok) {
209
+ const failure = state.error;
210
+ if (failure.kind === 'gone') continue;
211
+ return Result.err(failure);
212
+ }
213
+ if (state.value.holder !== null) return Result.ok(null);
214
+ headToken = state.value.token;
215
+ }
216
+ const won = advance(base, head.value, headToken, process.pid);
217
+ if (!won.ok) return won;
218
+ if (won.value !== null) return Result.ok({ base, generation: head.value + 1, token: won.value });
219
+ }
220
+ return Result.ok(null);
221
+ }
222
+
223
+ /**
224
+ * Hands `lease` to process `holder`, in one step that succeeds only if the
225
+ * lease is still that generation: no reclaimer, release or other handover
226
+ * acted on it first. Null when one did.
227
+ */
228
+ export function handOverLease(lease: Lease, holder: number): Result<Lease | null, LeaseFailure> {
229
+ const moved = advance(lease.base, lease.generation, lease.token, holder);
230
+ if (!moved.ok) return moved;
231
+ return Result.ok(moved.value === null ? null : { base: lease.base, generation: lease.generation + 1, token: moved.value });
232
+ }
233
+
234
+ /** Frees the lease if it is still `lease`'s generation; false (and nothing changed) when it had moved on. */
235
+ export function releaseLease(lease: Lease): Result<boolean, LeaseFailure> {
236
+ const released = advance(lease.base, lease.generation, lease.token, null);
237
+ if (!released.ok) return released;
238
+ return Result.ok(released.value !== null);
239
+ }
240
+
241
+ /** The process `lease`'s generation records as its holder, alive or not; null when it records none or is gone. */
242
+ export function recordedHolder(lease: Lease): number | null {
243
+ const text = Trust.decide(
244
+ Trust.try(() => readFileSync(leaseFile(lease), 'utf8'), () => ({ kind: 'unreadable' as const })),
245
+ { unreadable: () => '' },
246
+ ).value;
247
+ const state = Trust.decide(fromJson(text), { invalid: () => null }).value;
248
+ if (typeof state !== 'object' || state === null || !('holder' in state)) return null;
249
+ const holder = state.holder;
250
+ return typeof holder === 'number' && Number.isInteger(holder) && holder > 0 ? holder : null;
251
+ }
252
+
253
+ /** The process holding the lease now, or null when it is free or its holder is dead. */
254
+ export function leaseHolder(base: string): Result<number | null, LeaseFailure> {
255
+ for (;;) {
256
+ const head = leaseHead(base);
257
+ if (!head.ok) return head;
258
+ if (head.value === 0) return Result.ok(null);
259
+ const state = readGeneration(base, head.value);
260
+ if (state.ok) return Result.ok(state.value.holder);
261
+ const failure = state.error;
262
+ // Pruned between the listing and the read: a newer generation exists, so look again.
263
+ if (failure.kind !== 'gone') return Result.err(failure);
264
+ }
265
+ }