@noego/sqlego 0.1.2 → 0.1.3-dev.0
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 +23 -9
- package/dist/client.d.ts +86 -12
- package/dist/index.d.ts +1 -1
- package/dist/index.js +151 -51
- package/dist/protocol.d.ts +35 -1
- package/package.json +7 -7
- package/src/cli.ts +3 -1
- package/src/client.ts +176 -45
- package/src/index.ts +1 -0
- package/src/protocol.ts +73 -1
- package/src/server.ts +258 -69
package/README.md
CHANGED
|
@@ -94,7 +94,8 @@ client: connect(socket) ──ok──▶ hello ──▶ requests
|
|
|
94
94
|
└──────────────────────────▶ connect ◀─────────┴────────────────┘
|
|
95
95
|
|
|
96
96
|
owner: per file: open db ▶ listen ▶ write <key>.json ▶ release <key>.lock ▶ serve
|
|
97
|
-
file's last client leaves ▶ idle timer (default 30 s) ▶ rm socket+meta
|
|
97
|
+
file's last client leaves ▶ idle timer (default 30 s) ▶ close db ▶ rm lock+socket+meta
|
|
98
|
+
file deleted or replaced at its path (checked every 5 s) ▶ same release, clients or not
|
|
98
99
|
last file released ▶ exit 0
|
|
99
100
|
```
|
|
100
101
|
|
|
@@ -105,10 +106,17 @@ Unix socket paths cap at 104 bytes. On Windows the socket is the named pipe
|
|
|
105
106
|
|
|
106
107
|
A client whose version differs from the owner's asks it to release the file
|
|
107
108
|
and places the file anew, so a rebuilt binary never keeps talking to an old
|
|
108
|
-
owner
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
109
|
+
owner — but only when it is the file's sole client and no transaction is
|
|
110
|
+
open (it asks `status` first). The same holds when a client sets
|
|
111
|
+
`serverPragmas` and the running owner opened the file with a different list
|
|
112
|
+
(`hello` and `status` report the owner's pragmas), or the owner speaks
|
|
113
|
+
another protocol. While other clients use the owner it is never retired: a
|
|
114
|
+
client of another build uses it as it is (`client.owner.mismatches` says
|
|
115
|
+
`version`), and one that cannot (another protocol, or pragmas it requires)
|
|
116
|
+
fails with `owner-in-use`. The owner itself refuses a `stop` with
|
|
117
|
+
`owner-busy` while other clients are connected. An owner of another build is
|
|
118
|
+
never adopted into; its other files are retired one by one as their own
|
|
119
|
+
clients arrive alone, or released when idle.
|
|
112
120
|
|
|
113
121
|
### Owner processes
|
|
114
122
|
|
|
@@ -126,8 +134,9 @@ build under the runtime directory, whichever app started it. Nothing is ever
|
|
|
126
134
|
refused for lack of a process.
|
|
127
135
|
|
|
128
136
|
Each file keeps its own socket, database connection, leased transaction and
|
|
129
|
-
idle timer. `sqlego <file> stop`
|
|
130
|
-
the
|
|
137
|
+
idle timer. `sqlego <file> stop` (refused while other clients use the file)
|
|
138
|
+
and the idle timeout release that one file; so does deleting the file or its
|
|
139
|
+
directory. The process exits when its last file is released. Spawning is serialized
|
|
131
140
|
through `spawn.lock` in the runtime directory so 40 files opened at once
|
|
132
141
|
share one process instead of starting 40.
|
|
133
142
|
|
|
@@ -253,7 +262,7 @@ sqlego <file> "DELETE …"
|
|
|
253
262
|
sqlego <file> status | stop
|
|
254
263
|
sqlego <file> watch "SELECT count(*) FROM logs" --every 2s
|
|
255
264
|
sqlego ls
|
|
256
|
-
sqlego serve <file> [--idle-ms 30000] [--tx-lease-ms 10000] [--tx-max-ms 60000] [--tx-queue-ms 30000] [--pragma "<name = value>"]...
|
|
265
|
+
sqlego serve <file> [--idle-ms 30000] [--file-check-ms 5000] [--tx-lease-ms 10000] [--tx-max-ms 60000] [--tx-queue-ms 30000] [--pragma "<name = value>"]...
|
|
257
266
|
```
|
|
258
267
|
|
|
259
268
|
## Library
|
|
@@ -287,7 +296,12 @@ await db.close();
|
|
|
287
296
|
|
|
288
297
|
A `SqlegoClientError` with code `tx-expired` means the server rolled the
|
|
289
298
|
transaction back (lease, hard cap, or disconnect); `tx-busy` means another
|
|
290
|
-
client's transaction kept the request waiting too long
|
|
299
|
+
client's transaction kept the request waiting too long; `owner-in-use` (from
|
|
300
|
+
`connect`) means the running owner cannot serve this client and other clients
|
|
301
|
+
are using it, so it was left running; `owner-busy` (from `stop`) means other
|
|
302
|
+
clients are using the file. `client.owner` (pid, `serverVersion`, protocol,
|
|
303
|
+
`mismatches`) stays readable after the connection is lost, for logging which
|
|
304
|
+
owner went.
|
|
291
305
|
|
|
292
306
|
Server location: see [Where the server binary comes from](#where-the-server-binary-comes-from);
|
|
293
307
|
pass `serverCommand` to override.
|
package/dist/client.d.ts
CHANGED
|
@@ -21,10 +21,11 @@ export type ClientOptions = Readonly<{
|
|
|
21
21
|
/**
|
|
22
22
|
* Pragmas the owner must have applied on open (`--pragma`), replacing its
|
|
23
23
|
* defaults. A spawned owner gets them; an owner already running with other
|
|
24
|
-
* pragmas is
|
|
25
|
-
* an owner from another build is
|
|
26
|
-
*
|
|
27
|
-
* one list per file, or leave this unset
|
|
24
|
+
* pragmas is retired and a fresh one spawned with these when this client
|
|
25
|
+
* is its file's only one, the way an owner from another build is. While
|
|
26
|
+
* other clients use it, `connect` fails with `owner-in-use` instead and the
|
|
27
|
+
* owner keeps serving them. Agree on one list per file, or leave this unset
|
|
28
|
+
* to accept whatever is running.
|
|
28
29
|
*/
|
|
29
30
|
serverPragmas?: readonly string[];
|
|
30
31
|
/**
|
|
@@ -44,6 +45,24 @@ export type ClientOptions = Readonly<{
|
|
|
44
45
|
requestTimeoutMs?: number;
|
|
45
46
|
}>;
|
|
46
47
|
export declare const DEFAULT_MAX_OWNERS = 4;
|
|
48
|
+
/** How an owner a client uses differs from the one it asked for. */
|
|
49
|
+
export type OwnerMismatch = 'version' | 'pragmas';
|
|
50
|
+
/**
|
|
51
|
+
* The owner process a client is connected to, as its hello reported it. It
|
|
52
|
+
* stays on the client after the connection is lost, so whoever logs the loss
|
|
53
|
+
* can name the owner that went (pid, build). `mismatches` lists how the
|
|
54
|
+
* owner differs from what this client asked for while the client uses it
|
|
55
|
+
* anyway: `version` (another build, kept because other clients use it or
|
|
56
|
+
* because `spawn` is false) and `pragmas` (only with `spawn: false`). Empty
|
|
57
|
+
* when it is the owner this client wants.
|
|
58
|
+
*/
|
|
59
|
+
export type OwnerInfo = Readonly<{
|
|
60
|
+
pid: number;
|
|
61
|
+
serverVersion: string;
|
|
62
|
+
protocol: number;
|
|
63
|
+
file: string;
|
|
64
|
+
mismatches: readonly OwnerMismatch[];
|
|
65
|
+
}>;
|
|
47
66
|
export type BeginOptions = Readonly<{
|
|
48
67
|
/** `immediate` takes the write lock at `begin`; `deferred` (default) on the first write. */
|
|
49
68
|
mode?: TransactionMode;
|
|
@@ -60,10 +79,13 @@ export declare class SqlegoClientError extends Error {
|
|
|
60
79
|
export declare class SqlegoClient {
|
|
61
80
|
readonly paths: FilePaths;
|
|
62
81
|
private socket;
|
|
63
|
-
|
|
82
|
+
/** Reply frames from `socket`; the socket decodes UTF-8 itself (`setEncoding`), split characters included. */
|
|
83
|
+
private readonly frames;
|
|
64
84
|
private nextId;
|
|
65
85
|
private readonly pending;
|
|
66
86
|
private hello;
|
|
87
|
+
/** How the owner in `hello` differs from the one this client asked for (see `OwnerInfo`). */
|
|
88
|
+
private mismatches;
|
|
67
89
|
/** Why the server this client spawned did not come up, if it did not. */
|
|
68
90
|
private spawnFailure;
|
|
69
91
|
/** True while this client is the one spawning an owner process (see `placeFile`). */
|
|
@@ -72,6 +94,12 @@ export declare class SqlegoClient {
|
|
|
72
94
|
private constructor();
|
|
73
95
|
static connect(file: string, options?: ClientOptions): Promise<SqlegoClient>;
|
|
74
96
|
get server(): HelloResult;
|
|
97
|
+
/**
|
|
98
|
+
* The owner this client talks to (see `OwnerInfo`); null before `connect`
|
|
99
|
+
* succeeded. Unlike `server` it never throws, and it is kept after the
|
|
100
|
+
* connection is lost, so the loss can be logged with the owner's pid and build.
|
|
101
|
+
*/
|
|
102
|
+
get owner(): OwnerInfo | null;
|
|
75
103
|
/** Opt this socket into committed-snapshot plain reads and queued plain writes. */
|
|
76
104
|
enableDetachedPlain(): Promise<boolean>;
|
|
77
105
|
query<Row extends SqlRow = SqlRow>(sql: string, params?: SqlParams): Promise<Row[]>;
|
|
@@ -113,17 +141,62 @@ export declare class SqlegoClient {
|
|
|
113
141
|
/** @internal */
|
|
114
142
|
transactionEnd(txId: number, how: 'commit' | 'rollback'): Promise<void>;
|
|
115
143
|
status(): Promise<StatusResult>;
|
|
116
|
-
/**
|
|
144
|
+
/**
|
|
145
|
+
* Asks the owner to release this file; the connection closes as a
|
|
146
|
+
* consequence. Refused with `owner-busy` while other clients are connected
|
|
147
|
+
* to the file (or another client's transaction is open): nothing is released.
|
|
148
|
+
*/
|
|
117
149
|
stop(): Promise<void>;
|
|
118
150
|
close(): Promise<void>;
|
|
151
|
+
/** `stop`, closing this client once it is granted; a refusal (`owner-busy`) or any other error reply is returned as is. */
|
|
119
152
|
private stopServer;
|
|
153
|
+
/**
|
|
154
|
+
* Connects and settles which owner this client uses. An owner other than
|
|
155
|
+
* the one it wants (another build or protocol, or other pragmas than
|
|
156
|
+
* `serverPragmas`) is retired — asked to release the file, which is then
|
|
157
|
+
* placed anew — only when this client is the file's sole connection and no
|
|
158
|
+
* transaction is open, as the owner's `status` reports. Otherwise the owner
|
|
159
|
+
* keeps serving the clients that use it (2026-10-18: a CLI from another
|
|
160
|
+
* build retired the running app's owner, a 7-minute outage): this client
|
|
161
|
+
* uses it as it is when only the build differs, noting that in `owner`, and
|
|
162
|
+
* fails with `owner-in-use` when it cannot (another protocol, or pragmas it
|
|
163
|
+
* requires); it never sends `stop` then. With `spawn: false` nothing is
|
|
164
|
+
* replaced. A connect that fails closes its connection, so a process whose
|
|
165
|
+
* connects keep failing never holds an owner busy.
|
|
166
|
+
*/
|
|
120
167
|
private open;
|
|
121
168
|
/**
|
|
122
|
-
*
|
|
123
|
-
*
|
|
169
|
+
* Connects (placing the file when nothing serves it) and says hello. An
|
|
170
|
+
* owner that drops the connection before answering was releasing the file
|
|
171
|
+
* at that moment: wait until it is gone and start again, until the
|
|
172
|
+
* deadline. Another protocol is an answer, not a failure: `open` decides.
|
|
173
|
+
*/
|
|
174
|
+
private handshake;
|
|
175
|
+
/**
|
|
176
|
+
* After the old owner granted `stop`: waits until it no longer answers (it
|
|
177
|
+
* closes the file before its socket stops answering), places the file anew
|
|
178
|
+
* and settles on whichever owner then serves it. Another client may have
|
|
179
|
+
* placed it first, with an owner that differs again: that one is used as it
|
|
180
|
+
* is, not retired in turn.
|
|
181
|
+
*/
|
|
182
|
+
private replace;
|
|
183
|
+
/** The owner that answered `hello` is the one this client uses; `mismatches` says how it differs from the one asked for. */
|
|
184
|
+
private settle;
|
|
185
|
+
/** A failed connect closes its connection, so it never counts as a client of the owner it could not use. */
|
|
186
|
+
private abandon;
|
|
187
|
+
/**
|
|
188
|
+
* Whether this client is its file's sole connection with no transaction
|
|
189
|
+
* open, as the owner's `status` reports (owners of every build answer it,
|
|
190
|
+
* before a hello too): the one case in which it may retire the owner. A
|
|
191
|
+
* status that cannot be read never is.
|
|
192
|
+
*/
|
|
193
|
+
private ownerUse;
|
|
194
|
+
/**
|
|
195
|
+
* How the owner that answered `hello` differs from the one this client
|
|
196
|
+
* wants: built from other source than this client, or opened with other
|
|
124
197
|
* pragmas than this client requires (`serverPragmas` unset accepts any).
|
|
125
198
|
*/
|
|
126
|
-
private
|
|
199
|
+
private mismatchesOf;
|
|
127
200
|
private connectOrSpawn;
|
|
128
201
|
/** The file's own claim lock: whoever holds it places the file with an owner. */
|
|
129
202
|
private claimLock;
|
|
@@ -142,12 +215,13 @@ export declare class SqlegoClient {
|
|
|
142
215
|
/**
|
|
143
216
|
* Owner processes of this build under this runtime directory, fewest files
|
|
144
217
|
* first, from the meta files their files wrote. An owner of another build
|
|
145
|
-
* is never adopted into (its files are retired one by one
|
|
146
|
-
*
|
|
218
|
+
* is never adopted into (its files are retired one by one by clients that
|
|
219
|
+
* find themselves alone on them, or released when idle); a dead one's metas
|
|
220
|
+
* are ignored.
|
|
147
221
|
*/
|
|
148
222
|
private currentOwners;
|
|
149
223
|
private releaseSpawnLock;
|
|
150
|
-
/** Waits until nothing answers on the file's socket (the old owner released it), or the deadline. */
|
|
224
|
+
/** Waits until nothing answers on the file's socket (the old owner released it, its database closed first), or the deadline. */
|
|
151
225
|
private waitForRelease;
|
|
152
226
|
private spawnServer;
|
|
153
227
|
/** The spawn never started: record why, and release the lock so another claimer can try. */
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { DEFAULT_MAX_OWNERS, SqlegoClient, SqlegoClientError, SqlegoTransaction, defaultServerCommand, type BeginOptions, type ClientOptions, } from './client.ts';
|
|
1
|
+
export { DEFAULT_MAX_OWNERS, SqlegoClient, SqlegoClientError, SqlegoTransaction, defaultServerCommand, type BeginOptions, type ClientOptions, type OwnerInfo, type OwnerMismatch, } from './client.ts';
|
|
2
2
|
export { SUPPORTED_PLATFORMS, binaryFileName, localBinaryName, locateServerBinary, platformPackageName, unpackedAsarPath, type BinaryLookup, } from './binary.ts';
|
|
3
3
|
export { USES_NAMED_PIPES, isNamedPipe, pathsFor, runtimeDirectory, canonicalFile, type FilePaths, type ServerMeta } from './paths.ts';
|
|
4
4
|
export { PROTOCOL_VERSION, type SqlParams, type SqlRow, type SqlValue, type Statement, type RunResult, type QueryResult, type BatchResult, type StatementResult, type ExecResult, type BeginResult, type StatusResult, type HelloResult, type TransactionMode, type TransactionStatus, } from './protocol.ts';
|
package/dist/index.js
CHANGED
|
@@ -262,7 +262,8 @@ var ERROR_CODES = [
|
|
|
262
262
|
"tx-expired",
|
|
263
263
|
"tx-invalid",
|
|
264
264
|
"tx-busy",
|
|
265
|
-
"adopt-failed"
|
|
265
|
+
"adopt-failed",
|
|
266
|
+
"owner-busy"
|
|
266
267
|
];
|
|
267
268
|
function parseErrorCode(input) {
|
|
268
269
|
const code = ERROR_CODES.find((known) => known === input);
|
|
@@ -512,11 +513,51 @@ function normalizePragma(pragma) {
|
|
|
512
513
|
function samePragmas(a, b) {
|
|
513
514
|
return a.length === b.length && a.every((pragma, index) => normalizePragma(pragma) === normalizePragma(b[index]));
|
|
514
515
|
}
|
|
515
|
-
|
|
516
|
-
|
|
516
|
+
class FrameReader {
|
|
517
|
+
pieces = [];
|
|
518
|
+
decoder = null;
|
|
519
|
+
searched = 0;
|
|
520
|
+
get scannedCharacters() {
|
|
521
|
+
return this.searched;
|
|
522
|
+
}
|
|
523
|
+
push(chunk) {
|
|
524
|
+
let newline = chunk.indexOf(`
|
|
517
525
|
`);
|
|
518
|
-
|
|
519
|
-
|
|
526
|
+
if (newline < 0) {
|
|
527
|
+
this.searched += chunk.length;
|
|
528
|
+
if (chunk.length > 0)
|
|
529
|
+
this.pieces.push(chunk);
|
|
530
|
+
return [];
|
|
531
|
+
}
|
|
532
|
+
const frames = [];
|
|
533
|
+
let start = 0;
|
|
534
|
+
while (newline >= 0) {
|
|
535
|
+
this.searched += newline + 1 - start;
|
|
536
|
+
let frame = chunk.slice(start, newline);
|
|
537
|
+
if (this.pieces.length > 0) {
|
|
538
|
+
this.pieces.push(frame);
|
|
539
|
+
frame = this.pieces.join("");
|
|
540
|
+
this.pieces = [];
|
|
541
|
+
}
|
|
542
|
+
if (frame.length > 0)
|
|
543
|
+
frames.push(frame);
|
|
544
|
+
start = newline + 1;
|
|
545
|
+
newline = chunk.indexOf(`
|
|
546
|
+
`, start);
|
|
547
|
+
}
|
|
548
|
+
this.searched += chunk.length - start;
|
|
549
|
+
if (start < chunk.length)
|
|
550
|
+
this.pieces.push(chunk.slice(start));
|
|
551
|
+
return frames;
|
|
552
|
+
}
|
|
553
|
+
pushBytes(chunk) {
|
|
554
|
+
this.decoder ??= new TextDecoder("utf-8", { ignoreBOM: true });
|
|
555
|
+
return this.push(this.decoder.decode(chunk, { stream: true }));
|
|
556
|
+
}
|
|
557
|
+
reset() {
|
|
558
|
+
this.pieces = [];
|
|
559
|
+
this.decoder = null;
|
|
560
|
+
}
|
|
520
561
|
}
|
|
521
562
|
function replaceBigInt(_key, value) {
|
|
522
563
|
return typeof value === "bigint" ? Number(value) : value;
|
|
@@ -638,7 +679,7 @@ import { fileURLToPath } from "node:url";
|
|
|
638
679
|
// package.json
|
|
639
680
|
var package_default = {
|
|
640
681
|
name: "@noego/sqlego",
|
|
641
|
-
version: "0.1.
|
|
682
|
+
version: "0.1.3-dev.0",
|
|
642
683
|
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.",
|
|
643
684
|
type: "module",
|
|
644
685
|
license: "ISC",
|
|
@@ -686,14 +727,14 @@ var package_default = {
|
|
|
686
727
|
typescript: "^5.6.0"
|
|
687
728
|
},
|
|
688
729
|
dependencies: {
|
|
689
|
-
"@noego/trust": "0.5.0
|
|
730
|
+
"@noego/trust": "^0.5.0"
|
|
690
731
|
},
|
|
691
732
|
optionalDependencies: {
|
|
692
|
-
"@noego/sqlego-darwin-arm64": "0.1.
|
|
693
|
-
"@noego/sqlego-darwin-x64": "0.1.
|
|
694
|
-
"@noego/sqlego-linux-x64": "0.1.
|
|
695
|
-
"@noego/sqlego-linux-arm64": "0.1.
|
|
696
|
-
"@noego/sqlego-win32-x64": "0.1.
|
|
733
|
+
"@noego/sqlego-darwin-arm64": "0.1.3-dev.0",
|
|
734
|
+
"@noego/sqlego-darwin-x64": "0.1.3-dev.0",
|
|
735
|
+
"@noego/sqlego-linux-x64": "0.1.3-dev.0",
|
|
736
|
+
"@noego/sqlego-linux-arm64": "0.1.3-dev.0",
|
|
737
|
+
"@noego/sqlego-win32-x64": "0.1.3-dev.0"
|
|
697
738
|
}
|
|
698
739
|
};
|
|
699
740
|
|
|
@@ -711,8 +752,8 @@ function sourceBuildId(sourceDirectory) {
|
|
|
711
752
|
}, (cause) => ({ kind: "source-unreadable", message: `cannot hash sources in ${sourceDirectory}: ${errorMessage(cause)}` }));
|
|
712
753
|
}
|
|
713
754
|
function resolveBuildId() {
|
|
714
|
-
if ("
|
|
715
|
-
return "
|
|
755
|
+
if ("3f3144144273".length > 0)
|
|
756
|
+
return "3f3144144273";
|
|
716
757
|
const directory = Trust.try(() => path3.dirname(fileURLToPath(import.meta.url)), (cause) => ({ kind: "module-path", message: errorMessage(cause) }));
|
|
717
758
|
if (!directory.ok)
|
|
718
759
|
return decideUnknownBuild(directory.error.kind);
|
|
@@ -764,10 +805,11 @@ function callerStatement(result) {
|
|
|
764
805
|
class SqlegoClient {
|
|
765
806
|
paths;
|
|
766
807
|
socket = null;
|
|
767
|
-
|
|
808
|
+
frames = new FrameReader;
|
|
768
809
|
nextId = 1;
|
|
769
810
|
pending = new Map;
|
|
770
811
|
hello = null;
|
|
812
|
+
mismatches = [];
|
|
771
813
|
spawnFailure = null;
|
|
772
814
|
holdsSpawnLock = false;
|
|
773
815
|
options;
|
|
@@ -789,6 +831,12 @@ class SqlegoClient {
|
|
|
789
831
|
return this.hello;
|
|
790
832
|
return unwrap(Result.err({ kind: "not-connected", message: "client is not connected" }));
|
|
791
833
|
}
|
|
834
|
+
get owner() {
|
|
835
|
+
const hello = this.hello;
|
|
836
|
+
if (!hello)
|
|
837
|
+
return null;
|
|
838
|
+
return { pid: hello.pid, serverVersion: hello.serverVersion, protocol: hello.protocol, file: hello.file, mismatches: this.mismatches };
|
|
839
|
+
}
|
|
792
840
|
async enableDetachedPlain() {
|
|
793
841
|
if (!this.server.capabilities.includes("detached-plain"))
|
|
794
842
|
return false;
|
|
@@ -880,40 +928,96 @@ class SqlegoClient {
|
|
|
880
928
|
}
|
|
881
929
|
async open() {
|
|
882
930
|
const deadline = Date.now() + (this.options.connectTimeoutMs ?? 1e4);
|
|
883
|
-
const
|
|
884
|
-
if (!
|
|
885
|
-
return
|
|
886
|
-
const
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
if (
|
|
891
|
-
return
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
931
|
+
const greeted = await this.handshake(deadline);
|
|
932
|
+
if (!greeted.ok)
|
|
933
|
+
return this.abandon(greeted);
|
|
934
|
+
const greeting = greeted.value;
|
|
935
|
+
const mismatches = greeting.kind === "hello" ? this.mismatchesOf(greeting.hello) : [];
|
|
936
|
+
if (greeting.kind === "hello" && (mismatches.length === 0 || this.options.spawn === false))
|
|
937
|
+
return this.settle(greeting.hello, mismatches);
|
|
938
|
+
if (greeting.kind === "other-protocol" && this.options.spawn === false) {
|
|
939
|
+
return this.abandon(Result.err({ kind: "protocol-mismatch", message: greeting.message }));
|
|
940
|
+
}
|
|
941
|
+
const use = await this.ownerUse();
|
|
942
|
+
if (use.sole) {
|
|
943
|
+
const stopped = await this.stopServer();
|
|
944
|
+
if (stopped.ok)
|
|
945
|
+
return this.replace(deadline);
|
|
946
|
+
if (stopped.error.kind !== "owner-busy")
|
|
947
|
+
return this.abandon(stopped);
|
|
948
|
+
}
|
|
949
|
+
if (greeting.kind === "hello" && !mismatches.includes("pragmas"))
|
|
950
|
+
return this.settle(greeting.hello, mismatches);
|
|
951
|
+
const what = greeting.kind === "hello" ? `its owner (pid ${greeting.hello.pid}) opened it with other pragmas than serverPragmas requires` : `its owner speaks another protocol (${greeting.message})`;
|
|
952
|
+
const why = use.sole ? "another client connected meanwhile" : use.why;
|
|
953
|
+
return this.abandon(Result.err({ kind: "owner-in-use", message: `${this.paths.file}: ${what}, and ${why}; it was left running` }));
|
|
954
|
+
}
|
|
955
|
+
async handshake(deadline) {
|
|
956
|
+
for (;; ) {
|
|
957
|
+
const socket = await this.connectOrSpawn(deadline);
|
|
958
|
+
if (!socket.ok)
|
|
959
|
+
return socket;
|
|
960
|
+
const attached = this.attach(socket.value);
|
|
961
|
+
if (!attached.ok)
|
|
962
|
+
return attached;
|
|
963
|
+
const hello = await this.call({ op: "hello", clientVersion: VERSION, protocol: PROTOCOL_VERSION }, parseHelloResult);
|
|
964
|
+
if (hello.ok)
|
|
965
|
+
return Result.ok({ kind: "hello", hello: hello.value });
|
|
966
|
+
switch (hello.error.kind) {
|
|
967
|
+
case "protocol-mismatch":
|
|
968
|
+
return Result.ok({ kind: "other-protocol", message: hello.error.message });
|
|
969
|
+
case "closed":
|
|
970
|
+
case "not-connected":
|
|
971
|
+
case "socket":
|
|
972
|
+
case "shutting-down":
|
|
973
|
+
if (Date.now() >= deadline)
|
|
974
|
+
return hello;
|
|
975
|
+
await this.close();
|
|
976
|
+
await this.waitForRelease(deadline);
|
|
977
|
+
break;
|
|
978
|
+
default:
|
|
979
|
+
return hello;
|
|
980
|
+
}
|
|
895
981
|
}
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
return stopped;
|
|
982
|
+
}
|
|
983
|
+
async replace(deadline) {
|
|
899
984
|
await this.waitForRelease(deadline);
|
|
900
|
-
const fresh = await this.
|
|
985
|
+
const fresh = await this.handshake(deadline);
|
|
901
986
|
if (!fresh.ok)
|
|
902
|
-
return fresh;
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
this.hello =
|
|
987
|
+
return this.abandon(fresh);
|
|
988
|
+
if (fresh.value.kind === "other-protocol") {
|
|
989
|
+
return this.abandon(Result.err({ kind: "protocol-mismatch", message: fresh.value.message }));
|
|
990
|
+
}
|
|
991
|
+
return this.settle(fresh.value.hello, this.mismatchesOf(fresh.value.hello));
|
|
992
|
+
}
|
|
993
|
+
settle(hello, mismatches) {
|
|
994
|
+
this.hello = hello;
|
|
995
|
+
this.mismatches = mismatches;
|
|
910
996
|
return Result.ok(undefined);
|
|
911
997
|
}
|
|
912
|
-
|
|
998
|
+
async abandon(failed) {
|
|
999
|
+
await this.close();
|
|
1000
|
+
return failed;
|
|
1001
|
+
}
|
|
1002
|
+
async ownerUse() {
|
|
1003
|
+
const status = await this.call({ op: "status" }, parseStatusResult);
|
|
1004
|
+
if (!status.ok)
|
|
1005
|
+
return { sole: false, why: `its status could not be read (${status.error.kind}: ${status.error.message})` };
|
|
1006
|
+
const others = status.value.clients - 1;
|
|
1007
|
+
if (others > 0)
|
|
1008
|
+
return { sole: false, why: `${others} other client${others === 1 ? " uses" : "s use"} it` };
|
|
1009
|
+
if (status.value.transaction !== null)
|
|
1010
|
+
return { sole: false, why: `transaction ${status.value.transaction.txId} is open` };
|
|
1011
|
+
return { sole: true, why: "" };
|
|
1012
|
+
}
|
|
1013
|
+
mismatchesOf(hello) {
|
|
1014
|
+
const mismatches = [];
|
|
913
1015
|
if (hello.serverVersion !== VERSION)
|
|
914
|
-
|
|
1016
|
+
mismatches.push("version");
|
|
915
1017
|
const required = this.options.serverPragmas;
|
|
916
|
-
|
|
1018
|
+
if (required !== undefined && !samePragmas(required, hello.pragmas))
|
|
1019
|
+
mismatches.push("pragmas");
|
|
1020
|
+
return mismatches;
|
|
917
1021
|
}
|
|
918
1022
|
async connectOrSpawn(deadline) {
|
|
919
1023
|
const first = await tryConnect(this.paths.socket);
|
|
@@ -1080,7 +1184,7 @@ class SqlegoClient {
|
|
|
1080
1184
|
}
|
|
1081
1185
|
attach(socket) {
|
|
1082
1186
|
this.socket = socket;
|
|
1083
|
-
this.
|
|
1187
|
+
this.frames.reset();
|
|
1084
1188
|
return Trust.try(() => {
|
|
1085
1189
|
socket.setEncoding("utf8");
|
|
1086
1190
|
socket.on("data", (chunk) => this.onData(chunk));
|
|
@@ -1095,14 +1199,12 @@ class SqlegoClient {
|
|
|
1095
1199
|
this.settleAll({ kind: "closed", message: "connection closed" });
|
|
1096
1200
|
}
|
|
1097
1201
|
onData(chunk) {
|
|
1098
|
-
const
|
|
1099
|
-
this.buffer = rest;
|
|
1100
|
-
for (const frame of frames) {
|
|
1202
|
+
for (const frame of this.frames.push(chunk)) {
|
|
1101
1203
|
const json = fromJson(frame);
|
|
1102
1204
|
const parsed = json.ok ? parseResponse(json.value) : json;
|
|
1103
1205
|
if (!parsed.ok) {
|
|
1104
1206
|
if (parsed.error.kind === "invalid") {
|
|
1105
|
-
this.
|
|
1207
|
+
this.frames.reset();
|
|
1106
1208
|
this.settleAll({ kind: "protocol", message: `malformed frame from server: ${parsed.error.message}` });
|
|
1107
1209
|
this.socket?.destroy();
|
|
1108
1210
|
}
|
|
@@ -1296,7 +1398,7 @@ function oneShot(socketPath, body, parse, timeoutMs) {
|
|
|
1296
1398
|
resolve(probeFailed(frame.error.message));
|
|
1297
1399
|
return;
|
|
1298
1400
|
}
|
|
1299
|
-
|
|
1401
|
+
const frames = new FrameReader;
|
|
1300
1402
|
let settled = false;
|
|
1301
1403
|
const started = Trust.try(() => {
|
|
1302
1404
|
const socket = new net.Socket;
|
|
@@ -1313,9 +1415,7 @@ function oneShot(socketPath, body, parse, timeoutMs) {
|
|
|
1313
1415
|
socket.once("error", (error) => finish(null, error.message));
|
|
1314
1416
|
socket.once("close", () => finish(null, "connection closed before a reply"));
|
|
1315
1417
|
socket.on("data", (chunk) => {
|
|
1316
|
-
const
|
|
1317
|
-
buffer = rest;
|
|
1318
|
-
const line = frames[0];
|
|
1418
|
+
const line = frames.push(chunk)[0];
|
|
1319
1419
|
if (line === undefined)
|
|
1320
1420
|
return;
|
|
1321
1421
|
const reply = parseOneShotReply(line, parse);
|
package/dist/protocol.d.ts
CHANGED
|
@@ -217,7 +217,14 @@ export type ErrorCode = 'sqlite' | 'bad-request' | 'protocol-mismatch' | 'shutti
|
|
|
217
217
|
/** Another client's transaction kept the request waiting past the server's queue limit. */
|
|
218
218
|
| 'tx-busy'
|
|
219
219
|
/** The owner could not take on the file an `adopt` named (cannot open it, cannot listen for it). */
|
|
220
|
-
| 'adopt-failed'
|
|
220
|
+
| 'adopt-failed'
|
|
221
|
+
/**
|
|
222
|
+
* A `stop` refused because other clients are using the file (or another
|
|
223
|
+
* client's transaction is open); nothing was released. A client of a build
|
|
224
|
+
* from before this code does not know it: its parser rejects the frame, so
|
|
225
|
+
* its request fails as `protocol` and its own connection closes.
|
|
226
|
+
*/
|
|
227
|
+
| 'owner-busy';
|
|
221
228
|
export type Response = {
|
|
222
229
|
id: number;
|
|
223
230
|
ok: true;
|
|
@@ -463,3 +470,30 @@ export declare function splitFrames(buffer: string): {
|
|
|
463
470
|
frames: string[];
|
|
464
471
|
rest: string;
|
|
465
472
|
};
|
|
473
|
+
/**
|
|
474
|
+
* The frames of one socket, read chunk by chunk in work proportional to what
|
|
475
|
+
* arrives, however finely it is chunked: only the new chunk is searched for
|
|
476
|
+
* newlines, and the pieces of an unfinished frame are kept apart and joined
|
|
477
|
+
* once, by the chunk that ends it. Splitting everything received so far on
|
|
478
|
+
* every chunk (`splitFrames(buffer + chunk)`) cost O(K²) for a frame that
|
|
479
|
+
* arrived in K chunks: 786 ms for a 4 MB reply in ~525 chunks (sqlego#7).
|
|
480
|
+
* Empty lines are skipped, as `splitFrames` skips them.
|
|
481
|
+
*/
|
|
482
|
+
export declare class FrameReader {
|
|
483
|
+
private pieces;
|
|
484
|
+
private decoder;
|
|
485
|
+
private searched;
|
|
486
|
+
/** Characters searched for a newline so far: each one pushed is searched once. */
|
|
487
|
+
get scannedCharacters(): number;
|
|
488
|
+
/** The frames `chunk` completes, in order; its unterminated tail waits for the next chunk. */
|
|
489
|
+
push(chunk: string): string[];
|
|
490
|
+
/**
|
|
491
|
+
* `push` for raw bytes, as the server's sockets deliver them. UTF-8 is
|
|
492
|
+
* decoded as one stream, so a character whose bytes straddle two chunks
|
|
493
|
+
* arrives whole; decoding each chunk alone turned it into U+FFFD. A BOM is
|
|
494
|
+
* kept, as `Buffer.toString('utf8')` keeps it.
|
|
495
|
+
*/
|
|
496
|
+
pushBytes(chunk: Uint8Array): string[];
|
|
497
|
+
/** Drops an unfinished frame (and a partly received character): the stream is starting over or was given up. */
|
|
498
|
+
reset(): void;
|
|
499
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@noego/sqlego",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3-dev.0",
|
|
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",
|
|
@@ -48,13 +48,13 @@
|
|
|
48
48
|
"typescript": "^5.6.0"
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
|
-
"@noego/trust": "0.5.0
|
|
51
|
+
"@noego/trust": "^0.5.0"
|
|
52
52
|
},
|
|
53
53
|
"optionalDependencies": {
|
|
54
|
-
"@noego/sqlego-darwin-arm64": "0.1.
|
|
55
|
-
"@noego/sqlego-darwin-x64": "0.1.
|
|
56
|
-
"@noego/sqlego-linux-x64": "0.1.
|
|
57
|
-
"@noego/sqlego-linux-arm64": "0.1.
|
|
58
|
-
"@noego/sqlego-win32-x64": "0.1.
|
|
54
|
+
"@noego/sqlego-darwin-arm64": "0.1.3-dev.0",
|
|
55
|
+
"@noego/sqlego-darwin-x64": "0.1.3-dev.0",
|
|
56
|
+
"@noego/sqlego-linux-x64": "0.1.3-dev.0",
|
|
57
|
+
"@noego/sqlego-linux-arm64": "0.1.3-dev.0",
|
|
58
|
+
"@noego/sqlego-win32-x64": "0.1.3-dev.0"
|
|
59
59
|
}
|
|
60
60
|
}
|
package/src/cli.ts
CHANGED
|
@@ -63,7 +63,7 @@ function usage(): Outcome {
|
|
|
63
63
|
sqlego <file> status | stop
|
|
64
64
|
sqlego <file> watch "<sql>" [--every 1s]
|
|
65
65
|
sqlego ls
|
|
66
|
-
sqlego serve <file> [--idle-ms 30000] [--tx-lease-ms 10000] [--tx-max-ms 60000] [--tx-queue-ms 30000] [--pragma "<name = value>"]...
|
|
66
|
+
sqlego serve <file> [--idle-ms 30000] [--file-check-ms 5000] [--tx-lease-ms 10000] [--tx-max-ms 60000] [--tx-queue-ms 30000] [--pragma "<name = value>"]...
|
|
67
67
|
`);
|
|
68
68
|
return exit(2);
|
|
69
69
|
}
|
|
@@ -135,6 +135,8 @@ async function serve(file: string, flags: Flags, pragmas: readonly string[]) {
|
|
|
135
135
|
txLeaseMs: millis('tx-lease-ms'),
|
|
136
136
|
txMaxDurationMs: millis('tx-max-ms'),
|
|
137
137
|
txQueueTimeoutMs: millis('tx-queue-ms'),
|
|
138
|
+
// Every file this process adopts later checks its path at the same pace.
|
|
139
|
+
fileCheckMs: millis('file-check-ms'),
|
|
138
140
|
log: flags.verbose ? (message, fields) => err(`[sqlego] ${message} ${displayJson(fields ?? {})}\n`) : undefined,
|
|
139
141
|
});
|
|
140
142
|
if (!started.ok) return started;
|