@jini-ai/db 0.6.15 → 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 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 () => { },
@@ -1,4 +1,4 @@
1
1
  /** Kysely's SQLite binding and kernel storage operations. */
2
2
  export { sqliteKernel, openSqliteFileKernel, openMemorySqliteKernel, closeSqliteConnection, sqliteClientOf, sqliteConnectionOf, type SqliteConnectionSource, type SqliteKernel } from "./driver.js";
3
- export { sqliteOps } from "./ops.js";
3
+ export { sqliteOps, copySqliteInto } from "./ops.js";
4
4
  //# sourceMappingURL=index.d.ts.map
@@ -1,4 +1,4 @@
1
1
  /** Kysely's SQLite binding and kernel storage operations. */
2
2
  export { sqliteKernel, openSqliteFileKernel, openMemorySqliteKernel, closeSqliteConnection, sqliteClientOf, sqliteConnectionOf } from "./driver.js";
3
- export { sqliteOps } from "./ops.js";
3
+ export { sqliteOps, copySqliteInto } from "./ops.js";
4
4
  //# sourceMappingURL=index.js.map
@@ -1,4 +1,17 @@
1
1
  import { type StorageKernel, type StorageOps } from "../index.js";
2
+ /** Synchronous WAL-safe snapshot for admission code that must commit under a synchronous lock.
3
+ * Accepts either the host's SQLite client or Node's built-in DatabaseSync; the caller owns it.
4
+ * @throws SQLite errors, including an existing destination or an active transaction.
5
+ * @complexity O(database bytes), performed by SQLite without buffering the database in JS.
6
+ */
7
+ export declare function copySqliteInto({ source, targetPath }: {
8
+ source: {
9
+ prepare(sql: string): {
10
+ run(targetPath: string): unknown;
11
+ };
12
+ };
13
+ targetPath: string;
14
+ }, _options?: {}): void;
2
15
  /**
3
16
  * The storage ops (`@jini-ai/db/kernel`'s `StorageOps`) for a kernel the sqlite driver built:
4
17
  * `VACUUM INTO` for the copy; `VACUUM` + WAL checkpoint + `integrity_check` for compacting. Must be
@@ -1,5 +1,14 @@
1
1
  import { outsideTransactionOf, StorageOpError } from "../index.js";
2
2
  import { sqliteConnectionOf } from "./driver.js";
3
+ /** Synchronous WAL-safe snapshot for admission code that must commit under a synchronous lock.
4
+ * Accepts either the host's SQLite client or Node's built-in DatabaseSync; the caller owns it.
5
+ * @throws SQLite errors, including an existing destination or an active transaction.
6
+ * @complexity O(database bytes), performed by SQLite without buffering the database in JS.
7
+ */
8
+ export function copySqliteInto({ source, targetPath }, _options = {}) {
9
+ // Bind the destination: quotes in a folder name must never become SQL syntax.
10
+ source.prepare("VACUUM INTO ?").run(targetPath);
11
+ }
3
12
  /**
4
13
  * The storage ops (`@jini-ai/db/kernel`'s `StorageOps`) for a kernel the sqlite driver built:
5
14
  * `VACUUM INTO` for the copy; `VACUUM` + WAL checkpoint + `integrity_check` for compacting. Must be
@@ -17,8 +26,7 @@ export function sqliteOps(kernel) {
17
26
  return {
18
27
  async copyTo(targetPath) {
19
28
  outsideTransaction("copyTo");
20
- // Bound parameter: VACUUM INTO takes an expression, so the path is never spliced into SQL.
21
- client.prepare("VACUUM INTO ?").run(targetPath);
29
+ copySqliteInto({ source: client, targetPath });
22
30
  },
23
31
  async compactAndVerify() {
24
32
  outsideTransaction("compactAndVerify");
@@ -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"). */
@@ -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 = options.backupPath === undefined ? { note } : { backupPath: options.backupPath, note };
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
- await kernel.backupTo(target);
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)
@@ -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
@@ -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.
@@ -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
  }
@@ -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";
@@ -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
@@ -69,6 +69,17 @@ export interface TransferSource {
69
69
  rows(table: string, columns: readonly string[], keep?: string): Iterable<unknown[]>;
70
70
  close(): void;
71
71
  }
72
+ /**
73
+ * A site database runs in WAL mode, and its snapshot's header says so (bytes 18-19 = 2). SQLite
74
+ * cannot open WAL-mode bytes in memory ("unable to open database file"), so a copy of the bytes is
75
+ * marked rollback-journal (1) first. The pages themselves are complete: a backup never needs the WAL.
76
+ * For complete backup/serialized images only, never a live main file with unapplied WAL pages.
77
+ * @returns Readable bytes; WAL headers are changed only on a copy, leaving the input untouched.
78
+ * @complexity O(snapshot bytes) time/space for WAL images, otherwise O(1).
79
+ */
80
+ export declare function inMemoryReadableBytes({ bytes }: {
81
+ bytes: Buffer;
82
+ }, _options?: Record<string, never>): Buffer;
72
83
  /** @complexity O(database size) to deserialize the snapshot. */
73
84
  export declare function openSqliteSnapshotSource({ bytes }: {
74
85
  bytes: Buffer;
@@ -9,8 +9,11 @@ function where(keep) {
9
9
  * A site database runs in WAL mode, and its snapshot's header says so (bytes 18-19 = 2). SQLite
10
10
  * cannot open WAL-mode bytes in memory ("unable to open database file"), so a copy of the bytes is
11
11
  * marked rollback-journal (1) first. The pages themselves are complete: a backup never needs the WAL.
12
+ * For complete backup/serialized images only, never a live main file with unapplied WAL pages.
13
+ * @returns Readable bytes; WAL headers are changed only on a copy, leaving the input untouched.
14
+ * @complexity O(snapshot bytes) time/space for WAL images, otherwise O(1).
12
15
  */
13
- function inMemoryReadableBytes(bytes) {
16
+ export function inMemoryReadableBytes({ bytes }, _options = {}) {
14
17
  if (bytes[18] !== 2 && bytes[19] !== 2)
15
18
  return bytes;
16
19
  const copy = Buffer.from(bytes);
@@ -57,7 +60,7 @@ function layoutOf(db, table) {
57
60
  }
58
61
  /** @complexity O(database size) to deserialize the snapshot. */
59
62
  export function openSqliteSnapshotSource({ bytes }, { open }) {
60
- const db = open(inMemoryReadableBytes(bytes), { readonly: true });
63
+ const db = open(inMemoryReadableBytes({ bytes }), { readonly: true });
61
64
  return {
62
65
  tableNames() {
63
66
  return db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").all().map((row) => row.name);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/db",
3
- "version": "0.6.15",
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": {
@@ -35,6 +35,12 @@
35
35
  "src/kernel/typegen.ts",
36
36
  "src/sqlite/checked-state.ts"
37
37
  ]
38
+ },
39
+ "optionalPeers": {
40
+ "better-sqlite3": "opt-in: sqlite storage — SQLite storage could not load better-sqlite3. Install better-sqlite3 to enable this feature, or check its installed version and native binaries.",
41
+ "@electric-sql/pglite": "opt-in: embedded postgresql storage — Embedded PostgreSQL storage could not load @electric-sql/pglite. Install @electric-sql/pglite to enable this feature, or check its installed version and native binaries.",
42
+ "pg": "opt-in: postgresql storage — PostgreSQL storage could not load pg. Install pg to enable this feature, or check its installed version and native binaries.",
43
+ "@jini-ai/platform": "opt-in: platform-backed adapters; import @jini-ai/db/secrets-vault — Platform-backed adapters could not load @jini-ai/platform. Install @jini-ai/platform to enable this feature, or check its installed version and native binaries."
38
44
  }
39
45
  },
40
46
  "type": "module",
@@ -203,15 +209,26 @@
203
209
  "registry": "https://registry.npmjs.org"
204
210
  },
205
211
  "dependencies": {
206
- "@jini-ai/core": "^0.6.15"
212
+ "kysely": "^0.29.6",
213
+ "@jini-ai/core": "^0.6.17"
207
214
  },
208
215
  "peerDependencies": {
209
- "kysely": "^0.29.6",
210
216
  "better-sqlite3": "^13.0.0",
211
217
  "@electric-sql/pglite": "0.5.8",
212
218
  "pg": "^8.23.0",
213
219
  "@jini-ai/platform": "^0.6.10"
214
220
  },
221
+ "devDependencies": {
222
+ "@electric-sql/pglite": "0.5.8",
223
+ "@types/better-sqlite3": "7.6.13",
224
+ "@types/pg": "8.23.1",
225
+ "@vitest/coverage-v8": "^2.1.9",
226
+ "better-sqlite3": "13.0.3",
227
+ "kysely": "0.29.6",
228
+ "pg": "8.23.0",
229
+ "@jini-ai/platform": "0.6.17",
230
+ "@jini-ai/core": "0.6.17"
231
+ },
215
232
  "peerDependenciesMeta": {
216
233
  "better-sqlite3": {
217
234
  "optional": true
@@ -222,24 +239,10 @@
222
239
  "pg": {
223
240
  "optional": true
224
241
  },
225
- "kysely": {
226
- "optional": true
227
- },
228
242
  "@jini-ai/platform": {
229
243
  "optional": true
230
244
  }
231
245
  },
232
- "devDependencies": {
233
- "@electric-sql/pglite": "0.5.8",
234
- "@types/better-sqlite3": "7.6.13",
235
- "@types/pg": "8.23.1",
236
- "@vitest/coverage-v8": "^2.1.9",
237
- "better-sqlite3": "13.0.3",
238
- "kysely": "0.29.6",
239
- "pg": "8.23.0",
240
- "@jini-ai/core": "0.6.15",
241
- "@jini-ai/platform": "0.6.15"
242
- },
243
246
  "scripts": {
244
247
  "build": "tsc -p tsconfig.build.json",
245
248
  "typecheck": "tsc -p tsconfig.json --noEmit",