@jini-ai/db 0.7.2 → 0.7.3-next.2
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 +1 -1
- package/README.md +33 -17
- package/dist/core/index.d.ts +1 -2
- package/dist/core/index.js +0 -1
- package/dist/core/pg-types.d.ts +4 -1
- package/dist/core/pg-types.js +1 -1
- package/dist/core/row-values.d.ts +0 -30
- package/dist/core/row-values.js +1 -41
- package/dist/data-modules/data-module.d.ts +260 -4
- package/dist/data-modules/data-module.js +105 -83
- package/dist/data-modules/disk-headroom.js +1 -1
- package/dist/data-modules/index.d.ts +2 -2
- package/dist/data-modules/index.js +2 -2
- package/dist/data-modules/migration-journal.js +6 -6
- package/dist/data-modules/migration-recovery.js +2 -2
- package/dist/data-modules/plugin-identity.js +5 -5
- package/dist/data-modules/plugin-store.d.ts +4 -4
- package/dist/data-modules/restore.js +5 -5
- package/dist/data-modules/snapshot.d.ts +1 -1
- package/dist/data-modules/snapshot.js +3 -3
- package/dist/events/change-set-repo.sql.d.ts +70 -0
- package/dist/events/change-set-repo.sql.js +72 -0
- package/dist/events/index.d.ts +4 -0
- package/dist/events/index.js +3 -0
- package/dist/events/outbox-repo.sql.d.ts +91 -0
- package/dist/events/outbox-repo.sql.js +108 -0
- package/dist/events/repo.rows.d.ts +44 -0
- package/dist/events/repo.rows.js +59 -0
- package/dist/gated-mutations/index.d.ts +3 -0
- package/dist/gated-mutations/index.js +2 -0
- package/dist/gated-mutations/repo.rows.d.ts +19 -0
- package/dist/gated-mutations/repo.rows.js +23 -0
- package/dist/gated-mutations/repo.sql.d.ts +67 -0
- package/dist/gated-mutations/repo.sql.js +71 -0
- package/dist/kernel/dialect.d.ts +53 -31
- package/dist/kernel/dialect.js +14 -36
- package/dist/kernel/index.d.ts +2 -2
- package/dist/kernel/index.js +1 -7
- package/dist/kernel/kernel-core.d.ts +7 -3
- package/dist/kernel/kernel-core.js +75 -66
- package/dist/kernel/ops.d.ts +9 -3
- package/dist/kernel/ops.js +2 -2
- package/dist/kernel/owned-transaction.d.ts +7 -7
- package/dist/kernel/owned-transaction.js +2 -2
- package/dist/kernel/pglite/driver.d.ts +2 -2
- package/dist/kernel/pglite/driver.js +18 -18
- package/dist/kernel/pglite/ops.d.ts +8 -3
- package/dist/kernel/pglite/ops.js +5 -5
- package/dist/kernel/port.d.ts +9 -76
- package/dist/kernel/port.js +1 -10
- package/dist/kernel/postgres/driver.d.ts +4 -2
- package/dist/kernel/postgres/driver.js +17 -17
- package/dist/kernel/postgres/ops.d.ts +5 -3
- package/dist/kernel/postgres/ops.js +3 -3
- package/dist/kernel/postgres/pglite-socket.d.ts +2 -2
- package/dist/kernel/postgres/pglite-socket.js +13 -13
- package/dist/kernel/schema-scope.d.ts +5 -2
- package/dist/kernel/schema-scope.js +1 -1
- package/dist/kernel/schema-shape.d.ts +7 -3
- package/dist/kernel/schema-shape.js +2 -2
- package/dist/kernel/session-lock.d.ts +6 -6
- package/dist/kernel/sqlite/driver.d.ts +16 -8
- package/dist/kernel/sqlite/driver.js +38 -38
- package/dist/kernel/sqlite/index.d.ts +1 -0
- package/dist/kernel/sqlite/index.js +1 -0
- package/dist/kernel/sqlite/ops.d.ts +4 -2
- package/dist/kernel/sqlite/ops.js +3 -3
- package/dist/kernel/sqlite/sqlite-only.d.ts +81 -0
- package/dist/kernel/sqlite/sqlite-only.js +58 -0
- package/dist/kernel/store-copy.d.ts +7 -7
- package/dist/kernel/store-copy.js +22 -14
- package/dist/kernel/typegen.d.ts +5 -3
- package/dist/kernel/typegen.js +1 -1
- package/dist/migrate/checksum.d.ts +3 -1
- package/dist/migrate/checksum.js +1 -1
- package/dist/migrate/index.d.ts +1 -1
- package/dist/migrate/legacy-ledger.d.ts +4 -4
- package/dist/migrate/runner.d.ts +12 -7
- package/dist/migrate/runner.js +7 -6
- package/dist/migrate/step.d.ts +3 -28
- package/dist/migrate/step.js +3 -3
- package/dist/owner-store/index.d.ts +47 -1
- package/dist/owner-store/index.js +28 -1
- package/dist/owner-store/migrations/0000_owner_store.d.ts +3 -2
- package/dist/owner-store/migrations/index.d.ts +1 -1
- package/dist/pglite/owner.d.ts +12 -4
- package/dist/pglite/owner.js +33 -27
- package/dist/pglite/socket-server.d.ts +5 -1
- package/dist/pglite/socket-server.js +5 -4
- package/dist/recovery/deep-link.d.ts +3 -3
- package/dist/recovery/degraded-banners.d.ts +3 -3
- package/dist/recovery/degraded-banners.js +3 -3
- package/dist/recovery/disclosure.d.ts +6 -6
- package/dist/recovery/disclosure.js +6 -6
- package/dist/recovery/evaluate-boot-migration-policy.d.ts +5 -5
- package/dist/recovery/evaluate-boot-migration-policy.js +5 -5
- package/dist/recovery/lookup-adapters.d.ts +1 -1
- package/dist/recovery/lookup-adapters.js +1 -1
- package/dist/recovery/migrate-forward-execute.d.ts +1 -1
- package/dist/recovery/migrate-forward-execute.js +5 -5
- package/dist/recovery/migrate-forward-hooks.d.ts +6 -6
- package/dist/recovery/migrate-forward-hooks.js +5 -5
- package/dist/recovery/operation-lock.d.ts +11 -11
- package/dist/recovery/operation-lock.js +3 -3
- package/dist/recovery/reconcile-interrupted-migration.d.ts +7 -7
- package/dist/recovery/reconcile-interrupted-migration.js +7 -7
- package/dist/recovery/recovery-orchestrator.d.ts +21 -21
- package/dist/recovery/recovery-orchestrator.js +9 -9
- package/dist/recovery/restore-hooks.d.ts +8 -8
- package/dist/recovery/restore-hooks.js +7 -7
- package/dist/recovery/restore-point-create.d.ts +3 -3
- package/dist/secrets-vault/repo.sql.d.ts +3 -3
- package/dist/secrets-vault/repo.sql.js +5 -4
- package/dist/settings/index.d.ts +3 -0
- package/dist/settings/index.js +2 -0
- package/dist/settings/repo.rows.d.ts +117 -0
- package/dist/settings/repo.rows.js +106 -0
- package/dist/settings/repo.sql.d.ts +99 -0
- package/dist/settings/repo.sql.js +219 -0
- package/dist/sqlite/checked-client.d.ts +1 -1
- package/dist/sqlite/checked-state.d.ts +3 -3
- package/dist/sqlite/db-ops.d.ts +1 -1
- package/dist/sqlite/db-ops.js +1 -1
- package/dist/sqlite/index.d.ts +1 -3
- package/dist/sqlite/index.js +2 -0
- package/dist/sqlite/inspect.d.ts +2 -2
- package/dist/sqlite/inspect.js +1 -1
- package/dist/sqlite/open.d.ts +1 -2
- package/dist/sqlite/stopped.d.ts +46 -0
- package/dist/sqlite/stopped.js +86 -0
- package/dist/sqlite/transaction.d.ts +2 -2
- package/dist/tools/database-catalog.d.ts +2 -2
- package/dist/tools/database-catalog.js +13 -3
- package/dist/tools/read-tools.js +70 -59
- package/dist/tools/restore-points.d.ts +1 -1
- package/dist/tools/transfer-tools.d.ts +0 -1
- package/dist/tools/transfer-tools.js +5 -4
- package/dist/transfer/copy-engine.js +10 -10
- package/dist/transfer/copy-order.d.ts +47 -0
- package/dist/transfer/copy-order.js +103 -0
- package/dist/transfer/index.d.ts +1 -0
- package/dist/transfer/index.js +1 -0
- package/dist/transfer/internal-ddl.d.ts +28 -6
- package/dist/transfer/internal-ddl.js +15 -15
- package/dist/transfer/postgres-ddl.js +6 -6
- package/dist/transfer/sqlite-source.d.ts +2 -3
- package/dist/transfer/sqlite-source.js +1 -1
- package/dist/verified-origin/index.d.ts +4 -0
- package/dist/verified-origin/index.js +3 -0
- package/dist/verified-origin/register.d.ts +43 -0
- package/dist/verified-origin/register.js +51 -0
- package/dist/verified-origin/repo.rows.d.ts +42 -0
- package/dist/verified-origin/repo.rows.js +47 -0
- package/dist/verified-origin/repo.sql.d.ts +67 -0
- package/dist/verified-origin/repo.sql.js +34 -0
- package/package.json +39 -12
- package/dist/sqlite/restore-types.d.ts +0 -46
- package/dist/sqlite/restore-types.js +0 -2
- package/dist/sqlite/sync-types.d.ts +0 -34
- package/dist/sqlite/sync-types.js +0 -2
- package/dist/sqlite/types.d.ts +0 -37
- package/dist/sqlite/types.js +0 -8
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @file The core-mediated plugin dataModule engine
|
|
2
|
+
* @file The core-mediated plugin dataModule engine.
|
|
3
3
|
*
|
|
4
4
|
* A plugin DECLARES its desired tables as data; CORE alone executes the DDL. A plugin never
|
|
5
5
|
* authors a migration and never holds a raw DB handle. The flow, in order:
|
|
@@ -211,8 +211,8 @@
|
|
|
211
211
|
* in the other direction (the same principle `discardCommittedSnapshot` already documents: "must
|
|
212
212
|
* not turn a successful migration into a reported failure").
|
|
213
213
|
*
|
|
214
|
-
* T2 (
|
|
215
|
-
* (2026-07-16), superseding
|
|
214
|
+
* T2 (the exclusive cross-process lock) is DELIBERATELY NOT acquired here — correction
|
|
215
|
+
* (2026-07-16), superseding the original implementation. The original design scopes T2's
|
|
216
216
|
* purpose narrowly: "The SQLite online backup API is safe under concurrent writers during
|
|
217
217
|
* snapshot creation — that step needs no change here. Restore is a different, less-safe
|
|
218
218
|
* operation" — the lock exists to guard RESTORE, not the live snapshot+DDL window. `restore.ts`'s
|
|
@@ -221,7 +221,7 @@
|
|
|
221
221
|
* any other connection exists) — so T2's stated danger literally cannot occur here. Holding a
|
|
222
222
|
* real `PRAGMA locking_mode=EXCLUSIVE` during the live window instead caused a genuine,
|
|
223
223
|
* deterministic production bug: a live multi-boot smoke test against the real server found the
|
|
224
|
-
* store plugin's own separate `content.db` connection (`store
|
|
224
|
+
* store plugin's own separate `content.db` connection (`store plugin bootstrap`) failing
|
|
225
225
|
* boot with "database is locked" every time, confirmed via A/B testing (disabling the lock calls
|
|
226
226
|
* made the failure disappear immediately) — the exact interleaving mechanism was not fully
|
|
227
227
|
* root-caused (multiple fire-and-forget dataModule declares and other writers share one
|
|
@@ -230,12 +230,12 @@
|
|
|
230
230
|
* ADR-stated justification doesn't apply here, rather than debugging a specific interleaving
|
|
231
231
|
* further, is the correct call.
|
|
232
232
|
*
|
|
233
|
-
*
|
|
233
|
+
* The dataModule design is ACCEPTED (2026-07-11) after a 3-round external audit whose T1-T8 findings are now
|
|
234
234
|
* ALL reflected in code across this file, `migration-journal.ts`, `disk-headroom.ts`,
|
|
235
|
-
* `plugin-identity.ts`, `migration-recovery.ts`, and `restore.ts` — see
|
|
236
|
-
* full record of which finding lives where. This engine exists ahead of
|
|
235
|
+
* `plugin-identity.ts`, `migration-recovery.ts`, and `restore.ts` — see the original specs for the
|
|
236
|
+
* full record of which finding lives where. This engine exists ahead of the "v1 ships seams
|
|
237
237
|
* only" schedule: §12's own last line permits shipping it early "against a concrete demand
|
|
238
|
-
* plugin," and Newsletter (
|
|
238
|
+
* plugin," and Newsletter (a host module) is exactly that — a real
|
|
239
239
|
* production consumer already calling this engine before this file's safety mechanics existed.
|
|
240
240
|
*
|
|
241
241
|
* STORAGE KERNEL (2026-09-28, storage plan P1): the engine runs on the storage kernel, so the same
|
|
@@ -249,9 +249,10 @@
|
|
|
249
249
|
*
|
|
250
250
|
* NOTE (§0 access-control caveat): a Tier-3 in-process plugin could bypass this by opening the db
|
|
251
251
|
* file directly. The RECOVERABILITY guarantee here (who snapshots + who runs DDL = core) holds
|
|
252
|
-
* unconditionally for core-mediated DDL; the access-control framing is advisory until
|
|
253
|
-
* Rung 2 (capability sandbox) ships — see
|
|
252
|
+
* unconditionally for core-mediated DDL; the access-control framing is advisory until
|
|
253
|
+
* Rung 2 (capability sandbox) ships — see the original design for the full, precise wording.
|
|
254
254
|
*/
|
|
255
|
+
import { createConsoleLogger } from "@jini-ai/core/primitives";
|
|
255
256
|
import { statSync } from "node:fs";
|
|
256
257
|
import { sql } from "kysely";
|
|
257
258
|
import { autoIdColumnSql, columnTypeSql, listColumns, listIndexes, listTables, } from "../kernel/index.js";
|
|
@@ -375,7 +376,7 @@ function validate(decl) {
|
|
|
375
376
|
* SQLite). The same text is what `_plugin_migrations.ddl` records.
|
|
376
377
|
*/
|
|
377
378
|
function columnSql(kernel, col) {
|
|
378
|
-
let ddl = `"${col.name}" ${columnTypeSql(kernel.dialect, col.type)}`;
|
|
379
|
+
let ddl = `"${col.name}" ${columnTypeSql({ dialect: kernel.dialect, affinity: col.type })}`;
|
|
379
380
|
if (col.primaryKey)
|
|
380
381
|
ddl += " PRIMARY KEY";
|
|
381
382
|
if (col.notNull)
|
|
@@ -392,30 +393,30 @@ function indexSql(fqTableName, idx) {
|
|
|
392
393
|
const columns = idx.columns.map((c) => `"${c}"`).join(", ");
|
|
393
394
|
return { indexName, sql: `CREATE ${unique}INDEX "${indexName}" ON "${fqTableName}" (${columns})` };
|
|
394
395
|
}
|
|
395
|
-
/** Core's own migration timeline, extended to admit plugin entries later
|
|
396
|
+
/** Core's own migration timeline, extended to admit plugin entries later. */
|
|
396
397
|
async function ensureJournal(kernel) {
|
|
397
|
-
const text = sql.raw(columnTypeSql(kernel.dialect, "TEXT"));
|
|
398
|
+
const text = sql.raw(columnTypeSql({ dialect: kernel.dialect, affinity: "TEXT" }));
|
|
398
399
|
await kernel.execute(sql `CREATE TABLE IF NOT EXISTS _plugin_migrations (
|
|
399
|
-
id ${sql.raw(autoIdColumnSql(kernel.dialect))},
|
|
400
|
+
id ${sql.raw(autoIdColumnSql({ dialect: kernel.dialect }))},
|
|
400
401
|
plugin_id ${text} NOT NULL,
|
|
401
402
|
table_name ${text} NOT NULL,
|
|
402
403
|
ddl ${text} NOT NULL,
|
|
403
404
|
snapshot_path ${text},
|
|
404
|
-
at ${sql.raw(columnTypeSql(kernel.dialect, "INTEGER"))} NOT NULL
|
|
405
|
+
at ${sql.raw(columnTypeSql({ dialect: kernel.dialect, affinity: "INTEGER" }))} NOT NULL
|
|
405
406
|
)`);
|
|
406
407
|
}
|
|
407
408
|
async function existingTables(kernel, names) {
|
|
408
409
|
if (names.length === 0)
|
|
409
410
|
return new Set();
|
|
410
411
|
const wanted = new Set(names);
|
|
411
|
-
return new Set((await listTables(kernel)).filter((name) => wanted.has(name)));
|
|
412
|
+
return new Set((await listTables({ kernel })).filter((name) => wanted.has(name)));
|
|
412
413
|
}
|
|
413
414
|
/**
|
|
414
415
|
* Reads `fqTableName`'s live column shape through the kernel's `listColumns` (SQLite:
|
|
415
416
|
* `pragma_table_info`, whose ordinal `pk` it already reads as "is part of the primary key").
|
|
416
417
|
*/
|
|
417
418
|
async function getExistingColumns(kernel, fqTableName) {
|
|
418
|
-
const columns = await listColumns(kernel, fqTableName);
|
|
419
|
+
const columns = await listColumns({ kernel, table: fqTableName });
|
|
419
420
|
return new Map(columns.map((c) => [c.name, { type: c.type, notNull: c.notNull, primaryKey: c.primaryKey }]));
|
|
420
421
|
}
|
|
421
422
|
/**
|
|
@@ -447,7 +448,7 @@ function planMissingColumn(tableName, col) {
|
|
|
447
448
|
*/
|
|
448
449
|
function assertColumnTypeMatches(kernel, tableName, col, existingCol) {
|
|
449
450
|
// Type names compare case-insensitively (SQLite's own rule): `listColumns` reports lower case.
|
|
450
|
-
if (existingCol.type === columnTypeSql(kernel.dialect, col.type).toLowerCase())
|
|
451
|
+
if (existingCol.type === columnTypeSql({ dialect: kernel.dialect, affinity: col.type }).toLowerCase())
|
|
451
452
|
return;
|
|
452
453
|
throw new DeclError("COLUMN_TYPE_MISMATCH", `table ${tableName} column "${col.name}" is declared ${col.type} but the live column is ` +
|
|
453
454
|
`${existingCol.type.toUpperCase()}. Changing a column's type needs a table rebuild, which this engine ` +
|
|
@@ -528,7 +529,7 @@ function indexMatches(idx, existing) {
|
|
|
528
529
|
* indexes) were never declared through `IndexDecl` or created by this module's own `indexSql`.
|
|
529
530
|
*/
|
|
530
531
|
async function planIndexReconciliation(kernel, table, fqTableName) {
|
|
531
|
-
const existingIndexes = await listIndexes(kernel, fqTableName);
|
|
532
|
+
const existingIndexes = await listIndexes({ kernel, table: fqTableName });
|
|
532
533
|
const indexesToAdd = [];
|
|
533
534
|
const indexesToRecreate = [];
|
|
534
535
|
for (const idx of table.indexes ?? []) {
|
|
@@ -581,7 +582,7 @@ async function recordMigration(kernel, pluginId, objectName, ddl, snapshotPath,
|
|
|
581
582
|
* only covers the alter path this fix adds, matching `missingColumns`'s scope one level up.
|
|
582
583
|
*/
|
|
583
584
|
async function verifyAlteredIndexes(kernel, alteration) {
|
|
584
|
-
const nowExistingIndexes = await listIndexes(kernel, alteration.fqTableName);
|
|
585
|
+
const nowExistingIndexes = await listIndexes({ kernel, table: alteration.fqTableName });
|
|
585
586
|
const declaredIndexes = [...alteration.indexesToAdd, ...alteration.indexesToRecreate];
|
|
586
587
|
return declaredIndexes
|
|
587
588
|
.map((idx) => indexSql(alteration.fqTableName, idx).indexName)
|
|
@@ -731,6 +732,83 @@ async function finishCommittedMigration({ kernel, journalId, snapshotPath }, _op
|
|
|
731
732
|
// Best-effort only — see the comment above. The migration itself already succeeded.
|
|
732
733
|
}
|
|
733
734
|
}
|
|
735
|
+
/** The SQLite file this connection really has open, warning when the configured path names another file.
|
|
736
|
+
* Unchanged for an in-memory path or a Postgres/PGlite kernel. */
|
|
737
|
+
async function resolveOpenDbPath({ kernel, dbPath, logger, pluginId }, _optional = {}) {
|
|
738
|
+
let openDbPath = dbPath;
|
|
739
|
+
if (kernel.dialect === "sqlite" && !isInMemoryDbPath({ dbPath })) {
|
|
740
|
+
const [main] = await kernel.query(sql `SELECT file FROM pragma_database_list WHERE name = 'main'`);
|
|
741
|
+
openDbPath = main?.file || ":memory:";
|
|
742
|
+
warnIfNotOpenFile({ dbPath, openFile: main?.file, logger, pluginId });
|
|
743
|
+
}
|
|
744
|
+
return openDbPath;
|
|
745
|
+
}
|
|
746
|
+
/** File identity is the filesystem's (dev, ino); a configured path naming another file warns and never blocks the install. */
|
|
747
|
+
function warnIfNotOpenFile({ dbPath, openFile, logger, pluginId }, _optional = {}) {
|
|
748
|
+
const named = statSync(dbPath, { throwIfNoEntry: false });
|
|
749
|
+
const open = openFile ? statSync(openFile, { throwIfNoEntry: false }) : undefined;
|
|
750
|
+
if (!named || !open || named.dev !== open.dev || named.ino !== open.ino) {
|
|
751
|
+
// Paths are left out of the line (they can name private locations); the plugin id says which one.
|
|
752
|
+
logger.warn({ message: `${pluginId}: the configured database path is not the database this connection has open (${openFile ? "another file is open" : "an in-memory database is open"}). Its tables are installed in the open database, and the safety snapshot and disk-space check use it too. Fix the configured database path.` });
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
/** Run all DDL for the plan in one transaction; any throw rolls it back and is reported as DDL_FAILED. */
|
|
756
|
+
async function applyPlanAtomically({ kernel, decl, plan, journalId, snapshotPath, logger }) {
|
|
757
|
+
const created = [];
|
|
758
|
+
const altered = [];
|
|
759
|
+
try {
|
|
760
|
+
await advancePhaseIfJournaled(kernel, journalId, "DDL_IN_PROGRESS");
|
|
761
|
+
// One transaction for ALL DDL — new tables, column additions, and index add/recreate on
|
|
762
|
+
// existing tables — PLUS the post-DDL verification AND the journal's own COMMITTED write (this
|
|
763
|
+
// file's header comment, POST-COMMIT DATA-LOSS WINDOW). Folding all four into one atomic unit
|
|
764
|
+
// is what makes "the DDL committed" and "the journal says COMMITTED" the same fact: either this
|
|
765
|
+
// whole callback returns and every one of those things is durably true together, or it throws
|
|
766
|
+
// and the kernel rolls every one of them back together (§9).
|
|
767
|
+
await kernel.transaction(async () => {
|
|
768
|
+
await ensureJournal(kernel);
|
|
769
|
+
const at = Date.now();
|
|
770
|
+
for (const table of plan.toCreate)
|
|
771
|
+
created.push(await applyTableCreate(kernel, decl.pluginId, table, snapshotPath, at));
|
|
772
|
+
for (const alteration of plan.toAlter) {
|
|
773
|
+
await applyTableAlteration(kernel, decl.pluginId, alteration, snapshotPath, at);
|
|
774
|
+
altered.push(alteration.fqTableName);
|
|
775
|
+
}
|
|
776
|
+
const problems = await verifyPostDdl(kernel, decl, plan);
|
|
777
|
+
if (problems.length > 0) {
|
|
778
|
+
throw new Error(`post-DDL verification failed: ${problems.join(", ")} not found after DDL`);
|
|
779
|
+
}
|
|
780
|
+
await stagePhaseIfJournaled(kernel, journalId, "COMMITTED");
|
|
781
|
+
});
|
|
782
|
+
}
|
|
783
|
+
catch (err) {
|
|
784
|
+
// `kernel.transaction()` above threw — DDL, verification, and the in-transaction "COMMITTED" write
|
|
785
|
+
// are now one atomic unit, so the transaction's own rollback really did undo ALL of them; the
|
|
786
|
+
// live db is unchanged and working (same-process, catchable-failure case — no restore needed,
|
|
787
|
+
// restore only ever runs at next-boot recovery for a CRASH, see migration-recovery.ts).
|
|
788
|
+
// `ROLLED_BACK` is therefore always truthful here now (this file's header comment, POST-COMMIT
|
|
789
|
+
// DATA-LOSS WINDOW) — there is no remaining case where this catch fires with the DDL actually
|
|
790
|
+
// live. The snapshot remains as the named recovery point (§9) for operator forensics; for an
|
|
791
|
+
// in-memory db, `snapshotPath`/`journalId` are both null (see above) — the same-process
|
|
792
|
+
// rollback just performed IS the full recovery, no crash-recovery boot path can ever exist for
|
|
793
|
+
// `:memory:` to need one.
|
|
794
|
+
await advancePhaseIfJournaled(kernel, journalId, "ROLLED_BACK");
|
|
795
|
+
// The native DDL error goes to the reporter only; the result names the plugin and the rollback.
|
|
796
|
+
const error = reportedFailure({ code: "DDL_FAILED", message: `The tables for plugin ${decl.pluginId} could not be created or altered; the change was rolled back.`, err, logger });
|
|
797
|
+
return { ok: false, created: [], altered: [], snapshotPath, recoveryPoint: snapshotPath ?? undefined, error };
|
|
798
|
+
}
|
|
799
|
+
return { ok: true, created, altered, snapshotPath };
|
|
800
|
+
}
|
|
801
|
+
/** A declaration refusal keeps its own text; anything else is reported and named without native text. */
|
|
802
|
+
function preflightError({ err, pluginId, logger }, _optional = {}) {
|
|
803
|
+
if (err instanceof DeclError)
|
|
804
|
+
return { code: err.code, message: err.message };
|
|
805
|
+
return reportedFailure({ code: "PREFLIGHT_FAILED", message: `The existing tables for plugin ${pluginId} could not be read, so nothing was changed.`, err, logger });
|
|
806
|
+
}
|
|
807
|
+
/** Sends the native error to the reporter and returns only the plain-words answer. */
|
|
808
|
+
function reportedFailure({ code, message, err, logger }, _optional = {}) {
|
|
809
|
+
logger.error({ message }, { error: err });
|
|
810
|
+
return { code, message };
|
|
811
|
+
}
|
|
734
812
|
/**
|
|
735
813
|
* Declare (reconcile) a plugin's tables. Core snapshots first, then runs the DDL transactionally.
|
|
736
814
|
*
|
|
@@ -743,7 +821,7 @@ async function finishCommittedMigration({ kernel, journalId, snapshotPath }, _op
|
|
|
743
821
|
* file's path still snapshots `db`, but beside that file, and sizes headroom from that file.
|
|
744
822
|
* `decl.provenance` is checked against the stored identity row; see {@link PluginProvenance}.
|
|
745
823
|
*/
|
|
746
|
-
export async function declareDataModule(required, { checkHeadroom = ({ dbPath }, _optional = {}) => checkDiskHeadroom({ dbPath }) } = {}) {
|
|
824
|
+
export async function declareDataModule(required, { checkHeadroom = ({ dbPath }, _optional = {}) => checkDiskHeadroom({ dbPath }), report: logger = createConsoleLogger({ prefix: "[data-module]" }) } = {}) {
|
|
747
825
|
const { dbPath, decl } = required;
|
|
748
826
|
const kernel = pluginKernel({ store: required.db });
|
|
749
827
|
let plan;
|
|
@@ -758,8 +836,7 @@ export async function declareDataModule(required, { checkHeadroom = ({ dbPath },
|
|
|
758
836
|
plan = await planReconciliation(kernel, decl, existing);
|
|
759
837
|
}
|
|
760
838
|
catch (err) {
|
|
761
|
-
|
|
762
|
-
return { ok: false, created: [], altered: [], snapshotPath: null, error: { code: e.code, message: e.message } };
|
|
839
|
+
return { ok: false, created: [], altered: [], snapshotPath: null, error: preflightError({ err, pluginId: decl.pluginId, logger }) };
|
|
763
840
|
}
|
|
764
841
|
if (plan.toCreate.length + plan.toAlter.length === 0) {
|
|
765
842
|
return { ok: true, created: [], altered: [], snapshotPath: null }; // idempotent no-op — nothing to snapshot
|
|
@@ -769,16 +846,7 @@ export async function declareDataModule(required, { checkHeadroom = ({ dbPath },
|
|
|
769
846
|
// The snapshot, its boot restore and the headroom check bind to the file this connection has open,
|
|
770
847
|
// not to the named path. Identity is the filesystem's (dev, ino): two paths (a second bind mount,
|
|
771
848
|
// a hard link) can name one file. A path naming another file warns and never blocks the install.
|
|
772
|
-
|
|
773
|
-
if (kernel.dialect === "sqlite" && !isInMemoryDbPath({ dbPath })) {
|
|
774
|
-
const [main] = await kernel.query(sql `SELECT file FROM pragma_database_list WHERE name = 'main'`);
|
|
775
|
-
openDbPath = main?.file || ":memory:";
|
|
776
|
-
const named = statSync(dbPath, { throwIfNoEntry: false });
|
|
777
|
-
const open = main?.file ? statSync(main.file, { throwIfNoEntry: false }) : undefined;
|
|
778
|
-
if (!named || !open || named.dev !== open.dev || named.ino !== open.ino) {
|
|
779
|
-
console.warn(`[data-module] ${decl.pluginId}: ${dbPath} is not the database this connection has open (${main?.file || "an in-memory database"}). Its tables are installed in the open database, and the safety snapshot and disk-space check use it too. Fix the configured database path.`);
|
|
780
|
-
}
|
|
781
|
-
}
|
|
849
|
+
const openDbPath = await resolveOpenDbPath({ kernel, dbPath, logger, pluginId: decl.pluginId });
|
|
782
850
|
const recoverable = kernel.dialect === "sqlite" && !isInMemoryDbPath({ dbPath: openDbPath });
|
|
783
851
|
const preflight = await runPreflightChecks(kernel, openDbPath, decl, recoverable, checkHeadroom);
|
|
784
852
|
if (!preflight.ok) {
|
|
@@ -797,55 +865,9 @@ export async function declareDataModule(required, { checkHeadroom = ({ dbPath },
|
|
|
797
865
|
// (§9, the only failure mode a same-process in-memory db can ever hit) is unaffected and remains
|
|
798
866
|
// the complete safety net.
|
|
799
867
|
const journalId = await openJournalIfFileBacked(kernel, decl.pluginId, snapshotPath);
|
|
800
|
-
const
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
// One transaction for ALL DDL — new tables, column additions, and index add/recreate on
|
|
805
|
-
// existing tables — PLUS the post-DDL verification AND the journal's own COMMITTED write (this
|
|
806
|
-
// file's header comment, POST-COMMIT DATA-LOSS WINDOW). Folding all four into one atomic unit
|
|
807
|
-
// is what makes "the DDL committed" and "the journal says COMMITTED" the same fact: either this
|
|
808
|
-
// whole callback returns and every one of those things is durably true together, or it throws
|
|
809
|
-
// and the kernel rolls every one of them back together (§9).
|
|
810
|
-
await kernel.transaction(async () => {
|
|
811
|
-
await ensureJournal(kernel);
|
|
812
|
-
const at = Date.now();
|
|
813
|
-
for (const table of plan.toCreate)
|
|
814
|
-
created.push(await applyTableCreate(kernel, decl.pluginId, table, snapshotPath, at));
|
|
815
|
-
for (const alteration of plan.toAlter) {
|
|
816
|
-
await applyTableAlteration(kernel, decl.pluginId, alteration, snapshotPath, at);
|
|
817
|
-
altered.push(alteration.fqTableName);
|
|
818
|
-
}
|
|
819
|
-
const problems = await verifyPostDdl(kernel, decl, plan);
|
|
820
|
-
if (problems.length > 0) {
|
|
821
|
-
throw new Error(`post-DDL verification failed: ${problems.join(", ")} not found after DDL`);
|
|
822
|
-
}
|
|
823
|
-
await stagePhaseIfJournaled(kernel, journalId, "COMMITTED");
|
|
824
|
-
});
|
|
825
|
-
}
|
|
826
|
-
catch (err) {
|
|
827
|
-
// `kernel.transaction()` above threw — DDL, verification, and the in-transaction "COMMITTED" write
|
|
828
|
-
// are now one atomic unit, so the transaction's own rollback really did undo ALL of them; the
|
|
829
|
-
// live db is unchanged and working (same-process, catchable-failure case — no restore needed,
|
|
830
|
-
// restore only ever runs at next-boot recovery for a CRASH, see migration-recovery.ts).
|
|
831
|
-
// `ROLLED_BACK` is therefore always truthful here now (this file's header comment, POST-COMMIT
|
|
832
|
-
// DATA-LOSS WINDOW) — there is no remaining case where this catch fires with the DDL actually
|
|
833
|
-
// live. The snapshot remains as the named recovery point (§9) for operator forensics; for an
|
|
834
|
-
// in-memory db, `snapshotPath`/`journalId` are both null (see above) — the same-process
|
|
835
|
-
// rollback just performed IS the full recovery, no crash-recovery boot path can ever exist for
|
|
836
|
-
// `:memory:` to need one.
|
|
837
|
-
await advancePhaseIfJournaled(kernel, journalId, "ROLLED_BACK");
|
|
838
|
-
const e = err;
|
|
839
|
-
return {
|
|
840
|
-
ok: false,
|
|
841
|
-
created: [],
|
|
842
|
-
altered: [],
|
|
843
|
-
snapshotPath,
|
|
844
|
-
recoveryPoint: snapshotPath ?? undefined,
|
|
845
|
-
error: { code: "DDL_FAILED", message: e.message },
|
|
846
|
-
};
|
|
847
|
-
}
|
|
848
|
-
await finishCommittedMigration({ kernel, journalId, snapshotPath });
|
|
849
|
-
return { ok: true, created, altered, snapshotPath };
|
|
868
|
+
const applied = await applyPlanAtomically({ kernel, decl, plan, journalId, snapshotPath, logger });
|
|
869
|
+
if (applied.ok)
|
|
870
|
+
await finishCommittedMigration({ kernel, journalId, snapshotPath });
|
|
871
|
+
return applied;
|
|
850
872
|
}
|
|
851
873
|
//# sourceMappingURL=data-module.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @file
|
|
2
|
+
* @file Disk-headroom preflight (T4 fix). Before any snapshot, core computes
|
|
3
3
|
* `required = 1.5 x (current DB file size + WAL file size)`. If free disk space on the volume
|
|
4
4
|
* holding `content.db` is below that, the dataModule operation fails closed before any file is
|
|
5
5
|
* touched.
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @file Public surface for the `plugins` feature. Deliberately narrow: only the
|
|
2
|
+
* @file Public surface for the `plugins` feature. Deliberately narrow: only the
|
|
3
3
|
* `dataModule` declaration contract that `comments` and `newsletter` both consume to register
|
|
4
4
|
* their own own-tables (`declareDataModule`, `DataModuleDecl`, `ColumnType`). Everything else
|
|
5
5
|
* under this directory (`lipay/`, `store/`, `migration-recovery.ts`) is reached
|
|
6
6
|
* only from the composition root or the assistant tool-catalog seam, which construct concrete
|
|
7
|
-
* implementations directly by design
|
|
7
|
+
* implementations directly by design — this barrel does not re-export them.
|
|
8
8
|
*/
|
|
9
9
|
export * from "./data-module.js";
|
|
10
10
|
export type { PluginStore as DataModuleStore } from "./plugin-store.js";
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @file Public surface for the `plugins` feature. Deliberately narrow: only the
|
|
2
|
+
* @file Public surface for the `plugins` feature. Deliberately narrow: only the
|
|
3
3
|
* `dataModule` declaration contract that `comments` and `newsletter` both consume to register
|
|
4
4
|
* their own own-tables (`declareDataModule`, `DataModuleDecl`, `ColumnType`). Everything else
|
|
5
5
|
* under this directory (`lipay/`, `store/`, `migration-recovery.ts`) is reached
|
|
6
6
|
* only from the composition root or the assistant tool-catalog seam, which construct concrete
|
|
7
|
-
* implementations directly by design
|
|
7
|
+
* implementations directly by design — this barrel does not re-export them.
|
|
8
8
|
*/
|
|
9
9
|
export * from "./data-module.js";
|
|
10
10
|
export * from "./migration-journal.js";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @file
|
|
2
|
+
* @file (T3 fix) — the durable, fsynced phase-marker journal for the dataModule
|
|
3
3
|
* engine. Every DDL attempt writes phase transitions here, in strict sequence:
|
|
4
4
|
* `PREPARED_SNAPSHOT → DDL_IN_PROGRESS → VERIFYING → COMMITTED` (success) or `→ ROLLED_BACK`
|
|
5
5
|
* (failure). Each transition is checkpointed (forced WAL fsync) before the corresponding DB
|
|
@@ -21,10 +21,10 @@ export function isIncompletePhase({ phase }, _optional = {}) {
|
|
|
21
21
|
}
|
|
22
22
|
export async function ensureMigrationJournal({ store }, _optional = {}) {
|
|
23
23
|
const kernel = pluginKernel({ store });
|
|
24
|
-
const integer = sql.raw(columnTypeSql(kernel.dialect, "INTEGER"));
|
|
25
|
-
const text = sql.raw(columnTypeSql(kernel.dialect, "TEXT"));
|
|
24
|
+
const integer = sql.raw(columnTypeSql({ dialect: kernel.dialect, affinity: "INTEGER" }));
|
|
25
|
+
const text = sql.raw(columnTypeSql({ dialect: kernel.dialect, affinity: "TEXT" }));
|
|
26
26
|
await kernel.execute(sql `CREATE TABLE IF NOT EXISTS _plugin_migration_journal (
|
|
27
|
-
id ${sql.raw(autoIdColumnSql(kernel.dialect))},
|
|
27
|
+
id ${sql.raw(autoIdColumnSql({ dialect: kernel.dialect }))},
|
|
28
28
|
plugin_id ${text} NOT NULL,
|
|
29
29
|
phase ${text} NOT NULL,
|
|
30
30
|
snapshot_path ${text} NOT NULL,
|
|
@@ -42,7 +42,7 @@ export async function beginJournalEntry(required, _optional = {}) {
|
|
|
42
42
|
.values({ plugin_id: pluginId, phase: "PREPARED_SNAPSHOT", snapshot_path: snapshotPath, started_at: now, updated_at: now })
|
|
43
43
|
.returning("id")
|
|
44
44
|
.executeTakeFirstOrThrow());
|
|
45
|
-
await checkpointWal(kernel);
|
|
45
|
+
await checkpointWal({ kernel });
|
|
46
46
|
return Number(row.id);
|
|
47
47
|
}
|
|
48
48
|
/**
|
|
@@ -68,7 +68,7 @@ export async function stageJournalPhase(required, _optional = {}) {
|
|
|
68
68
|
export async function advanceJournalPhase(required, _optional = {}) {
|
|
69
69
|
const kernel = pluginKernel({ store: required.db });
|
|
70
70
|
await stageJournalPhase({ db: kernel, id: required.id, phase: required.phase });
|
|
71
|
-
await checkpointWal(kernel);
|
|
71
|
+
await checkpointWal({ kernel });
|
|
72
72
|
}
|
|
73
73
|
/** Boot-time recovery scan (§2): any entry NOT in a terminal phase is a crash-interrupted attempt. */
|
|
74
74
|
export async function findIncompleteJournalEntries({ store }, _optional = {}) {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @file
|
|
2
|
+
* @file Boot-time crash recovery for the dataModule engine, on the storage kernel.
|
|
3
3
|
* The site opener calls {@link recoverIncompleteDataModuleMigrations} right after it opens the
|
|
4
4
|
* content database and before anything else reads it — before the SQLite migrations run.
|
|
5
5
|
*
|
|
@@ -37,7 +37,7 @@ const JOURNAL_TABLE = "_plugin_migration_journal";
|
|
|
37
37
|
*/
|
|
38
38
|
export async function recoverIncompleteDataModuleMigrations(required, _optional = {}) {
|
|
39
39
|
const kernel = pluginKernel({ store: required.store });
|
|
40
|
-
if (!(await tableExists(kernel, JOURNAL_TABLE)))
|
|
40
|
+
if (!(await tableExists({ kernel, table: JOURNAL_TABLE })))
|
|
41
41
|
return { recovered: 0, entries: [] };
|
|
42
42
|
const incomplete = await findIncompleteJournalEntries({ store: kernel });
|
|
43
43
|
if (incomplete.length === 0)
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @file
|
|
2
|
+
* @file Permanent plugin-ID retirement (T5 fix, round-2 revision) plus the
|
|
3
3
|
* two-track fail-closed namespace-adoption guard.
|
|
4
4
|
*
|
|
5
5
|
* A `pluginId` is permanently retired the moment it is first minted (this record is never
|
|
@@ -15,8 +15,8 @@
|
|
|
15
15
|
* surfaced here as a typed refusal, since no consent-prompt UI exists in this codebase yet.
|
|
16
16
|
*
|
|
17
17
|
* Signature verification here is a same-string comparison, not real cryptographic verification —
|
|
18
|
-
*
|
|
19
|
-
* in this codebase yet (confirmed:
|
|
18
|
+
* the original design leaves `signature` optional and no signing/verification infrastructure exists anywhere
|
|
19
|
+
* in this codebase yet (confirmed: the dataModule design says the same — "track (a) will rarely fire
|
|
20
20
|
* ... track (b) is the load-bearing path" — this is the intended, honest degraded behavior, not
|
|
21
21
|
* an unfinished shortcut).
|
|
22
22
|
*/
|
|
@@ -25,13 +25,13 @@ import { columnTypeSql } from "../kernel/index.js";
|
|
|
25
25
|
import { pluginKernel } from "./plugin-store.js";
|
|
26
26
|
export async function ensurePluginIdentityTable({ store }, _optional = {}) {
|
|
27
27
|
const kernel = pluginKernel({ store });
|
|
28
|
-
const text = sql.raw(columnTypeSql(kernel.dialect, "TEXT"));
|
|
28
|
+
const text = sql.raw(columnTypeSql({ dialect: kernel.dialect, affinity: "TEXT" }));
|
|
29
29
|
await kernel.execute(sql `CREATE TABLE IF NOT EXISTS _plugin_identity (
|
|
30
30
|
plugin_id ${text} PRIMARY KEY,
|
|
31
31
|
source_url ${text} NOT NULL,
|
|
32
32
|
publisher ${text} NOT NULL,
|
|
33
33
|
signature ${text},
|
|
34
|
-
minted_at ${sql.raw(columnTypeSql(kernel.dialect, "INTEGER"))} NOT NULL
|
|
34
|
+
minted_at ${sql.raw(columnTypeSql({ dialect: kernel.dialect, affinity: "INTEGER" }))} NOT NULL
|
|
35
35
|
)`);
|
|
36
36
|
}
|
|
37
37
|
export async function getPluginIdentity(required, _optional = {}) {
|
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
import type { Generated } from "kysely";
|
|
2
|
-
import type {
|
|
2
|
+
import type { KyselyKernel } from "../kernel/index.js";
|
|
3
3
|
/**
|
|
4
4
|
* @file The database a plugin data module works on: the storage kernel, whichever driver is
|
|
5
|
-
* underneath
|
|
5
|
+
* underneath. The core's own `_plugin_*` bookkeeping tables are typed here; the plugins'
|
|
6
6
|
* own `p_{pluginId}__*` tables are declared at runtime and reached through raw kernel statements.
|
|
7
7
|
*/
|
|
8
8
|
/**
|
|
9
9
|
* A composed kernel over ANY table typing (a `ContentKernel`, a `PluginKernel`…). `any`: a `Kysely<DB>` is invariant in
|
|
10
10
|
* `DB`, so no narrower type admits every kernel; the engine only reads its own tables through it.
|
|
11
11
|
*/
|
|
12
|
-
export type PluginStore =
|
|
12
|
+
export type PluginStore = KyselyKernel<any>;
|
|
13
13
|
export interface PluginCoreTables {
|
|
14
14
|
_plugin_migration_journal: {
|
|
15
15
|
id: Generated<number>;
|
|
@@ -35,7 +35,7 @@ export interface PluginCoreTables {
|
|
|
35
35
|
at: number;
|
|
36
36
|
};
|
|
37
37
|
}
|
|
38
|
-
export type PluginKernel =
|
|
38
|
+
export type PluginKernel = KyselyKernel<PluginCoreTables>;
|
|
39
39
|
/** The composed kernel behind `store`, viewed through the plugin table contract. */
|
|
40
40
|
export declare function pluginKernel({ store }: {
|
|
41
41
|
store: PluginStore;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @file
|
|
2
|
+
* @file The restore half of the snapshot/restore pair (T8 fix).
|
|
3
3
|
*
|
|
4
4
|
* A plain file copy of the snapshot back over the live `content.db` (§4 — restore is a "different,
|
|
5
5
|
* less-safe operation" than the WAL-safe online-backup snapshot). Before releasing whatever lock
|
|
@@ -8,17 +8,17 @@
|
|
|
8
8
|
* open.
|
|
9
9
|
*
|
|
10
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 —
|
|
11
|
+
* (single Node process, single long-lived `better-sqlite3` connection per site — the original design's own
|
|
12
12
|
* "single-node remains target" line), restore only ever runs at BOOT-TIME recovery
|
|
13
13
|
* (`migration-recovery.ts`), before the app's long-lived connection is constructed and before any
|
|
14
14
|
* traffic is served. There is structurally no concurrent connection to quiesce at that point, so
|
|
15
|
-
*
|
|
15
|
+
* the exclusive-lock requirement is satisfied by the boot sequencing itself, not by an
|
|
16
16
|
* explicit `PRAGMA locking_mode=EXCLUSIVE` call here. If a future LIVE (mid-process) restore path
|
|
17
17
|
* is ever added, it MUST acquire that lock first — this file does not, and must not be reused for
|
|
18
18
|
* a live restore without adding it.
|
|
19
19
|
*
|
|
20
|
-
*
|
|
21
|
-
* same lock too, on the theory that it should be "held through the DDL attempt" per the
|
|
20
|
+
* 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 original design's own
|
|
22
22
|
* wording. Removed after a live multi-boot smoke test found it caused a real, deterministic
|
|
23
23
|
* "database is locked" failure against a genuine second connection (the store plugin's own
|
|
24
24
|
* dedicated `content.db` handle) — see `data-module.ts`'s file header for the full account. The
|
|
@@ -31,7 +31,7 @@ export declare function snapshotDb(required: {
|
|
|
31
31
|
* AFTER the migration it guarded is already committed, so a failure to unlink is untidy, not
|
|
32
32
|
* unsafe, and must not turn a successful migration into a reported failure.
|
|
33
33
|
*
|
|
34
|
-
*
|
|
34
|
+
* Amendment (2026-08-02). The original design specified taking the snapshot but never said when one
|
|
35
35
|
* stops being needed, so nothing ever deleted them: every plugin that declared tables left a
|
|
36
36
|
* whole-database copy on disk permanently, three at a time for a stock install (`store`,
|
|
37
37
|
* `newsletter`, `comments`), each the full size of `content.db`.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @file SPIKE — whole-file snapshot before a schema change
|
|
2
|
+
* @file SPIKE — whole-file snapshot before a schema change.
|
|
3
3
|
*
|
|
4
4
|
* The never-brick reversibility anchor: core takes a whole-file snapshot via SQLite's ONLINE
|
|
5
5
|
* BACKUP API (not a raw `fs` copy — the backup API is WAL-safe on a live db) before ANY plugin
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* snapshot exists. Before this fix, `path.dirname(":memory:")` resolved to `"."` (the process's
|
|
15
15
|
* current working directory) and `path.basename(":memory:")` resolved to the literal string
|
|
16
16
|
* `":memory:"`, so every call against an in-memory test db (used pervasively by this repo's test
|
|
17
|
-
* suite, e.g.
|
|
17
|
+
* suite, e.g. a host module via `openContentDb(":memory:")`)
|
|
18
18
|
* wrote a REAL, non-empty SQLite backup file literally named `:memory:.snapshot-<label>-<ts>` into
|
|
19
19
|
* the repo root — hundreds of MB accumulated across a single session's test runs.
|
|
20
20
|
*/
|
|
@@ -68,7 +68,7 @@ export async function snapshotDb(required, _optional = {}) {
|
|
|
68
68
|
* AFTER the migration it guarded is already committed, so a failure to unlink is untidy, not
|
|
69
69
|
* unsafe, and must not turn a successful migration into a reported failure.
|
|
70
70
|
*
|
|
71
|
-
*
|
|
71
|
+
* Amendment (2026-08-02). The original design specified taking the snapshot but never said when one
|
|
72
72
|
* stops being needed, so nothing ever deleted them: every plugin that declared tables left a
|
|
73
73
|
* whole-database copy on disk permanently, three at a time for a stock install (`store`,
|
|
74
74
|
* `newsletter`, `comments`), each the full size of `content.db`.
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import type { Kysely } from "kysely";
|
|
2
|
+
import type { StorageKernel } from "@jini-ai/core/contracts/storage";
|
|
3
|
+
import type { DomainEvent, ChangeSetItemRecord, ChangeSetRecord, ChangeSetRepoPort, ChangeSetWithItems } from "@jini-ai/core/contracts/events";
|
|
4
|
+
/**
|
|
5
|
+
* @file Phase 1 — THE `ChangeSetRepoPort` adapter: one Kysely query body for every
|
|
6
|
+
* dialect (storage plan). Rule-of-two "second adapter" half;
|
|
7
|
+
* Jini `@jini-ai/cms/core/commands`'s `InMemoryChangeSetRepo` is the first.
|
|
8
|
+
* The host's binding is the thin class that builds it from the content db handle.
|
|
9
|
+
*
|
|
10
|
+
* Purpose:
|
|
11
|
+
* Change-set mutation history (the audit/undo trail) previously lived only in-memory in the
|
|
12
|
+
* real running server, lost on every restart — the original design's context names
|
|
13
|
+
* this explicitly as unacceptable for user-visible state. This adapter closes that gap.
|
|
14
|
+
*
|
|
15
|
+
* Transaction-participation scope (disclosed, deliberate): `insert()` writes the change-set header,
|
|
16
|
+
* its items, AND (BR-04 resolution, 2026-07-16 swarm debate — full record:
|
|
17
|
+
* `ADS-memory/reports/swarm-consensus/runs/20260716T-br04-outbox-seam-consensus-report.md`)
|
|
18
|
+
* its optional outbox event, as ONE atomic kernel transaction — none of the three rows can ever
|
|
19
|
+
* partially land. This does NOT extend to wrapping the *domain* mutation's own write in the same
|
|
20
|
+
* transaction as this repo's insert — `core/commands/command.ts`'s `executeCommand()` keeps its
|
|
21
|
+
* existing capture-then-compensating-rollback design unchanged for the domain write (Phase
|
|
22
|
+
* 1's own instruction for this row: "migrate existing local semantics without changing route
|
|
23
|
+
* contracts"). Unifying the domain write and this repo's write into one shared transaction would
|
|
24
|
+
* mean threading a transaction handle through every `CommandMutation.execute()` across the whole
|
|
25
|
+
* codebase — that is Phase 3 (composition-root rework) territory, not this row's job.
|
|
26
|
+
*
|
|
27
|
+
* Architectural role:
|
|
28
|
+
* Infrastructure adapter. `core/commands` never imports this file — it depends only on
|
|
29
|
+
* `ChangeSetRepoPort`; composition roots bind the concrete class.
|
|
30
|
+
*/
|
|
31
|
+
/** Host-owned table names. No schema or product table default lives in the adapter. */
|
|
32
|
+
export interface ChangeSetTables {
|
|
33
|
+
changeSets: string;
|
|
34
|
+
changeSetItems: string;
|
|
35
|
+
outboxEvents: string;
|
|
36
|
+
}
|
|
37
|
+
export interface ChangeSetSqlRequired {
|
|
38
|
+
kernel: StorageKernel<Kysely<unknown>, unknown>;
|
|
39
|
+
tables: ChangeSetTables;
|
|
40
|
+
}
|
|
41
|
+
export type ChangeSetSqlOptional = Record<string, never>;
|
|
42
|
+
export declare class SqlChangeSetRepo implements ChangeSetRepoPort {
|
|
43
|
+
protected readonly kernel: StorageKernel<Kysely<unknown>, unknown>;
|
|
44
|
+
protected readonly tables: ChangeSetTables;
|
|
45
|
+
constructor({ kernel, tables }: ChangeSetSqlRequired, _optional?: ChangeSetSqlOptional);
|
|
46
|
+
private sets;
|
|
47
|
+
private items;
|
|
48
|
+
/** Header + items + (when supplied) the outbox event land as one atomic transaction — never a
|
|
49
|
+
* partial write (the "transaction participation" requirement, and the
|
|
50
|
+
* resolution for the outbox event specifically; see this file's header). */
|
|
51
|
+
insert({ record, items }: {
|
|
52
|
+
record: ChangeSetRecord;
|
|
53
|
+
items: ChangeSetItemRecord[];
|
|
54
|
+
}, { event }?: {
|
|
55
|
+
event?: DomainEvent;
|
|
56
|
+
}): Promise<void>;
|
|
57
|
+
findById(required: {
|
|
58
|
+
workspaceId: string;
|
|
59
|
+
id: string;
|
|
60
|
+
}, _optional?: ChangeSetSqlOptional): Promise<ChangeSetWithItems | null>;
|
|
61
|
+
findByIdempotencyKey(required: {
|
|
62
|
+
workspaceId: string;
|
|
63
|
+
idempotencyKey: string;
|
|
64
|
+
}, _optional?: ChangeSetSqlOptional): Promise<ChangeSetRecord | null>;
|
|
65
|
+
listByWorkspace(required: {
|
|
66
|
+
workspaceId: string;
|
|
67
|
+
}, _optional?: ChangeSetSqlOptional): Promise<ChangeSetRecord[]>;
|
|
68
|
+
save(record: ChangeSetRecord): Promise<void>;
|
|
69
|
+
}
|
|
70
|
+
//# sourceMappingURL=change-set-repo.sql.d.ts.map
|