@mostra/runtime 0.0.0-stage → 0.1.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/LICENSE +202 -0
- package/README.md +39 -2
- package/dist/bin.d.ts +1 -0
- package/dist/bin.js +236 -0
- package/dist/bin.js.map +1 -0
- package/dist/builder/child/main.d.ts +1 -0
- package/dist/builder/child/main.js +1408 -0
- package/dist/builder/child/main.js.map +1 -0
- package/dist/child-xrHmytks.js +49 -0
- package/dist/child-xrHmytks.js.map +1 -0
- package/dist/deps/child/install.d.ts +1 -0
- package/dist/deps/child/install.js +33 -0
- package/dist/deps/child/install.js.map +1 -0
- package/dist/index.d.ts +221 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/instance-D7_UVdoN.js +15752 -0
- package/dist/instance-D7_UVdoN.js.map +1 -0
- package/dist/types-NjNy7gXX.js +57 -0
- package/dist/types-NjNy7gXX.js.map +1 -0
- package/package.json +87 -3
- package/src/actions/index.ts +622 -0
- package/src/addressing/index.ts +281 -0
- package/src/bin.ts +240 -0
- package/src/builder/child/dev.ts +383 -0
- package/src/builder/child/fields.ts +363 -0
- package/src/builder/child/main.ts +47 -0
- package/src/builder/child/plugins.ts +195 -0
- package/src/builder/child/scan.ts +459 -0
- package/src/builder/child/spa.ts +348 -0
- package/src/builder/coverage.ts +72 -0
- package/src/builder/index.ts +406 -0
- package/src/builder/types.ts +180 -0
- package/src/deps/child/install.ts +30 -0
- package/src/deps/index.ts +918 -0
- package/src/deps/installer.ts +321 -0
- package/src/deps/lock.ts +82 -0
- package/src/deps/scan.ts +266 -0
- package/src/deps/specifier.ts +64 -0
- package/src/deps/warm.ts +57 -0
- package/src/dev/index.ts +518 -0
- package/src/faults.ts +65 -0
- package/src/gate.ts +55 -0
- package/src/gateway/actions.ts +268 -0
- package/src/gateway/browser.ts +650 -0
- package/src/gateway/capabilities.ts +739 -0
- package/src/gateway/controls.ts +91 -0
- package/src/gateway/dev.ts +119 -0
- package/src/gateway/http.ts +229 -0
- package/src/gateway/index.ts +1209 -0
- package/src/gateway/integrity.ts +117 -0
- package/src/gateway/listener.ts +217 -0
- package/src/gateway/routes.ts +197 -0
- package/src/gateway/serve.ts +138 -0
- package/src/gc/index.ts +451 -0
- package/src/home/acquire.ts +276 -0
- package/src/home/index.ts +16 -0
- package/src/home/paths.ts +192 -0
- package/src/home/platform.ts +34 -0
- package/src/home/record.ts +76 -0
- package/src/home/settings.ts +113 -0
- package/src/index.ts +30 -0
- package/src/instance/index.ts +942 -0
- package/src/interaction/ephemeral.ts +300 -0
- package/src/interaction/events.ts +355 -0
- package/src/interaction/fields.ts +392 -0
- package/src/interaction/index.ts +1009 -0
- package/src/interaction/outbox.ts +493 -0
- package/src/interaction/policy.ts +26 -0
- package/src/interaction/results.ts +341 -0
- package/src/interaction/runs.ts +313 -0
- package/src/interaction/signals.ts +120 -0
- package/src/interaction/submissions.ts +585 -0
- package/src/interaction/subscriptions.ts +258 -0
- package/src/interaction/viewers.ts +173 -0
- package/src/interaction/wait.ts +201 -0
- package/src/ledger/index.ts +442 -0
- package/src/ledger/migrations.ts +583 -0
- package/src/ledger/requests.ts +105 -0
- package/src/ledger/types.ts +28 -0
- package/src/live/index.ts +573 -0
- package/src/log.ts +316 -0
- package/src/processes/child.ts +67 -0
- package/src/processes/environment.ts +64 -0
- package/src/processes/identity.ts +191 -0
- package/src/processes/index.ts +19 -0
- package/src/processes/manager.ts +543 -0
- package/src/protocol-server/client.ts +94 -0
- package/src/protocol-server/index.ts +91 -0
- package/src/protocol-server/server.ts +509 -0
- package/src/protocol-server/streams.ts +81 -0
- package/src/publish/checks.ts +92 -0
- package/src/publish/digest.ts +87 -0
- package/src/publish/index.ts +23 -0
- package/src/publish/manifest.ts +409 -0
- package/src/publish/methods.ts +96 -0
- package/src/publish/publisher.ts +913 -0
- package/src/publish/source.ts +272 -0
- package/src/publish/tar.ts +110 -0
- package/src/registry/index.ts +481 -0
- package/src/registry/store.ts +136 -0
- package/src/secrets/index.ts +223 -0
- package/src/service/idle.ts +64 -0
- package/src/service/index.ts +3 -0
- package/src/service/unit.ts +250 -0
- package/src/verify/fields.ts +125 -0
- package/src/verify/index.ts +913 -0
- package/src/verify/regression.ts +157 -0
- package/src/verify/runner.ts +230 -0
- package/src/verify/sandbox.ts +407 -0
- package/src/verify/typecheck.ts +371 -0
- package/src/workers/index.ts +17 -0
- package/src/workers/launcher.ts +260 -0
- package/src/workers/pool.ts +708 -0
|
@@ -0,0 +1,442 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The ledger (D58, D71, D81; DATA_MODEL §3, §6): the home's one SQLite database, in WAL mode with
|
|
3
|
+
* `synchronous=FULL`, opened with an exclusive lock that decides who owns the home. The
|
|
4
|
+
* supervisor is its only reader and writer; every other module reaches it through
|
|
5
|
+
* {@link Ledger.write} and {@link Ledger.read}, and nothing else in the process opens the file
|
|
6
|
+
* (POSIX drops a process's locks on a file when any descriptor for it closes).
|
|
7
|
+
*
|
|
8
|
+
* ```ts
|
|
9
|
+
* const opened = openLedger({ storeDir, runtimeVersion, owner, log });
|
|
10
|
+
* if (!opened.ok) return attachToOwner(); // another supervisor holds the lock
|
|
11
|
+
* opened.ledger.write((db) => db.run("INSERT INTO child …", …));
|
|
12
|
+
* ```
|
|
13
|
+
*/
|
|
14
|
+
import {
|
|
15
|
+
closeSync,
|
|
16
|
+
existsSync,
|
|
17
|
+
fsyncSync,
|
|
18
|
+
linkSync,
|
|
19
|
+
mkdirSync,
|
|
20
|
+
openSync,
|
|
21
|
+
readdirSync,
|
|
22
|
+
rmSync,
|
|
23
|
+
statSync,
|
|
24
|
+
} from "node:fs";
|
|
25
|
+
import { createRequire } from "node:module";
|
|
26
|
+
import { join } from "node:path";
|
|
27
|
+
import { createDiagnostic, RpcError } from "@mostra/protocol";
|
|
28
|
+
import type BetterSqlite3 from "better-sqlite3";
|
|
29
|
+
import type { Log } from "../log.ts";
|
|
30
|
+
import { BOOTSTRAP_SQL, MIGRATIONS, type Migration } from "./migrations.ts";
|
|
31
|
+
import type { LedgerDb, MigrationDb, RunResult, SqlValue } from "./types.ts";
|
|
32
|
+
|
|
33
|
+
export { MIGRATIONS, type Migration } from "./migrations.ts";
|
|
34
|
+
export {
|
|
35
|
+
InflightRequests,
|
|
36
|
+
type RequestKey,
|
|
37
|
+
recordedResult,
|
|
38
|
+
recordResult,
|
|
39
|
+
requestKey,
|
|
40
|
+
} from "./requests.ts";
|
|
41
|
+
export type { LedgerDb } from "./types.ts";
|
|
42
|
+
|
|
43
|
+
/** The ledger's file name inside `<home>/store`. */
|
|
44
|
+
export const LEDGER_FILE = "ledger.sqlite";
|
|
45
|
+
|
|
46
|
+
/** The process that holds the ledger's lock. */
|
|
47
|
+
export interface LedgerOwner {
|
|
48
|
+
readonly pid: number;
|
|
49
|
+
/** Its start time (processes/identity.ts). */
|
|
50
|
+
readonly startTime: string;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Options for {@link openLedger}. */
|
|
54
|
+
export interface OpenLedgerOptions {
|
|
55
|
+
/** `<home>/store`, created with mode 0700 when missing. */
|
|
56
|
+
readonly storeDir: string;
|
|
57
|
+
/** This runtime's release, recorded with each migration and named by `MOSTRA_HOME_TOO_NEW`. */
|
|
58
|
+
readonly runtimeVersion: string;
|
|
59
|
+
/** Who takes the lock, recorded in `ledger_lock`. */
|
|
60
|
+
readonly owner: LedgerOwner;
|
|
61
|
+
readonly log: Log;
|
|
62
|
+
/** The migrations to apply. Default: this runtime's {@link MIGRATIONS}. */
|
|
63
|
+
readonly migrations?: readonly Migration[];
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** The open ledger. Holding this object holds the home's lock. */
|
|
67
|
+
export interface Ledger {
|
|
68
|
+
/** The ledger file. */
|
|
69
|
+
readonly file: string;
|
|
70
|
+
/** The schema version after migrations. */
|
|
71
|
+
readonly schemaVersion: number;
|
|
72
|
+
/** The migrations applied while opening, with the backup taken first (when any). */
|
|
73
|
+
readonly migrated:
|
|
74
|
+
| { readonly from: number; readonly to: number; readonly backup?: string }
|
|
75
|
+
| undefined;
|
|
76
|
+
/**
|
|
77
|
+
* Runs `fn` in one write transaction (`BEGIN IMMEDIATE`) and commits it, durably
|
|
78
|
+
* (`synchronous=FULL`), before returning (FAILURE_MODEL §1 rule 1). A full disk throws
|
|
79
|
+
* `MOSTRA_HOME_DISK_FULL`; a removed ledger throws `MOSTRA_HOME_GONE`. Nothing partial commits.
|
|
80
|
+
*/
|
|
81
|
+
write<T>(fn: (db: LedgerDb) => T): T;
|
|
82
|
+
/** Runs `fn` in one read transaction, so it sees a single consistent state. */
|
|
83
|
+
read<T>(fn: (db: LedgerDb) => T): T;
|
|
84
|
+
/**
|
|
85
|
+
* Calls `listener` after every write transaction that committed, so readers waiting for new
|
|
86
|
+
* events (`wait`, subscriptions, event streams) look again. Returns the unsubscribe function.
|
|
87
|
+
* A listener's exception is swallowed: it never undoes or fails the commit.
|
|
88
|
+
*/
|
|
89
|
+
onCommit(listener: () => void): () => void;
|
|
90
|
+
/** Runs SQLite's full integrity check: `ok`, or the problems it reports. */
|
|
91
|
+
checkIntegrity(): { readonly ok: boolean; readonly problems: readonly string[] };
|
|
92
|
+
/** Closes the ledger and releases the home's lock. Idempotent. */
|
|
93
|
+
close(): void;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The outcome of {@link openLedger}. */
|
|
97
|
+
export type LedgerOpening =
|
|
98
|
+
| { readonly ok: true; readonly ledger: Ledger }
|
|
99
|
+
| { readonly ok: false; readonly reason: "locked" };
|
|
100
|
+
|
|
101
|
+
type Database = BetterSqlite3.Database;
|
|
102
|
+
type DatabaseConstructor = typeof BetterSqlite3;
|
|
103
|
+
|
|
104
|
+
let driver: DatabaseConstructor | undefined;
|
|
105
|
+
/** Loads the native driver on first use, so importing this module loads no native code. */
|
|
106
|
+
function loadDriver(): DatabaseConstructor {
|
|
107
|
+
driver ??= createRequire(import.meta.url)("better-sqlite3") as DatabaseConstructor;
|
|
108
|
+
return driver;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const sqliteCode = (error: unknown): string | undefined =>
|
|
112
|
+
typeof error === "object" && error !== null && "code" in error && typeof error.code === "string"
|
|
113
|
+
? error.code
|
|
114
|
+
: undefined;
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Turns a SQLite failure into the diagnostic the caller can act on, or `undefined` for failures
|
|
118
|
+
* that are defects (they stay internal errors).
|
|
119
|
+
*/
|
|
120
|
+
function diagnose(error: unknown, file: string): RpcError | undefined {
|
|
121
|
+
const code = sqliteCode(error);
|
|
122
|
+
if (code === undefined) return undefined;
|
|
123
|
+
if (code === "SQLITE_FULL") {
|
|
124
|
+
return new RpcError(
|
|
125
|
+
createDiagnostic("MOSTRA_HOME_DISK_FULL", {
|
|
126
|
+
message: `The disk holding ${file} is full; the change was rolled back.`,
|
|
127
|
+
}),
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
if (code === "SQLITE_READONLY_DBMOVED") {
|
|
131
|
+
return new RpcError(
|
|
132
|
+
createDiagnostic("MOSTRA_HOME_GONE", {
|
|
133
|
+
message: `The ledger ${file} was moved or deleted while the instance was running.`,
|
|
134
|
+
}),
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
if (code === "SQLITE_NOTADB" || code.startsWith("SQLITE_CORRUPT") || code === "SQLITE_CANTOPEN") {
|
|
138
|
+
return unreadable(file, describe(code));
|
|
139
|
+
}
|
|
140
|
+
return undefined;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function describe(code: string): string {
|
|
144
|
+
if (code === "SQLITE_NOTADB") return "it isn't a SQLite database";
|
|
145
|
+
if (code === "SQLITE_CANTOPEN") return "it can't be opened";
|
|
146
|
+
return "it is damaged";
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function unreadable(file: string, why: string): RpcError {
|
|
150
|
+
return new RpcError(
|
|
151
|
+
createDiagnostic("MOSTRA_HOME_LEDGER_UNREADABLE", {
|
|
152
|
+
message: `The ledger ${file} can't be read: ${why}.`,
|
|
153
|
+
}),
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Builds a new ledger file at `file` without ever replacing an existing one (DATA_MODEL §6). */
|
|
158
|
+
function createLedgerFile(storeDir: string, file: string, log: Log): void {
|
|
159
|
+
const Driver = loadDriver();
|
|
160
|
+
const temp = join(storeDir, `${LEDGER_FILE}.${process.pid}.${Date.now()}.creating`);
|
|
161
|
+
const db = new Driver(temp);
|
|
162
|
+
try {
|
|
163
|
+
db.pragma("journal_mode = WAL");
|
|
164
|
+
db.pragma("synchronous = FULL");
|
|
165
|
+
db.exec(BOOTSTRAP_SQL);
|
|
166
|
+
} finally {
|
|
167
|
+
db.close();
|
|
168
|
+
}
|
|
169
|
+
const fd = openSync(temp, "r");
|
|
170
|
+
try {
|
|
171
|
+
fsyncSync(fd);
|
|
172
|
+
} finally {
|
|
173
|
+
closeSync(fd);
|
|
174
|
+
}
|
|
175
|
+
try {
|
|
176
|
+
linkSync(temp, file);
|
|
177
|
+
log.info("ledger.created", { file });
|
|
178
|
+
} catch (error) {
|
|
179
|
+
// Another starter created it first; theirs is the ledger.
|
|
180
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
|
181
|
+
} finally {
|
|
182
|
+
rmSync(temp, { force: true });
|
|
183
|
+
}
|
|
184
|
+
syncDirectory(storeDir);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function syncDirectory(dir: string): void {
|
|
188
|
+
try {
|
|
189
|
+
const fd = openSync(dir, "r");
|
|
190
|
+
try {
|
|
191
|
+
fsyncSync(fd);
|
|
192
|
+
} finally {
|
|
193
|
+
closeSync(fd);
|
|
194
|
+
}
|
|
195
|
+
} catch {
|
|
196
|
+
// Some file systems can't fsync a directory; the data itself is synced.
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Removes `*.creating` files left by starters that died while building a ledger. A file whose
|
|
202
|
+
* creator still runs is another starter's work in progress and stays.
|
|
203
|
+
*/
|
|
204
|
+
function removeAbandonedFiles(storeDir: string): void {
|
|
205
|
+
for (const name of readdirSync(storeDir)) {
|
|
206
|
+
const match = /^ledger\.sqlite\.(\d+)\.\d+\.creating(-wal|-shm|-journal)?$/.exec(name);
|
|
207
|
+
if (match && !processExists(Number(match[1]))) rmSync(join(storeDir, name), { force: true });
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function processExists(pid: number): boolean {
|
|
212
|
+
try {
|
|
213
|
+
process.kill(pid, 0);
|
|
214
|
+
return true;
|
|
215
|
+
} catch (error) {
|
|
216
|
+
return (error as NodeJS.ErrnoException).code === "EPERM";
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function queries(db: Database): MigrationDb {
|
|
221
|
+
const cache = new Map<string, BetterSqlite3.Statement>();
|
|
222
|
+
const prepare = (sql: string): BetterSqlite3.Statement => {
|
|
223
|
+
let statement = cache.get(sql);
|
|
224
|
+
if (!statement) {
|
|
225
|
+
statement = db.prepare(sql);
|
|
226
|
+
cache.set(sql, statement);
|
|
227
|
+
}
|
|
228
|
+
return statement;
|
|
229
|
+
};
|
|
230
|
+
return {
|
|
231
|
+
run(sql: string, ...params: readonly SqlValue[]): RunResult {
|
|
232
|
+
const result = prepare(sql).run(...params);
|
|
233
|
+
return { changes: result.changes, lastInsertRowid: result.lastInsertRowid };
|
|
234
|
+
},
|
|
235
|
+
get<T>(sql: string, ...params: readonly SqlValue[]): T | undefined {
|
|
236
|
+
return prepare(sql).get(...params) as T | undefined;
|
|
237
|
+
},
|
|
238
|
+
all<T>(sql: string, ...params: readonly SqlValue[]): T[] {
|
|
239
|
+
return prepare(sql).all(...params) as T[];
|
|
240
|
+
},
|
|
241
|
+
exec(sql: string): void {
|
|
242
|
+
db.exec(sql);
|
|
243
|
+
},
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Opens the home's ledger and takes its exclusive lock (D81). Returns `{ ok: false, reason:
|
|
249
|
+
* "locked" }` when another process holds it. Throws an `RpcError` with `MOSTRA_HOME_TOO_NEW`,
|
|
250
|
+
* `MOSTRA_HOME_LEDGER_UNREADABLE` or `MOSTRA_HOME_DISK_FULL` when the ledger can't be used.
|
|
251
|
+
*
|
|
252
|
+
* Opening creates a missing ledger, applies pending migrations in one transaction after an
|
|
253
|
+
* integrity check and a `VACUUM INTO` backup (`ledger.sqlite.bak-<from>-<to>`), and records the
|
|
254
|
+
* owner in `ledger_lock`.
|
|
255
|
+
*/
|
|
256
|
+
export function openLedger(options: OpenLedgerOptions): LedgerOpening {
|
|
257
|
+
const { storeDir, log } = options;
|
|
258
|
+
const migrations = options.migrations ?? MIGRATIONS;
|
|
259
|
+
const latest = migrations.at(-1)?.version ?? 0;
|
|
260
|
+
mkdirSync(storeDir, { recursive: true, mode: 0o700 });
|
|
261
|
+
const file = join(storeDir, LEDGER_FILE);
|
|
262
|
+
if (!existsSync(file)) createLedgerFile(storeDir, file, log);
|
|
263
|
+
|
|
264
|
+
const Driver = loadDriver();
|
|
265
|
+
let db: Database;
|
|
266
|
+
try {
|
|
267
|
+
db = new Driver(file, { timeout: 0, fileMustExist: true });
|
|
268
|
+
} catch (error) {
|
|
269
|
+
throw diagnose(error, file) ?? error;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
try {
|
|
273
|
+
// EXCLUSIVE before the first WAL access: no shared-memory index, and no other connection.
|
|
274
|
+
db.pragma("locking_mode = EXCLUSIVE");
|
|
275
|
+
const mode = db.pragma("journal_mode = WAL", { simple: true });
|
|
276
|
+
if (mode !== "wal") throw unreadable(file, `its journal mode is ${String(mode)}, not WAL`);
|
|
277
|
+
db.pragma("synchronous = FULL");
|
|
278
|
+
db.pragma("foreign_keys = ON");
|
|
279
|
+
// A write transaction takes and keeps the exclusive lock from the start (D81).
|
|
280
|
+
db.prepare("BEGIN EXCLUSIVE").run();
|
|
281
|
+
try {
|
|
282
|
+
db.prepare(
|
|
283
|
+
"INSERT OR REPLACE INTO ledger_lock (id, pid, start_time, acquired_at) VALUES (1, ?, ?, ?)",
|
|
284
|
+
).run(options.owner.pid, options.owner.startTime, new Date().toISOString());
|
|
285
|
+
db.prepare("COMMIT").run();
|
|
286
|
+
} catch (error) {
|
|
287
|
+
if (db.inTransaction) db.prepare("ROLLBACK").run();
|
|
288
|
+
throw error;
|
|
289
|
+
}
|
|
290
|
+
} catch (error) {
|
|
291
|
+
db.close();
|
|
292
|
+
if (sqliteCode(error) === "SQLITE_BUSY") return { ok: false, reason: "locked" };
|
|
293
|
+
if (error instanceof RpcError) throw error;
|
|
294
|
+
if (/no such table/.test((error as Error).message)) {
|
|
295
|
+
throw unreadable(file, "it isn't a Mostra ledger");
|
|
296
|
+
}
|
|
297
|
+
throw diagnose(error, file) ?? error;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
try {
|
|
301
|
+
removeAbandonedFiles(storeDir);
|
|
302
|
+
const migrated = migrate(db, file, storeDir, latest, migrations, options);
|
|
303
|
+
return { ok: true, ledger: wrap(db, file, latest, migrated) };
|
|
304
|
+
} catch (error) {
|
|
305
|
+
db.close();
|
|
306
|
+
throw diagnose(error, file) ?? error;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
function migrate(
|
|
311
|
+
db: Database,
|
|
312
|
+
file: string,
|
|
313
|
+
storeDir: string,
|
|
314
|
+
latest: number,
|
|
315
|
+
migrations: readonly Migration[],
|
|
316
|
+
options: OpenLedgerOptions,
|
|
317
|
+
): Ledger["migrated"] {
|
|
318
|
+
const current = db
|
|
319
|
+
.prepare("SELECT version, runtime_version FROM schema_migration ORDER BY version DESC LIMIT 1")
|
|
320
|
+
.get() as { version: number; runtime_version: string } | undefined;
|
|
321
|
+
const from = current?.version ?? 0;
|
|
322
|
+
if (from > latest) {
|
|
323
|
+
throw new RpcError(
|
|
324
|
+
createDiagnostic("MOSTRA_HOME_TOO_NEW", {
|
|
325
|
+
message: `This home's ledger is at schema version ${from}, written by Mostra ${current?.runtime_version ?? "unknown"}; this runtime (${options.runtimeVersion}) understands schema versions up to ${latest}.`,
|
|
326
|
+
}),
|
|
327
|
+
);
|
|
328
|
+
}
|
|
329
|
+
if (from === latest) return undefined;
|
|
330
|
+
|
|
331
|
+
let backup: string | undefined;
|
|
332
|
+
if (from > 0) {
|
|
333
|
+
const check = db.pragma("quick_check") as { quick_check: string }[];
|
|
334
|
+
const problems = check.map((row) => row.quick_check).filter((text) => text !== "ok");
|
|
335
|
+
if (problems.length > 0) {
|
|
336
|
+
throw unreadable(
|
|
337
|
+
file,
|
|
338
|
+
`SQLite's integrity check failed (${problems.slice(0, 3).join("; ")})`,
|
|
339
|
+
);
|
|
340
|
+
}
|
|
341
|
+
backup = join(storeDir, `${LEDGER_FILE}.bak-${from}-${latest}`);
|
|
342
|
+
rmSync(backup, { force: true });
|
|
343
|
+
// VACUUM INTO writes a consistent copy through SQLite, fsynced under synchronous=FULL;
|
|
344
|
+
// copying the file with fs would drop this process's lock (DATA_MODEL §1).
|
|
345
|
+
db.prepare("VACUUM INTO ?").run(backup);
|
|
346
|
+
options.log.info("ledger.backup", { file: backup, from, to: latest });
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
const pending = migrations.filter((migration) => migration.version > from);
|
|
350
|
+
const apply = db.transaction(() => {
|
|
351
|
+
const target = queries(db);
|
|
352
|
+
for (const migration of pending) {
|
|
353
|
+
migration.up(target);
|
|
354
|
+
target.run(
|
|
355
|
+
"INSERT INTO schema_migration (version, name, runtime_version, applied_at) VALUES (?, ?, ?, ?)",
|
|
356
|
+
migration.version,
|
|
357
|
+
migration.name,
|
|
358
|
+
options.runtimeVersion,
|
|
359
|
+
new Date().toISOString(),
|
|
360
|
+
);
|
|
361
|
+
}
|
|
362
|
+
});
|
|
363
|
+
apply.immediate();
|
|
364
|
+
options.log.info("ledger.migrated", { from, to: latest });
|
|
365
|
+
return backup === undefined ? { from, to: latest } : { from, to: latest, backup };
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
function inodeOf(file: string): string | undefined {
|
|
369
|
+
try {
|
|
370
|
+
const stats = statSync(file);
|
|
371
|
+
return `${stats.dev}:${stats.ino}`;
|
|
372
|
+
} catch {
|
|
373
|
+
return undefined;
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
function wrap(
|
|
378
|
+
db: Database,
|
|
379
|
+
file: string,
|
|
380
|
+
schemaVersion: number,
|
|
381
|
+
migrated: Ledger["migrated"],
|
|
382
|
+
): Ledger {
|
|
383
|
+
const target = queries(db);
|
|
384
|
+
let open = true;
|
|
385
|
+
const listeners = new Set<() => void>();
|
|
386
|
+
// SQLite keeps writing to a ledger whose file was removed (its open descriptors outlive the
|
|
387
|
+
// name), and the data would be lost on close. Every write checks that the file is still the one
|
|
388
|
+
// it opened, before and after the commit, and fails closed otherwise (FAILURE_MODEL §3).
|
|
389
|
+
const opened = inodeOf(file);
|
|
390
|
+
const assertInPlace = (): void => {
|
|
391
|
+
if (inodeOf(file) === opened) return;
|
|
392
|
+
throw new RpcError(
|
|
393
|
+
createDiagnostic("MOSTRA_HOME_GONE", {
|
|
394
|
+
message: `The ledger ${file} was moved or deleted while the instance was running.`,
|
|
395
|
+
}),
|
|
396
|
+
);
|
|
397
|
+
};
|
|
398
|
+
const guarded = <T>(run: () => T): T => {
|
|
399
|
+
try {
|
|
400
|
+
return run();
|
|
401
|
+
} catch (error) {
|
|
402
|
+
throw diagnose(error, file) ?? error;
|
|
403
|
+
}
|
|
404
|
+
};
|
|
405
|
+
return {
|
|
406
|
+
file,
|
|
407
|
+
schemaVersion,
|
|
408
|
+
migrated,
|
|
409
|
+
write<T>(fn: (db: LedgerDb) => T): T {
|
|
410
|
+
assertInPlace();
|
|
411
|
+
const result = guarded(() => db.transaction(() => fn(target)).immediate());
|
|
412
|
+
assertInPlace();
|
|
413
|
+
// A write nested in another commits with the outer one; listeners hear of that one.
|
|
414
|
+
if (db.inTransaction) return result;
|
|
415
|
+
for (const listener of listeners) {
|
|
416
|
+
try {
|
|
417
|
+
listener();
|
|
418
|
+
} catch {
|
|
419
|
+
// A listener's failure is its own; the commit stands.
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
return result;
|
|
423
|
+
},
|
|
424
|
+
onCommit(listener) {
|
|
425
|
+
listeners.add(listener);
|
|
426
|
+
return () => listeners.delete(listener);
|
|
427
|
+
},
|
|
428
|
+
read<T>(fn: (db: LedgerDb) => T): T {
|
|
429
|
+
return guarded(() => db.transaction(() => fn(target)).deferred());
|
|
430
|
+
},
|
|
431
|
+
checkIntegrity() {
|
|
432
|
+
const rows = db.pragma("integrity_check") as { integrity_check: string }[];
|
|
433
|
+
const problems = rows.map((row) => row.integrity_check).filter((text) => text !== "ok");
|
|
434
|
+
return { ok: problems.length === 0, problems };
|
|
435
|
+
},
|
|
436
|
+
close() {
|
|
437
|
+
if (!open) return;
|
|
438
|
+
open = false;
|
|
439
|
+
db.close();
|
|
440
|
+
},
|
|
441
|
+
};
|
|
442
|
+
}
|