@noego/sqlego 0.1.6-dev.0 → 0.1.6-dev.10
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/README.md +67 -10
- package/dist/client.d.ts +57 -9
- package/dist/index.js +488 -86
- package/dist/lease.d.ts +39 -0
- package/dist/legacy_lock.d.ts +20 -0
- package/dist/paths.d.ts +6 -0
- package/dist/protocol.d.ts +28 -2
- package/dist/version.d.ts +17 -3
- package/package.json +9 -8
- package/src/cli.ts +121 -2
- package/src/client.ts +188 -85
- package/src/lease.ts +265 -0
- package/src/legacy_lock.ts +123 -0
- package/src/paths.ts +4 -0
- package/src/protocol.ts +56 -6
- package/src/server.ts +355 -30
- package/src/version.ts +75 -7
package/src/client.ts
CHANGED
|
@@ -1,16 +1,17 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
|
-
import {
|
|
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
|
-
/**
|
|
208
|
-
private
|
|
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) {
|
|
@@ -511,34 +514,111 @@ export class SqlegoClient {
|
|
|
511
514
|
if (this.options.spawn === false) {
|
|
512
515
|
return Result.err({ kind: 'not-running', message: `no sqlego server for ${this.paths.file}` });
|
|
513
516
|
}
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
517
|
+
for (;;) {
|
|
518
|
+
const claimed = this.claimLock();
|
|
519
|
+
if (!claimed.ok) return claimed;
|
|
520
|
+
if (claimed.value) {
|
|
521
|
+
const placed = await this.placeFile(deadline);
|
|
522
|
+
if (!placed.ok) {
|
|
523
|
+
// Nothing will serve the file: the spawn lock (when this client took it) and the claim must go so the next client can try.
|
|
524
|
+
this.releaseSpawnLock();
|
|
525
|
+
const released = this.releaseLock();
|
|
526
|
+
const suffix = !released.ok && released.error.kind === 'lock-failed' ? `; lock not released: ${released.error.message}` : '';
|
|
527
|
+
return Result.err({ kind: placed.error.kind, message: `${placed.error.message}${suffix}` });
|
|
528
|
+
}
|
|
523
529
|
}
|
|
530
|
+
// Claimer or not, the socket appears when the winner is listening.
|
|
531
|
+
const waited = await this.waitForSocket(deadline, !claimed.value);
|
|
532
|
+
if (!waited.ok) return waited;
|
|
533
|
+
if (waited.value) return Result.ok(waited.value);
|
|
534
|
+
// The claim it waited on was freed with nothing listening: place the file now.
|
|
524
535
|
}
|
|
525
|
-
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
/** How often a client waiting on another process's claim checks whether that claim was freed. */
|
|
539
|
+
private static readonly CLAIM_RECHECK_MS = 100;
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* Waits for the file's socket until `deadline`. A client that found the
|
|
543
|
+
* claim held by another process (`watchClaim`) also watches that claim:
|
|
544
|
+
* an owner that is stopping removes its socket and meta while it still
|
|
545
|
+
* holds the claim and frees it last, so once the claim is free nothing
|
|
546
|
+
* will listen unless this client places the file itself (ok, null).
|
|
547
|
+
*/
|
|
548
|
+
private async waitForSocket(deadline: number, watchClaim: boolean) {
|
|
549
|
+
let rechecked = Date.now();
|
|
526
550
|
for (let delayMs = 2; Date.now() < deadline; delayMs = Math.min(25, delayMs * 2)) {
|
|
527
551
|
const socket = await tryConnect(this.paths.socket);
|
|
528
552
|
if (socket) {
|
|
529
|
-
this.
|
|
530
|
-
return Result.ok(socket);
|
|
553
|
+
this.settleLeases();
|
|
554
|
+
return Result.ok<typeof socket | null>(socket);
|
|
555
|
+
}
|
|
556
|
+
if (watchClaim && Date.now() - rechecked >= SqlegoClient.CLAIM_RECHECK_MS) {
|
|
557
|
+
rechecked = Date.now();
|
|
558
|
+
// A claim that cannot be read is not known to be free.
|
|
559
|
+
if (Trust.decide(leaseHolder(this.paths.lease), { 'lease-failed': () => -1 }).value === null) return Result.ok(null);
|
|
531
560
|
}
|
|
532
561
|
await sleep(delayMs);
|
|
533
562
|
}
|
|
534
|
-
this.
|
|
563
|
+
this.settleLeases();
|
|
535
564
|
const cause = this.spawnFailure ? ` (${this.spawnFailure})` : '';
|
|
536
|
-
return Result.err({ kind: 'connect-timeout', message: `no sqlego server became reachable for ${this.paths.file}${cause}` });
|
|
565
|
+
return Result.err({ kind: 'connect-timeout' as const, message: `no sqlego server became reachable for ${this.paths.file}${cause}` });
|
|
537
566
|
}
|
|
538
567
|
|
|
539
|
-
/**
|
|
568
|
+
/**
|
|
569
|
+
* The file's claim: whoever holds it places the file with an owner, which
|
|
570
|
+
* then holds it while it serves the file. See `takeClaim`.
|
|
571
|
+
*/
|
|
540
572
|
private claimLock() {
|
|
541
|
-
|
|
573
|
+
const taken = this.takeClaim();
|
|
574
|
+
if (!taken.ok) return taken;
|
|
575
|
+
this.claim = taken.value;
|
|
576
|
+
return Result.ok(taken.value !== null);
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
/**
|
|
580
|
+
* Takes the file's claim lease and, with it, the claim lock older builds
|
|
581
|
+
* use (`<key>.lock`, see legacy_lock.ts) so that they see the file claimed
|
|
582
|
+
* too. Null when either is held: the lease by a process of this build, the
|
|
583
|
+
* lock by a live client of an older build placing the file.
|
|
584
|
+
*/
|
|
585
|
+
private takeClaim(): Result<Lease | null, { readonly kind: 'lock-failed'; readonly message: string }> {
|
|
586
|
+
const acquired = acquireLease(this.paths.lease);
|
|
587
|
+
if (!acquired.ok) return Result.err({ kind: 'lock-failed', message: `cannot claim ${this.paths.file}: ${acquired.error.message}` });
|
|
588
|
+
const lease = acquired.value;
|
|
589
|
+
if (!lease) return Result.ok(null);
|
|
590
|
+
const legacy = takeLegacyLock(this.paths.lock, process.pid);
|
|
591
|
+
if (legacy.ok && legacy.value) return Result.ok(lease);
|
|
592
|
+
const released = releaseLease(lease);
|
|
593
|
+
if (!released.ok && released.error.kind === 'lease-failed') {
|
|
594
|
+
// It names this live process; it frees itself when the process exits.
|
|
595
|
+
}
|
|
596
|
+
if (!legacy.ok) return Result.err({ kind: 'lock-failed', message: `cannot claim ${this.paths.file}: ${legacy.error.message}` });
|
|
597
|
+
return Result.ok(null);
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
/**
|
|
601
|
+
* Where this client's claim stands. `own` while this client still holds
|
|
602
|
+
* it (or holds none); `placed` once a live process holds it instead — the
|
|
603
|
+
* owner that took the file on, or another client placing it. An owner that
|
|
604
|
+
* took the claim over and then could not serve the file (its open or bind
|
|
605
|
+
* failed) released it again: this client takes it back and keeps placing.
|
|
606
|
+
*/
|
|
607
|
+
private followClaim(): Result<'own' | 'placed', { readonly kind: 'lock-failed'; readonly message: string }> {
|
|
608
|
+
const claim = this.claim;
|
|
609
|
+
if (!claim) return Result.ok('own');
|
|
610
|
+
// A lease that cannot be read is not known to have moved on.
|
|
611
|
+
if (Trust.decide(leaseHead(claim.base), { 'lease-failed': () => 0 }).value <= claim.generation) return Result.ok('own');
|
|
612
|
+
const holder = leaseHolder(claim.base);
|
|
613
|
+
if (!holder.ok) return Result.err({ kind: 'lock-failed', message: `cannot read the claim on ${this.paths.file}: ${holder.error.message}` });
|
|
614
|
+
if (holder.value !== null) {
|
|
615
|
+
this.claim = null;
|
|
616
|
+
return Result.ok('placed');
|
|
617
|
+
}
|
|
618
|
+
const again = this.takeClaim();
|
|
619
|
+
if (!again.ok) return Result.err({ kind: 'lock-failed', message: `cannot claim ${this.paths.file} again: ${again.error.message}` });
|
|
620
|
+
this.claim = again.value;
|
|
621
|
+
return Result.ok(again.value === null ? 'placed' : 'own');
|
|
542
622
|
}
|
|
543
623
|
|
|
544
624
|
/* ------------------------------------------------------------------ *
|
|
@@ -550,32 +630,45 @@ export class SqlegoClient {
|
|
|
550
630
|
return Number.isFinite(configured) && configured >= 0 ? Math.floor(configured) : DEFAULT_MAX_OWNERS;
|
|
551
631
|
}
|
|
552
632
|
|
|
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
633
|
/**
|
|
559
|
-
* Gets this client's file served, holding the file's claim
|
|
634
|
+
* Gets this client's file served, holding the file's claim: by the
|
|
560
635
|
* running owner process (of this build) serving the fewest files, or by a
|
|
561
636
|
* new process while fewer than `maxOwners` are running. Spawning is
|
|
562
|
-
* serialized through the spawn
|
|
637
|
+
* serialized through the spawn lease so many files opened at once share
|
|
563
638
|
* one process instead of each starting their own; a client that loses
|
|
564
|
-
* that
|
|
639
|
+
* that lease waits for the new owner to appear and adopts into it. The
|
|
640
|
+
* owner a client spawns takes both leases over (see `serve` in cli.ts), so
|
|
641
|
+
* the reservation lasts until that owner is counted even if this client
|
|
642
|
+
* exits first.
|
|
565
643
|
*/
|
|
566
644
|
private async placeFile(deadline: number) {
|
|
567
645
|
const budget = this.ownerBudget();
|
|
568
646
|
let lastRefusal: string | null = null;
|
|
647
|
+
const refusal = () => (lastRefusal ? `: ${lastRefusal}` : '');
|
|
569
648
|
while (Date.now() < deadline) {
|
|
649
|
+
// An owner took the file on (an adopt that timed out here, say): it serves it.
|
|
650
|
+
const standing = this.followClaim();
|
|
651
|
+
if (!standing.ok) return Result.err({ kind: standing.error.kind, message: `${standing.error.message}${refusal()}` });
|
|
652
|
+
if (standing.value === 'placed') return Result.ok(undefined);
|
|
570
653
|
const owners = this.currentOwners();
|
|
571
654
|
if (!owners.ok) return owners;
|
|
572
655
|
if (budget === 0 || owners.value.length < budget) {
|
|
573
656
|
if (budget === 0) return this.spawnServer();
|
|
574
|
-
const claimed =
|
|
575
|
-
if (!claimed.ok) return claimed;
|
|
657
|
+
const claimed = acquireLease(spawnLeaseBase(path.dirname(this.paths.lease)));
|
|
658
|
+
if (!claimed.ok) return Result.err({ kind: 'lock-failed' as const, message: `cannot reserve a spawn: ${claimed.error.message}` });
|
|
576
659
|
if (claimed.value) {
|
|
577
|
-
this.
|
|
578
|
-
|
|
660
|
+
this.spawnLease = claimed.value;
|
|
661
|
+
// The count above was read before the lease was ours: the spawner
|
|
662
|
+
// that just released it may have published its owner since. Count
|
|
663
|
+
// again under the lease, and adopt instead if the budget is now met.
|
|
664
|
+
const settled = this.currentOwners();
|
|
665
|
+
if (!settled.ok) {
|
|
666
|
+
this.releaseSpawnLock();
|
|
667
|
+
return settled;
|
|
668
|
+
}
|
|
669
|
+
if (settled.value.length < budget) return this.spawnServer();
|
|
670
|
+
this.releaseSpawnLock();
|
|
671
|
+
continue;
|
|
579
672
|
}
|
|
580
673
|
// Another client is spawning an owner; it will be adoptable once up.
|
|
581
674
|
await sleep(25);
|
|
@@ -586,15 +679,19 @@ export class SqlegoClient {
|
|
|
586
679
|
if (remaining <= 0) break;
|
|
587
680
|
const adopted = await oneShot(owner.socket, {
|
|
588
681
|
op: 'adopt', file: this.paths.file, pragmas: this.options.serverPragmas, idleTimeoutMs: this.options.idleTimeoutMs ?? 30_000,
|
|
682
|
+
claim: this.claim ? encodeLease(this.claim) : undefined,
|
|
589
683
|
}, parseAdoptResult, Math.min(ADOPT_TIMEOUT_MS, remaining));
|
|
590
684
|
if (adopted.ok) return Result.ok(undefined);
|
|
591
685
|
if (adopted.error.kind === 'probe-failed') lastRefusal = `owner ${owner.pid}: ${adopted.error.message}`;
|
|
686
|
+
// The owner may have taken the claim over and released it again (it could not serve the file): take it back for the next.
|
|
687
|
+
const after = this.followClaim();
|
|
688
|
+
if (!after.ok) return Result.err({ kind: after.error.kind, message: `${after.error.message}${refusal()}` });
|
|
689
|
+
if (after.value === 'placed') return Result.ok(undefined);
|
|
592
690
|
}
|
|
593
691
|
// Every owner went away or refused; the owner set may have changed.
|
|
594
692
|
await sleep(25);
|
|
595
693
|
}
|
|
596
|
-
const
|
|
597
|
-
return Result.err({ kind: 'connect-timeout' as const, message: `no sqlego owner took on ${this.paths.file}${why}` });
|
|
694
|
+
return Result.err({ kind: 'connect-timeout' as const, message: `no sqlego owner took on ${this.paths.file}${refusal()}` });
|
|
598
695
|
}
|
|
599
696
|
|
|
600
697
|
/**
|
|
@@ -637,15 +734,24 @@ export class SqlegoClient {
|
|
|
637
734
|
return Result.ok(owners);
|
|
638
735
|
}
|
|
639
736
|
|
|
737
|
+
/**
|
|
738
|
+
* Releases the spawn reservation unless it has moved on: once the spawned
|
|
739
|
+
* owner has taken it over, this is a no-op and never frees the owner's.
|
|
740
|
+
*/
|
|
640
741
|
private releaseSpawnLock(): void {
|
|
641
|
-
|
|
642
|
-
this.
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
)
|
|
647
|
-
|
|
648
|
-
|
|
742
|
+
const lease = this.spawnLease;
|
|
743
|
+
this.spawnLease = null;
|
|
744
|
+
if (!lease) return;
|
|
745
|
+
const released = releaseLease(lease);
|
|
746
|
+
// A reservation that cannot be released names this process; it frees itself when the process exits.
|
|
747
|
+
if (!released.ok && released.error.kind === 'lease-failed') this.spawnFailure = `spawn lock not released: ${released.error.message}`;
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
/** Connected or given up: whatever this client still holds goes (a no-op for anything an owner took over). */
|
|
751
|
+
private settleLeases(): void {
|
|
752
|
+
this.releaseSpawnLock();
|
|
753
|
+
const released = this.releaseLock();
|
|
754
|
+
if (!released.ok && released.error.kind === 'lock-failed') this.spawnFailure = `claim not released: ${released.error.message}`;
|
|
649
755
|
}
|
|
650
756
|
|
|
651
757
|
/** Waits until nothing answers on the file's socket (the old owner released it, its database closed first), or the deadline. */
|
|
@@ -663,7 +769,13 @@ export class SqlegoClient {
|
|
|
663
769
|
if (!resolved.ok) return resolved;
|
|
664
770
|
const [command, ...args] = resolved.value;
|
|
665
771
|
const pragmaArgs = (this.options.serverPragmas ?? []).flatMap((pragma) => ['--pragma', pragma]);
|
|
666
|
-
|
|
772
|
+
// The owner takes the claim and the spawn reservation over (see `serve` in cli.ts).
|
|
773
|
+
const env: Record<string, string | undefined> = { ...process.env };
|
|
774
|
+
delete env.SQLEGO_CLAIM_LEASE;
|
|
775
|
+
delete env.SQLEGO_SPAWN_LEASE;
|
|
776
|
+
if (this.claim) env.SQLEGO_CLAIM_LEASE = encodeLease(this.claim);
|
|
777
|
+
if (this.spawnLease) env.SQLEGO_SPAWN_LEASE = encodeLease(this.spawnLease);
|
|
778
|
+
const spawned = Trust.try(
|
|
667
779
|
() => {
|
|
668
780
|
const child = spawn(command, [...args, 'serve', this.paths.file, '--idle-ms', String(this.options.idleTimeoutMs ?? 30_000), ...pragmaArgs], {
|
|
669
781
|
detached: true,
|
|
@@ -672,7 +784,7 @@ export class SqlegoClient {
|
|
|
672
784
|
// stderr is captured (bounded) only to explain a failed start; it never
|
|
673
785
|
// keeps this process alive.
|
|
674
786
|
stdio: ['ignore', 'ignore', 'pipe'],
|
|
675
|
-
env
|
|
787
|
+
env,
|
|
676
788
|
});
|
|
677
789
|
let stderr = '';
|
|
678
790
|
child.stderr?.on('data', (chunk: Buffer) => { if (stderr.length < 2_000) stderr += chunk.toString(); });
|
|
@@ -687,23 +799,50 @@ export class SqlegoClient {
|
|
|
687
799
|
if (!this.hello) this.spawnFailure = `server exited before listening (code ${code}, signal ${signal})${stderr ? `: ${stderr.trim()}` : ''}`;
|
|
688
800
|
});
|
|
689
801
|
child.unref();
|
|
802
|
+
return child.pid;
|
|
690
803
|
},
|
|
691
804
|
(cause) => ({ kind: 'spawn-failed' as const, message: `spawn ${command} failed: ${errorMessage(cause)}` }),
|
|
692
805
|
);
|
|
806
|
+
// The older builds' claim lock keeps naming this client until the owner
|
|
807
|
+
// moves it to itself with the claim (see `serve` in cli.ts). If this
|
|
808
|
+
// client dies first and an older client takes the lock, the owner finds
|
|
809
|
+
// it held by a live process other than its spawner and refuses the file.
|
|
810
|
+
if (!spawned.ok) return spawned;
|
|
811
|
+
return Result.ok(undefined);
|
|
693
812
|
}
|
|
694
813
|
|
|
695
|
-
/** The spawn never started: record why, and release
|
|
814
|
+
/** The spawn never started: record why, and release both locks so another claimer can try. */
|
|
696
815
|
private onSpawnError(command: string, error: Error): void {
|
|
816
|
+
// First: a spawn lock that cannot be removed records that in `spawnFailure`, which the cause below must replace.
|
|
817
|
+
this.releaseSpawnLock();
|
|
697
818
|
this.spawnFailure = `spawn ${command} failed: ${error.message}`;
|
|
698
819
|
const released = this.releaseLock();
|
|
699
820
|
if (!released.ok && released.error.kind === 'lock-failed') this.spawnFailure += `; lock not released: ${released.error.message}`;
|
|
700
821
|
}
|
|
701
822
|
|
|
823
|
+
/**
|
|
824
|
+
* Releases this client's claim unless an owner has taken it over (then this
|
|
825
|
+
* is a no-op), or it was released already. First the claim moves to a new
|
|
826
|
+
* generation this client holds — one step that fails if an owner took it
|
|
827
|
+
* over meanwhile, in which case the older builds' claim lock is the
|
|
828
|
+
* owner's and stays. Holding that generation, no owner can take the claim
|
|
829
|
+
* over any more, so the lock (only if it names this client) goes before
|
|
830
|
+
* the claim is freed: freed first, a client taking it would find the lock
|
|
831
|
+
* still naming this live process, back off, and wait for a socket nobody
|
|
832
|
+
* starts.
|
|
833
|
+
*/
|
|
702
834
|
private releaseLock() {
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
);
|
|
835
|
+
const claim = this.claim;
|
|
836
|
+
this.claim = null;
|
|
837
|
+
if (!claim) return Result.ok(undefined);
|
|
838
|
+
const releasing = handOverLease(claim, process.pid);
|
|
839
|
+
if (!releasing.ok) return Result.err({ kind: 'lock-failed' as const, message: releasing.error.message });
|
|
840
|
+
if (!releasing.value) return Result.ok(undefined);
|
|
841
|
+
const dropped = dropLegacyLock(this.paths.lock, [process.pid]);
|
|
842
|
+
const released = releaseLease(releasing.value);
|
|
843
|
+
if (!dropped.ok) return Result.err({ kind: 'lock-failed' as const, message: dropped.error.message });
|
|
844
|
+
if (!released.ok) return Result.err({ kind: 'lock-failed' as const, message: released.error.message });
|
|
845
|
+
return Result.ok(undefined);
|
|
707
846
|
}
|
|
708
847
|
|
|
709
848
|
private attach(socket: net.Socket) {
|
|
@@ -803,42 +942,6 @@ export class SqlegoClient {
|
|
|
803
942
|
|
|
804
943
|
}
|
|
805
944
|
|
|
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
945
|
/**
|
|
843
946
|
* One open transaction on a `SqlegoClient`. Every method rejects with a
|
|
844
947
|
* `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
|
+
}
|