@jini-ai/db 0.6.16 → 0.6.17
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 +8 -0
- package/dist/kernel/sqlite/driver.js +2 -0
- package/dist/migrate/runner.d.ts +5 -1
- package/dist/migrate/runner.js +21 -2
- package/dist/migrate/step.d.ts +9 -0
- package/dist/sqlite/backup-policy.d.ts +35 -0
- package/dist/sqlite/backup-policy.js +44 -0
- package/dist/sqlite/db-ops.d.ts +2 -0
- package/dist/sqlite/db-ops.js +4 -2
- package/dist/sqlite/index.d.ts +1 -0
- package/dist/sqlite/index.js +1 -0
- package/package.json +4 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,11 @@
|
|
|
1
|
+
## 0.6.17
|
|
2
|
+
|
|
3
|
+
### Patch Changes
|
|
4
|
+
|
|
5
|
+
- Keep the newest five database backups and restore points.
|
|
6
|
+
- Check free space before database copies and report insufficient capacity with DatabaseDiskSpaceError.
|
|
7
|
+
- Accept a directory option in captureRestorePoint.
|
|
8
|
+
|
|
1
9
|
## 0.6.15
|
|
2
10
|
|
|
3
11
|
### Minor Changes
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import path from "node:path";
|
|
2
|
+
import { assertDatabaseCopySpace } from "../../sqlite/backup-policy.js";
|
|
2
3
|
import { Kysely, SqliteDialect } from "kysely";
|
|
3
4
|
import { buildKernel, TurnLock } from "../index.js";
|
|
4
5
|
import { checkedClients, checkedStates, connectionsByKernel, rawKernelClients } from "../../sqlite/checked-state.js";
|
|
@@ -88,6 +89,7 @@ export function sqliteKernel(source) {
|
|
|
88
89
|
lockKey: async () => { },
|
|
89
90
|
foreignTransactionOpen: () => client.inTransaction,
|
|
90
91
|
backup: async (destPath) => {
|
|
92
|
+
await assertDatabaseCopySpace({ sourcePath: client.memory ? ':memory:' : client.name, destinationPath: destPath });
|
|
91
93
|
await client.backup(destPath);
|
|
92
94
|
},
|
|
93
95
|
close: async () => { },
|
package/dist/migrate/runner.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { type Clock } from "@jini-ai/core/primitives";
|
|
|
2
2
|
import { type StorageKernel } from "../kernel/index.js";
|
|
3
3
|
import { type LegacyLedgerMapping } from "./legacy-ledger.js";
|
|
4
4
|
export type { Ledger, LedgerRow } from "./ledger-contracts.js";
|
|
5
|
-
import { type MigrationStep } from "./step.js";
|
|
5
|
+
import { type MigrationContext, type MigrationStep } from "./step.js";
|
|
6
6
|
export interface MigrationOptions {
|
|
7
7
|
/** The ledger table (REQUIRED, no default); also the migration lock's key. */
|
|
8
8
|
ledgerTable: string;
|
|
@@ -10,6 +10,10 @@ export interface MigrationOptions {
|
|
|
10
10
|
allowUnknownApplied?: boolean;
|
|
11
11
|
/** Where to copy an existing database before the first pending step changes it (see the file header). */
|
|
12
12
|
backupPath?: string;
|
|
13
|
+
/** Opt-in host recovery policy. Without it every backup failure still aborts migration. */
|
|
14
|
+
onBackupError?: MigrationContext['onBackupError'];
|
|
15
|
+
/** Host-owned retention runs on successful copies even when a subsequent migration fails. */
|
|
16
|
+
onBackupComplete?: MigrationContext['onBackupComplete'];
|
|
13
17
|
/** Postgres only: the schema holding the ledger, created with it when missing. */
|
|
14
18
|
schema?: string;
|
|
15
19
|
/** Names the newer runtime in {@link UnknownAppliedMigrationError}'s message (default "version"). */
|
package/dist/migrate/runner.js
CHANGED
|
@@ -152,7 +152,7 @@ export async function runMigrations(kernel, steps, options) {
|
|
|
152
152
|
const note = (message) => {
|
|
153
153
|
report.notes.push(message);
|
|
154
154
|
};
|
|
155
|
-
const context =
|
|
155
|
+
const context = migrationContext({ options, note });
|
|
156
156
|
if (options.atomicity === "batch")
|
|
157
157
|
return applyBatch({ kernel, ledger, steps, options, context, report });
|
|
158
158
|
const done = new Set(report.alreadyApplied);
|
|
@@ -175,6 +175,16 @@ export async function runMigrations(kernel, steps, options) {
|
|
|
175
175
|
}
|
|
176
176
|
return report;
|
|
177
177
|
}
|
|
178
|
+
/** Expose only step context, retaining absent optional fields for existing prepare hooks.
|
|
179
|
+
* @complexity O(1), no I/O. */
|
|
180
|
+
function migrationContext({ options, note }, _optional = {}) {
|
|
181
|
+
return {
|
|
182
|
+
note,
|
|
183
|
+
...(options.backupPath === undefined ? {} : { backupPath: options.backupPath }),
|
|
184
|
+
...(options.onBackupError === undefined ? {} : { onBackupError: options.onBackupError }),
|
|
185
|
+
...(options.onBackupComplete === undefined ? {} : { onBackupComplete: options.onBackupComplete }),
|
|
186
|
+
};
|
|
187
|
+
}
|
|
178
188
|
async function preparePendingStep({ kernel, context, step, backedUp }) {
|
|
179
189
|
if (!backedUp)
|
|
180
190
|
await backUpBeforeChange(kernel, context);
|
|
@@ -187,8 +197,17 @@ async function backUpBeforeChange(kernel, context) {
|
|
|
187
197
|
return;
|
|
188
198
|
// The folder is made only when a copy is taken, so a run with nothing to copy leaves none behind.
|
|
189
199
|
fs.mkdirSync(path.dirname(path.resolve(target)), { recursive: true });
|
|
190
|
-
|
|
200
|
+
try {
|
|
201
|
+
await kernel.backupTo(target);
|
|
202
|
+
}
|
|
203
|
+
catch (error) {
|
|
204
|
+
if (context.onBackupError === undefined)
|
|
205
|
+
throw error;
|
|
206
|
+
context.onBackupError({ error, backupPath: target });
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
191
209
|
context.note(`backed up the database to ${target} before migrating it`);
|
|
210
|
+
await context.onBackupComplete?.({ backupPath: target });
|
|
192
211
|
}
|
|
193
212
|
async function ledgerExists(kernel, ledger) {
|
|
194
213
|
if (ledger.schema === undefined)
|
package/dist/migrate/step.d.ts
CHANGED
|
@@ -9,6 +9,15 @@ export declare const MIGRATION_ID: RegExp;
|
|
|
9
9
|
export interface MigrationContext {
|
|
10
10
|
/** Where the runner copied (or would copy) the database before the first pending step; the caller decides. */
|
|
11
11
|
readonly backupPath?: string;
|
|
12
|
+
/** A host may explicitly continue after selected backup failures; throwing preserves refusal. */
|
|
13
|
+
readonly onBackupError?: (input: {
|
|
14
|
+
error: unknown;
|
|
15
|
+
backupPath: string;
|
|
16
|
+
}) => void;
|
|
17
|
+
/** Runs only after the copy succeeds, before any step changes the source database. */
|
|
18
|
+
readonly onBackupComplete?: (input: {
|
|
19
|
+
backupPath: string;
|
|
20
|
+
}) => Promise<void>;
|
|
12
21
|
/** Something worth telling the operator (a backup taken, a legacy tail applied). */
|
|
13
22
|
note(message: string): void;
|
|
14
23
|
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
export declare const DATABASE_COPY_RETENTION = 5;
|
|
2
|
+
/** Safe operator-facing refusal; callers can map it without exposing driver errors or paths. */
|
|
3
|
+
export declare class DatabaseDiskSpaceError extends Error {
|
|
4
|
+
readonly code = "INSUFFICIENT_STORAGE";
|
|
5
|
+
readonly status = 507;
|
|
6
|
+
constructor({ freeBytes, requiredBytes }: {
|
|
7
|
+
freeBytes: number;
|
|
8
|
+
requiredBytes: number;
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
/** Check the destination filesystem before allocating a full copy. Source/statfs errors propagate.
|
|
12
|
+
* The reserve leaves room for the live DB's WAL and journal during the operation.
|
|
13
|
+
* @complexity O(1), two metadata reads; no database bytes are read.
|
|
14
|
+
* @example await assertDatabaseCopySpace({ sourcePath: '/site/content.db', destinationPath: '/site/copy.db' }); */
|
|
15
|
+
export declare function assertDatabaseCopySpace({ sourcePath, destinationPath }: {
|
|
16
|
+
sourcePath: string;
|
|
17
|
+
destinationPath: string;
|
|
18
|
+
}, _options?: Record<string, never>): Promise<void>;
|
|
19
|
+
export interface DatabaseCopy {
|
|
20
|
+
readonly filePath: string;
|
|
21
|
+
readonly createdAt: number;
|
|
22
|
+
}
|
|
23
|
+
/** Prune only caller-owned candidates beside the successful new copy. Hosts select exact naming
|
|
24
|
+
* patterns and supply repository deletion when files have rows; protected copies exceed the cap.
|
|
25
|
+
* Never prune before a new copy succeeds: an I/O failure must not consume the recovery window.
|
|
26
|
+
* @complexity O(n log n) time, O(n) space; deletion is sequential to bound filesystem/DB work.
|
|
27
|
+
* @example await pruneDatabaseCopies({ copies, justWritten }, { protectedPaths: activeArtifacts }); */
|
|
28
|
+
export declare function pruneDatabaseCopies({ copies, justWritten }: {
|
|
29
|
+
copies: readonly DatabaseCopy[];
|
|
30
|
+
justWritten: string;
|
|
31
|
+
}, { protectedPaths, remove }?: {
|
|
32
|
+
protectedPaths?: ReadonlySet<string>;
|
|
33
|
+
remove?: (copy: DatabaseCopy) => Promise<void>;
|
|
34
|
+
}): Promise<void>;
|
|
35
|
+
//# sourceMappingURL=backup-policy.d.ts.map
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/** Shared disk budget and retention for host-owned SQLite recovery copies. */
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
export const DATABASE_COPY_RETENTION = 5;
|
|
5
|
+
const MB = 1024 * 1024;
|
|
6
|
+
const DISK_RESERVE_BYTES = 50 * MB;
|
|
7
|
+
/** Safe operator-facing refusal; callers can map it without exposing driver errors or paths. */
|
|
8
|
+
export class DatabaseDiskSpaceError extends Error {
|
|
9
|
+
code = 'INSUFFICIENT_STORAGE';
|
|
10
|
+
status = 507;
|
|
11
|
+
constructor({ freeBytes, requiredBytes }) {
|
|
12
|
+
super(`The server's disk is almost full (${Math.floor(freeBytes / MB)} MB free, needs ${Math.ceil(requiredBytes / MB)} MB) — free space or grow the disk.`);
|
|
13
|
+
this.name = 'DatabaseDiskSpaceError';
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
/** Check the destination filesystem before allocating a full copy. Source/statfs errors propagate.
|
|
17
|
+
* The reserve leaves room for the live DB's WAL and journal during the operation.
|
|
18
|
+
* @complexity O(1), two metadata reads; no database bytes are read.
|
|
19
|
+
* @example await assertDatabaseCopySpace({ sourcePath: '/site/content.db', destinationPath: '/site/copy.db' }); */
|
|
20
|
+
export async function assertDatabaseCopySpace({ sourcePath, destinationPath }, _options = {}) {
|
|
21
|
+
const sourceBytes = sourcePath === ':memory:' ? 0 : (await fs.stat(sourcePath)).size;
|
|
22
|
+
const space = await fs.statfs(path.dirname(path.resolve(destinationPath)));
|
|
23
|
+
const freeBytes = space.bavail * space.bsize;
|
|
24
|
+
const requiredBytes = Math.ceil(sourceBytes * 1.2) + DISK_RESERVE_BYTES;
|
|
25
|
+
if (freeBytes < requiredBytes)
|
|
26
|
+
throw new DatabaseDiskSpaceError({ freeBytes, requiredBytes });
|
|
27
|
+
}
|
|
28
|
+
/** Prune only caller-owned candidates beside the successful new copy. Hosts select exact naming
|
|
29
|
+
* patterns and supply repository deletion when files have rows; protected copies exceed the cap.
|
|
30
|
+
* Never prune before a new copy succeeds: an I/O failure must not consume the recovery window.
|
|
31
|
+
* @complexity O(n log n) time, O(n) space; deletion is sequential to bound filesystem/DB work.
|
|
32
|
+
* @example await pruneDatabaseCopies({ copies, justWritten }, { protectedPaths: activeArtifacts }); */
|
|
33
|
+
export async function pruneDatabaseCopies({ copies, justWritten }, { protectedPaths = new Set(), remove = async ({ filePath }) => fs.rm(filePath, { force: true }) } = {}) {
|
|
34
|
+
const directory = path.dirname(path.resolve(justWritten));
|
|
35
|
+
const local = copies.filter(copy => path.dirname(path.resolve(copy.filePath)) === directory);
|
|
36
|
+
local.sort((a, b) => b.createdAt - a.createdAt || b.filePath.localeCompare(a.filePath));
|
|
37
|
+
const retained = new Set(local.slice(0, DATABASE_COPY_RETENTION).map(copy => copy.filePath));
|
|
38
|
+
for (const copy of local) {
|
|
39
|
+
if (copy.filePath === justWritten || retained.has(copy.filePath) || protectedPaths.has(copy.filePath))
|
|
40
|
+
continue;
|
|
41
|
+
await remove(copy);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
//# sourceMappingURL=backup-policy.js.map
|
package/dist/sqlite/db-ops.d.ts
CHANGED
|
@@ -32,6 +32,8 @@ export declare class SqliteDbOpsAdapter implements DbOpsPort {
|
|
|
32
32
|
*/
|
|
33
33
|
captureRestorePoint(required: {
|
|
34
34
|
scopeId: string;
|
|
35
|
+
}, options?: {
|
|
36
|
+
directory?: string;
|
|
35
37
|
}): Promise<RestorePoint>;
|
|
36
38
|
/**
|
|
37
39
|
* Physically swaps the live database file for a previously-captured artifact.
|
package/dist/sqlite/db-ops.js
CHANGED
|
@@ -14,6 +14,7 @@ import fs from 'node:fs/promises';
|
|
|
14
14
|
import os from 'node:os';
|
|
15
15
|
import path from 'node:path';
|
|
16
16
|
import { restorePointFilename } from '../core/artifact-naming.js';
|
|
17
|
+
import { assertDatabaseCopySpace } from './backup-policy.js';
|
|
17
18
|
/** Sentinel `filePath` for an ephemeral connection with no file behind it. */
|
|
18
19
|
const IN_MEMORY = ':memory:';
|
|
19
20
|
export class SqliteDbOpsAdapter {
|
|
@@ -38,10 +39,11 @@ export class SqliteDbOpsAdapter {
|
|
|
38
39
|
* An in-memory connection has no directory of its own, so its artifacts land in the OS temp
|
|
39
40
|
* directory rather than failing: the backup itself is still a real, consistent file.
|
|
40
41
|
*/
|
|
41
|
-
async captureRestorePoint(required) {
|
|
42
|
+
async captureRestorePoint(required, options = {}) {
|
|
42
43
|
const watermarkAtCapture = await this.readWatermark();
|
|
43
|
-
const targetDir = this.filePath === IN_MEMORY ? os.tmpdir() : path.dirname(this.filePath);
|
|
44
|
+
const targetDir = options.directory ?? (this.filePath === IN_MEMORY ? os.tmpdir() : path.dirname(this.filePath));
|
|
44
45
|
const artifactRef = path.join(targetDir, restorePointFilename({ scopeId: required.scopeId, watermarkAtCapture, timestamp: this.now() }));
|
|
46
|
+
await assertDatabaseCopySpace({ sourcePath: this.filePath, destinationPath: artifactRef });
|
|
45
47
|
await this.connection.backup(artifactRef);
|
|
46
48
|
return { artifactRef, watermarkAtCapture };
|
|
47
49
|
}
|
package/dist/sqlite/index.d.ts
CHANGED
|
@@ -5,6 +5,7 @@ export { SqliteClientError } from "./checked-state.js";
|
|
|
5
5
|
export { withSqliteTransaction, type TransactionSession, type Work } from "./transaction.js";
|
|
6
6
|
export { openSqliteConnection, DEFAULT_PRAGMAS } from "./open.js";
|
|
7
7
|
export { SqliteDbOpsAdapter, type SqliteDbOpsAdapterDeps } from "./db-ops.js";
|
|
8
|
+
export { DATABASE_COPY_RETENTION, DatabaseDiskSpaceError, assertDatabaseCopySpace, pruneDatabaseCopies, type DatabaseCopy } from "./backup-policy.js";
|
|
8
9
|
export type { SqliteBackupSource, SqliteRecoveryHook, OpenSqliteConnectionOptions } from "./restore-types.js";
|
|
9
10
|
export type { SqliteSyncClient, SqliteSyncStatement, SqliteSyncTransaction, SqliteSyncOpener, SqliteDb } from "./sync-types.js";
|
|
10
11
|
export { inspectSqliteDatabase, verifySqliteIntegrity } from "./inspect.js";
|
package/dist/sqlite/index.js
CHANGED
|
@@ -3,5 +3,6 @@ export { SqliteClientError } from "./checked-state.js";
|
|
|
3
3
|
export { withSqliteTransaction } from "./transaction.js";
|
|
4
4
|
export { openSqliteConnection, DEFAULT_PRAGMAS } from "./open.js";
|
|
5
5
|
export { SqliteDbOpsAdapter } from "./db-ops.js";
|
|
6
|
+
export { DATABASE_COPY_RETENTION, DatabaseDiskSpaceError, assertDatabaseCopySpace, pruneDatabaseCopies } from "./backup-policy.js";
|
|
6
7
|
export { inspectSqliteDatabase, verifySqliteIntegrity } from "./inspect.js";
|
|
7
8
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jini-ai/db",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.17",
|
|
4
4
|
"description": "Database ports, connection helpers, ownership, isolated Kysely kernels and migrations. All peers are optional; drivers are injected.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -210,7 +210,7 @@
|
|
|
210
210
|
},
|
|
211
211
|
"dependencies": {
|
|
212
212
|
"kysely": "^0.29.6",
|
|
213
|
-
"@jini-ai/core": "^0.6.
|
|
213
|
+
"@jini-ai/core": "^0.6.17"
|
|
214
214
|
},
|
|
215
215
|
"peerDependencies": {
|
|
216
216
|
"better-sqlite3": "^13.0.0",
|
|
@@ -226,8 +226,8 @@
|
|
|
226
226
|
"better-sqlite3": "13.0.3",
|
|
227
227
|
"kysely": "0.29.6",
|
|
228
228
|
"pg": "8.23.0",
|
|
229
|
-
"@jini-ai/
|
|
230
|
-
"@jini-ai/
|
|
229
|
+
"@jini-ai/platform": "0.6.17",
|
|
230
|
+
"@jini-ai/core": "0.6.17"
|
|
231
231
|
},
|
|
232
232
|
"peerDependenciesMeta": {
|
|
233
233
|
"better-sqlite3": {
|