@jini-ai/db 0.7.3-next.1 → 0.7.3-next.3
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 +6 -0
- package/README.md +46 -1
- package/dist/core/ports.d.ts +2 -2
- package/dist/core/ports.js +2 -2
- package/dist/data-modules/data-module.d.ts +2 -46
- package/dist/data-modules/plugin-identity.d.ts +2 -11
- package/dist/data-modules/snapshot.d.ts +5 -3
- package/dist/data-modules/snapshot.js +5 -3
- package/dist/events/change-set-repo.sql.d.ts +18 -5
- package/dist/events/change-set-repo.sql.js +25 -8
- package/dist/events/index.d.ts +1 -1
- package/dist/events/outbox-repo.sql.d.ts +26 -1
- package/dist/events/outbox-repo.sql.js +36 -2
- package/dist/events/repo.rows.d.ts +22 -4
- package/dist/events/repo.rows.js +32 -4
- package/dist/kernel/idle-turn.d.ts +62 -0
- package/dist/kernel/idle-turn.js +32 -0
- package/dist/kernel/index.d.ts +1 -0
- package/dist/kernel/index.js +1 -0
- package/dist/kernel/kernel-core.js +28 -0
- package/dist/kernel/schema-scope.js +2 -0
- package/dist/kernel/sqlite/driver.js +2 -0
- package/dist/kernel/turn-lock.d.ts +2 -0
- package/dist/kernel/turn-lock.js +7 -0
- package/dist/pglite/copy-source.d.ts +45 -0
- package/dist/pglite/copy-source.js +36 -0
- package/dist/pglite/index.d.ts +1 -0
- package/dist/pglite/index.js +1 -0
- package/dist/react/recovery/Recovery.d.ts +205 -0
- package/dist/react/recovery/Recovery.js +141 -0
- package/dist/react/recovery/Recovery.restore-steps.d.ts +10 -0
- package/dist/react/recovery/Recovery.restore-steps.js +71 -0
- package/dist/recovery/agent-tools.d.ts +33 -0
- package/dist/recovery/agent-tools.js +166 -0
- package/dist/recovery/drift.d.ts +47 -0
- package/dist/recovery/drift.js +51 -0
- package/dist/recovery/journal-kernel.d.ts +80 -0
- package/dist/recovery/journal-kernel.js +40 -0
- package/dist/recovery/journal-repo.sql.d.ts +154 -0
- package/dist/recovery/journal-repo.sql.js +303 -0
- package/dist/recovery/journal-schema.d.ts +37 -0
- package/dist/recovery/journal-schema.js +110 -0
- package/dist/recovery/migrate-forward-hooks.d.ts +2 -1
- package/dist/recovery/migrate-forward-hooks.js +3 -3
- package/dist/recovery/operation-lock.d.ts +2 -17
- package/dist/recovery/reconcile-interrupted-migration.d.ts +2 -5
- package/dist/recovery/reconcile-interrupted-migration.js +0 -30
- package/dist/recovery/restore-hooks.d.ts +4 -0
- package/dist/recovery/restore-hooks.js +1 -1
- package/dist/recovery/tool-registrations.d.ts +175 -0
- package/dist/recovery/tool-registrations.js +295 -0
- package/dist/site/repo.memory.d.ts +149 -0
- package/dist/site/repo.memory.js +162 -0
- package/dist/site/tool-registrations.d.ts +130 -0
- package/dist/site/tool-registrations.js +185 -0
- package/dist/sqlite/backup-policy.d.ts +14 -0
- package/dist/sqlite/backup-policy.js +47 -3
- package/dist/sqlite/compaction-steps.d.ts +43 -0
- package/dist/sqlite/compaction-steps.js +73 -0
- package/dist/sqlite/compaction.d.ts +63 -0
- package/dist/sqlite/compaction.js +263 -0
- package/dist/sqlite/index.d.ts +2 -1
- package/dist/sqlite/index.js +2 -1
- package/dist/tools/index.d.ts +2 -0
- package/dist/tools/index.js +2 -0
- package/dist/tools/plan-store.d.ts +1 -1
- package/dist/tools/plan-store.js +10 -6
- package/dist/tools/site-db-messages.d.ts +10 -0
- package/dist/tools/site-db-messages.js +23 -0
- package/dist/tools/site-transfer-messages.d.ts +9 -0
- package/dist/tools/site-transfer-messages.js +20 -0
- package/dist/transfer/confirmation-ui.d.ts +19 -0
- package/dist/transfer/confirmation-ui.js +39 -0
- package/dist/transfer/copy-engine.js +11 -11
- package/dist/transfer/destination-store.d.ts +69 -0
- package/dist/transfer/destination-store.js +75 -0
- package/dist/transfer/index.d.ts +2 -0
- package/dist/transfer/index.js +2 -0
- package/dist/transfer/internal-ddl.d.ts +6 -2
- package/dist/transfer/internal-ddl.js +15 -15
- package/dist/transfer/postgres-ddl.js +2 -2
- package/dist/transfer/schema-catalog.d.ts +148 -0
- package/dist/transfer/schema-catalog.js +141 -0
- package/dist/transfer/sqlite-backup.d.ts +27 -0
- package/dist/transfer/sqlite-backup.js +31 -0
- package/dist/transfer/table-catalog.js +1 -0
- package/dist/watermark/kernel.d.ts +64 -0
- package/dist/watermark/kernel.js +45 -0
- package/package.json +105 -10
|
@@ -39,9 +39,7 @@ export async function assertDatabaseCopySpace({ sourcePath, destinationPath }, _
|
|
|
39
39
|
* @complexity O(n log n) time, O(n) space; deletion is sequential to bound filesystem/DB work.
|
|
40
40
|
* @example await pruneDatabaseCopies({ copies, justWritten }, { protectedPaths: activeArtifacts }); */
|
|
41
41
|
export async function pruneDatabaseCopies({ copies, justWritten }, { protectedPaths = new Set(), remove = async ({ filePath }) => fs.rm(filePath, { force: true }) } = {}) {
|
|
42
|
-
const
|
|
43
|
-
const local = copies.filter(copy => path.dirname(path.resolve(copy.filePath)) === directory);
|
|
44
|
-
local.sort((a, b) => b.createdAt - a.createdAt || b.filePath.localeCompare(a.filePath));
|
|
42
|
+
const local = localCopiesNewestFirst({ copies, anchorPath: justWritten });
|
|
45
43
|
const retained = new Set(local.slice(0, DATABASE_COPY_RETENTION).map(copy => copy.filePath));
|
|
46
44
|
for (const copy of local) {
|
|
47
45
|
if (copy.filePath === justWritten || retained.has(copy.filePath) || protectedPaths.has(copy.filePath))
|
|
@@ -49,4 +47,50 @@ export async function pruneDatabaseCopies({ copies, justWritten }, { protectedPa
|
|
|
49
47
|
await remove(copy);
|
|
50
48
|
}
|
|
51
49
|
}
|
|
50
|
+
/** The one ordering and folder rule both the live pruner and the selection pass use, so a pass can
|
|
51
|
+
* never disagree with boot about which copies are "the newest five".
|
|
52
|
+
* @complexity O(n log n) time, O(n) space. */
|
|
53
|
+
function localCopiesNewestFirst({ copies, anchorPath }, _optional = {}) {
|
|
54
|
+
const directory = path.dirname(path.resolve(anchorPath));
|
|
55
|
+
const local = copies.filter(copy => path.dirname(path.resolve(copy.filePath)) === directory);
|
|
56
|
+
return local.sort((a, b) => b.createdAt - a.createdAt || b.filePath.localeCompare(a.filePath));
|
|
57
|
+
}
|
|
58
|
+
/** Pure selection for a scheduled retention pass: which caller-owned copies a pass MAY remove.
|
|
59
|
+
* Nothing is selected unless `verifiedNewest` names the newest local copy, because pruning against an
|
|
60
|
+
* unverified (possibly torn) copy would spend the only good recovery window. Protected copies are
|
|
61
|
+
* kept beyond `keep`, and copies outside the anchor's folder are never candidates. Selection only:
|
|
62
|
+
* the caller removes files, under whatever lock its backup publication and recovery readers share.
|
|
63
|
+
* @complexity O(n log n) time, O(n) space; no filesystem access.
|
|
64
|
+
* @example selectDatabaseCopiesToPrune({ copies, verifiedNewest: newest.filePath }, { protectedPaths }); */
|
|
65
|
+
export function selectDatabaseCopiesToPrune({ copies, verifiedNewest }, { keep = DATABASE_COPY_RETENTION, protectedPaths = new Set() } = {}) {
|
|
66
|
+
if (!Number.isInteger(keep) || keep < 1) {
|
|
67
|
+
throw new RangeError(`Copy retention keep must be a whole number of at least 1 (got ${keep}).`);
|
|
68
|
+
}
|
|
69
|
+
if (!verifiedNewest)
|
|
70
|
+
return [];
|
|
71
|
+
const anchor = path.resolve(verifiedNewest);
|
|
72
|
+
// Identities, not spellings: an alias of a retained copy must neither take a window slot nor be selected.
|
|
73
|
+
const local = collapseByIdentity(localCopiesNewestFirst({ copies, anchorPath: anchor }));
|
|
74
|
+
// The anchor has to be the newest listed copy: a newer copy written after verification is unproven.
|
|
75
|
+
if (local.length === 0 || local[0].identity !== anchor)
|
|
76
|
+
return [];
|
|
77
|
+
// The anchor is listed explicitly even though collapse + keep >= 1 already retain it: selection must never
|
|
78
|
+
// depend on that coupling to spare the only verified copy.
|
|
79
|
+
const kept = new Set([...[...protectedPaths].map(filePath => path.resolve(filePath)), anchor]);
|
|
80
|
+
return local.slice(keep).filter(entry => !kept.has(entry.identity)).map(entry => entry.copy);
|
|
81
|
+
}
|
|
82
|
+
/** First (newest) row wins for each resolved path; later rows naming the same file are dropped.
|
|
83
|
+
* @complexity O(n) time, O(n) space. */
|
|
84
|
+
function collapseByIdentity(newestFirst, _optional = {}) {
|
|
85
|
+
const seen = new Set();
|
|
86
|
+
const unique = [];
|
|
87
|
+
for (const copy of newestFirst) {
|
|
88
|
+
const identity = path.resolve(copy.filePath);
|
|
89
|
+
if (seen.has(identity))
|
|
90
|
+
continue;
|
|
91
|
+
seen.add(identity);
|
|
92
|
+
unique.push({ copy, identity });
|
|
93
|
+
}
|
|
94
|
+
return unique;
|
|
95
|
+
}
|
|
52
96
|
//# sourceMappingURL=backup-policy.js.map
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module compaction-steps
|
|
3
|
+
* The copy and rewrite steps of `convertToIncrementalVacuum` (`./compaction.ts`), on a connection that
|
|
4
|
+
* already holds SQLite's exclusive lock.
|
|
5
|
+
*/
|
|
6
|
+
import type { SqliteCompactionFs, SqliteDb } from '@jini-ai/core/contracts/storage';
|
|
7
|
+
import type { StoppedSqliteOpener } from './stopped.js';
|
|
8
|
+
/** A connection admitted under EXCLUSIVE locking mode; nothing else can open the file while it lives. */
|
|
9
|
+
export type Admitted = SqliteDb;
|
|
10
|
+
/**
|
|
11
|
+
* WAL-consistent copy (`VACUUM INTO`) to `<target>.partial`, checked, then durably renamed into place.
|
|
12
|
+
* A copy that fails its check is removed (it was never published) and the error propagates.
|
|
13
|
+
* @complexity O(database bytes).
|
|
14
|
+
*/
|
|
15
|
+
export declare function copySqliteFile({ db, targetPath, io, open }: {
|
|
16
|
+
db: Admitted;
|
|
17
|
+
targetPath: string;
|
|
18
|
+
io: SqliteCompactionFs;
|
|
19
|
+
open: StoppedSqliteOpener;
|
|
20
|
+
}): Promise<void>;
|
|
21
|
+
/** Opens the copy read-only and requires `integrity_check` = ok. @throws when the copy is not whole. */
|
|
22
|
+
export declare function verifyCopy({ copyPath, open }: {
|
|
23
|
+
copyPath: string;
|
|
24
|
+
open: StoppedSqliteOpener;
|
|
25
|
+
}): void;
|
|
26
|
+
/**
|
|
27
|
+
* True only when the copy opens read-only and `integrity_check` answers ok. A file that is not a database
|
|
28
|
+
* at all (a torn or foreign file) answers false rather than throwing; anything else propagates.
|
|
29
|
+
*/
|
|
30
|
+
export declare function copyIsWhole({ copyPath, open }: {
|
|
31
|
+
copyPath: string;
|
|
32
|
+
open: StoppedSqliteOpener;
|
|
33
|
+
}): boolean;
|
|
34
|
+
/**
|
|
35
|
+
* The rewrite and its check, in `compactAndVerify`'s order: VACUUM, WAL switch, TRUNCATE checkpoint
|
|
36
|
+
* (busy must be 0), then integrity_check, then `auto_vacuum` must read back as 2.
|
|
37
|
+
* @returns undefined when verified; otherwise the plain reason recorded in the marker.
|
|
38
|
+
*/
|
|
39
|
+
export declare function verifyRewrite({ db, alreadyConverted }: {
|
|
40
|
+
db: Admitted;
|
|
41
|
+
alreadyConverted: boolean;
|
|
42
|
+
}): string | undefined;
|
|
43
|
+
//# sourceMappingURL=compaction-steps.d.ts.map
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WAL-consistent copy (`VACUUM INTO`) to `<target>.partial`, checked, then durably renamed into place.
|
|
3
|
+
* A copy that fails its check is removed (it was never published) and the error propagates.
|
|
4
|
+
* @complexity O(database bytes).
|
|
5
|
+
*/
|
|
6
|
+
export async function copySqliteFile({ db, targetPath, io, open }) {
|
|
7
|
+
const partial = `${targetPath}.partial`;
|
|
8
|
+
await io.removeOwn(partial);
|
|
9
|
+
try {
|
|
10
|
+
// Same statement as kernel/sqlite/ops.ts `copySqliteInto`, which this connection-only entry must
|
|
11
|
+
// not import (it loads the kernel). Bound, so a quote in a folder name never becomes SQL.
|
|
12
|
+
db.prepare('VACUUM INTO ?').run(partial);
|
|
13
|
+
verifyCopy({ copyPath: partial, open });
|
|
14
|
+
}
|
|
15
|
+
catch (error) {
|
|
16
|
+
await io.removeOwn(partial);
|
|
17
|
+
throw error;
|
|
18
|
+
}
|
|
19
|
+
await io.publish(partial, targetPath);
|
|
20
|
+
}
|
|
21
|
+
/** Opens the copy read-only and requires `integrity_check` = ok. @throws when the copy is not whole. */
|
|
22
|
+
export function verifyCopy({ copyPath, open }) {
|
|
23
|
+
if (!copyIsWhole({ copyPath, open }))
|
|
24
|
+
throw new Error('The recovery copy made before compaction did not pass its check; nothing was changed.');
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* True only when the copy opens read-only and `integrity_check` answers ok. A file that is not a database
|
|
28
|
+
* at all (a torn or foreign file) answers false rather than throwing; anything else propagates.
|
|
29
|
+
*/
|
|
30
|
+
export function copyIsWhole({ copyPath, open }) {
|
|
31
|
+
let copy;
|
|
32
|
+
try {
|
|
33
|
+
copy = open(copyPath, { readonly: true, fileMustExist: true });
|
|
34
|
+
const [result] = copy.pragma('integrity_check');
|
|
35
|
+
return result?.integrity_check === 'ok';
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
if (isNotADatabase(error))
|
|
39
|
+
return false;
|
|
40
|
+
throw error;
|
|
41
|
+
}
|
|
42
|
+
finally {
|
|
43
|
+
copy?.close();
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
function isNotADatabase(error) {
|
|
47
|
+
const code = error?.code;
|
|
48
|
+
return code === 'SQLITE_NOTADB' || code === 'SQLITE_CORRUPT';
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* The rewrite and its check, in `compactAndVerify`'s order: VACUUM, WAL switch, TRUNCATE checkpoint
|
|
52
|
+
* (busy must be 0), then integrity_check, then `auto_vacuum` must read back as 2.
|
|
53
|
+
* @returns undefined when verified; otherwise the plain reason recorded in the marker.
|
|
54
|
+
*/
|
|
55
|
+
export function verifyRewrite({ db, alreadyConverted }) {
|
|
56
|
+
if (!alreadyConverted) {
|
|
57
|
+
// auto_vacuum only changes through a full VACUUM, and not while the file is in WAL mode.
|
|
58
|
+
db.exec('PRAGMA journal_mode = DELETE; PRAGMA auto_vacuum = INCREMENTAL; VACUUM;');
|
|
59
|
+
}
|
|
60
|
+
// WAL switch and checkpoint BEFORE integrity_check (see kernel/sqlite/ops.ts: the reverse order left a lock).
|
|
61
|
+
db.pragma('journal_mode = WAL');
|
|
62
|
+
const [checkpoint] = db.pragma('wal_checkpoint(TRUNCATE)');
|
|
63
|
+
if (checkpoint === undefined || checkpoint.busy !== 0)
|
|
64
|
+
return `final WAL checkpoint reported busy=${checkpoint?.busy}`;
|
|
65
|
+
const [integrity] = db.pragma('integrity_check');
|
|
66
|
+
if (integrity?.integrity_check !== 'ok')
|
|
67
|
+
return `integrity_check: ${integrity?.integrity_check ?? 'no answer'}`;
|
|
68
|
+
const mode = db.pragma('auto_vacuum', { simple: true });
|
|
69
|
+
if (mode !== 2)
|
|
70
|
+
return `auto_vacuum reads ${String(mode)} after the rewrite`;
|
|
71
|
+
return undefined;
|
|
72
|
+
}
|
|
73
|
+
//# sourceMappingURL=compaction-steps.js.map
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { SqliteCompactionFs, SqliteCompactionMarkerStore, SqliteConversionOutcome, SqliteDb, SqliteVacuumStepOutcome } from '@jini-ai/core/contracts/storage';
|
|
2
|
+
import type { StoppedSqliteOpener } from './stopped.js';
|
|
3
|
+
export declare const COMPACTION_MESSAGES: {
|
|
4
|
+
readonly running: "This website is running; compaction needs it stopped.";
|
|
5
|
+
readonly busy: "This website's database is busy; compaction will try again later.";
|
|
6
|
+
readonly needsAttention: "This website's database did not pass its check after compaction. The copy made before compaction was kept; nothing was deleted.";
|
|
7
|
+
readonly notConverted: "This website's database has not been prepared for compaction yet.";
|
|
8
|
+
readonly nothingToReclaim: "This website's database has little free space to reclaim.";
|
|
9
|
+
};
|
|
10
|
+
/** `pre-compact-<db name>-<ms>.db` beside the database: apart from `pre-migrations-*` rotation and per DB. */
|
|
11
|
+
export declare function compactionRecoveryCopyPath({ filePath, now }: {
|
|
12
|
+
filePath: string;
|
|
13
|
+
now: number;
|
|
14
|
+
}, _optional?: Record<string, never>): string;
|
|
15
|
+
type ConvertRequired = {
|
|
16
|
+
filePath: string;
|
|
17
|
+
open: StoppedSqliteOpener;
|
|
18
|
+
marker: SqliteCompactionMarkerStore;
|
|
19
|
+
holdsRunningLease: () => boolean;
|
|
20
|
+
fs: SqliteCompactionFs;
|
|
21
|
+
now: () => number;
|
|
22
|
+
};
|
|
23
|
+
type ConvertOptional = {
|
|
24
|
+
recoveryCopyPath?: string;
|
|
25
|
+
reserveBytes?: number;
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* One-time conversion of a stopped database file to `auto_vacuum = INCREMENTAL`.
|
|
29
|
+
* Every refusal before the rewrite leaves the file byte-for-byte unchanged. A failed check after the
|
|
30
|
+
* rewrite is recorded as `needs-attention` and is never retried automatically.
|
|
31
|
+
* @param required.holdsRunningLease the host's running-lease probe (the same lease `serve` takes); asked at
|
|
32
|
+
* entry, after admission and before the rewrite, so a lease lost mid-run stops before any rewrite.
|
|
33
|
+
* @param required.fs the host's filesystem port, including the folder SQLite builds its temp database in.
|
|
34
|
+
* @param _optional.reserveBytes headroom per filesystem on top of the copy, journal and temp budgets (64 MiB).
|
|
35
|
+
* @throws on a handle already inside a transaction; a recovery copy path that is the database or an
|
|
36
|
+
* existing file; marker-store and fs errors.
|
|
37
|
+
* @complexity O(database bytes): one copy, one rewrite, two integrity checks.
|
|
38
|
+
*/
|
|
39
|
+
export declare function convertToIncrementalVacuum(required: ConvertRequired, _optional?: ConvertOptional): Promise<SqliteConversionOutcome>;
|
|
40
|
+
type StepRequired = {
|
|
41
|
+
db: SqliteDb;
|
|
42
|
+
filePath: string;
|
|
43
|
+
marker: SqliteCompactionMarkerStore;
|
|
44
|
+
fs: SqliteCompactionFs;
|
|
45
|
+
mono: () => number;
|
|
46
|
+
};
|
|
47
|
+
type StepOptional = {
|
|
48
|
+
maxPages?: number;
|
|
49
|
+
minFreeRatio?: number;
|
|
50
|
+
minFreeBytes?: number;
|
|
51
|
+
busyTimeoutMs?: number;
|
|
52
|
+
};
|
|
53
|
+
/**
|
|
54
|
+
* One bounded `incremental_vacuum(maxPages)` on the host's coordinated handle. Runs only for a file
|
|
55
|
+
* converted under its current identity; skips when free space is below BOTH thresholds; a busy or
|
|
56
|
+
* locked database defers to the next pass. The handle's own busy timeout is restored afterwards.
|
|
57
|
+
* @param required.mono the host's monotonic clock, for `elapsedMs`.
|
|
58
|
+
* @throws when called inside a transaction (incremental_vacuum would join it).
|
|
59
|
+
* @complexity O(maxPages) page moves; two metadata reads before and after.
|
|
60
|
+
*/
|
|
61
|
+
export declare function incrementalVacuumStep(required: StepRequired, _optional?: StepOptional): Promise<SqliteVacuumStepOutcome>;
|
|
62
|
+
export {};
|
|
63
|
+
//# sourceMappingURL=compaction.d.ts.map
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module compaction
|
|
3
|
+
*
|
|
4
|
+
* Reclaiming SQLite free pages without a serving-time `VACUUM`, in two separate operations:
|
|
5
|
+
*
|
|
6
|
+
* 1. `convertToIncrementalVacuum` — once per file, on a STOPPED database. Never a migration: the
|
|
7
|
+
* migration runner wraps each step in a transaction and `VACUUM` cannot run inside one. Order:
|
|
8
|
+
* running lease → SQLite exclusive admission (proves no other connection, before any byte changes)
|
|
9
|
+
* → lease again → disk budget → `copying` marker → verified, durably published recovery copy →
|
|
10
|
+
* `copied` → lease again → `rewriting` → rewrite → check → `converted(dev:ino)`.
|
|
11
|
+
* 2. `incrementalVacuumStep` — the bounded daily step on the host's own coordinated handle; it runs
|
|
12
|
+
* only for a file whose marker says it was converted AND whose `auto_vacuum` reads 2.
|
|
13
|
+
*
|
|
14
|
+
* The host owns the marker store, the clocks and every filesystem call (ports from
|
|
15
|
+
* `@jini-ai/core/contracts/storage`); this module ships no Node filesystem default. The `./sqlite` entry
|
|
16
|
+
* stays connection-only (no Kysely), so the rewrite check mirrors `kernel/sqlite/ops.ts`'s
|
|
17
|
+
* `compactAndVerify` order instead of building a kernel to call it.
|
|
18
|
+
*/
|
|
19
|
+
import path from 'node:path';
|
|
20
|
+
import { copyIsWhole, copySqliteFile, verifyCopy, verifyRewrite } from './compaction-steps.js';
|
|
21
|
+
const MiB = 1024 * 1024;
|
|
22
|
+
const AUTO_VACUUM_INCREMENTAL = 2;
|
|
23
|
+
export const COMPACTION_MESSAGES = {
|
|
24
|
+
running: 'This website is running; compaction needs it stopped.',
|
|
25
|
+
busy: "This website's database is busy; compaction will try again later.",
|
|
26
|
+
needsAttention: "This website's database did not pass its check after compaction. The copy made before compaction was kept; nothing was deleted.",
|
|
27
|
+
notConverted: "This website's database has not been prepared for compaction yet.",
|
|
28
|
+
nothingToReclaim: "This website's database has little free space to reclaim.",
|
|
29
|
+
};
|
|
30
|
+
const IN_TRANSACTION = 'Compaction must run on its own connection, outside any migration or transaction.';
|
|
31
|
+
/** `pre-compact-<db name>-<ms>.db` beside the database: apart from `pre-migrations-*` rotation and per DB. */
|
|
32
|
+
export function compactionRecoveryCopyPath({ filePath, now }, _optional = {}) {
|
|
33
|
+
const name = path.basename(filePath, path.extname(filePath));
|
|
34
|
+
return path.join(path.dirname(filePath), `pre-compact-${name}-${now}.db`);
|
|
35
|
+
}
|
|
36
|
+
const deferredRunning = () => ({ status: 'deferred', reason: 'running', message: COMPACTION_MESSAGES.running });
|
|
37
|
+
/**
|
|
38
|
+
* One-time conversion of a stopped database file to `auto_vacuum = INCREMENTAL`.
|
|
39
|
+
* Every refusal before the rewrite leaves the file byte-for-byte unchanged. A failed check after the
|
|
40
|
+
* rewrite is recorded as `needs-attention` and is never retried automatically.
|
|
41
|
+
* @param required.holdsRunningLease the host's running-lease probe (the same lease `serve` takes); asked at
|
|
42
|
+
* entry, after admission and before the rewrite, so a lease lost mid-run stops before any rewrite.
|
|
43
|
+
* @param required.fs the host's filesystem port, including the folder SQLite builds its temp database in.
|
|
44
|
+
* @param _optional.reserveBytes headroom per filesystem on top of the copy, journal and temp budgets (64 MiB).
|
|
45
|
+
* @throws on a handle already inside a transaction; a recovery copy path that is the database or an
|
|
46
|
+
* existing file; marker-store and fs errors.
|
|
47
|
+
* @complexity O(database bytes): one copy, one rewrite, two integrity checks.
|
|
48
|
+
*/
|
|
49
|
+
export async function convertToIncrementalVacuum(required, _optional = {}) {
|
|
50
|
+
const { reserveBytes = 64 * MiB } = _optional;
|
|
51
|
+
if (!required.holdsRunningLease())
|
|
52
|
+
return deferredRunning();
|
|
53
|
+
const prior = await required.marker.read();
|
|
54
|
+
if (prior?.state === 'needs-attention')
|
|
55
|
+
return { status: 'deferred', reason: 'needs-attention', message: COMPACTION_MESSAGES.needsAttention, recoveryCopyPath: prior.recoveryCopyPath };
|
|
56
|
+
const recoveryCopyPath = await pickRecoveryCopy({ filePath: required.filePath, prior, requested: _optional.recoveryCopyPath, io: required.fs, now: required.now });
|
|
57
|
+
const db = admit({ filePath: required.filePath, open: required.open });
|
|
58
|
+
if (db === undefined)
|
|
59
|
+
return { status: 'deferred', reason: 'busy', message: COMPACTION_MESSAGES.busy };
|
|
60
|
+
try {
|
|
61
|
+
if (!required.holdsRunningLease())
|
|
62
|
+
return deferredRunning();
|
|
63
|
+
return await convertAdmitted({ ...required, db, prior, recoveryCopyPath, reserveBytes });
|
|
64
|
+
}
|
|
65
|
+
finally {
|
|
66
|
+
db.close();
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Why BOTH a verified copy and exclusive admission: admission proves no other connection (a server, a
|
|
71
|
+
* reader pinning the WAL, a writer) can see or change the file while it is rewritten, so the copy and the
|
|
72
|
+
* rewrite describe the same bytes; the verified, published copy is the way back if the rewrite itself is
|
|
73
|
+
* damaged by a crash or a bug. Admission without a copy leaves no way back; a copy without admission can
|
|
74
|
+
* miss a concurrent writer's commit, so restoring it would silently lose data.
|
|
75
|
+
*/
|
|
76
|
+
async function convertAdmitted(job) {
|
|
77
|
+
if (await isAlreadyConverted(job))
|
|
78
|
+
return { status: 'already-converted', message: "This website's database is already prepared for compaction." };
|
|
79
|
+
const before = await measure({ db: job.db, filePath: job.filePath, io: job.fs });
|
|
80
|
+
const shortfall = await budget({ ...job, bytes: before.mainBytes + before.walBytes });
|
|
81
|
+
if (shortfall !== undefined)
|
|
82
|
+
return { status: 'deferred', reason: 'low-disk', message: shortfall };
|
|
83
|
+
await copy(job);
|
|
84
|
+
if (!job.holdsRunningLease())
|
|
85
|
+
return deferredRunning();
|
|
86
|
+
const failure = await rewrite(job);
|
|
87
|
+
if (failure !== undefined)
|
|
88
|
+
return { status: 'deferred', reason: 'needs-attention', message: COMPACTION_MESSAGES.needsAttention, recoveryCopyPath: job.recoveryCopyPath };
|
|
89
|
+
return mark(job, before);
|
|
90
|
+
}
|
|
91
|
+
async function isAlreadyConverted({ db, prior, filePath, fs }) {
|
|
92
|
+
if (db.pragma('auto_vacuum', { simple: true }) !== AUTO_VACUUM_INCREMENTAL || prior?.state !== 'converted')
|
|
93
|
+
return false;
|
|
94
|
+
return prior.identity === await fs.identity(filePath);
|
|
95
|
+
}
|
|
96
|
+
/** Reuse the copy an interrupted attempt named (a `copying` path even if not yet written); otherwise a new, unused path. */
|
|
97
|
+
async function pickRecoveryCopy({ filePath, prior, requested, io, now }) {
|
|
98
|
+
if (prior?.state === 'copying')
|
|
99
|
+
return prior.recoveryCopyPath;
|
|
100
|
+
if (prior !== undefined && prior.state !== 'converted' && await io.exists(prior.recoveryCopyPath))
|
|
101
|
+
return prior.recoveryCopyPath;
|
|
102
|
+
const chosen = requested ?? compactionRecoveryCopyPath({ filePath, now: now() });
|
|
103
|
+
if (path.resolve(chosen) === path.resolve(filePath) || await io.exists(chosen)) {
|
|
104
|
+
throw new Error('The recovery copy must be a new file next to the database, not the database itself or an existing file.');
|
|
105
|
+
}
|
|
106
|
+
return chosen;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* SQLite's exclusive lock is the admission proof: in WAL mode every open connection (an idle one, a
|
|
110
|
+
* reader pinning the WAL, a writer) holds a shared lock, so `BEGIN EXCLUSIVE` under EXCLUSIVE locking
|
|
111
|
+
* mode fails at once with SQLITE_BUSY. Once taken, the lock is held until close, fencing out every
|
|
112
|
+
* other connection for the whole copy + rewrite. Nothing has been written when this refuses.
|
|
113
|
+
* A handle already inside a transaction is a shared one (a migration's): it is refused untouched and NOT
|
|
114
|
+
* closed, because closing it would roll back its owner's transaction.
|
|
115
|
+
*/
|
|
116
|
+
function admit({ filePath, open }) {
|
|
117
|
+
const db = open(filePath, { fileMustExist: true, timeout: 0 });
|
|
118
|
+
if (db.inTransaction)
|
|
119
|
+
throw new Error(IN_TRANSACTION);
|
|
120
|
+
try {
|
|
121
|
+
db.exec('PRAGMA locking_mode=EXCLUSIVE; BEGIN EXCLUSIVE; ROLLBACK;');
|
|
122
|
+
return db;
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
db.close();
|
|
126
|
+
if (isBusy(error))
|
|
127
|
+
return undefined;
|
|
128
|
+
throw error;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
function isBusy(error) {
|
|
132
|
+
const code = error?.code;
|
|
133
|
+
return typeof code === 'string' && (code.startsWith('SQLITE_BUSY') || code.startsWith('SQLITE_LOCKED'));
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Peak space per distinct filesystem: the new copy (only when none is reusable), the DELETE-mode rollback
|
|
137
|
+
* journal beside the database (up to 1×), and SQLite's temp database for `VACUUM` (1×, in the host's temp
|
|
138
|
+
* folder). Each filesystem touched also keeps `reserveBytes` free.
|
|
139
|
+
*/
|
|
140
|
+
async function budget({ filePath, recoveryCopyPath, bytes, reserveBytes, fs: io }) {
|
|
141
|
+
const needs = new Map();
|
|
142
|
+
const add = async (dir, amount) => {
|
|
143
|
+
const device = await io.deviceOf(dir);
|
|
144
|
+
const entry = needs.get(device) ?? { dir, need: reserveBytes };
|
|
145
|
+
needs.set(device, { dir: entry.dir, need: entry.need + amount });
|
|
146
|
+
};
|
|
147
|
+
await add(path.dirname(filePath), bytes);
|
|
148
|
+
await add(path.dirname(recoveryCopyPath), (await io.exists(recoveryCopyPath)) ? 0 : bytes);
|
|
149
|
+
await add(io.tempDirectory(), bytes);
|
|
150
|
+
for (const { dir, need } of needs.values()) {
|
|
151
|
+
const free = await io.freeBytes(dir);
|
|
152
|
+
if (free < need) {
|
|
153
|
+
return `There is not enough free disk space to compact this website's database (needs ${Math.ceil(need / MiB)} MB, ${Math.floor(free / MiB)} MB free). Nothing was changed.`;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return undefined;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Write-ahead `copying` marker, then `VACUUM INTO` → check → publish, then `copied`. A copy already
|
|
160
|
+
* published under `copied`/`rewriting` must still verify (else throw: nothing is rewritten). One left under
|
|
161
|
+
* `copying` (crash after publish, before `copied`) is reused when whole, otherwise redone at the same path.
|
|
162
|
+
*/
|
|
163
|
+
async function copy({ db, prior, recoveryCopyPath, marker, fs: io, open, now }) {
|
|
164
|
+
const named = prior?.recoveryCopyPath === recoveryCopyPath && await io.exists(recoveryCopyPath);
|
|
165
|
+
if (named && prior?.state !== 'copying') {
|
|
166
|
+
verifyCopy({ copyPath: recoveryCopyPath, open });
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
if (named && copyIsWhole({ copyPath: recoveryCopyPath, open })) {
|
|
170
|
+
await marker.write({ state: 'copied', recoveryCopyPath, at: now() });
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
if (named)
|
|
174
|
+
await io.removeOwn(recoveryCopyPath);
|
|
175
|
+
await marker.write({ state: 'copying', recoveryCopyPath, at: now() });
|
|
176
|
+
await copySqliteFile({ db, targetPath: recoveryCopyPath, io, open });
|
|
177
|
+
await marker.write({ state: 'copied', recoveryCopyPath, at: now() });
|
|
178
|
+
}
|
|
179
|
+
/** Records `rewriting`, rewrites and checks. A failed check records `needs-attention` (copy kept) and returns why. */
|
|
180
|
+
async function rewrite({ db, recoveryCopyPath, marker, now }) {
|
|
181
|
+
await marker.write({ state: 'rewriting', recoveryCopyPath, at: now() });
|
|
182
|
+
const failure = verifyRewrite({ db, alreadyConverted: db.pragma('auto_vacuum', { simple: true }) === AUTO_VACUUM_INCREMENTAL });
|
|
183
|
+
if (failure !== undefined)
|
|
184
|
+
await marker.write({ state: 'needs-attention', recoveryCopyPath, at: now(), reason: failure });
|
|
185
|
+
return failure;
|
|
186
|
+
}
|
|
187
|
+
/** Only after `verifyRewrite` passed (integrity ok, `auto_vacuum` reads 2): `converted`, scoped to this file's identity. */
|
|
188
|
+
async function mark({ db, filePath, recoveryCopyPath, marker, fs: io, now }, before) {
|
|
189
|
+
await marker.write({ state: 'converted', recoveryCopyPath, at: now(), identity: await io.identity(filePath) });
|
|
190
|
+
return { status: 'converted', recoveryCopyPath, before, after: await measure({ db, filePath, io }), message: "This website's database is now prepared for compaction." };
|
|
191
|
+
}
|
|
192
|
+
async function measure({ db, filePath, io }) {
|
|
193
|
+
return {
|
|
194
|
+
mainBytes: await io.size(filePath),
|
|
195
|
+
walBytes: await io.size(`${filePath}-wal`),
|
|
196
|
+
freePages: Number(db.pragma('freelist_count', { simple: true })),
|
|
197
|
+
pageSize: Number(db.pragma('page_size', { simple: true })),
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* One bounded `incremental_vacuum(maxPages)` on the host's coordinated handle. Runs only for a file
|
|
202
|
+
* converted under its current identity; skips when free space is below BOTH thresholds; a busy or
|
|
203
|
+
* locked database defers to the next pass. The handle's own busy timeout is restored afterwards.
|
|
204
|
+
* @param required.mono the host's monotonic clock, for `elapsedMs`.
|
|
205
|
+
* @throws when called inside a transaction (incremental_vacuum would join it).
|
|
206
|
+
* @complexity O(maxPages) page moves; two metadata reads before and after.
|
|
207
|
+
*/
|
|
208
|
+
export async function incrementalVacuumStep(required, _optional = {}) {
|
|
209
|
+
const { db, filePath, marker, fs: io, mono } = required;
|
|
210
|
+
if (db.inTransaction)
|
|
211
|
+
throw new Error('incrementalVacuumStep must run outside a transaction.');
|
|
212
|
+
if (!(await isConvertedHere({ db, filePath, marker, io }))) {
|
|
213
|
+
return { status: 'skipped', reason: 'not-converted', message: COMPACTION_MESSAGES.notConverted };
|
|
214
|
+
}
|
|
215
|
+
const before = await measure({ db, filePath, io });
|
|
216
|
+
if (!worthReclaiming({ db, before, ..._optional })) {
|
|
217
|
+
return { status: 'skipped', reason: 'nothing-to-reclaim', message: COMPACTION_MESSAGES.nothingToReclaim, before };
|
|
218
|
+
}
|
|
219
|
+
// The awaits above leave a gap in which a foreign `BEGIN` can open on the shared handle; the
|
|
220
|
+
// vacuum would then join that transaction. Re-check with no await before the pragma.
|
|
221
|
+
if (db.inTransaction)
|
|
222
|
+
return { status: 'skipped', reason: 'busy', message: COMPACTION_MESSAGES.busy, before };
|
|
223
|
+
const started = mono();
|
|
224
|
+
if (!runBoundedVacuum({ db, ..._optional }))
|
|
225
|
+
return { status: 'skipped', reason: 'busy', message: COMPACTION_MESSAGES.busy, before };
|
|
226
|
+
const after = await measure({ db, filePath, io });
|
|
227
|
+
return {
|
|
228
|
+
status: 'reclaimed', before, after, elapsedMs: mono() - started,
|
|
229
|
+
message: `Reclaimed ${before.freePages - after.freePages} free pages. The file shrinks on disk at the next checkpoint; a long-running reader can delay that.`,
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
/** Converted under THIS file's identity (a restored or replaced file does not inherit it) and `auto_vacuum` reads 2. */
|
|
233
|
+
async function isConvertedHere({ db, filePath, marker, io }) {
|
|
234
|
+
const recorded = await marker.read();
|
|
235
|
+
if (recorded?.state !== 'converted' || recorded.identity !== await io.identity(filePath))
|
|
236
|
+
return false;
|
|
237
|
+
return db.pragma('auto_vacuum', { simple: true }) === AUTO_VACUUM_INCREMENTAL;
|
|
238
|
+
}
|
|
239
|
+
/** False when there are no free pages, or free space is below BOTH the byte and the ratio threshold. */
|
|
240
|
+
function worthReclaiming({ db, before, minFreeRatio = 0.2, minFreeBytes = 8 * MiB }) {
|
|
241
|
+
if (before.freePages === 0)
|
|
242
|
+
return false;
|
|
243
|
+
const pageCount = Number(db.pragma('page_count', { simple: true }));
|
|
244
|
+
return before.freePages * before.pageSize >= minFreeBytes || before.freePages / pageCount >= minFreeRatio;
|
|
245
|
+
}
|
|
246
|
+
/** False when SQLite reported busy/locked. The handle's prior busy timeout is restored either way. */
|
|
247
|
+
function runBoundedVacuum({ db, maxPages = 2048, busyTimeoutMs = 250 }) {
|
|
248
|
+
const previousTimeout = db.pragma('busy_timeout', { simple: true });
|
|
249
|
+
db.pragma(`busy_timeout = ${Math.max(0, Math.floor(busyTimeoutMs))}`);
|
|
250
|
+
try {
|
|
251
|
+
db.pragma(`incremental_vacuum(${Math.max(1, Math.floor(maxPages))})`);
|
|
252
|
+
return true;
|
|
253
|
+
}
|
|
254
|
+
catch (error) {
|
|
255
|
+
if (!isBusy(error))
|
|
256
|
+
throw error;
|
|
257
|
+
return false;
|
|
258
|
+
}
|
|
259
|
+
finally {
|
|
260
|
+
db.pragma(`busy_timeout = ${Number(previousTimeout)}`);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
//# sourceMappingURL=compaction.js.map
|
package/dist/sqlite/index.d.ts
CHANGED
|
@@ -4,7 +4,8 @@ export { SqliteClientError } from "./checked-state.js";
|
|
|
4
4
|
export { withSqliteTransaction, type TransactionSession, type Work } from "./transaction.js";
|
|
5
5
|
export { openSqliteConnection, DEFAULT_PRAGMAS } from "./open.js";
|
|
6
6
|
export { SqliteDbOpsAdapter, type SqliteDbOpsAdapterDeps } from "./db-ops.js";
|
|
7
|
-
export { DATABASE_COPY_RETENTION, DatabaseDiskSpaceError, assertDatabaseCopySpace, pruneDatabaseCopies, type DatabaseCopy } from "./backup-policy.js";
|
|
7
|
+
export { DATABASE_COPY_RETENTION, DatabaseDiskSpaceError, assertDatabaseCopySpace, pruneDatabaseCopies, selectDatabaseCopiesToPrune, type DatabaseCopy } from "./backup-policy.js";
|
|
8
|
+
export { COMPACTION_MESSAGES, compactionRecoveryCopyPath, convertToIncrementalVacuum, incrementalVacuumStep } from "./compaction.js";
|
|
8
9
|
export { inspectSqliteDatabase, verifySqliteIntegrity } from "./inspect.js";
|
|
9
10
|
export { assertSqliteStopped, checkpointStoppedSqliteWal, inspectStoppedSqlite, type StoppedSqliteOpener } from "./stopped.js";
|
|
10
11
|
export type { DaemonDbTableInfo, DaemonDbStatusReport, DbIntegrityIssueKind, DbIntegrityIssue, DbIntegrityReport, VerifyDbOptions } from "./inspect.js";
|
package/dist/sqlite/index.js
CHANGED
|
@@ -4,7 +4,8 @@ export { SqliteClientError } from "./checked-state.js";
|
|
|
4
4
|
export { withSqliteTransaction } from "./transaction.js";
|
|
5
5
|
export { openSqliteConnection, DEFAULT_PRAGMAS } from "./open.js";
|
|
6
6
|
export { SqliteDbOpsAdapter } from "./db-ops.js";
|
|
7
|
-
export { DATABASE_COPY_RETENTION, DatabaseDiskSpaceError, assertDatabaseCopySpace, pruneDatabaseCopies } from "./backup-policy.js";
|
|
7
|
+
export { DATABASE_COPY_RETENTION, DatabaseDiskSpaceError, assertDatabaseCopySpace, pruneDatabaseCopies, selectDatabaseCopiesToPrune } from "./backup-policy.js";
|
|
8
|
+
export { COMPACTION_MESSAGES, compactionRecoveryCopyPath, convertToIncrementalVacuum, incrementalVacuumStep } from "./compaction.js";
|
|
8
9
|
export { inspectSqliteDatabase, verifySqliteIntegrity } from "./inspect.js";
|
|
9
10
|
export { assertSqliteStopped, checkpointStoppedSqliteWal, inspectStoppedSqlite } from "./stopped.js";
|
|
10
11
|
//# sourceMappingURL=index.js.map
|
package/dist/tools/index.d.ts
CHANGED
|
@@ -8,6 +8,8 @@ export * from "./timeline.js";
|
|
|
8
8
|
export * from "./restore-points.js";
|
|
9
9
|
export * from "./plan-store.js";
|
|
10
10
|
export * from "./destination-port.js";
|
|
11
|
+
export { SITE_DATABASE_MESSAGES } from "./site-db-messages.js";
|
|
12
|
+
export { SITE_TRANSFER_MESSAGES } from "./site-transfer-messages.js";
|
|
11
13
|
export type { InputReaders } from "./registration.js";
|
|
12
14
|
export type { TransferSurfacePorts, SurfaceExchange, SurfaceMessage } from "./surface-port.js";
|
|
13
15
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/tools/index.js
CHANGED
|
@@ -8,4 +8,6 @@ export * from "./timeline.js";
|
|
|
8
8
|
export * from "./restore-points.js";
|
|
9
9
|
export * from "./plan-store.js";
|
|
10
10
|
export * from "./destination-port.js";
|
|
11
|
+
export { SITE_DATABASE_MESSAGES } from "./site-db-messages.js";
|
|
12
|
+
export { SITE_TRANSFER_MESSAGES } from "./site-transfer-messages.js";
|
|
11
13
|
//# sourceMappingURL=index.js.map
|
|
@@ -45,7 +45,7 @@ export declare class DatabaseTransferPlanStore {
|
|
|
45
45
|
constructor(_required?: Record<string, never>, optional?: {
|
|
46
46
|
now?: () => number;
|
|
47
47
|
});
|
|
48
|
-
/** @complexity O(plans held)
|
|
48
|
+
/** @complexity O(plans held): at most {@link DEFAULT_MAX_PLANS} per principal, expired ones pruned first. */
|
|
49
49
|
save(input: {
|
|
50
50
|
principalId: string;
|
|
51
51
|
workspaceId: string;
|
package/dist/tools/plan-store.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
2
|
const DEFAULT_PLAN_TTL_MS = 10 * 60 * 1000;
|
|
3
|
-
/** Each plan holds a whole database snapshot, so only a couple are kept. */
|
|
3
|
+
/** Each plan holds a whole database snapshot, so only a couple are kept per principal. */
|
|
4
4
|
const DEFAULT_MAX_PLANS = 2;
|
|
5
5
|
export class DatabaseTransferPlanStore {
|
|
6
6
|
plans = new Map();
|
|
@@ -8,19 +8,23 @@ export class DatabaseTransferPlanStore {
|
|
|
8
8
|
constructor(_required = {}, optional = {}) {
|
|
9
9
|
this.now = optional.now ?? Date.now;
|
|
10
10
|
}
|
|
11
|
-
/** @complexity O(plans held)
|
|
11
|
+
/** @complexity O(plans held): at most {@link DEFAULT_MAX_PLANS} per principal, expired ones pruned first. */
|
|
12
12
|
save(input, _optional = {}) {
|
|
13
13
|
const nowMs = this.now();
|
|
14
14
|
for (const [id, plan] of this.plans) {
|
|
15
15
|
if (plan.expiresAtMs <= nowMs)
|
|
16
16
|
this.plans.delete(id);
|
|
17
17
|
}
|
|
18
|
-
// Evict oldest
|
|
19
|
-
//
|
|
20
|
-
|
|
21
|
-
|
|
18
|
+
// Evict this principal's own oldest plans first (a Map iterates in insertion order) until there is
|
|
19
|
+
// room. The cap is per principal (B166): a global cap let one user's new plan evict another's.
|
|
20
|
+
let held = [...this.plans.values()].filter(plan => plan.principalId === input.principalId).length;
|
|
21
|
+
for (const [id, plan] of this.plans) {
|
|
22
|
+
if (held < DEFAULT_MAX_PLANS)
|
|
22
23
|
break;
|
|
24
|
+
if (plan.principalId !== input.principalId)
|
|
25
|
+
continue;
|
|
23
26
|
this.plans.delete(id);
|
|
27
|
+
held -= 1;
|
|
24
28
|
}
|
|
25
29
|
const plan = { ...input.content, planId: randomUUID(), principalId: input.principalId, workspaceId: input.workspaceId, expiresAtMs: nowMs + DEFAULT_PLAN_TTL_MS };
|
|
26
30
|
this.plans.set(plan.planId, plan);
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { type DbMessages } from "../core/messages.js";
|
|
2
|
+
/**
|
|
3
|
+
* @file Site wording for the `@jini-ai/db/tools` database tools. The package defaults speak of "the
|
|
4
|
+
* source"; a host that serves one site has its tools say "this site", and their descriptions are the
|
|
5
|
+
* bytes the host's descriptor snapshot pins from the pre-extraction catalog. The transfer tools' copy
|
|
6
|
+
* lives in `site-transfer-messages.ts`. Specification references (requirement or decision ids) are
|
|
7
|
+
* not part of this profile: a host that cites its own documents in this copy overrides those fields.
|
|
8
|
+
*/
|
|
9
|
+
export declare const SITE_DATABASE_MESSAGES: DbMessages;
|
|
10
|
+
//# sourceMappingURL=site-db-messages.d.ts.map
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { defaultDbMessages } from "../core/messages.js";
|
|
2
|
+
/**
|
|
3
|
+
* @file Site wording for the `@jini-ai/db/tools` database tools. The package defaults speak of "the
|
|
4
|
+
* source"; a host that serves one site has its tools say "this site", and their descriptions are the
|
|
5
|
+
* bytes the host's descriptor snapshot pins from the pre-extraction catalog. The transfer tools' copy
|
|
6
|
+
* lives in `site-transfer-messages.ts`. Specification references (requirement or decision ids) are
|
|
7
|
+
* not part of this profile: a host that cites its own documents in this copy overrides those fields.
|
|
8
|
+
*/
|
|
9
|
+
export const SITE_DATABASE_MESSAGES = {
|
|
10
|
+
...defaultDbMessages,
|
|
11
|
+
restorePointUnavailable: "no restore-point mechanism is available for this site; the in-product migrate is refused with no attestation override",
|
|
12
|
+
restorePointCostAck: "Explicit cost acknowledgment. Required (must be true) only when this site's restore-point cost class is 'expensive'; ignored when 'cheap'. The call is refused with no override at all when cost class is 'unavailable' (no attestation override).",
|
|
13
|
+
databaseHealth: "Reports a summary of this site's database health (connectivity, disk headroom, pending-migration/interrupted-migration state).",
|
|
14
|
+
databaseSchemaState: "Reports this site's schema drift status (in-sync/ahead/diverged/behind) between its persisted schema snapshot and the runtime's current schema.",
|
|
15
|
+
databasePendingMigrations: "Lists migrations pending against this site that have not yet been applied.",
|
|
16
|
+
databaseRestorePoints: "Lists every restore point recorded for this site, newest first, with its trigger, cost class, and capture time.",
|
|
17
|
+
databasePlanMigrate: "Previews what forward-migrating this site's schema would do — cost class and a plan hash — without applying anything.",
|
|
18
|
+
databaseExecuteMigrate: "Moves this site's database forward to the current schema. Shows the user a confirm dialog first and only runs if they " +
|
|
19
|
+
"confirm. A restore point is taken first. Call database_plan_migrate_forward first to see the cost class.",
|
|
20
|
+
databaseCreateRestorePoint: "Mints a new restore point for this site independent of any migration, subject to the site's cost-acknowledgment rule.",
|
|
21
|
+
databaseRestoreGuidance: "Returns a deep-link routing envelope pointing at the Recovery surface for restoring this site to an earlier snapshot. Never itself a restore lever.",
|
|
22
|
+
};
|
|
23
|
+
//# sourceMappingURL=site-db-messages.js.map
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { DbMessages, DbTransferMessages } from "../core/messages.js";
|
|
2
|
+
/**
|
|
3
|
+
* @file Site wording for the `@jini-ai/db/tools` transfer tools. The package defaults speak of "the
|
|
4
|
+
* source"; a host that serves one site has its transfer tools say "this site", and the four
|
|
5
|
+
* descriptions are the bytes the host's descriptor snapshot pins from the pre-extraction catalog.
|
|
6
|
+
* `plan` names the real schemas from the host's `TransferNaming` (its default schema and per-site prefix).
|
|
7
|
+
*/
|
|
8
|
+
export declare const SITE_TRANSFER_MESSAGES: DbTransferMessages & Pick<DbMessages, "privateAreasTaken" | "noDestination" | "uncheckedLinks" | "destinationSaved" | "missingSourceTable" | "missingSourceColumn">;
|
|
9
|
+
//# sourceMappingURL=site-transfer-messages.d.ts.map
|