@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.
@@ -0,0 +1,39 @@
1
+ import { Result } from '@noego/trust';
2
+ /** A lease this process holds: generation `generation` (whose token is `token`) of the lease at `base`. */
3
+ export type Lease = Readonly<{
4
+ base: string;
5
+ generation: number;
6
+ token: string;
7
+ }>;
8
+ type LeaseFailure = {
9
+ readonly kind: 'lease-failed';
10
+ readonly message: string;
11
+ };
12
+ /** The runtime directory's spawn reservation: at most one owner process is being started at a time. */
13
+ export declare function spawnLeaseBase(runtimeDirectory: string): string;
14
+ /** The generation file `lease` names (what a long-lived holder keeps fresh against temp cleaners). */
15
+ export declare function leaseFile(lease: Lease): string;
16
+ /** `<generation>:<token>`, the form a lease travels in to another process (an environment variable, an `adopt`). */
17
+ export declare function encodeLease(lease: Lease): string;
18
+ /** The lease `encodeLease` wrote, at `base`; null for anything else. */
19
+ export declare function decodeLease(base: string, encoded: string | undefined): Lease | null;
20
+ /** The lease's newest generation; 0 when it was never taken. */
21
+ export declare function leaseHead(base: string): import("@noego/trust").Err<LeaseFailure> | import("@noego/trust").Ok<number>;
22
+ /**
23
+ * Takes the lease for this process if it is free or its holder is dead. Null
24
+ * when a live process holds it (this one included: a lease is not re-entrant).
25
+ */
26
+ export declare function acquireLease(base: string): Result<Lease | null, LeaseFailure>;
27
+ /**
28
+ * Hands `lease` to process `holder`, in one step that succeeds only if the
29
+ * lease is still that generation: no reclaimer, release or other handover
30
+ * acted on it first. Null when one did.
31
+ */
32
+ export declare function handOverLease(lease: Lease, holder: number): Result<Lease | null, LeaseFailure>;
33
+ /** Frees the lease if it is still `lease`'s generation; false (and nothing changed) when it had moved on. */
34
+ export declare function releaseLease(lease: Lease): Result<boolean, LeaseFailure>;
35
+ /** The process `lease`'s generation records as its holder, alive or not; null when it records none or is gone. */
36
+ export declare function recordedHolder(lease: Lease): number | null;
37
+ /** The process holding the lease now, or null when it is free or its holder is dead. */
38
+ export declare function leaseHolder(base: string): Result<number | null, LeaseFailure>;
39
+ export {};
@@ -0,0 +1,20 @@
1
+ import { Result } from '@noego/trust';
2
+ type LegacyLockFailure = {
3
+ readonly kind: 'legacy-lock-failed';
4
+ readonly message: string;
5
+ };
6
+ /**
7
+ * Takes `lock` for `pid`, as an older build would: created if absent,
8
+ * reclaimed if its holder is dead or unrecorded. False when a live process
9
+ * other than `pid` holds it — an older build's client placing the file.
10
+ */
11
+ export declare function takeLegacyLock(lock: string, pid: number): Result<boolean, LegacyLockFailure>;
12
+ /**
13
+ * Moves `lock` from `from` (the process the claim lease was handed over by)
14
+ * to `to`, keeping the file claimed throughout. False when a live process
15
+ * other than these two holds it.
16
+ */
17
+ export declare function passLegacyLock(lock: string, from: number | null, to: number): Result<boolean, LegacyLockFailure>;
18
+ /** Removes `lock` if it names one of `pids`; a lock another process holds is left alone. */
19
+ export declare function dropLegacyLock(lock: string, pids: readonly number[]): Result<boolean, LegacyLockFailure>;
20
+ export {};
package/dist/paths.d.ts CHANGED
@@ -20,7 +20,10 @@ 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. */
23
24
  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;
24
27
  meta: string;
25
28
  }>;
26
29
  /** Windows has no Unix domain sockets; the local transport there is a named pipe. */
@@ -48,7 +51,10 @@ export declare function resolvePaths(file: string): import("@noego/trust").Err<{
48
51
  key: string;
49
52
  /** Unix domain socket path, or a `\\.\pipe\` named pipe on Windows (see `isNamedPipe`). */
50
53
  socket: string;
54
+ /** The claim lock older builds take (a pid in one file); still honoured while its process lives. */
51
55
  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;
52
58
  meta: string;
53
59
  }>>;
54
60
  /** Public, exception-based form of `resolveRuntimeDirectory`. */
@@ -105,8 +105,10 @@ 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), listen on that file's own socket, release
109
- * that file's claim lock. The reply names the socket to connect to.
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.
110
112
  */
111
113
  | {
112
114
  id: number;
@@ -114,6 +116,7 @@ export type Request = {
114
116
  file: string;
115
117
  pragmas?: readonly string[];
116
118
  idleTimeoutMs?: number;
119
+ claim?: string;
117
120
  };
118
121
  export type RunResult = Readonly<{
119
122
  changes: number;
@@ -506,6 +509,12 @@ export declare function splitFrames(buffer: string): {
506
509
  frames: string[];
507
510
  rest: string;
508
511
  };
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;
509
518
  /**
510
519
  * The frames of one socket, read chunk by chunk in work proportional to what
511
520
  * arrives, however finely it is chunked: only the new chunk is searched for
@@ -516,11 +525,26 @@ export declare function splitFrames(buffer: string): {
516
525
  * Empty lines are skipped, as `splitFrames` skips them.
517
526
  */
518
527
  export declare class FrameReader {
528
+ private readonly maxFrameLength;
519
529
  private pieces;
530
+ /** Characters held in `pieces`: the length of the unfinished frame so far. */
531
+ private held;
532
+ private overflowed;
520
533
  private decoder;
521
534
  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);
522
540
  /** Characters searched for a newline so far: each one pushed is searched once. */
523
541
  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;
524
548
  /** The frames `chunk` completes, in order; its unterminated tail waits for the next chunk. */
525
549
  push(chunk: string): string[];
526
550
  /**
@@ -532,4 +556,6 @@ export declare class FrameReader {
532
556
  pushBytes(chunk: Uint8Array): string[];
533
557
  /** Drops an unfinished frame (and a partly received character): the stream is starting over or was given up. */
534
558
  reset(): void;
559
+ /** Gives up the unfinished frame; `frames` are the ones completed before it. */
560
+ private overflow;
535
561
  }
package/dist/version.d.ts CHANGED
@@ -1,8 +1,12 @@
1
1
  import { Result } from '@noego/trust';
2
2
  /**
3
- * Hash of every `src/*.ts` file, so the two artifacts built from one tree
4
- * (Node client in dist/, Bun server in bin/) and a source run agree, while any
5
- * edit yields a new id. `source` when the tree is not there.
3
+ * Hash of every `src/*.ts` file (name, bytes), then, in a tree with
4
+ * `rust/Cargo.toml`, of the Rust owner's inputs (`/`-separated path, bytes,
5
+ * sorted): `RUST_BUILD_FILES` that exist and every file under `rust/src/`.
6
+ * So the artifacts built from one tree (Node client in dist/, the owner
7
+ * binary in bin/) and a source run agree, while any edit on either side
8
+ * yields a new id. `rust/build.rs` computes the same for the binary.
9
+ * `source` when the tree is not there.
6
10
  */
7
11
  export declare function sourceBuildId(sourceDirectory: string): Result<string, {
8
12
  kind: "source-unreadable";
@@ -10,6 +14,16 @@ export declare function sourceBuildId(sourceDirectory: string): Result<string, {
10
14
  }>;
11
15
  /** Exception-based form of `sourceBuildId` for the build script, which must stop on an unreadable tree. */
12
16
  export declare function computeSourceBuildId(sourceDirectory: string): string;
17
+ /**
18
+ * Which build id an artifact reports. `defined` (stamped into dist by the
19
+ * build) always wins. Otherwise a tree holding the Rust sources
20
+ * (`rustInTree`: a checkout) hashes itself, exactly as the build does. A
21
+ * tree without them is the published package run from `src/` by Bun, whose
22
+ * hash would leave out the Rust inputs the owner binary was built with: it
23
+ * takes the id the release stamped into its package.json (`stamped`), and
24
+ * hashes only when there is none.
25
+ */
26
+ export declare function chooseBuildId(defined: unknown, stamped: unknown, rustInTree: boolean, fromSource: () => string): string;
13
27
  /** Build identity of this artifact: the source hash it was built from. */
14
28
  export declare const BUILD_ID: string;
15
29
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noego/sqlego",
3
- "version": "0.1.6-dev.0",
3
+ "version": "0.1.6-dev.10",
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,11 @@
51
51
  "@noego/trust": "^0.5.1"
52
52
  },
53
53
  "optionalDependencies": {
54
- "@noego/sqlego-darwin-arm64": "0.1.6-dev.0",
55
- "@noego/sqlego-darwin-x64": "0.1.6-dev.0",
56
- "@noego/sqlego-linux-x64": "0.1.6-dev.0",
57
- "@noego/sqlego-linux-arm64": "0.1.6-dev.0",
58
- "@noego/sqlego-win32-x64": "0.1.6-dev.0"
59
- }
54
+ "@noego/sqlego-darwin-arm64": "0.1.6-dev.10",
55
+ "@noego/sqlego-darwin-x64": "0.1.6-dev.10",
56
+ "@noego/sqlego-linux-x64": "0.1.6-dev.10",
57
+ "@noego/sqlego-linux-arm64": "0.1.6-dev.10",
58
+ "@noego/sqlego-win32-x64": "0.1.6-dev.10"
59
+ },
60
+ "sqlegoBuild": "247f5e669b76"
60
61
  }
package/src/cli.ts CHANGED
@@ -12,7 +12,9 @@ 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 { isProcessAlive, parseServerMeta, resolveRuntimeDirectory } from './paths.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';
16
18
  import { errorMessage, fromJson, parseSqlParams, toJson, type SqlRow } from './protocol.ts';
17
19
  import { VERSION } from './version.ts';
18
20
 
@@ -118,12 +120,124 @@ function render(rows: SqlRow[], flags: Flags): string {
118
120
  return renderBox(rows);
119
121
  }
120
122
 
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
+
121
220
  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;
122
232
  const loaded = await Trust.tryAsync(
123
233
  () => import('./server.ts'),
124
234
  (cause) => ({ kind: 'failed' as const, message: `cannot load the server: ${errorMessage(cause)}` }),
125
235
  );
126
- if (!loaded.ok) return loaded;
236
+ if (!loaded.ok) {
237
+ releaseTakenOver(claim, lock);
238
+ releaseTakenOver(spawn);
239
+ return loaded;
240
+ }
127
241
  const { SqlegoServer, DEFAULT_PRAGMAS, stopAll } = loaded.value;
128
242
  const idleTimeoutMs = flags['idle-ms'] ? Number(flags['idle-ms']) : 30_000;
129
243
  const millis = (flag: string) => (typeof flags[flag] === 'string' ? Number(flags[flag]) : undefined);
@@ -137,6 +251,7 @@ async function serve(file: string, flags: Flags, pragmas: readonly string[]) {
137
251
  ? undefined
138
252
  : new loaded.value.ReaderPool({ size: readers ?? loaded.value.DEFAULT_READERS, queueLimit: readerQueue ?? loaded.value.DEFAULT_READER_QUEUE_LIMIT, log });
139
253
  // The first file of this owner process; clients add more through `adopt`.
254
+ // The server keeps the claim while it serves the file.
140
255
  const started = SqlegoServer.start({
141
256
  file,
142
257
  idleTimeoutMs,
@@ -148,7 +263,11 @@ async function serve(file: string, flags: Flags, pragmas: readonly string[]) {
148
263
  fileCheckMs: millis('file-check-ms'),
149
264
  readerPool,
150
265
  log,
266
+ claim,
151
267
  });
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);
152
271
  if (!started.ok) return started;
153
272
  const shutdown = (signal: string) => { stopAll(signal); process.exit(0); };
154
273
  return Trust.try(