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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/paths.d.ts CHANGED
@@ -20,10 +20,7 @@ export type FilePaths = Readonly<{
20
20
  key: string;
21
21
  /** Unix domain socket path, or a `\\.\pipe\` named pipe on Windows (see `isNamedPipe`). */
22
22
  socket: string;
23
- /** The claim lock older builds take (a pid in one file); still honoured while its process lives. */
24
23
  lock: string;
25
- /** The file's claim as a lease (`lease.ts`): held by the client placing the file, then by the owner serving it. */
26
- lease: string;
27
24
  meta: string;
28
25
  }>;
29
26
  /** Windows has no Unix domain sockets; the local transport there is a named pipe. */
@@ -51,10 +48,7 @@ export declare function resolvePaths(file: string): import("@noego/trust").Err<{
51
48
  key: string;
52
49
  /** Unix domain socket path, or a `\\.\pipe\` named pipe on Windows (see `isNamedPipe`). */
53
50
  socket: string;
54
- /** The claim lock older builds take (a pid in one file); still honoured while its process lives. */
55
51
  lock: string;
56
- /** The file's claim as a lease (`lease.ts`): held by the client placing the file, then by the owner serving it. */
57
- lease: string;
58
52
  meta: string;
59
53
  }>>;
60
54
  /** Public, exception-based form of `resolveRuntimeDirectory`. */
@@ -105,10 +105,8 @@ export type Request = {
105
105
  }
106
106
  /**
107
107
  * Asks this owner process to serve one more file: open it with `pragmas`
108
- * (its defaults when absent) and listen on that file's own socket. `claim`
109
- * is the file's claim lease the asking client holds (`<generation>:<token>`);
110
- * the owner takes it over before opening the file and refuses if it cannot
111
- * (`lease.ts`). The reply names the socket to connect to.
108
+ * (its defaults when absent), listen on that file's own socket, release
109
+ * that file's claim lock. The reply names the socket to connect to.
112
110
  */
113
111
  | {
114
112
  id: number;
@@ -116,7 +114,6 @@ export type Request = {
116
114
  file: string;
117
115
  pragmas?: readonly string[];
118
116
  idleTimeoutMs?: number;
119
- claim?: string;
120
117
  };
121
118
  export type RunResult = Readonly<{
122
119
  changes: number;
@@ -509,12 +506,6 @@ export declare function splitFrames(buffer: string): {
509
506
  frames: string[];
510
507
  rest: string;
511
508
  };
512
- /**
513
- * The longest request frame the server reads, in decoded characters (the
514
- * newline not counted). A longer one is never complete in memory: the
515
- * server drops the connection once an unfinished frame passes it.
516
- */
517
- export declare const DEFAULT_MAX_FRAME_LENGTH: number;
518
509
  /**
519
510
  * The frames of one socket, read chunk by chunk in work proportional to what
520
511
  * arrives, however finely it is chunked: only the new chunk is searched for
@@ -525,26 +516,11 @@ export declare const DEFAULT_MAX_FRAME_LENGTH: number;
525
516
  * Empty lines are skipped, as `splitFrames` skips them.
526
517
  */
527
518
  export declare class FrameReader {
528
- private readonly maxFrameLength;
529
519
  private pieces;
530
- /** Characters held in `pieces`: the length of the unfinished frame so far. */
531
- private held;
532
- private overflowed;
533
520
  private decoder;
534
521
  private searched;
535
- /**
536
- * `maxFrameLength` bounds one frame in characters (its newline not
537
- * counted); unbounded by default, as a client reads replies of any size.
538
- */
539
- constructor(maxFrameLength?: number);
540
522
  /** Characters searched for a newline so far: each one pushed is searched once. */
541
523
  get scannedCharacters(): number;
542
- /**
543
- * Whether a frame passed `maxFrameLength`. Its pieces were dropped and
544
- * nothing more is read until `reset`: the stream has no trustworthy next
545
- * frame boundary.
546
- */
547
- get oversized(): boolean;
548
524
  /** The frames `chunk` completes, in order; its unterminated tail waits for the next chunk. */
549
525
  push(chunk: string): string[];
550
526
  /**
@@ -556,6 +532,4 @@ export declare class FrameReader {
556
532
  pushBytes(chunk: Uint8Array): string[];
557
533
  /** Drops an unfinished frame (and a partly received character): the stream is starting over or was given up. */
558
534
  reset(): void;
559
- /** Gives up the unfinished frame; `frames` are the ones completed before it. */
560
- private overflow;
561
535
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noego/sqlego",
3
- "version": "0.1.6-dev.6",
3
+ "version": "0.1.6-dev.7",
4
4
  "description": "One owner per SQLite file, many files per owner process. Clients (CLI, Node, Bun) pass SQL over a local socket (Unix) or named pipe (Windows); the owner starts on demand and exits when idle.",
5
5
  "type": "module",
6
6
  "license": "ISC",
@@ -31,7 +31,7 @@
31
31
  "README.md"
32
32
  ],
33
33
  "scripts": {
34
- "prepare": "bun scripts/build.ts all",
34
+ "prepare": "bun scripts/build.ts lib",
35
35
  "build": "bun scripts/build.ts all",
36
36
  "build:all": "bun scripts/build.ts all:platforms",
37
37
  "build:lib": "bun scripts/build.ts lib",
@@ -51,10 +51,10 @@
51
51
  "@noego/trust": "^0.5.1"
52
52
  },
53
53
  "optionalDependencies": {
54
- "@noego/sqlego-darwin-arm64": "0.1.6-dev.6",
55
- "@noego/sqlego-darwin-x64": "0.1.6-dev.6",
56
- "@noego/sqlego-linux-x64": "0.1.6-dev.6",
57
- "@noego/sqlego-linux-arm64": "0.1.6-dev.6",
58
- "@noego/sqlego-win32-x64": "0.1.6-dev.6"
54
+ "@noego/sqlego-darwin-arm64": "0.1.6-dev.7",
55
+ "@noego/sqlego-darwin-x64": "0.1.6-dev.7",
56
+ "@noego/sqlego-linux-x64": "0.1.6-dev.7",
57
+ "@noego/sqlego-linux-arm64": "0.1.6-dev.7",
58
+ "@noego/sqlego-win32-x64": "0.1.6-dev.7"
59
59
  }
60
60
  }
package/src/cli.ts CHANGED
@@ -12,9 +12,7 @@ import { readdirSync, readFileSync } from 'node:fs';
12
12
  import path from 'node:path';
13
13
  import { Result, Trust } from '@noego/trust';
14
14
  import { SqlegoClient, SqlegoClientError } from './client.ts';
15
- import { acquireLease, decodeLease, handOverLease, recordedHolder, releaseLease, spawnLeaseBase, type Lease } from './lease.ts';
16
- import { dropLegacyLock, passLegacyLock } from './legacy_lock.ts';
17
- import { isProcessAlive, parseServerMeta, resolvePaths, resolveRuntimeDirectory } from './paths.ts';
15
+ import { isProcessAlive, parseServerMeta, resolveRuntimeDirectory } from './paths.ts';
18
16
  import { errorMessage, fromJson, parseSqlParams, toJson, type SqlRow } from './protocol.ts';
19
17
  import { VERSION } from './version.ts';
20
18
 
@@ -120,124 +118,12 @@ function render(rows: SqlRow[], flags: Flags): string {
120
118
  return renderBox(rows);
121
119
  }
122
120
 
123
- /** What a spawned owner took over from the client that spawned it (none when started by hand). */
124
- type TakenOver = { readonly claim: Lease | undefined; readonly spawn: Lease | null; readonly lock?: string };
125
-
126
- /** Frees a lease this process took over but will not keep (and, for a claim, the older builds' lock `lock` with it). */
127
- function releaseTakenOver(lease: Lease | null | undefined, lock?: string): void {
128
- if (!lease) return;
129
- if (lock) {
130
- const dropped = dropLegacyLock(lock, [process.pid]);
131
- if (!dropped.ok && dropped.error.kind === 'legacy-lock-failed') {
132
- // It names this process, so older builds reclaim it once this process exits.
133
- }
134
- }
135
- const released = releaseLease(lease);
136
- if (!released.ok && released.error.kind === 'lease-failed') {
137
- // It names this process, so it frees itself when this process exits.
138
- }
139
- }
140
-
141
- /** The claim an owner took over from an older client: the lease and the claim lock beside it; null when no older client spawned it. */
142
- type OlderClaim = { readonly claim: Lease; readonly lock: string } | null;
143
-
144
- /**
145
- * An owner spawned by a client of a build before leases (main 1ec410c and
146
- * earlier: it passes no lease, only its pid as `SQLEGO_CLAIMED_BY`) takes
147
- * the file's claim as its own: it takes the claim lease, then moves that
148
- * client's claim lock (`<key>.lock`) to itself, and holds both while it
149
- * serves the file, releasing them when it stops (as any owner of this build
150
- * does). Owners of those builds removed the lock once listening; the client
151
- * never removes it itself, so left naming the client it would keep every
152
- * client from placing the file again until that client exits. Moving the
153
- * lock rather than removing it keeps the file claimed throughout and never
154
- * removes a lock another process has taken. When the lease is held
155
- * elsewhere, or the lock names a live process other than that client,
156
- * another process has claimed the file since (its spawner died, say): this
157
- * owner must not serve it, so the takeover fails and `serve` exits before
158
- * opening or binding anything. Null only when no older client spawned it.
159
- */
160
- function takeOverOlderClaim(file: string): Result<OlderClaim, { readonly kind: 'failed'; readonly message: string }> {
161
- const claimer = Number(process.env.SQLEGO_CLAIMED_BY);
162
- if (!Number.isInteger(claimer) || claimer <= 0) return Result.ok(null);
163
- const paths = resolvePaths(file);
164
- if (!paths.ok) return Result.err({ kind: 'failed' as const, message: `cannot take the older client's claim over: ${paths.error.message}` });
165
- const refused = (why: string) => Result.err({ kind: 'failed' as const, message: `${why}; not serving ${paths.value.file}` });
166
- const acquired = acquireLease(paths.value.lease);
167
- if (!acquired.ok) return refused(`cannot take the older client's claim over: ${acquired.error.message}`);
168
- if (!acquired.value) return refused('its claim is held by another process since the older client spawned this owner');
169
- const moved = passLegacyLock(paths.value.lock, claimer, process.pid);
170
- if (moved.ok && moved.value) return Result.ok({ claim: acquired.value, lock: paths.value.lock });
171
- releaseTakenOver(acquired.value);
172
- return refused(moved.ok
173
- ? 'its claim lock is held by another live process since the older client spawned this owner'
174
- : `cannot take the older client's claim lock over: ${moved.error.message}`);
175
- }
176
-
177
- /**
178
- * An owner a client spawned takes the file's claim and the spawn
179
- * reservation over from that client before it opens anything: the client
180
- * passes the leases it holds (`SQLEGO_CLAIM_LEASE`, `SQLEGO_SPAWN_LEASE`,
181
- * each `<generation>:<token>`), and each handover is one step that succeeds
182
- * only if no one acted on that generation since (`lease.ts`). The older
183
- * builds' claim lock (`<key>.lock`) moves to this process with the claim. From then on
184
- * both name this live process, so the client exiting frees neither: no other
185
- * client can place the file again or spawn past `maxOwners` while this owner
186
- * starts. If either was taken first (the client died and another reclaimed
187
- * it, or the client gave up and released it), this process must not serve
188
- * the file.
189
- */
190
- function takeOverLeases(file: string) {
191
- if (process.env.SQLEGO_CLAIM_LEASE === undefined) return Result.ok<TakenOver>({ claim: undefined, spawn: null });
192
- const paths = resolvePaths(file);
193
- if (!paths.ok) return paths;
194
- const refused = (why: string) => Result.err({ kind: 'failed' as const, message: `${why}; not serving ${paths.value.file}` });
195
- const handed = decodeLease(paths.value.lease, process.env.SQLEGO_CLAIM_LEASE);
196
- if (!handed) return refused(`SQLEGO_CLAIM_LEASE is not a lease: ${process.env.SQLEGO_CLAIM_LEASE}`);
197
- const spawner = recordedHolder(handed);
198
- const claim = handOverLease(handed, process.pid);
199
- if (!claim.ok) return refused(`cannot take the claim over: ${claim.error.message}`);
200
- if (!claim.value) return refused('its claim was taken by another client since this owner was spawned');
201
- const legacy = passLegacyLock(paths.value.lock, spawner, process.pid);
202
- if (!legacy.ok || !legacy.value) {
203
- releaseTakenOver(claim.value);
204
- return refused(legacy.ok
205
- ? 'a client of an older build holds its claim lock'
206
- : `cannot take its claim lock over: ${legacy.error.message}`);
207
- }
208
- const lock = paths.value.lock;
209
- if (process.env.SQLEGO_SPAWN_LEASE === undefined) return Result.ok<TakenOver>({ claim: claim.value, spawn: null, lock });
210
- const reserved = decodeLease(spawnLeaseBase(path.dirname(paths.value.lease)), process.env.SQLEGO_SPAWN_LEASE);
211
- const spawn = reserved ? handOverLease(reserved, process.pid) : Result.ok<Lease | null>(null);
212
- if (spawn.ok && spawn.value) return Result.ok<TakenOver>({ claim: claim.value, spawn: spawn.value, lock });
213
- // Without the reservation another owner may be starting under the same budget: give the file back.
214
- releaseTakenOver(claim.value, paths.value.lock);
215
- return refused(spawn.ok
216
- ? 'the spawn reservation it was started under was taken by another client since'
217
- : `cannot take the spawn reservation over: ${spawn.error.message}`);
218
- }
219
-
220
121
  async function serve(file: string, flags: Flags, pragmas: readonly string[]) {
221
- const leases = takeOverLeases(file);
222
- if (!leases.ok) return leases;
223
- const { spawn } = leases.value;
224
- // An owner an older client spawned holds the file's claim as its own from here (see `takeOverOlderClaim`).
225
- const older = leases.value.claim ? Result.ok<OlderClaim>(null) : takeOverOlderClaim(file);
226
- if (!older.ok) {
227
- releaseTakenOver(spawn);
228
- return older;
229
- }
230
- const claim = leases.value.claim ?? older.value?.claim;
231
- const lock = leases.value.lock ?? older.value?.lock;
232
122
  const loaded = await Trust.tryAsync(
233
123
  () => import('./server.ts'),
234
124
  (cause) => ({ kind: 'failed' as const, message: `cannot load the server: ${errorMessage(cause)}` }),
235
125
  );
236
- if (!loaded.ok) {
237
- releaseTakenOver(claim, lock);
238
- releaseTakenOver(spawn);
239
- return loaded;
240
- }
126
+ if (!loaded.ok) return loaded;
241
127
  const { SqlegoServer, DEFAULT_PRAGMAS, stopAll } = loaded.value;
242
128
  const idleTimeoutMs = flags['idle-ms'] ? Number(flags['idle-ms']) : 30_000;
243
129
  const millis = (flag: string) => (typeof flags[flag] === 'string' ? Number(flags[flag]) : undefined);
@@ -251,7 +137,6 @@ async function serve(file: string, flags: Flags, pragmas: readonly string[]) {
251
137
  ? undefined
252
138
  : new loaded.value.ReaderPool({ size: readers ?? loaded.value.DEFAULT_READERS, queueLimit: readerQueue ?? loaded.value.DEFAULT_READER_QUEUE_LIMIT, log });
253
139
  // The first file of this owner process; clients add more through `adopt`.
254
- // The server keeps the claim while it serves the file.
255
140
  const started = SqlegoServer.start({
256
141
  file,
257
142
  idleTimeoutMs,
@@ -263,11 +148,7 @@ async function serve(file: string, flags: Flags, pragmas: readonly string[]) {
263
148
  fileCheckMs: millis('file-check-ms'),
264
149
  readerPool,
265
150
  log,
266
- claim,
267
151
  });
268
- // This owner is now counted (its meta published) and listening, or it never
269
- // will be: either way the next spawner may go ahead.
270
- releaseTakenOver(spawn);
271
152
  if (!started.ok) return started;
272
153
  const shutdown = (signal: string) => { stopAll(signal); process.exit(0); };
273
154
  return Trust.try(
package/src/client.ts CHANGED
@@ -1,17 +1,16 @@
1
1
  import { spawn } from 'node:child_process';
2
- import { readdirSync, readFileSync, existsSync } from 'node:fs';
2
+ import { closeSync, openSync, readdirSync, readFileSync, rmSync, writeSync, 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';
11
9
  import {
12
10
  FrameReader,
13
11
  PROTOCOL_VERSION,
14
12
  encodeRequestFrame,
13
+ errnoCode,
15
14
  errorMessage,
16
15
  fromJson,
17
16
  parseBatchResult,
@@ -205,10 +204,8 @@ export class SqlegoClient {
205
204
  private mismatches: readonly OwnerMismatch[] = [];
206
205
  /** Why the server this client spawned did not come up, if it did not. */
207
206
  private spawnFailure: string | null = null;
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;
207
+ /** True while this client is the one spawning an owner process (see `placeFile`). */
208
+ private holdsSpawnLock = false;
212
209
  private readonly options: ClientOptions;
213
210
 
214
211
  private constructor(paths: FilePaths, options: ClientOptions) {
@@ -519,8 +516,7 @@ export class SqlegoClient {
519
516
  if (claimed.value) {
520
517
  const placed = await this.placeFile(deadline);
521
518
  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();
519
+ // Nothing will serve the file: the claim must go so the next client can try.
524
520
  const released = this.releaseLock();
525
521
  const suffix = !released.ok && released.error.kind === 'lock-failed' ? `; lock not released: ${released.error.message}` : '';
526
522
  return Result.err({ kind: placed.error.kind, message: `${placed.error.message}${suffix}` });
@@ -530,70 +526,19 @@ export class SqlegoClient {
530
526
  for (let delayMs = 2; Date.now() < deadline; delayMs = Math.min(25, delayMs * 2)) {
531
527
  const socket = await tryConnect(this.paths.socket);
532
528
  if (socket) {
533
- this.settleLeases();
529
+ this.releaseSpawnLock();
534
530
  return Result.ok(socket);
535
531
  }
536
532
  await sleep(delayMs);
537
533
  }
538
- this.settleLeases();
534
+ this.releaseSpawnLock();
539
535
  const cause = this.spawnFailure ? ` (${this.spawnFailure})` : '';
540
536
  return Result.err({ kind: 'connect-timeout', message: `no sqlego server became reachable for ${this.paths.file}${cause}` });
541
537
  }
542
538
 
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
- */
539
+ /** The file's own claim lock: whoever holds it places the file with an owner. */
547
540
  private claimLock() {
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');
541
+ return claimLockAt(this.paths.lock);
597
542
  }
598
543
 
599
544
  /* ------------------------------------------------------------------ *
@@ -605,45 +550,32 @@ export class SqlegoClient {
605
550
  return Number.isFinite(configured) && configured >= 0 ? Math.floor(configured) : DEFAULT_MAX_OWNERS;
606
551
  }
607
552
 
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
+
608
558
  /**
609
- * Gets this client's file served, holding the file's claim: by the
559
+ * Gets this client's file served, holding the file's claim lock: by the
610
560
  * running owner process (of this build) serving the fewest files, or by a
611
561
  * new process while fewer than `maxOwners` are running. Spawning is
612
- * serialized through the spawn lease so many files opened at once share
562
+ * serialized through the spawn lock so many files opened at once share
613
563
  * one process instead of each starting their own; a client that loses
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.
564
+ * that lock waits for the new owner to appear and adopts into it.
618
565
  */
619
566
  private async placeFile(deadline: number) {
620
567
  const budget = this.ownerBudget();
621
568
  let lastRefusal: string | null = null;
622
- const refusal = () => (lastRefusal ? `: ${lastRefusal}` : '');
623
569
  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);
628
570
  const owners = this.currentOwners();
629
571
  if (!owners.ok) return owners;
630
572
  if (budget === 0 || owners.value.length < budget) {
631
573
  if (budget === 0) return this.spawnServer();
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}` });
574
+ const claimed = claimLockAt(this.spawnLockPath());
575
+ if (!claimed.ok) return claimed;
634
576
  if (claimed.value) {
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;
577
+ this.holdsSpawnLock = true;
578
+ return this.spawnServer();
647
579
  }
648
580
  // Another client is spawning an owner; it will be adoptable once up.
649
581
  await sleep(25);
@@ -654,19 +586,15 @@ export class SqlegoClient {
654
586
  if (remaining <= 0) break;
655
587
  const adopted = await oneShot(owner.socket, {
656
588
  op: 'adopt', file: this.paths.file, pragmas: this.options.serverPragmas, idleTimeoutMs: this.options.idleTimeoutMs ?? 30_000,
657
- claim: this.claim ? encodeLease(this.claim) : undefined,
658
589
  }, parseAdoptResult, Math.min(ADOPT_TIMEOUT_MS, remaining));
659
590
  if (adopted.ok) return Result.ok(undefined);
660
591
  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);
665
592
  }
666
593
  // Every owner went away or refused; the owner set may have changed.
667
594
  await sleep(25);
668
595
  }
669
- return Result.err({ kind: 'connect-timeout' as const, message: `no sqlego owner took on ${this.paths.file}${refusal()}` });
596
+ const why = lastRefusal ? `: ${lastRefusal}` : '';
597
+ return Result.err({ kind: 'connect-timeout' as const, message: `no sqlego owner took on ${this.paths.file}${why}` });
670
598
  }
671
599
 
672
600
  /**
@@ -709,24 +637,15 @@ export class SqlegoClient {
709
637
  return Result.ok(owners);
710
638
  }
711
639
 
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
- */
716
640
  private releaseSpawnLock(): void {
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}`;
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}`;
730
649
  }
731
650
 
732
651
  /** Waits until nothing answers on the file's socket (the old owner released it, its database closed first), or the deadline. */
@@ -744,13 +663,7 @@ export class SqlegoClient {
744
663
  if (!resolved.ok) return resolved;
745
664
  const [command, ...args] = resolved.value;
746
665
  const pragmaArgs = (this.options.serverPragmas ?? []).flatMap((pragma) => ['--pragma', pragma]);
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(
666
+ return Trust.try(
754
667
  () => {
755
668
  const child = spawn(command, [...args, 'serve', this.paths.file, '--idle-ms', String(this.options.idleTimeoutMs ?? 30_000), ...pragmaArgs], {
756
669
  detached: true,
@@ -759,7 +672,7 @@ export class SqlegoClient {
759
672
  // stderr is captured (bounded) only to explain a failed start; it never
760
673
  // keeps this process alive.
761
674
  stdio: ['ignore', 'ignore', 'pipe'],
762
- env,
675
+ env: { ...process.env, SQLEGO_CLAIMED_BY: String(process.pid) },
763
676
  });
764
677
  let stderr = '';
765
678
  child.stderr?.on('data', (chunk: Buffer) => { if (stderr.length < 2_000) stderr += chunk.toString(); });
@@ -774,50 +687,23 @@ export class SqlegoClient {
774
687
  if (!this.hello) this.spawnFailure = `server exited before listening (code ${code}, signal ${signal})${stderr ? `: ${stderr.trim()}` : ''}`;
775
688
  });
776
689
  child.unref();
777
- return child.pid;
778
690
  },
779
691
  (cause) => ({ kind: 'spawn-failed' as const, message: `spawn ${command} failed: ${errorMessage(cause)}` }),
780
692
  );
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);
787
693
  }
788
694
 
789
- /** The spawn never started: record why, and release both locks so another claimer can try. */
695
+ /** The spawn never started: record why, and release the lock so another claimer can try. */
790
696
  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();
793
697
  this.spawnFailure = `spawn ${command} failed: ${error.message}`;
794
698
  const released = this.releaseLock();
795
699
  if (!released.ok && released.error.kind === 'lock-failed') this.spawnFailure += `; lock not released: ${released.error.message}`;
796
700
  }
797
701
 
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
- */
809
702
  private releaseLock() {
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);
703
+ return Trust.try(
704
+ () => rmSync(this.paths.lock, { force: true }),
705
+ (cause) => ({ kind: 'lock-failed' as const, message: errorMessage(cause) }),
706
+ );
821
707
  }
822
708
 
823
709
  private attach(socket: net.Socket) {
@@ -917,6 +803,42 @@ export class SqlegoClient {
917
803
 
918
804
  }
919
805
 
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
+
920
842
  /**
921
843
  * One open transaction on a `SqlegoClient`. Every method rejects with a
922
844
  * `SqlegoClientError` whose code is `tx-expired` once the server has rolled
package/src/paths.ts CHANGED
@@ -52,10 +52,7 @@ export type FilePaths = Readonly<{
52
52
  key: string;
53
53
  /** Unix domain socket path, or a `\\.\pipe\` named pipe on Windows (see `isNamedPipe`). */
54
54
  socket: string;
55
- /** The claim lock older builds take (a pid in one file); still honoured while its process lives. */
56
55
  lock: string;
57
- /** The file's claim as a lease (`lease.ts`): held by the client placing the file, then by the owner serving it. */
58
- lease: string;
59
56
  meta: string;
60
57
  }>;
61
58
 
@@ -107,7 +104,6 @@ export function resolvePaths(file: string) {
107
104
  key,
108
105
  socket,
109
106
  lock: path.join(directory.value, `${key}.lock`),
110
- lease: path.join(directory.value, `${key}.lease`),
111
107
  meta: path.join(directory.value, `${key}.json`),
112
108
  });
113
109
  return Result.ok(paths);