@jini-ai/db 0.6.17 → 0.7.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/CHANGELOG.md +27 -0
- package/dist/core/pg-types.d.ts +2 -0
- package/dist/data-modules/data-module.d.ts +90 -0
- package/dist/data-modules/data-module.js +851 -0
- package/dist/data-modules/disk-headroom.d.ts +11 -0
- package/dist/data-modules/disk-headroom.js +44 -0
- package/dist/data-modules/index.d.ts +18 -0
- package/dist/data-modules/index.js +17 -0
- package/dist/data-modules/migration-journal.d.ts +65 -0
- package/dist/data-modules/migration-journal.js +90 -0
- package/dist/data-modules/migration-recovery.d.ts +37 -0
- package/dist/data-modules/migration-recovery.js +62 -0
- package/dist/data-modules/plugin-identity.d.ts +43 -0
- package/dist/data-modules/plugin-identity.js +101 -0
- package/dist/data-modules/plugin-store.d.ts +43 -0
- package/dist/data-modules/plugin-store.js +6 -0
- package/dist/data-modules/restore.d.ts +5 -0
- package/dist/data-modules/restore.js +42 -0
- package/dist/data-modules/snapshot.d.ts +57 -0
- package/dist/data-modules/snapshot.js +94 -0
- package/dist/kernel/index.d.ts +1 -0
- package/dist/kernel/index.js +1 -0
- package/dist/kernel/kernel-core.d.ts +2 -0
- package/dist/kernel/kernel-core.js +2 -0
- package/dist/kernel/port.d.ts +5 -0
- package/dist/kernel/postgres/driver.js +16 -1
- package/dist/kernel/schema-scope.js +2 -0
- package/dist/kernel/session-lock.d.ts +40 -0
- package/dist/kernel/session-lock.js +48 -0
- package/dist/sqlite/backup-policy.d.ts +2 -1
- package/dist/sqlite/backup-policy.js +10 -2
- package/dist/sqlite/db-ops.js +32 -3
- package/package.json +15 -5
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export interface HeadroomCheck {
|
|
2
|
+
ok: boolean;
|
|
3
|
+
requiredBytes: number;
|
|
4
|
+
freeBytes: number | null;
|
|
5
|
+
/** Set when the check could not measure free space at all (see file header). */
|
|
6
|
+
measurementFailed?: boolean;
|
|
7
|
+
}
|
|
8
|
+
export declare function checkDiskHeadroom({ dbPath }: {
|
|
9
|
+
dbPath: string;
|
|
10
|
+
}, _optional?: Record<string, never>): HeadroomCheck;
|
|
11
|
+
//# sourceMappingURL=disk-headroom.d.ts.map
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file ADR-023 §3 (T4 fix) — disk-headroom preflight. Before any snapshot, core computes
|
|
3
|
+
* `required = 1.5 x (current DB file size + WAL file size)`. If free disk space on the volume
|
|
4
|
+
* holding `content.db` is below that, the dataModule operation fails closed before any file is
|
|
5
|
+
* touched.
|
|
6
|
+
*
|
|
7
|
+
* Disclosed limitation: `fs.statfsSync` (Node 18.15+/20.4+) is used to read free space. If it is
|
|
8
|
+
* unavailable on the running platform/Node version, this is a MEASUREMENT failure, not a
|
|
9
|
+
* headroom-insufficiency finding — the check logs a warning and reports `ok: true` (proceeds)
|
|
10
|
+
* rather than failing closed on an unrelated platform gap. Failing closed is reserved for a
|
|
11
|
+
* genuine, measured insufficiency.
|
|
12
|
+
*/
|
|
13
|
+
import { existsSync, statSync, statfsSync } from "node:fs";
|
|
14
|
+
import path from "node:path";
|
|
15
|
+
import { isInMemoryDbPath } from "./snapshot.js";
|
|
16
|
+
const HEADROOM_MULTIPLIER = 1.5;
|
|
17
|
+
function fileSize(filePath) {
|
|
18
|
+
return existsSync(filePath) ? statSync(filePath).size : 0;
|
|
19
|
+
}
|
|
20
|
+
export function checkDiskHeadroom({ dbPath }, _optional = {}) {
|
|
21
|
+
// BUG FIX (2026-07-28): an in-memory (or SQLite's other non-file) `dbPath` never gets a snapshot
|
|
22
|
+
// file written (see `snapshot.ts`'s `isInMemoryDbPath`/`snapshotDb`), so there is no on-disk
|
|
23
|
+
// headroom requirement to preflight — the check is not just redundant but potentially WRONG
|
|
24
|
+
// without this guard: `path.dirname(":memory:")` resolves to the process's CURRENT WORKING
|
|
25
|
+
// DIRECTORY, so a low-disk cwd could fail-close a dataModule declare that will never touch disk
|
|
26
|
+
// at all. `requiredBytes: 0` mirrors the existing "nonexistent file" case below (real dbPath,
|
|
27
|
+
// file not yet created) rather than inventing a new shape for callers to handle.
|
|
28
|
+
if (isInMemoryDbPath({ dbPath })) {
|
|
29
|
+
return { ok: true, requiredBytes: 0, freeBytes: null };
|
|
30
|
+
}
|
|
31
|
+
const dbSize = fileSize(dbPath);
|
|
32
|
+
const walSize = fileSize(`${dbPath}-wal`);
|
|
33
|
+
const requiredBytes = Math.ceil(HEADROOM_MULTIPLIER * (dbSize + walSize));
|
|
34
|
+
let freeBytes = null;
|
|
35
|
+
try {
|
|
36
|
+
const stats = statfsSync(path.dirname(dbPath));
|
|
37
|
+
freeBytes = stats.bavail * stats.bsize;
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return { ok: true, requiredBytes, freeBytes: null, measurementFailed: true };
|
|
41
|
+
}
|
|
42
|
+
return { ok: freeBytes >= requiredBytes, requiredBytes, freeBytes };
|
|
43
|
+
}
|
|
44
|
+
//# sourceMappingURL=disk-headroom.js.map
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file Public surface for the `plugins` feature. Deliberately narrow: only the ADR-023
|
|
3
|
+
* `dataModule` declaration contract that `comments` and `newsletter` both consume to register
|
|
4
|
+
* their own own-tables (`declareDataModule`, `DataModuleDecl`, `ColumnType`). Everything else
|
|
5
|
+
* under this directory (`lipay/`, `store/`, `migration-recovery.ts`) is reached
|
|
6
|
+
* only from the composition root or the assistant tool-catalog seam, which construct concrete
|
|
7
|
+
* implementations directly by design (ADR-009 §1) — this barrel does not re-export them.
|
|
8
|
+
*/
|
|
9
|
+
export * from "./data-module.js";
|
|
10
|
+
export type { PluginStore as DataModuleStore } from "./plugin-store.js";
|
|
11
|
+
export * from "./migration-journal.js";
|
|
12
|
+
export * from "./plugin-identity.js";
|
|
13
|
+
export * from "./snapshot.js";
|
|
14
|
+
export * from "./migration-recovery.js";
|
|
15
|
+
export * from "./disk-headroom.js";
|
|
16
|
+
export * from "./plugin-store.js";
|
|
17
|
+
export * from "./restore.js";
|
|
18
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file Public surface for the `plugins` feature. Deliberately narrow: only the ADR-023
|
|
3
|
+
* `dataModule` declaration contract that `comments` and `newsletter` both consume to register
|
|
4
|
+
* their own own-tables (`declareDataModule`, `DataModuleDecl`, `ColumnType`). Everything else
|
|
5
|
+
* under this directory (`lipay/`, `store/`, `migration-recovery.ts`) is reached
|
|
6
|
+
* only from the composition root or the assistant tool-catalog seam, which construct concrete
|
|
7
|
+
* implementations directly by design (ADR-009 §1) — this barrel does not re-export them.
|
|
8
|
+
*/
|
|
9
|
+
export * from "./data-module.js";
|
|
10
|
+
export * from "./migration-journal.js";
|
|
11
|
+
export * from "./plugin-identity.js";
|
|
12
|
+
export * from "./snapshot.js";
|
|
13
|
+
export * from "./migration-recovery.js";
|
|
14
|
+
export * from "./disk-headroom.js";
|
|
15
|
+
export * from "./plugin-store.js";
|
|
16
|
+
export * from "./restore.js";
|
|
17
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { type PluginStore } from "./plugin-store.js";
|
|
2
|
+
export type JournalPhase = "PREPARED_SNAPSHOT" | "DDL_IN_PROGRESS" | "VERIFYING" | "COMMITTED" | "ROLLED_BACK";
|
|
3
|
+
export interface JournalEntry {
|
|
4
|
+
id: number;
|
|
5
|
+
pluginId: string;
|
|
6
|
+
phase: JournalPhase;
|
|
7
|
+
snapshotPath: string;
|
|
8
|
+
startedAt: number;
|
|
9
|
+
updatedAt: number;
|
|
10
|
+
}
|
|
11
|
+
/** True for an entry boot recovery must act on: any phase short of `COMMITTED`/`ROLLED_BACK`. */
|
|
12
|
+
export declare function isIncompletePhase({ phase }: {
|
|
13
|
+
phase: string;
|
|
14
|
+
}, _optional?: Record<string, never>): boolean;
|
|
15
|
+
export declare function ensureMigrationJournal({ store }: {
|
|
16
|
+
store: PluginStore;
|
|
17
|
+
}, _optional?: Record<string, never>): Promise<void>;
|
|
18
|
+
/** Opens a new journal entry at `PREPARED_SNAPSHOT` and returns its id. Checkpointed before returning. */
|
|
19
|
+
export declare function beginJournalEntry(required: {
|
|
20
|
+
db: PluginStore;
|
|
21
|
+
pluginId: string;
|
|
22
|
+
snapshotPath: string;
|
|
23
|
+
}, _optional?: Record<string, never>): Promise<number>;
|
|
24
|
+
/**
|
|
25
|
+
* Writes a phase transition WITHOUT checkpointing (BUG FIX, 2026-08-12 — see `data-module.ts`'s
|
|
26
|
+
* header comment, POST-COMMIT DATA-LOSS WINDOW). Exists solely for a caller that needs to write a
|
|
27
|
+
* phase transition from INSIDE an already-open kernel transaction, where `advanceJournalPhase`'s
|
|
28
|
+
* checkpoint cannot run: a SQLite WAL checkpoint issued by the SAME connection that holds an open
|
|
29
|
+
* write transaction throws `database table is locked` (confirmed directly against this repo's
|
|
30
|
+
* better-sqlite3 build, not assumed from SQLite's docs, which don't call out same-connection
|
|
31
|
+
* mid-transaction checkpoint behavior at all). The caller is responsible for checkpointing the SAME
|
|
32
|
+
* id once its own transaction has committed — typically by calling `advanceJournalPhase` again for
|
|
33
|
+
* the same id/phase, which re-writes the (already correct) row and performs the deferred checkpoint
|
|
34
|
+
* in one call. Skipping that follow-up checkpoint does not weaken crash-durability: the phase
|
|
35
|
+
* transition is already durable the instant the caller's transaction commits (a normal SQLite WAL
|
|
36
|
+
* commit), the same as any other write in that transaction — the checkpoint only controls when the
|
|
37
|
+
* WAL is merged back into the main db file, not whether the write survives a crash.
|
|
38
|
+
*/
|
|
39
|
+
export declare function stageJournalPhase(required: {
|
|
40
|
+
db: PluginStore;
|
|
41
|
+
id: number;
|
|
42
|
+
phase: JournalPhase;
|
|
43
|
+
}, _optional?: Record<string, never>): Promise<void>;
|
|
44
|
+
/** Advances a journal entry to `phase`, checkpointed before returning (durable before the next step runs). */
|
|
45
|
+
export declare function advanceJournalPhase(required: {
|
|
46
|
+
db: PluginStore;
|
|
47
|
+
id: number;
|
|
48
|
+
phase: JournalPhase;
|
|
49
|
+
}, _optional?: Record<string, never>): Promise<void>;
|
|
50
|
+
/** Boot-time recovery scan (§2): any entry NOT in a terminal phase is a crash-interrupted attempt. */
|
|
51
|
+
export declare function findIncompleteJournalEntries({ store }: {
|
|
52
|
+
store: PluginStore;
|
|
53
|
+
}, _optional?: Record<string, never>): Promise<JournalEntry[]>;
|
|
54
|
+
/** One `_plugin_migration_journal` row as a {@link JournalEntry} (numbers normalized across drivers). */
|
|
55
|
+
export declare function journalEntryOf({ row }: {
|
|
56
|
+
row: {
|
|
57
|
+
id: number;
|
|
58
|
+
plugin_id: string;
|
|
59
|
+
phase: string;
|
|
60
|
+
snapshot_path: string;
|
|
61
|
+
started_at: number;
|
|
62
|
+
updated_at: number;
|
|
63
|
+
};
|
|
64
|
+
}, _optional?: Record<string, never>): JournalEntry;
|
|
65
|
+
//# sourceMappingURL=migration-journal.d.ts.map
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file ADR-023 §2 (T3 fix) — the durable, fsynced phase-marker journal for the dataModule
|
|
3
|
+
* engine. Every DDL attempt writes phase transitions here, in strict sequence:
|
|
4
|
+
* `PREPARED_SNAPSHOT → DDL_IN_PROGRESS → VERIFYING → COMMITTED` (success) or `→ ROLLED_BACK`
|
|
5
|
+
* (failure). Each transition is checkpointed (forced WAL fsync) before the corresponding DB
|
|
6
|
+
* operation is attempted, so a crash can always be placed at a known, durable phase on next boot.
|
|
7
|
+
*
|
|
8
|
+
* One row per attempt, phase column UPDATEd in place (not append-only) — boot recovery
|
|
9
|
+
* (`migration-recovery.ts`) needs to find "the" in-flight entry per plugin cheaply.
|
|
10
|
+
*
|
|
11
|
+
* On the storage kernel, every dialect: `data-module.ts` only opens entries for a file-backed
|
|
12
|
+
* SQLite database (the one with a snapshot to restore), but the table and its queries are portable.
|
|
13
|
+
*/
|
|
14
|
+
import { sql } from "kysely";
|
|
15
|
+
import { autoIdColumnSql, checkpointWal, columnTypeSql } from "../kernel/index.js";
|
|
16
|
+
import { pluginKernel } from "./plugin-store.js";
|
|
17
|
+
const TERMINAL_PHASES = new Set(["COMMITTED", "ROLLED_BACK"]);
|
|
18
|
+
/** True for an entry boot recovery must act on: any phase short of `COMMITTED`/`ROLLED_BACK`. */
|
|
19
|
+
export function isIncompletePhase({ phase }, _optional = {}) {
|
|
20
|
+
return !TERMINAL_PHASES.has(phase);
|
|
21
|
+
}
|
|
22
|
+
export async function ensureMigrationJournal({ store }, _optional = {}) {
|
|
23
|
+
const kernel = pluginKernel({ store });
|
|
24
|
+
const integer = sql.raw(columnTypeSql(kernel.dialect, "INTEGER"));
|
|
25
|
+
const text = sql.raw(columnTypeSql(kernel.dialect, "TEXT"));
|
|
26
|
+
await kernel.execute(sql `CREATE TABLE IF NOT EXISTS _plugin_migration_journal (
|
|
27
|
+
id ${sql.raw(autoIdColumnSql(kernel.dialect))},
|
|
28
|
+
plugin_id ${text} NOT NULL,
|
|
29
|
+
phase ${text} NOT NULL,
|
|
30
|
+
snapshot_path ${text} NOT NULL,
|
|
31
|
+
started_at ${integer} NOT NULL,
|
|
32
|
+
updated_at ${integer} NOT NULL
|
|
33
|
+
)`);
|
|
34
|
+
}
|
|
35
|
+
/** Opens a new journal entry at `PREPARED_SNAPSHOT` and returns its id. Checkpointed before returning. */
|
|
36
|
+
export async function beginJournalEntry(required, _optional = {}) {
|
|
37
|
+
const { pluginId, snapshotPath } = required;
|
|
38
|
+
const kernel = pluginKernel({ store: required.db });
|
|
39
|
+
const now = Date.now();
|
|
40
|
+
const row = await kernel.run((db) => db
|
|
41
|
+
.insertInto("_plugin_migration_journal")
|
|
42
|
+
.values({ plugin_id: pluginId, phase: "PREPARED_SNAPSHOT", snapshot_path: snapshotPath, started_at: now, updated_at: now })
|
|
43
|
+
.returning("id")
|
|
44
|
+
.executeTakeFirstOrThrow());
|
|
45
|
+
await checkpointWal(kernel);
|
|
46
|
+
return Number(row.id);
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Writes a phase transition WITHOUT checkpointing (BUG FIX, 2026-08-12 — see `data-module.ts`'s
|
|
50
|
+
* header comment, POST-COMMIT DATA-LOSS WINDOW). Exists solely for a caller that needs to write a
|
|
51
|
+
* phase transition from INSIDE an already-open kernel transaction, where `advanceJournalPhase`'s
|
|
52
|
+
* checkpoint cannot run: a SQLite WAL checkpoint issued by the SAME connection that holds an open
|
|
53
|
+
* write transaction throws `database table is locked` (confirmed directly against this repo's
|
|
54
|
+
* better-sqlite3 build, not assumed from SQLite's docs, which don't call out same-connection
|
|
55
|
+
* mid-transaction checkpoint behavior at all). The caller is responsible for checkpointing the SAME
|
|
56
|
+
* id once its own transaction has committed — typically by calling `advanceJournalPhase` again for
|
|
57
|
+
* the same id/phase, which re-writes the (already correct) row and performs the deferred checkpoint
|
|
58
|
+
* in one call. Skipping that follow-up checkpoint does not weaken crash-durability: the phase
|
|
59
|
+
* transition is already durable the instant the caller's transaction commits (a normal SQLite WAL
|
|
60
|
+
* commit), the same as any other write in that transaction — the checkpoint only controls when the
|
|
61
|
+
* WAL is merged back into the main db file, not whether the write survives a crash.
|
|
62
|
+
*/
|
|
63
|
+
export async function stageJournalPhase(required, _optional = {}) {
|
|
64
|
+
const { id, phase } = required;
|
|
65
|
+
await pluginKernel({ store: required.db }).run((db) => db.updateTable("_plugin_migration_journal").set({ phase, updated_at: Date.now() }).where("id", "=", id).execute());
|
|
66
|
+
}
|
|
67
|
+
/** Advances a journal entry to `phase`, checkpointed before returning (durable before the next step runs). */
|
|
68
|
+
export async function advanceJournalPhase(required, _optional = {}) {
|
|
69
|
+
const kernel = pluginKernel({ store: required.db });
|
|
70
|
+
await stageJournalPhase({ db: kernel, id: required.id, phase: required.phase });
|
|
71
|
+
await checkpointWal(kernel);
|
|
72
|
+
}
|
|
73
|
+
/** Boot-time recovery scan (§2): any entry NOT in a terminal phase is a crash-interrupted attempt. */
|
|
74
|
+
export async function findIncompleteJournalEntries({ store }, _optional = {}) {
|
|
75
|
+
const kernel = pluginKernel({ store });
|
|
76
|
+
const rows = await kernel.run((db) => db.selectFrom("_plugin_migration_journal").select(["id", "plugin_id", "phase", "snapshot_path", "started_at", "updated_at"]).orderBy("id").execute());
|
|
77
|
+
return rows.filter((r) => isIncompletePhase({ phase: r.phase })).map((row) => journalEntryOf({ row }));
|
|
78
|
+
}
|
|
79
|
+
/** One `_plugin_migration_journal` row as a {@link JournalEntry} (numbers normalized across drivers). */
|
|
80
|
+
export function journalEntryOf({ row }, _optional = {}) {
|
|
81
|
+
return {
|
|
82
|
+
id: Number(row.id),
|
|
83
|
+
pluginId: row.plugin_id,
|
|
84
|
+
phase: row.phase,
|
|
85
|
+
snapshotPath: row.snapshot_path,
|
|
86
|
+
startedAt: Number(row.started_at),
|
|
87
|
+
updatedAt: Number(row.updated_at),
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
//# sourceMappingURL=migration-journal.js.map
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { type JournalEntry } from "./migration-journal.js";
|
|
2
|
+
import { type PluginStore } from "./plugin-store.js";
|
|
3
|
+
export interface RecoveryResult {
|
|
4
|
+
recovered: number;
|
|
5
|
+
entries: Array<{
|
|
6
|
+
pluginId: string;
|
|
7
|
+
snapshotPath: string;
|
|
8
|
+
}>;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Finds and settles every crash-interrupted dataModule attempt in `store`'s database. A database
|
|
12
|
+
* with no journal table yet has none.
|
|
13
|
+
*
|
|
14
|
+
* NOTE (SQLite): the journal entry itself is NOT marked `ROLLED_BACK` post-restore. The journal row
|
|
15
|
+
* was inserted AFTER the snapshot it references was taken (§2's phase sequence starts at
|
|
16
|
+
* `PREPARED_SNAPSHOT`, meaning "the snapshot already exists"), so the snapshot never contains that
|
|
17
|
+
* row — restoring from it reverts the live file to a state that has no record of the interrupted
|
|
18
|
+
* attempt at all, which is correct (the attempt is fully undone). The returned `entries` list IS the
|
|
19
|
+
* audit record for this boot's recovery action; the caller must log it.
|
|
20
|
+
*
|
|
21
|
+
* @param required.restoreSnapshots SQLite only: close the connection under `store`, then restore
|
|
22
|
+
* the entries' snapshots (normally {@link restoreSqliteSnapshots}). `store` is unusable after it.
|
|
23
|
+
*
|
|
24
|
+
* @agent-note Run this right after opening the database, before anything else reads or migrates
|
|
25
|
+
* it. On SQLite, `restoreSnapshots` must close the connection under `store` before it copies any
|
|
26
|
+
* snapshot, restore over the same file the declares named as `dbPath`, and the caller reopens after.
|
|
27
|
+
*/
|
|
28
|
+
export declare function recoverIncompleteDataModuleMigrations(required: {
|
|
29
|
+
store: PluginStore;
|
|
30
|
+
restoreSnapshots: (entries: readonly JournalEntry[]) => void | Promise<void>;
|
|
31
|
+
}, _optional?: Record<string, never>): Promise<RecoveryResult>;
|
|
32
|
+
/** Restores each entry's snapshot over the SQLite file at `dbPath`. No connection may hold it open. */
|
|
33
|
+
export declare function restoreSqliteSnapshots({ dbPath, entries }: {
|
|
34
|
+
dbPath: string;
|
|
35
|
+
entries: readonly JournalEntry[];
|
|
36
|
+
}, _optional?: Record<string, never>): void;
|
|
37
|
+
//# sourceMappingURL=migration-recovery.d.ts.map
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file ADR-023 §2 — boot-time crash recovery for the dataModule engine, on the storage kernel.
|
|
3
|
+
* The site opener calls {@link recoverIncompleteDataModuleMigrations} right after it opens the
|
|
4
|
+
* content database and before anything else reads it — before the SQLite migrations run.
|
|
5
|
+
*
|
|
6
|
+
* Any journal entry not in a terminal phase (`COMMITTED`/`ROLLED_BACK`) is a crash-interrupted
|
|
7
|
+
* attempt — mandatory, blocking:
|
|
8
|
+
* - SQLite: the caller's `restoreSnapshots` closes its connection and restores each entry's
|
|
9
|
+
* snapshot file ({@link restoreSqliteSnapshots}); the caller then reopens. No restore ever runs
|
|
10
|
+
* against a file a connection still holds open (T2/T8's corruption vector).
|
|
11
|
+
* - Postgres/PGlite: DDL and the journal commit in one transaction, so an incomplete entry can only
|
|
12
|
+
* be an attempt whose transaction rolled back. Nothing to restore; the entry is marked
|
|
13
|
+
* `ROLLED_BACK`.
|
|
14
|
+
*/
|
|
15
|
+
import { tableExists } from "../kernel/index.js";
|
|
16
|
+
import { advanceJournalPhase, findIncompleteJournalEntries } from "./migration-journal.js";
|
|
17
|
+
import { pluginKernel } from "./plugin-store.js";
|
|
18
|
+
import { restoreFromSnapshot } from "./restore.js";
|
|
19
|
+
const JOURNAL_TABLE = "_plugin_migration_journal";
|
|
20
|
+
/**
|
|
21
|
+
* Finds and settles every crash-interrupted dataModule attempt in `store`'s database. A database
|
|
22
|
+
* with no journal table yet has none.
|
|
23
|
+
*
|
|
24
|
+
* NOTE (SQLite): the journal entry itself is NOT marked `ROLLED_BACK` post-restore. The journal row
|
|
25
|
+
* was inserted AFTER the snapshot it references was taken (§2's phase sequence starts at
|
|
26
|
+
* `PREPARED_SNAPSHOT`, meaning "the snapshot already exists"), so the snapshot never contains that
|
|
27
|
+
* row — restoring from it reverts the live file to a state that has no record of the interrupted
|
|
28
|
+
* attempt at all, which is correct (the attempt is fully undone). The returned `entries` list IS the
|
|
29
|
+
* audit record for this boot's recovery action; the caller must log it.
|
|
30
|
+
*
|
|
31
|
+
* @param required.restoreSnapshots SQLite only: close the connection under `store`, then restore
|
|
32
|
+
* the entries' snapshots (normally {@link restoreSqliteSnapshots}). `store` is unusable after it.
|
|
33
|
+
*
|
|
34
|
+
* @agent-note Run this right after opening the database, before anything else reads or migrates
|
|
35
|
+
* it. On SQLite, `restoreSnapshots` must close the connection under `store` before it copies any
|
|
36
|
+
* snapshot, restore over the same file the declares named as `dbPath`, and the caller reopens after.
|
|
37
|
+
*/
|
|
38
|
+
export async function recoverIncompleteDataModuleMigrations(required, _optional = {}) {
|
|
39
|
+
const kernel = pluginKernel({ store: required.store });
|
|
40
|
+
if (!(await tableExists(kernel, JOURNAL_TABLE)))
|
|
41
|
+
return { recovered: 0, entries: [] };
|
|
42
|
+
const incomplete = await findIncompleteJournalEntries({ store: kernel });
|
|
43
|
+
if (incomplete.length === 0)
|
|
44
|
+
return { recovered: 0, entries: [] };
|
|
45
|
+
if (kernel.dialect === "sqlite") {
|
|
46
|
+
await required.restoreSnapshots(incomplete);
|
|
47
|
+
}
|
|
48
|
+
else {
|
|
49
|
+
for (const entry of incomplete)
|
|
50
|
+
await advanceJournalPhase({ db: kernel, id: entry.id, phase: "ROLLED_BACK" });
|
|
51
|
+
}
|
|
52
|
+
return { recovered: incomplete.length, entries: incomplete.map((e) => ({ pluginId: e.pluginId, snapshotPath: e.snapshotPath })) };
|
|
53
|
+
}
|
|
54
|
+
/** Restores each entry's snapshot over the SQLite file at `dbPath`. No connection may hold it open. */
|
|
55
|
+
export function restoreSqliteSnapshots({ dbPath, entries }, _optional = {}) {
|
|
56
|
+
// The journal scan returns oldest first. Newer whole-file snapshots may contain older pending
|
|
57
|
+
// journal rows, so unwind newest first or the final copy revives an attempt already restored.
|
|
58
|
+
for (const entry of [...entries].reverse()) {
|
|
59
|
+
restoreFromSnapshot({ dbPath, snapshotPath: entry.snapshotPath });
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
//# sourceMappingURL=migration-recovery.js.map
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { type PluginStore } from "./plugin-store.js";
|
|
2
|
+
/**
|
|
3
|
+
* @agent-note Saved format. The first declare that applies DDL stores these fields in
|
|
4
|
+
* `_plugin_identity`; they are never updated. Later declares compare all three with strict string
|
|
5
|
+
* equality, so a renamed publisher or moved URL is refused as `consent-required` the next time
|
|
6
|
+
* that plugin has DDL to apply, unless both sides carry the same `signature`.
|
|
7
|
+
*/
|
|
8
|
+
export interface PluginProvenance {
|
|
9
|
+
sourceUrl: string;
|
|
10
|
+
publisher: string;
|
|
11
|
+
signature?: string;
|
|
12
|
+
}
|
|
13
|
+
export interface PluginIdentityRecord {
|
|
14
|
+
pluginId: string;
|
|
15
|
+
provenance: PluginProvenance;
|
|
16
|
+
mintedAt: number;
|
|
17
|
+
}
|
|
18
|
+
export type NamespaceAdoptionDecision = {
|
|
19
|
+
allowed: true;
|
|
20
|
+
track: "first-mint" | "unchanged" | "verified-signature";
|
|
21
|
+
} | {
|
|
22
|
+
allowed: false;
|
|
23
|
+
track: "consent-required";
|
|
24
|
+
reason: string;
|
|
25
|
+
};
|
|
26
|
+
export declare function ensurePluginIdentityTable({ store }: {
|
|
27
|
+
store: PluginStore;
|
|
28
|
+
}, _optional?: Record<string, never>): Promise<void>;
|
|
29
|
+
export declare function getPluginIdentity(required: {
|
|
30
|
+
db: PluginStore;
|
|
31
|
+
pluginId: string;
|
|
32
|
+
}, _optional?: Record<string, never>): Promise<PluginIdentityRecord | null>;
|
|
33
|
+
/**
|
|
34
|
+
* Mints the identity record on first sight (always `allowed: true`). On a subsequent declare,
|
|
35
|
+
* applies the two-track rule. Does NOT mutate the identity record on anything but first mint —
|
|
36
|
+
* a provenance mismatch never silently overwrites the record on record (permanent retirement).
|
|
37
|
+
*/
|
|
38
|
+
export declare function checkNamespaceAdoption(required: {
|
|
39
|
+
db: PluginStore;
|
|
40
|
+
pluginId: string;
|
|
41
|
+
provenance: PluginProvenance;
|
|
42
|
+
}, _optional?: Record<string, never>): Promise<NamespaceAdoptionDecision>;
|
|
43
|
+
//# sourceMappingURL=plugin-identity.d.ts.map
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file ADR-023 §5/§6 (T5 fix, round-2 revision) — permanent plugin-ID retirement plus the
|
|
3
|
+
* two-track fail-closed namespace-adoption guard.
|
|
4
|
+
*
|
|
5
|
+
* A `pluginId` is permanently retired the moment it is first minted (this record is never
|
|
6
|
+
* deleted, including after a future uninstall+purge — no purge/uninstall flow exists in this
|
|
7
|
+
* codebase yet, so this module's row is never actually removed by anything today; that absence
|
|
8
|
+
* IS the correct behavior per §6's "retirement is permanent" rule, not a gap).
|
|
9
|
+
*
|
|
10
|
+
* Two-track adoption rule (§6): a SUBSEQUENT declare for an already-identified `pluginId` is
|
|
11
|
+
* allowed automatically when its provenance is unchanged from what's on record (the common case —
|
|
12
|
+
* the same first-party module re-declaring at every boot), OR when both the stored and incoming
|
|
13
|
+
* provenance carry a matching signature (track a — "verified same-key signature"). Anything else
|
|
14
|
+
* (no signature on one/both sides, or a mismatch) requires explicit operator consent (track b) —
|
|
15
|
+
* surfaced here as a typed refusal, since no consent-prompt UI exists in this codebase yet.
|
|
16
|
+
*
|
|
17
|
+
* Signature verification here is a same-string comparison, not real cryptographic verification —
|
|
18
|
+
* ADR-004 leaves `signature` optional and no signing/verification infrastructure exists anywhere
|
|
19
|
+
* in this codebase yet (confirmed: ADR-023 §6 itself says the same — "track (a) will rarely fire
|
|
20
|
+
* ... track (b) is the load-bearing path" — this is the intended, honest degraded behavior, not
|
|
21
|
+
* an unfinished shortcut).
|
|
22
|
+
*/
|
|
23
|
+
import { sql } from "kysely";
|
|
24
|
+
import { columnTypeSql } from "../kernel/index.js";
|
|
25
|
+
import { pluginKernel } from "./plugin-store.js";
|
|
26
|
+
export async function ensurePluginIdentityTable({ store }, _optional = {}) {
|
|
27
|
+
const kernel = pluginKernel({ store });
|
|
28
|
+
const text = sql.raw(columnTypeSql(kernel.dialect, "TEXT"));
|
|
29
|
+
await kernel.execute(sql `CREATE TABLE IF NOT EXISTS _plugin_identity (
|
|
30
|
+
plugin_id ${text} PRIMARY KEY,
|
|
31
|
+
source_url ${text} NOT NULL,
|
|
32
|
+
publisher ${text} NOT NULL,
|
|
33
|
+
signature ${text},
|
|
34
|
+
minted_at ${sql.raw(columnTypeSql(kernel.dialect, "INTEGER"))} NOT NULL
|
|
35
|
+
)`);
|
|
36
|
+
}
|
|
37
|
+
export async function getPluginIdentity(required, _optional = {}) {
|
|
38
|
+
const { pluginId } = required;
|
|
39
|
+
const row = await pluginKernel({ store: required.db }).run((db) => db
|
|
40
|
+
.selectFrom("_plugin_identity")
|
|
41
|
+
.select(["plugin_id", "source_url", "publisher", "signature", "minted_at"])
|
|
42
|
+
.where("plugin_id", "=", pluginId)
|
|
43
|
+
.executeTakeFirst());
|
|
44
|
+
if (!row)
|
|
45
|
+
return null;
|
|
46
|
+
return {
|
|
47
|
+
pluginId: row.plugin_id,
|
|
48
|
+
provenance: { sourceUrl: row.source_url, publisher: row.publisher, ...(row.signature != null ? { signature: row.signature } : {}) },
|
|
49
|
+
mintedAt: Number(row.minted_at),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
/** First-write-wins. Never called again for a `pluginId` once minted (see `checkNamespaceAdoption`). */
|
|
53
|
+
async function mintPluginIdentity(kernel, pluginId, provenance) {
|
|
54
|
+
await kernel.run((db) => db
|
|
55
|
+
.insertInto("_plugin_identity")
|
|
56
|
+
.values({
|
|
57
|
+
plugin_id: pluginId,
|
|
58
|
+
source_url: provenance.sourceUrl,
|
|
59
|
+
publisher: provenance.publisher,
|
|
60
|
+
signature: provenance.signature ?? null,
|
|
61
|
+
minted_at: Date.now(),
|
|
62
|
+
})
|
|
63
|
+
.execute());
|
|
64
|
+
}
|
|
65
|
+
function provenanceEqual(a, b) {
|
|
66
|
+
if (a.sourceUrl !== b.sourceUrl || a.publisher !== b.publisher)
|
|
67
|
+
return false;
|
|
68
|
+
return (a.signature ?? null) === (b.signature ?? null);
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Mints the identity record on first sight (always `allowed: true`). On a subsequent declare,
|
|
72
|
+
* applies the two-track rule. Does NOT mutate the identity record on anything but first mint —
|
|
73
|
+
* a provenance mismatch never silently overwrites the record on record (permanent retirement).
|
|
74
|
+
*/
|
|
75
|
+
export async function checkNamespaceAdoption(required, _optional = {}) {
|
|
76
|
+
const { pluginId, provenance } = required;
|
|
77
|
+
const kernel = pluginKernel({ store: required.db });
|
|
78
|
+
await ensurePluginIdentityTable({ store: kernel });
|
|
79
|
+
// Read-then-mint: the lock keeps two first declares of one plugin from both minting.
|
|
80
|
+
const existing = await kernel.transaction(async () => {
|
|
81
|
+
await kernel.lockKey(`plugin-identity:${pluginId}`);
|
|
82
|
+
const found = await getPluginIdentity({ db: kernel, pluginId });
|
|
83
|
+
if (!found)
|
|
84
|
+
await mintPluginIdentity(kernel, pluginId, provenance);
|
|
85
|
+
return found;
|
|
86
|
+
});
|
|
87
|
+
if (!existing)
|
|
88
|
+
return { allowed: true, track: "first-mint" };
|
|
89
|
+
if (provenanceEqual(existing.provenance, provenance)) {
|
|
90
|
+
return { allowed: true, track: "unchanged" };
|
|
91
|
+
}
|
|
92
|
+
if (existing.provenance.signature && provenance.signature && existing.provenance.signature === provenance.signature) {
|
|
93
|
+
return { allowed: true, track: "verified-signature" };
|
|
94
|
+
}
|
|
95
|
+
return {
|
|
96
|
+
allowed: false,
|
|
97
|
+
track: "consent-required",
|
|
98
|
+
reason: `pluginId '${pluginId}' has retained data from a previously-seen, provenance-mismatched artifact — explicit operator consent is required before adopting this namespace`,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
//# sourceMappingURL=plugin-identity.js.map
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { Generated } from "kysely";
|
|
2
|
+
import type { StorageKernel } from "../kernel/index.js";
|
|
3
|
+
/**
|
|
4
|
+
* @file The database a plugin data module works on: the storage kernel, whichever driver is
|
|
5
|
+
* underneath (ADR-066). The core's own `_plugin_*` bookkeeping tables are typed here; the plugins'
|
|
6
|
+
* own `p_{pluginId}__*` tables are declared at runtime and reached through raw kernel statements.
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* A composed kernel over ANY table typing (a `ContentKernel`, a `PluginKernel`…). `any`: a `Kysely<DB>` is invariant in
|
|
10
|
+
* `DB`, so no narrower type admits every kernel; the engine only reads its own tables through it.
|
|
11
|
+
*/
|
|
12
|
+
export type PluginStore = StorageKernel<any>;
|
|
13
|
+
export interface PluginCoreTables {
|
|
14
|
+
_plugin_migration_journal: {
|
|
15
|
+
id: Generated<number>;
|
|
16
|
+
plugin_id: string;
|
|
17
|
+
phase: string;
|
|
18
|
+
snapshot_path: string;
|
|
19
|
+
started_at: number;
|
|
20
|
+
updated_at: number;
|
|
21
|
+
};
|
|
22
|
+
_plugin_identity: {
|
|
23
|
+
plugin_id: string;
|
|
24
|
+
source_url: string;
|
|
25
|
+
publisher: string;
|
|
26
|
+
signature: string | null;
|
|
27
|
+
minted_at: number;
|
|
28
|
+
};
|
|
29
|
+
_plugin_migrations: {
|
|
30
|
+
id: Generated<number>;
|
|
31
|
+
plugin_id: string;
|
|
32
|
+
table_name: string;
|
|
33
|
+
ddl: string;
|
|
34
|
+
snapshot_path: string | null;
|
|
35
|
+
at: number;
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
export type PluginKernel = StorageKernel<PluginCoreTables>;
|
|
39
|
+
/** The composed kernel behind `store`, viewed through the plugin table contract. */
|
|
40
|
+
export declare function pluginKernel({ store }: {
|
|
41
|
+
store: PluginStore;
|
|
42
|
+
}, _optional?: Record<string, never>): PluginKernel;
|
|
43
|
+
//# sourceMappingURL=plugin-store.d.ts.map
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** The composed kernel behind `store`, viewed through the plugin table contract. */
|
|
2
|
+
export function pluginKernel({ store }, _optional = {}) {
|
|
3
|
+
// The type parameter only names the tables Kysely checks queries against; the kernel is the same.
|
|
4
|
+
return store;
|
|
5
|
+
}
|
|
6
|
+
//# sourceMappingURL=plugin-store.js.map
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file ADR-023 §4/§8 (T8 fix) — the restore half of the snapshot/restore pair.
|
|
3
|
+
*
|
|
4
|
+
* A plain file copy of the snapshot back over the live `content.db` (§4 — restore is a "different,
|
|
5
|
+
* less-safe operation" than the WAL-safe online-backup snapshot). Before releasing whatever lock
|
|
6
|
+
* guards this window, the caller must also clear the DDL attempt's own `-wal`/`-shm` sidecar
|
|
7
|
+
* files (T8) so no stale WAL frames get replayed against the restored (older) snapshot on next
|
|
8
|
+
* open.
|
|
9
|
+
*
|
|
10
|
+
* T2 scope note (exclusive cross-process lock): in this codebase's actual deployment topology
|
|
11
|
+
* (single Node process, single long-lived `better-sqlite3` connection per site — ADR-046's own
|
|
12
|
+
* "single-node remains target" line), restore only ever runs at BOOT-TIME recovery
|
|
13
|
+
* (`migration-recovery.ts`), before the app's long-lived connection is constructed and before any
|
|
14
|
+
* traffic is served. There is structurally no concurrent connection to quiesce at that point, so
|
|
15
|
+
* ADR-023 §4's exclusive-lock requirement is satisfied by the boot sequencing itself, not by an
|
|
16
|
+
* explicit `PRAGMA locking_mode=EXCLUSIVE` call here. If a future LIVE (mid-process) restore path
|
|
17
|
+
* is ever added, it MUST acquire that lock first — this file does not, and must not be reused for
|
|
18
|
+
* a live restore without adding it.
|
|
19
|
+
*
|
|
20
|
+
* SPEC-033 correction (2026-07-16): `data-module.ts`'s LIVE snapshot+DDL path used to acquire this
|
|
21
|
+
* same lock too, on the theory that it should be "held through the DDL attempt" per the ADR's own
|
|
22
|
+
* wording. Removed after a live multi-boot smoke test found it caused a real, deterministic
|
|
23
|
+
* "database is locked" failure against a genuine second connection (the store plugin's own
|
|
24
|
+
* dedicated `content.db` handle) — see `data-module.ts`'s file header for the full account. The
|
|
25
|
+
* reasoning above (restore never runs live) already meant the lock's ADR-stated justification
|
|
26
|
+
* ("Restore is a different, less-safe operation" — the snapshot/DDL steps are explicitly called
|
|
27
|
+
* out as safe without it) never applied to the live path either; this file was always the correct
|
|
28
|
+
* scope for where a live exclusive lock would matter, and the fix simply stopped taking it
|
|
29
|
+
* somewhere it never needed to be taken.
|
|
30
|
+
*/
|
|
31
|
+
import { copyFileSync, existsSync, rmSync } from "node:fs";
|
|
32
|
+
export function restoreFromSnapshot(required, _optional = {}) {
|
|
33
|
+
const { dbPath, snapshotPath } = required;
|
|
34
|
+
copyFileSync(snapshotPath, dbPath);
|
|
35
|
+
const walPath = `${dbPath}-wal`;
|
|
36
|
+
const shmPath = `${dbPath}-shm`;
|
|
37
|
+
if (existsSync(walPath))
|
|
38
|
+
rmSync(walPath);
|
|
39
|
+
if (existsSync(shmPath))
|
|
40
|
+
rmSync(shmPath);
|
|
41
|
+
}
|
|
42
|
+
//# sourceMappingURL=restore.js.map
|