Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
standalone/backup: use a proper way to generate backups
Adorian Doran8e8fc2b7c29f
diff --git a/apps/standalone/src/lightweight/backup-stream.spec.ts b/apps/standalone/src/lightweight/backup-stream.spec.tsnew file mode 100644index 0000000000..1ffa81ee90--- /dev/null+++ b/apps/standalone/src/lightweight/backup-stream.spec.ts@@ -0,0 +1,252 @@+import { getSql } from "@triliumnext/core";+import { describe, expect, it } from "vitest";++import {+ openBackupDestination,+ type SnapshotConnection,+ type SnapshotStatement,+ streamDatabasePages,+ type SyncFileAccess+} from "./backup-stream.js";+import BrowserSqlProvider from "./sql_provider.js";++// The sqlite-wasm module can only be initialized once per worker (test_setup.ts already does it+// for core), so every provider here borrows that module rather than calling initWasm() again.+type WithSqlite3 = {+ sqlite3: {+ capi: { sqlite3_js_db_export(db: unknown): Uint8Array };+ oo1: { DB: new (filename: string, flags?: string) => SnapshotConnection };+ };+};+type WithDb = { db: SnapshotConnection };++function newProviderWithModule(): BrowserSqlProvider {+ const provider = new BrowserSqlProvider();+ (provider as unknown as WithSqlite3).sqlite3 =+ (getSql() as unknown as { dbConnection: unknown } as { dbConnection: WithSqlite3 })+ .dbConnection.sqlite3;+ return provider;+}++function rawConnection(provider: BrowserSqlProvider): SnapshotConnection {+ return (provider as unknown as WithDb).db;+}++async function drain(stream: ReadableStream<Uint8Array>): Promise<Uint8Array> {+ const chunks: Uint8Array[] = [];+ const reader = stream.getReader();+ for (;;) {+ const { done, value } = await reader.read();+ if (done) {+ break;+ }+ chunks.push(value);+ }++ const whole = new Uint8Array(chunks.reduce((total, chunk) => total + chunk.byteLength, 0));+ let offset = 0;+ for (const chunk of chunks) {+ whole.set(chunk, offset);+ offset += chunk.byteLength;+ }+ return whole;+}++describe("streamDatabasePages against the real engine", () => {+ it("streams a database as its exact file bytes", async () => {+ const provider = newProviderWithModule();+ provider.loadFromMemory();+ provider.exec("CREATE TABLE t (id INTEGER PRIMARY KEY, payload BLOB)");+ // Enough rows to span several batches even at the smallest page size.+ provider.exec("INSERT INTO t (payload) SELECT randomblob(1000) "+ + "FROM (WITH RECURSIVE c(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM c WHERE n < 500) "+ + "SELECT n FROM c)");++ const connection = rawConnection(provider);+ const exported = (provider as unknown as WithSqlite3).sqlite3.capi+ .sqlite3_js_db_export(connection);++ const { byteSize, stream } = streamDatabasePages(connection);+ const streamed = await drain(stream);++ expect(byteSize).toBe(exported.byteLength);+ expect(streamed.byteLength).toBe(byteSize);+ expect(streamed).toEqual(exported);+ });++ it("round-trips through VACUUM INTO the way a backup does", async () => {+ const provider = newProviderWithModule();+ provider.loadFromMemory();+ provider.exec("CREATE TABLE notes (id INTEGER PRIMARY KEY, title TEXT)");+ provider.exec("INSERT INTO notes (title) VALUES ('first'), ('second')");+ // Deleted rows leave freelist pages behind, which the vacuum must drop.+ provider.exec("INSERT INTO notes (id, title) VALUES (99, 'doomed')");+ provider.exec("DELETE FROM notes WHERE id = 99");++ provider.exec("VACUUM INTO 'backup-stream-snapshot.db'");+ // Opened the way the backup service opens a pool snapshot, minus the pool: straight oo1.+ const sqlite3 = (provider as unknown as WithSqlite3).sqlite3;+ const snapshot = new sqlite3.oo1.DB("backup-stream-snapshot.db", "r");++ const streamed = await drain(streamDatabasePages(snapshot).stream);++ const restored = newProviderWithModule();+ restored.loadFromBuffer(streamed);+ expect(restored.prepare("SELECT count(*) FROM notes").pluck().get([])).toBe(2);+ expect(restored.prepare("SELECT title FROM notes ORDER BY id").pluck().all())+ .toEqual([ "first", "second" ]);+ restored.close();+ provider.close();+ });+});++/** A connection serving `pageCount` constant-filled pages of `pageSize` bytes. */+function fakeConnection(pageSize: number, pageCount: number): SnapshotConnection & {+ closed: number;+ finalized: number;+} {+ const self = {+ closed: 0,+ finalized: 0,+ selectValue(sql: string) {+ return sql.includes("page_size") ? pageSize : pageCount;+ },+ prepare(): SnapshotStatement {+ let bound = 0;+ return {+ bind(values: unknown[]) {+ bound = values[0] as number;+ return this;+ },+ step: () => bound >= 1 && bound <= pageCount,+ get: () => [ new Uint8Array(pageSize).fill(bound & 0xff) ],+ reset: () => undefined,+ finalize: () => void self.finalized+++ };+ },+ close: () => void self.closed+++ };+ return self;+}++describe("streamDatabasePages error handling", () => {+ it("refuses a database that reports no usable page size", () => {+ const connection = fakeConnection(0, 4);+ expect(() => streamDatabasePages(connection)).toThrow(/page_size/);+ });++ it("names sqlite_dbpage when the statement cannot be prepared", () => {+ const connection = fakeConnection(512, 4);+ connection.prepare = () => {+ throw new Error("no such table: sqlite_dbpage");+ };+ expect(() => streamDatabasePages(connection)).toThrow(/sqlite_dbpage/);+ });++ it("errors the stream and releases the connection when a page goes missing", async () => {+ const connection = fakeConnection(512, 4);+ const statement = connection.prepare("");+ statement.step = () => false;+ connection.prepare = () => statement;++ const { stream } = streamDatabasePages(connection);+ await expect(drain(stream)).rejects.toThrow(/page 1/);+ expect(connection.closed).toBe(1);+ expect(connection.finalized).toBe(1);+ });++ it("errors the stream when a page comes back the wrong size", async () => {+ const connection = fakeConnection(512, 4);+ const statement = connection.prepare("");+ statement.get = () => [ new Uint8Array(100) ];+ connection.prepare = () => statement;++ await expect(drain(streamDatabasePages(connection).stream)).rejects.toThrow(/malformed/);+ expect(connection.closed).toBe(1);+ });++ it("releases the connection exactly once when the stream is cancelled", async () => {+ const connection = fakeConnection(512, 4);+ const { stream } = streamDatabasePages(connection);++ const reader = stream.getReader();+ await reader.read();+ await reader.cancel();++ expect(connection.closed).toBe(1);+ expect(connection.finalized).toBe(1);+ });+});++/** An in-memory file recording every write, able to act short or full on demand. */+function fakeFile(maxWrite = Number.POSITIVE_INFINITY): SyncFileAccess & {+ bytes: Uint8Array;+ truncated: number[];+ flushes: number;+ closes: number;+} {+ const self = {+ bytes: new Uint8Array(0),+ truncated: [] as number[],+ flushes: 0,+ closes: 0,+ write(buffer: Uint8Array, options?: { at?: number }) {+ const at = options?.at ?? 0;+ const count = Math.min(buffer.byteLength, maxWrite);+ if (at + count > self.bytes.byteLength) {+ const grown = new Uint8Array(at + count);+ grown.set(self.bytes);+ self.bytes = grown;+ }+ self.bytes.set(buffer.subarray(0, count), at);+ return count;+ },+ truncate: (size: number) => void self.truncated.push(size),+ flush: () => void self.flushes++,+ close: () => void self.closes+++ };+ return self;+}++describe("openBackupDestination", () => {+ it("writes sequentially, patches at an offset after close, and releases once", async () => {+ const file = fakeFile();+ const destination = openBackupDestination(file);+ expect(file.truncated).toEqual([ 0 ]);++ const writer = destination.writable.getWriter();+ await writer.write(new Uint8Array([ 1, 2, 3 ]));+ await writer.write(new Uint8Array([ 4, 5 ]));+ await writer.close();++ // The patch lands while the file is still open, as the container's digest fixup does.+ destination.patch(1, new Uint8Array([ 9, 9 ]));+ destination.close();+ destination.close();++ expect(Array.from(file.bytes)).toEqual([ 1, 9, 9, 4, 5 ]);+ expect(file.closes).toBe(1);+ expect(file.flushes).toBeGreaterThan(0);+ });++ it("loops short writes until the chunk is fully written", async () => {+ const file = fakeFile(2);+ const destination = openBackupDestination(file);++ const writer = destination.writable.getWriter();+ await writer.write(new Uint8Array([ 1, 2, 3, 4, 5 ]));+ await writer.close();+ destination.close();++ expect(Array.from(file.bytes)).toEqual([ 1, 2, 3, 4, 5 ]);+ });++ it("reports a file that stops accepting writes instead of spinning", async () => {+ const file = fakeFile(0);+ const destination = openBackupDestination(file);++ const writer = destination.writable.getWriter();+ await expect(writer.write(new Uint8Array([ 1 ]))).rejects.toThrow(/stopped accepting/);+ destination.close();+ });+});diff --git a/apps/standalone/src/lightweight/backup-stream.ts b/apps/standalone/src/lightweight/backup-stream.tsnew file mode 100644index 0000000000..6b846ed6e1--- /dev/null+++ b/apps/standalone/src/lightweight/backup-stream.ts@@ -0,0 +1,212 @@+/**+ * Streams a database between the SAH pool and a plain OPFS file without ever holding it whole.+ *+ * The pool has no streaming read: its `exportFile` builds the entire file as one array, which for+ * a database measured in gigabytes is the difference between a backup and a crashed tab. What it+ * does have is SQLite itself, and SQLite can serve its own file a page at a time through the+ * `sqlite_dbpage` table, the same mechanism the official `sqlite3_rsync` utility is built on. For+ * a quiesced, freshly `VACUUM INTO`-ed database the pages in order *are* the file, byte for byte,+ * and SQLite hands them over without this code knowing anything about their layout.+ *+ * The two halves here are deliberately dumb pipes: {@link streamDatabasePages} turns an open+ * database into a `ReadableStream` of page batches, and {@link openBackupDestination} turns a+ * synchronous OPFS file handle into the `WritableStream`-plus-random-access the backup container+ * writer needs. What flows between them, and whether a container wraps it, is the caller's story.+ *+ * @module+ */++/** How many pages travel per stream chunk: 1 MiB at the default 8 KiB page size. */+const BATCH_PAGES = 128;++/** What the page streamer asks of a database connection. `oo1.DB` matches it as it stands. */+export interface SnapshotConnection {+ selectValue(sql: string, bind?: unknown[]): unknown;+ prepare(sql: string): SnapshotStatement;+ close(): void;+}++/** The slice of a prepared statement the page reads use. */+export interface SnapshotStatement {+ bind(values: unknown[]): unknown;+ step(): boolean;+ get(target: unknown[]): unknown[];+ reset(): unknown;+ finalize(): unknown;+}++export interface DatabaseStream {+ /** Exact size of the streamed database, known before the first byte flows. */+ byteSize: number;+ stream: ReadableStream<Uint8Array>;+}++/**+ * Streams the database open on `db` as its exact file bytes, a batch of pages at a time.+ *+ * The connection is taken over: it is closed when the stream ends, errors, or is cancelled, and+ * must not be used by anyone else meanwhile. The database must be quiescent and not in WAL mode,+ * which is what `VACUUM INTO` produces; a database being written to mid-stream would hand over+ * pages of two different files.+ *+ * @throws Error before any stream exists when the engine lacks `sqlite_dbpage`, so a caller fails+ * before it has created a destination to clean up.+ */+export function streamDatabasePages(db: SnapshotConnection): DatabaseStream {+ let pageSize: number;+ let pageCount: number;+ let statement: SnapshotStatement;+ try {+ pageSize = countOf(db.selectValue("PRAGMA page_size"), "page_size");+ pageCount = countOf(db.selectValue("PRAGMA page_count"), "page_count");+ statement = preparePageReader(db);+ } catch (e) {+ // The connection was taken over, so it is not left open on the way out either.+ db.close();+ throw e;+ }++ let nextPage = 1;+ let released = false;+ const release = () => {+ if (!released) {+ released = true;+ statement.finalize();+ db.close();+ }+ };++ return {+ byteSize: pageSize * pageCount,+ stream: new ReadableStream<Uint8Array>({+ pull(controller) {+ try {+ if (nextPage > pageCount) {+ release();+ controller.close();+ return;+ }++ const pages = Math.min(BATCH_PAGES, pageCount - nextPage + 1);+ const batch = new Uint8Array(pages * pageSize);+ for (let index = 0; index < pages; index++, nextPage++) {+ batch.set(readPage(statement, nextPage, pageSize), index * pageSize);+ }+ controller.enqueue(batch);+ } catch (e) {+ release();+ controller.error(e);+ }+ },+ cancel: release+ })+ };+}++/** The slice of `FileSystemSyncAccessHandle` a backup write needs, kept structural for tests. */+export interface SyncFileAccess {+ write(buffer: Uint8Array, options?: { at?: number }): number;+ truncate(newSize: number): void;+ flush(): void;+ close(): void;+}++export interface BackupDestination {+ /** Takes the payload in order. Closing it flushes but keeps the file open for {@link patch}. */+ writable: WritableStream<Uint8Array>;+ /** Writes at an absolute offset: the digest a container learns only after its payload. */+ patch(offset: number, data: Uint8Array): void;+ /** Flushes and releases the file. Safe to call more than once, and meant for a `finally`. */+ close(): void;+}++/**+ * Turns a synchronous OPFS file handle into a backup destination.+ *+ * The handle is truncated on open, so a leftover from an interrupted attempt is overwritten rather+ * than appended to, and it stays open across the writable's own close: the container writer patches+ * its header digest *after* it has ended the payload stream, and reopening the file between the two+ * would be a second handle on a file the first still locks.+ */+export function openBackupDestination(access: SyncFileAccess): BackupDestination {+ access.truncate(0);+ let offset = 0;+ let open = true;++ return {+ writable: new WritableStream<Uint8Array>({+ write(chunk) {+ offset += writeFully(access, chunk, offset);+ },+ close() {+ access.flush();+ }+ }),+ patch(at, data) {+ writeFully(access, data, at);+ },+ close() {+ if (open) {+ open = false;+ access.flush();+ access.close();+ }+ }+ };+}++function preparePageReader(db: SnapshotConnection): SnapshotStatement {+ try {+ return db.prepare("SELECT data FROM sqlite_dbpage WHERE pgno = ?");+ } catch (e) {+ throw new Error("This SQLite build cannot serve database pages (sqlite_dbpage is "+ + `missing), so nothing can be backed up: ${messageOf(e)}`);+ }+}++/** One page, checked to be exactly a page: anything else means the file is not what it claims. */+function readPage(statement: SnapshotStatement, pageNumber: number, pageSize: number): Uint8Array {+ statement.bind([ pageNumber ]);+ try {+ if (!statement.step()) {+ throw new Error(`The database did not serve page ${pageNumber}.`);+ }++ const data = statement.get([])[0];+ if (!(data instanceof Uint8Array) || data.byteLength !== pageSize) {+ throw new Error(`Page ${pageNumber} came back malformed.`);+ }+ return data;+ } finally {+ statement.reset();+ }+}++/** A pragma answer as the positive integer it must be, or the reason it is not a database. */+function countOf(value: unknown, name: string): number {+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) {+ throw new Error(`The database reports no usable ${name} (got ${String(value)}).`);+ }+ return value;+}++/**+ * Writes all of `data` at `at`, looping in case the handle takes it piecemeal. The specification+ * lets `write` return short; a handle doing so repeatedly without progress is reported rather than+ * spun on.+ */+function writeFully(access: SyncFileAccess, data: Uint8Array, at: number): number {+ let written = 0;+ while (written < data.byteLength) {+ const count = access.write(data.subarray(written), { at: at + written });+ if (!(count > 0)) {+ throw new Error("The backup file stopped accepting writes.");+ }+ written += count;+ }+ return written;+}++function messageOf(e: unknown): string {+ return e instanceof Error ? e.message : String(e);+}diff --git a/apps/standalone/src/lightweight/backup_provider.spec.ts b/apps/standalone/src/lightweight/backup_provider.spec.tsindex af225e1294..f11d05f9fb 100644--- a/apps/standalone/src/lightweight/backup_provider.spec.ts+++ b/apps/standalone/src/lightweight/backup_provider.spec.ts@@ -1,35 +1,77 @@-import { getSql, options } from "@triliumnext/core";+import { readBackupContainer } from "@triliumnext/backup-container";+import { peekBackupContainer } from "@triliumnext/backup-container/web";+import { options } from "@triliumnext/core";+import { Readable, Writable } from "stream";import { afterEach, describe, expect, it, vi } from "vitest";-import StandaloneBackupService from "./backup_provider.js";+import StandaloneBackupService, {+ type BackupSqlAccess,+ type SnapshotPool+} from "./backup_provider.js";interface NavWithStorage {- storage?: { getDirectory?: () => Promise<unknown> };+ storage?: {+ getDirectory?: () => Promise<unknown>;+ estimate?: () => Promise<{ quota?: number; usage?: number }>;+ };}const realStorageDescriptor = Object.getOwnPropertyDescriptor(navigator, "storage");-/** Build an in-memory OPFS directory handle backed by a Map. */+/**+ * An in-memory OPFS directory backed by a Map, close enough for the service: file handles carry+ * `getFile` (with `slice`, for the container header peek) and `createSyncAccessHandle` (which is+ * how backups are written).+ */function makeOpfs(seed: Record<string, { data: Uint8Array; lastModified: number }> = {}) {const files = new Map(Object.entries(seed));+ const failures = { syncAccess: false };+ let clock = 1000;function fileHandle(name: string) {return {kind: "file" as const,async getFile() {const entry = files.get(name);+ const data = entry?.data ?? new Uint8Array();return {lastModified: entry?.lastModified ?? 0,+ size: data.byteLength,+ slice(start?: number, end?: number) {+ const part = data.slice(start, end);+ return { async arrayBuffer() {+ return part.buffer.slice(part.byteOffset, part.byteOffset + part.byteLength);+ } };+ },async arrayBuffer() {- return (entry?.data ?? new Uint8Array()).buffer;+ return data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);}};},- async createWritable() {- let chunk = new Uint8Array();+ async createSyncAccessHandle() {+ if (failures.syncAccess) {+ throw new Error("file is locked");+ }return {- async write(d: Uint8Array) { chunk = d; },- async close() { files.set(name, { data: chunk, lastModified: 1000 }); }+ write(buffer: Uint8Array, opts?: { at?: number }) {+ const at = opts?.at ?? 0;+ const current = files.get(name)?.data ?? new Uint8Array();+ const grown = at + buffer.byteLength > current.byteLength+ ? new Uint8Array(at + buffer.byteLength)+ : current;+ if (grown !== current) {+ grown.set(current);+ }+ grown.set(buffer, at);+ files.set(name, { data: grown, lastModified: clock++ });+ return buffer.byteLength;+ },+ truncate(size: number) {+ const current = files.get(name)?.data ?? new Uint8Array();+ files.set(name, { data: current.slice(0, size), lastModified: clock++ });+ },+ flush() {},+ close() {}};}};@@ -37,32 +79,130 @@ function makeOpfs(seed: Record<string, { data: Uint8Array; lastModified: numberconst dir = {async getFileHandle(name: string, opts?: { create?: boolean }) {- if (!files.has(name) && opts?.create) {- files.set(name, { data: new Uint8Array(), lastModified: 0 });- }if (!files.has(name)) {- throw new Error(`missing ${name}`);+ if (!opts?.create) {+ throw new Error(`missing ${name}`);+ }+ files.set(name, { data: new Uint8Array(), lastModified: clock++ });}return fileHandle(name);},- async removeEntry(name: string) { files.delete(name); },+ async removeEntry(name: string) {+ if (!files.delete(name)) {+ throw new Error(`missing ${name}`);+ }+ },async *entries(): AsyncGenerator<[string, unknown]> {- // include a directory entry and a non-matching file to exercise filtering- yield ["nested", { kind: "directory" }];- for (const [name, entry] of files) {- yield [name, {- kind: "file",- async getFile() { return { lastModified: entry.lastModified, size: entry.data.byteLength }; }- }];+ // A directory entry and a non-backup file exercise the listing filters.+ yield [ "nested", { kind: "directory" } ];+ for (const name of [ ...files.keys() ]) {+ yield [ name, fileHandle(name) ];}}};- return { dir, files, root: { async getDirectoryHandle() { return dir; } } };+ return { dir, files, failures, root: { async getDirectoryHandle() { return dir; } } };+}++function installOpfs(+ getDirectory: () => Promise<unknown>,+ estimate?: () => Promise<{ quota?: number; usage?: number }>+) {+ Object.defineProperty(navigator, "storage", {+ value: { getDirectory, estimate },+ configurable: true+ });}-function installOpfs(getDirectory: () => Promise<unknown>) {- Object.defineProperty(navigator, "storage", { value: { getDirectory }, configurable: true });+/** What the first page must start with: the container reader refuses payloads without it. */+const SQLITE_MAGIC = new TextEncoder().encode("SQLite format 3\u0000");++/** One fake page: filled with its own number, except that page 1 opens like a real database. */+function pageBytes(page: number, pageSize: number): Uint8Array {+ const bytes = new Uint8Array(pageSize).fill(page & 0xff);+ if (page === 1) {+ bytes.set(SQLITE_MAGIC);+ // Big-endian page size at offset 16, which the container reader checks as well.+ bytes[16] = pageSize >> 8;+ bytes[17] = pageSize & 0xff;+ }+ return bytes;+}++/**+ * A SQL provider whose pool serves `pageCount` pages of `pageSize` bytes for whatever snapshot+ * name is opened. What the service executed and unlinked is recorded for the assertions.+ */+function makeSqlAccess({ pageSize = 512, pageCount = 8, free = 1 } = {}) {+ const executed: string[] = [];+ const unlinked: string[] = [];+ const capacityAdded: number[] = [];++ class FakePoolDb {+ constructor(readonly name: string) {}+ selectValue(sql: string) {+ return sql.includes("page_size") ? pageSize : pageCount;+ }+ prepare() {+ let page = 0;+ return {+ bind: (values: unknown[]) => void (page = values[0] as number),+ step: () => page >= 1 && page <= pageCount,+ get: () => [ pageBytes(page, pageSize) ],+ reset: () => undefined,+ finalize: () => undefined+ };+ }+ close() {}+ }++ const pool = {+ OpfsSAHPoolDb: FakePoolDb,+ unlink: (name: string) => {+ unlinked.push(name);+ return true;+ },+ getFileCount: () => 6 - free,+ getCapacity: () => 6,+ addCapacity: async (entries: number) => {+ capacityAdded.push(entries);+ return 6 + entries;+ }+ } as unknown as SnapshotPool;++ const access: BackupSqlAccess = {+ exec: (sql: string) => void executed.push(sql),+ sahPool: pool+ };++ return { access, executed, unlinked, capacityAdded, pool };+}++function service(access?: BackupSqlAccess) {+ return new StandaloneBackupService(options, () => access);+}++/** Unwraps a container through the Node reader, proving the web writer's output reads back. */+async function unwrapContainer(container: Uint8Array): Promise<Uint8Array> {+ const chunks: Buffer[] = [];+ const sink = new Writable({+ write(chunk: Buffer, _encoding, callback) {+ chunks.push(chunk);+ callback();+ }+ });+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- a Node stream over the bytes.+ await readBackupContainer(Readable.from([ Buffer.from(container) ]) as any, sink);+ return new Uint8Array(Buffer.concat(chunks));+}++/** The bytes the fake pool's snapshot streams out as: pages 1..n, laid end to end. */+function expectedSnapshotBytes(pageSize = 512, pageCount = 8): Uint8Array {+ const bytes = new Uint8Array(pageSize * pageCount);+ for (let page = 1; page <= pageCount; page++) {+ bytes.set(pageBytes(page, pageSize), (page - 1) * pageSize);+ }+ return bytes;}afterEach(() => {@@ -77,7 +217,7 @@ afterEach(() => {describe("StandaloneBackupService without OPFS", () => {function serviceWithoutOpfs() {delete (navigator as unknown as NavWithStorage).storage;- return new StandaloneBackupService(options);+ return service(makeSqlAccess().access);}it("scheduleBackups is a no-op", () => {@@ -86,117 +226,261 @@ describe("StandaloneBackupService without OPFS", () => {it("backupNow warns and returns the nominal path", async () => {const warn = vi.spyOn(console, "warn").mockImplementation(() => {});- const service = serviceWithoutOpfs();- expect(await service.backupNow("now")).toBe("/backups/backup-now.db");+ expect(await serviceWithoutOpfs().backupNow("now")).toBe("/backups/backup-now.db");expect(warn).toHaveBeenCalled();});- it("listing, deleting and reading return empty results", async () => {- const service = serviceWithoutOpfs();- expect(await service.getExistingBackups()).toEqual([]);- await expect(service.deleteBackup("backup-x.db")).resolves.toBeUndefined();- expect(await service.getBackupContent("/backups/backup-x.db")).toBeNull();+ it("backupAs refuses outright, because its caller shows the result to the user", async () => {+ await expect(serviceWithoutOpfs().backupAs("Backup 1")).rejects.toThrow(/OPFS/);});- it("ensureBackupDirectory resolves to null when OPFS is unavailable", async () => {- const service = serviceWithoutOpfs();- const ensure = (service as unknown as { ensureBackupDirectory(): Promise<unknown> }).ensureBackupDirectory();- expect(await ensure).toBeNull();+ it("listing, deleting and reading return empty results", async () => {+ const svc = serviceWithoutOpfs();+ expect(await svc.getExistingBackups()).toEqual([]);+ await expect(svc.deleteBackup("backup-x.db")).resolves.toBeUndefined();+ expect(await svc.getBackupContent("/backups/backup-x.db")).toBeNull();});});-describe("StandaloneBackupService with OPFS", () => {- it("writes a serialized backup and reports the path", async () => {+describe("StandaloneBackupService writing backups", () => {+ it("streams a plain .db backup out of a vacuumed pool snapshot", async () => {const fs = makeOpfs();installOpfs(async () => fs.root);vi.spyOn(console, "log").mockImplementation(() => {});+ const sql = makeSqlAccess();++ const path = await service(sql.access).backupNow("daily");- const service = new StandaloneBackupService(options);- const path = await service.backupNow("daily");expect(path).toBe("/backups/backup-daily.db");- expect(fs.files.get("backup-daily.db")?.data.byteLength).toBeGreaterThan(0);+ expect(fs.files.get("backup-daily.db")?.data).toEqual(expectedSnapshotBytes());+ expect(fs.files.has("backup-daily.db.part")).toBe(false);+ expect(sql.executed).toEqual([ "VACUUM INTO '/backup-snapshot.db'" ]);+ // Unlinked once to clear the name for the vacuum and once to clean up after.+ expect(sql.unlinked).toEqual([ "/backup-snapshot.db", "/backup-snapshot.db" ]);+ // One free slot is one short of snapshot plus journal.+ expect(sql.capacityAdded).toEqual([ 1 ]);});- it("leaves a database too large to hold in memory unbacked-up", async () => {+ it("sanitizes the backup name the way the server does", async () => {const fs = makeOpfs();installOpfs(async () => fs.root);- const warn = vi.spyOn(console, "warn").mockImplementation(() => {});- // Serializing builds the whole database in the WebAssembly heap twice over, so past a size- // the attempt takes the tab down rather than failing. Nothing is written instead.- vi.spyOn(getSql(), "getValue").mockReturnValue(4 * 1024 * 1024 * 1024);- const serialize = vi.spyOn(getSql(), "serialize");+ vi.spyOn(console, "log").mockImplementation(() => {});++ expect(await service(makeSqlAccess().access).backupNow("../evil name"))+ .toBe("/backups/backup-evilname.db");+ expect(fs.files.has("backup-evilname.db")).toBe(true);+ });++ it("wraps the backup in a compressed container when the option asks for it", async () => {+ const fs = makeOpfs({+ // A stale plain copy under the same base name, which the container must retire.+ "backup-daily.db": { data: new Uint8Array(4), lastModified: 1 }+ });+ installOpfs(async () => fs.root);+ vi.spyOn(console, "log").mockImplementation(() => {});+ vi.spyOn(options, "getOptionOrNull").mockImplementation(+ (name: string) => name === "backupEnableCompression" ? "true" : null+ );- expect(await new StandaloneBackupService(options).backupNow("before-migration"))- .toBe("/backups/backup-before-migration.db");+ const path = await service(makeSqlAccess().access).backupNow("daily");+ expect(path).toBe("/backups/backup-daily.tnbackup");- expect(serialize).not.toHaveBeenCalled();+ const container = fs.files.get("backup-daily.tnbackup")?.data;+ if (!container) {+ throw new Error("no container was written");+ }+ const info = peekBackupContainer(container.slice(0, 256));+ expect(info?.compressed).toBe(true);+ expect(info?.encrypted).toBe(false);+ expect(info?.plaintextSize).toBe(expectedSnapshotBytes().byteLength);++ expect(await unwrapContainer(container)).toEqual(expectedSnapshotBytes());+ expect(fs.files.has("backup-daily.db")).toBe(false);+ });++ it("refuses to start when the quota cannot hold the database", async () => {+ const fs = makeOpfs();+ installOpfs(async () => fs.root, async () => ({ quota: 100, usage: 100 }));+ const error = vi.spyOn(console, "error").mockImplementation(() => {});+ const sql = makeSqlAccess();++ await service(sql.access).backupNow("daily");++ expect(sql.executed).toEqual([]);expect(fs.files.size).toBe(0);- expect(warn).toHaveBeenCalled();+ expect(error.mock.calls.join("\n")).toMatch(/browser storage/);++ await expect(service(sql.access).backupAs("Backup 1")).rejects.toThrow(/browser storage/);});- it("lists matching backups newest-first and ignores non-backup entries", async () => {+ it("cleans up the ruined file and marker when the stream fails mid-write", async () => {+ const fs = makeOpfs();+ installOpfs(async () => fs.root);+ vi.spyOn(console, "error").mockImplementation(() => {});+ const sql = makeSqlAccess();+ // Pages come back the wrong size, which errors the stream partway through.+ sql.pool.OpfsSAHPoolDb = class {+ selectValue(query: string) {+ return query.includes("page_size") ? 512 : 8;+ }+ prepare() {+ return {+ bind: () => undefined,+ step: () => true,+ get: () => [ new Uint8Array(3) ],+ reset: () => undefined,+ finalize: () => undefined+ };+ }+ close() {}+ } as unknown as SnapshotPool["OpfsSAHPoolDb"];++ await service(sql.access).backupNow("daily");++ expect(fs.files.has("backup-daily.db")).toBe(false);+ expect(fs.files.has("backup-daily.db.part")).toBe(false);+ // The snapshot does not outlive the failure either.+ expect(sql.unlinked).toEqual([ "/backup-snapshot.db", "/backup-snapshot.db" ]);+ });++ it("keeps an older backup of the same name when the new file never opened", async () => {+ const previous = new Uint8Array([ 9, 9, 9 ]);+ const fs = makeOpfs({ "backup-daily.db": { data: previous, lastModified: 5 } });+ fs.failures.syncAccess = true;+ installOpfs(async () => fs.root);+ vi.spyOn(console, "error").mockImplementation(() => {});++ await service(makeSqlAccess().access).backupNow("daily");++ expect(fs.files.get("backup-daily.db")?.data).toEqual(previous);+ expect(fs.files.has("backup-daily.db.part")).toBe(false);+ });++ it("sweeps out an abandoned partial backup before writing the next one", async () => {+ const fs = makeOpfs({+ "backup-crashed.tnbackup": { data: new Uint8Array(10), lastModified: 1 },+ "backup-crashed.tnbackup.part": { data: new Uint8Array(), lastModified: 2 }+ });+ installOpfs(async () => fs.root);+ vi.spyOn(console, "log").mockImplementation(() => {});++ await service(makeSqlAccess().access).backupNow("daily");++ expect(fs.files.has("backup-crashed.tnbackup")).toBe(false);+ expect(fs.files.has("backup-crashed.tnbackup.part")).toBe(false);+ expect(fs.files.has("backup-daily.db")).toBe(true);+ });++ it("fails gracefully when no SQL access was wired in", async () => {+ installOpfs(async () => makeOpfs().root);+ const error = vi.spyOn(console, "error").mockImplementation(() => {});++ expect(await service(undefined).backupNow("daily")).toBe("/backups/backup-daily.db");+ expect(error).toHaveBeenCalled();+ });++ it("backupAs reports what it wrote and keeps path separators out of the name", async () => {+ const fs = makeOpfs();+ installOpfs(async () => fs.root);+ vi.spyOn(console, "log").mockImplementation(() => {});++ const written = await service(makeSqlAccess().access).backupAs("Backup 2026/08/07");++ expect(written).toEqual({+ fileName: "Backup 2026-08-07.db",+ filePath: "/backups/Backup 2026-08-07.db",+ directoryPath: "/backups",+ fileSize: expectedSnapshotBytes().byteLength,+ encrypted: false+ });+ expect(fs.files.has("Backup 2026-08-07.db")).toBe(true);+ });+});++describe("StandaloneBackupService listing and reading", () => {+ it("lists backups of both shapes newest-first, with container metadata", async () => {const fs = makeOpfs({"backup-old.db": { data: new Uint8Array(3), lastModified: 100 },- "backup-new.db": { data: new Uint8Array(8), lastModified: 200 },"notes.txt": { data: new Uint8Array(), lastModified: 300 }});installOpfs(async () => fs.root);+ vi.spyOn(console, "log").mockImplementation(() => {});+ vi.spyOn(options, "getOptionOrNull").mockImplementation(+ (name: string) => name === "backupEnableCompression" ? "true" : null+ );++ await service(makeSqlAccess().access).backupNow("new");+ const backups = await service(makeSqlAccess().access).getExistingBackups();++ expect(backups.map((backup) => backup.fileName))+ .toEqual([ "backup-new.tnbackup", "backup-old.db" ]);+ expect(backups[0].compressed).toBe(true);+ expect(backups[0].encrypted).toBe(false);+ expect(backups[0].plaintextSize).toBe(expectedSnapshotBytes().byteLength);+ expect(backups[1].compressed).toBeUndefined();+ expect(backups[1].filePath).toBe("/backups/backup-old.db");+ });++ it("does not list a backup its marker disowns", async () => {+ const fs = makeOpfs({+ "backup-good.db": { data: new Uint8Array(3), lastModified: 100 },+ "backup-half.tnbackup": { data: new Uint8Array(5), lastModified: 200 },+ "backup-half.tnbackup.part": { data: new Uint8Array(), lastModified: 201 }+ });+ installOpfs(async () => fs.root);- const backups = await new StandaloneBackupService(options).getExistingBackups();- expect(backups.map(b => b.fileName)).toEqual(["backup-new.db", "backup-old.db"]);- expect(backups[0].filePath).toBe("/backups/backup-new.db");- expect(backups.map(b => b.fileSize)).toEqual([8, 3]);+ const backups = await service(makeSqlAccess().access).getExistingBackups();+ expect(backups.map((backup) => backup.fileName)).toEqual([ "backup-good.db" ]);});- it("reads and deletes a backup by path/name", async () => {- const fs = makeOpfs({ "backup-keep.db": { data: new Uint8Array([1, 2, 3]), lastModified: 1 } });+ it("reads and deletes a backup by path/name, marker included", async () => {+ const fs = makeOpfs({+ "backup-keep.tnbackup": { data: new Uint8Array([ 1, 2, 3 ]), lastModified: 1 },+ "backup-keep.tnbackup.part": { data: new Uint8Array(), lastModified: 2 }+ });installOpfs(async () => fs.root);vi.spyOn(console, "log").mockImplementation(() => {});- const service = new StandaloneBackupService(options);- const content = await service.getBackupContent("/backups/backup-keep.db");- expect(content && Array.from(content)).toEqual([1, 2, 3]);+ const svc = service(makeSqlAccess().access);+ const content = await svc.getBackupContent("/backups/backup-keep.tnbackup");+ expect(content && Array.from(content)).toEqual([ 1, 2, 3 ]);- await service.deleteBackup("backup-keep.db");- expect(fs.files.has("backup-keep.db")).toBe(false);+ await svc.deleteBackup("backup-keep.tnbackup");+ expect(fs.files.has("backup-keep.tnbackup")).toBe(false);+ expect(fs.files.has("backup-keep.tnbackup.part")).toBe(false);});it("returns null when the requested file name is not a backup", async () => {installOpfs(async () => makeOpfs().root);- const service = new StandaloneBackupService(options);- expect(await service.getBackupContent("/backups/secrets.txt")).toBeNull();+ expect(await service(makeSqlAccess().access).getBackupContent("/backups/secrets.txt"))+ .toBeNull();});it("handles a missing backup directory handle gracefully", async () => {- // root.getDirectoryHandle resolves to undefined → ensureBackupDirectory() returns null.+ // root.getDirectoryHandle resolves to undefined → every operation degrades quietly.const root = { async getDirectoryHandle() { return undefined; } };installOpfs(async () => root);- vi.spyOn(console, "warn").mockImplementation(() => {});+ vi.spyOn(console, "error").mockImplementation(() => {});- const service = new StandaloneBackupService(options);- expect(await service.backupNow("x")).toBe("/backups/backup-x.db");- expect(await service.getExistingBackups()).toEqual([]);- await expect(service.deleteBackup("backup-x.db")).resolves.toBeUndefined();- expect(await service.getBackupContent("/backups/backup-x.db")).toBeNull();+ const svc = service(makeSqlAccess().access);+ expect(await svc.backupNow("x")).toBe("/backups/backup-x.db");+ expect(await svc.getExistingBackups()).toEqual([]);+ await expect(svc.deleteBackup("backup-x.db")).resolves.toBeUndefined();+ expect(await svc.getBackupContent("/backups/backup-x.db")).toBeNull();});- it("swallows OPFS errors on every operation", async () => {- const boom = async () => { throw new Error("opfs down"); };+ it("swallows OPFS errors on every operation but backupAs", async () => {+ const boom = async () => {+ throw new Error("opfs down");+ };installOpfs(boom);vi.spyOn(console, "error").mockImplementation(() => {});- const service = new StandaloneBackupService(options);- expect(await service.backupNow("x")).toBe("/backups/backup-x.db");- expect(await service.getExistingBackups()).toEqual([]);- await expect(service.deleteBackup("backup-x.db")).resolves.toBeUndefined();- expect(await service.getBackupContent("/backups/backup-x.db")).toBeNull();- });-- it("caches the OPFS availability probe", async () => {- installOpfs(async () => makeOpfs().root);- const service = new StandaloneBackupService(options);- // Two calls; the second should reuse the cached availability flag.- await service.getExistingBackups();- await service.getExistingBackups();+ const svc = service(makeSqlAccess().access);+ expect(await svc.backupNow("x")).toBe("/backups/backup-x.db");+ expect(await svc.getExistingBackups()).toEqual([]);+ await expect(svc.deleteBackup("backup-x.db")).resolves.toBeUndefined();+ expect(await svc.getBackupContent("/backups/backup-x.db")).toBeNull();+ await expect(svc.backupAs("Backup 1")).rejects.toThrow("opfs down");});});diff --git a/apps/standalone/src/lightweight/backup_provider.ts b/apps/standalone/src/lightweight/backup_provider.tsindex bbe9dd8ec1..782893843b 100644--- a/apps/standalone/src/lightweight/backup_provider.ts+++ b/apps/standalone/src/lightweight/backup_provider.ts@@ -1,32 +1,83 @@-import type { DatabaseBackup } from "@triliumnext/commons";-import { BackupOptionsService, BackupService, getSql } from "@triliumnext/core";+import {+ FIXED_HEADER_BYTES,+ peekBackupContainer,+ writeBackupContainer+} from "@triliumnext/backup-container/web";+import type { DatabaseBackup, SetupExistingBackup } from "@triliumnext/commons";+import { BackupOptionsService, BackupService, getSql, sync_mutex as syncMutex } from "@triliumnext/core";++import {+ type BackupDestination,+ type DatabaseStream,+ openBackupDestination,+ type SnapshotConnection,+ streamDatabasePages,+ type SyncFileAccess+} from "./backup-stream.js";const BACKUP_DIR_NAME = "backups";-const BACKUP_FILE_PATTERN = /^backup-.*\.db$/;++/** Backups that are compressed are containers rather than plain database copies, as on the server. */+const CONTAINER_EXTENSION = ".tnbackup";+const DATABASE_EXTENSION = ".db";/**- * How large a database may be and still be backed up here.- *- * A backup on this platform is a `serialize()`, which builds the whole database as one array inside- * the WebAssembly heap and then copies it out to JavaScript: two copies of it in memory at once, in- * an address space a fraction of what a native process has. Past a certain size that allocation does- * not fail, it takes the tab down with it, so anything larger is left unbacked-up instead.- *- * The size that matters is the one a restore can bring in: a database restored from a large backup- * migrates on the next start, and the migration asks for a backup first.+ * Marks the backup it names as still being written: `x.db.part` disowns `x.db`. Presence is the+ * whole signal, because OPFS offers no rename old enough to rely on, so a finished backup cannot+ * move into place — instead it is written under its final name and owned up to only when this+ * marker goes away.*/-const MAX_SERIALIZABLE_BYTES = 256 * 1024 * 1024;+const PARTIAL_SUFFIX = ".part";++/** The pool entry `VACUUM INTO` fills. Never one of the names the live database alternates between. */+const SNAPSHOT_NAME = "/backup-snapshot.db";++/** Pool slots a snapshot needs: the file itself and the rollback journal the vacuum gives it. */+const SNAPSHOT_SLOTS = 2;++/** Space kept free beyond what a backup needs, so it never lands exactly on the quota. */+const QUOTA_MARGIN_BYTES = 32 * 1024 * 1024;++/** The slice of the SQL provider a backup needs. `BrowserSqlProvider` matches it as it stands. */+export interface BackupSqlAccess {+ exec(query: string): void;+ readonly sahPool?: SnapshotPool;+}++/** The slice of the SAH pool used here, kept structural so tests need not build a real one. */+export interface SnapshotPool {+ /**+ * Opens a database on the named entry. What comes back is used as a {@link SnapshotConnection};+ * it is typed loose only because the sqlite-wasm class's overloads defeat structural matching.+ */+ OpfsSAHPoolDb: new (filename: string) => unknown;+ unlink(filename: string): boolean;+ getFileCount(): number;+ getCapacity(): number;+ addCapacity(entries: number): Promise<number>;+}/**- * Standalone backup service using OPFS (Origin Private File System).- * Stores database backups as serialized byte arrays in OPFS.- * Falls back to no-op behavior when OPFS is not available (e.g., in tests).+ * Standalone backup service: streams the database into a file under OPFS `/backups`.+ *+ * A backup is taken in two moves, neither of which ever holds the database whole. `VACUUM INTO`+ * writes a consistent, compacted snapshot into a scratch entry of the SAH pool, through SQLite's+ * own pager and with no more memory than its page cache. The snapshot is then streamed out page by+ * page and lands in `/backups` either as a plain `.db` copy or, when compression is on, wrapped in+ * a backup container. The whole run sits under the sync mutex, like the server's, so it never+ * snapshots a database mid-sync.+ *+ * Encryption is not offered yet: the container needs a passphrase and the browser has no keyring+ * to keep one, so encrypting waits on a flow that asks the user at backup time.*/export default class StandaloneBackupService extends BackupService {private backupDir: FileSystemDirectoryHandle | null = null;private opfsAvailable: boolean | null = null;- constructor(options: BackupOptionsService) {+ constructor(+ options: BackupOptionsService,+ private readonly sqlAccess: () => BackupSqlAccess | undefined = () => undefined+ ) {super(options);}@@ -34,74 +85,47 @@ export default class StandaloneBackupService extends BackupService {// No scheduled backups on standalone/mobile}- private isOpfsAvailable(): boolean {- if (this.opfsAvailable === null) {- this.opfsAvailable = typeof navigator !== "undefined"- && navigator.storage- && typeof navigator.storage.getDirectory === "function";- }- return this.opfsAvailable;- }-- private async ensureBackupDirectory(): Promise<FileSystemDirectoryHandle | null> {- if (!this.isOpfsAvailable()) {- return null;- }-- if (!this.backupDir) {- const root = await navigator.storage.getDirectory();- this.backupDir = await root.getDirectoryHandle(BACKUP_DIR_NAME, { create: true });- }- return this.backupDir;- }-override async backupNow(name: string): Promise<string> {- const fileName = `backup-${name}.db`;+ // Sanitized like the server's, and to the same end: the name reaches a filename.+ const sanitized = name.replace(/[^a-zA-Z0-9_-]/g, "") || "unnamed";+ const fileName = `backup-${sanitized}${this.backupExtension()}`;+ const nominalPath = `/${BACKUP_DIR_NAME}/${fileName}`;- // Check if OPFS is availableif (!this.isOpfsAvailable()) {console.warn(`[Backup] OPFS not available, skipping backup: ${fileName}`);- return `/${BACKUP_DIR_NAME}/${fileName}`;+ return nominalPath;}try {- const dir = await this.ensureBackupDirectory();- if (!dir) {- console.warn(`[Backup] Backup directory not available, skipping: ${fileName}`);- return `/${BACKUP_DIR_NAME}/${fileName}`;- }-- const size = this.databaseSize();- if (size > MAX_SERIALIZABLE_BYTES) {- console.warn(`[Backup] Database is too large to back up in the browser (${size} bytes), skipping: ${fileName}`);- return `/${BACKUP_DIR_NAME}/${fileName}`;- }-- // Serialize the database- const data = getSql().serialize();-- // Write to OPFS- const fileHandle = await dir.getFileHandle(fileName, { create: true });- const writable = await fileHandle.createWritable();- await writable.write(data);- await writable.close();-- console.log(`[Backup] Created backup: ${fileName} (${data.byteLength} bytes)`);- return `/${BACKUP_DIR_NAME}/${fileName}`;+ await this.writeBackup(fileName);+ console.log(`[Backup] Created backup: ${fileName}`);} catch (error) {+ // Logged rather than thrown: the callers are the scheduler and the pre-migration+ // hook, and neither must be stopped by a backup that could not be taken.console.error(`[Backup] Failed to create backup ${fileName}:`, error);- // Don't throw - backup failure shouldn't block operations- return `/${BACKUP_DIR_NAME}/${fileName}`;}+ return nominalPath;}- /** How many bytes the live database occupies, asked of the database rather than of a copy of it. */- private databaseSize(): number {- const size = getSql().getValue<number>(- "SELECT page_count * page_size FROM pragma_page_count(), pragma_page_size()"- );+ override async backupAs(+ baseName: string,+ onProgress?: (fraction: number) => void+ ): Promise<SetupExistingBackup> {+ if (!this.isOpfsAvailable()) {+ throw new Error("Backups need OPFS, which this browser does not provide.");+ }- return typeof size === "number" ? size : 0;+ // As it stands but for path separators, which OPFS names cannot carry.+ const fileName = `${baseName.replace(/[/\\]/g, "-")}${this.backupExtension()}`;+ await this.writeBackup(fileName, onProgress);++ return {+ fileName,+ filePath: `/${BACKUP_DIR_NAME}/${fileName}`,+ directoryPath: `/${BACKUP_DIR_NAME}`,+ fileSize: await this.backupFileSize(fileName),+ encrypted: false+ };}override async getExistingBackups(): Promise<DatabaseBackup[]> {@@ -115,19 +139,23 @@ export default class StandaloneBackupService extends BackupService {return [];}+ const entries = await fileEntriesIn(dir);+ const names = new Set(entries.map(([ name ]) => name));const backups: DatabaseBackup[] = [];- for await (const [name, handle] of dir.entries()) {- if (handle.kind !== "file" || !BACKUP_FILE_PATTERN.test(name)) {+ for (const [ name, handle ] of entries) {+ // A file its marker disowns is mid-write or abandoned, not a backup.+ if (!isBackupFileName(name) || names.has(`${name}${PARTIAL_SUFFIX}`)) {continue;}- const file = await (handle as FileSystemFileHandle).getFile();+ const file = await handle.getFile();backups.push({fileName: name,filePath: `/${BACKUP_DIR_NAME}/${name}`,mtime: new Date(file.lastModified),- fileSize: file.size+ fileSize: file.size,+ ...await describeContainer(file, name)});}@@ -154,6 +182,7 @@ export default class StandaloneBackupService extends BackupService {return;}await dir.removeEntry(fileName);+ await removeEntryQuietly(dir, `${fileName}${PARTIAL_SUFFIX}`);console.log(`[Backup] Deleted backup: ${fileName}`);} catch (error) {console.error(`[Backup] Failed to delete backup ${fileName}:`, error);@@ -171,9 +200,9 @@ export default class StandaloneBackupService extends BackupService {return null;}- // Extract fileName from filePath (e.g., "/backups/backup-now.db" -> "backup-now.db")+ // Extract fileName from filePath (e.g. "/backups/backup-now.db" -> "backup-now.db")const fileName = filePath.split("/").pop();- if (!fileName || !BACKUP_FILE_PATTERN.test(fileName)) {+ if (!fileName || !isBackupFileName(fileName)) {return null;}@@ -186,4 +215,275 @@ export default class StandaloneBackupService extends BackupService {return null;}}++ /**+ * Streams the database into `/backups/<fileName>`, replacing what was there under that name.+ *+ * The snapshot is vacuumed into the pool, streamed out into the destination, and unlinked+ * again whatever happens; the destination is disowned by its marker for as long as it is+ * incomplete. Failing before the destination was ever opened leaves an older backup of the+ * same name exactly as it was.+ */+ private async writeBackup(+ fileName: string,+ onProgress?: (fraction: number) => void+ ): Promise<void> {+ const access = this.sqlAccess();+ const pool = access?.sahPool;+ if (!access || !pool) {+ throw new Error("The live database is not in the SAH pool, so there is nothing to back up.");+ }++ const dir = await this.ensureBackupDirectory();+ if (!dir) {+ throw new Error("The backup directory could not be opened.");+ }++ // The mutex serializes backups too, which is what lets leftovers be cleaned here.+ await syncMutex.doExclusively(async () => {+ await removeAbandonedPartials(dir);+ await this.ensureFreeSpace(this.databaseSize());++ await reserveSnapshotSlots(pool);+ removeSnapshotQuietly(pool);+ access.exec(`VACUUM INTO '${SNAPSHOT_NAME}'`);++ try {+ const connection = new pool.OpfsSAHPoolDb(SNAPSHOT_NAME) as SnapshotConnection;+ const snapshot = streamDatabasePages(connection);+ await this.writeDestination(dir, fileName, snapshot, onProgress);+ } finally {+ removeSnapshotQuietly(pool);+ }+ });++ await removeCounterpart(dir, fileName);+ }++ /** Streams the snapshot into the marker-guarded destination file, consuming it either way. */+ private async writeDestination(+ dir: FileSystemDirectoryHandle,+ fileName: string,+ snapshot: DatabaseStream,+ onProgress?: (fraction: number) => void+ ): Promise<void> {+ const marker = `${fileName}${PARTIAL_SUFFIX}`;+ let destination: BackupDestination | undefined;++ try {+ // Checked against the snapshot's exact size, which the first check could only guess at.+ await this.ensureFreeSpace(snapshot.byteSize);++ await dir.getFileHandle(marker, { create: true });+ destination = openBackupDestination(await syncAccessTo(dir, fileName));++ if (this.isContainerFormat()) {+ await writeBackupContainer(snapshot.stream, destination.writable, {+ compress: true,+ plaintextSize: snapshot.byteSize,+ onProgress,+ patchHeader: destination.patch+ });+ } else {+ await snapshot.stream.pipeTo(destination.writable);+ }++ destination.close();+ await removeEntryQuietly(dir, marker);+ onProgress?.(1);+ } catch (error) {+ await cancelQuietly(snapshot.stream);+ closeQuietly(destination);+ if (destination) {+ // Only what this run ruined: before the destination opened, an older backup of+ // the same name is still intact and stays.+ await removeEntryQuietly(dir, fileName);+ }+ await removeEntryQuietly(dir, marker);+ throw error;+ }+ }++ /**+ * Refuses work that `needed` more bytes of OPFS would not fit. A browser that cannot say is+ * not refused: a false "no" here loses a backup, while a false "yes" fails mid-write and is+ * cleaned up.+ */+ private async ensureFreeSpace(needed: number): Promise<void> {+ const estimate = await navigator.storage.estimate?.().catch(() => undefined);+ if (typeof estimate?.quota !== "number" || typeof estimate.usage !== "number") {+ return;+ }++ const available = estimate.quota - estimate.usage;+ if (available < needed + QUOTA_MARGIN_BYTES) {+ throw new Error("Not enough browser storage for a backup: it needs about "+ + `${toMiB(needed)} MiB and ${toMiB(Math.max(available, 0))} MiB are free.`);+ }+ }++ /** Whether backups are wrapped in a container, which is what compression takes. */+ private isContainerFormat(): boolean {+ return this.options.getOptionOrNull("backupEnableCompression") === "true";+ }++ private backupExtension(): string {+ return this.isContainerFormat() ? CONTAINER_EXTENSION : DATABASE_EXTENSION;+ }++ /** How many bytes the live database occupies, asked of the database rather than of a copy. */+ private databaseSize(): number {+ const size = getSql().getValue<number>(+ "SELECT page_count * page_size FROM pragma_page_count(), pragma_page_size()"+ );++ return typeof size === "number" ? size : 0;+ }++ private async backupFileSize(fileName: string): Promise<number> {+ const dir = await this.ensureBackupDirectory();+ if (!dir) {+ return 0;+ }++ const handle = await dir.getFileHandle(fileName);+ return (await handle.getFile()).size;+ }++ private isOpfsAvailable(): boolean {+ if (this.opfsAvailable === null) {+ this.opfsAvailable = typeof navigator !== "undefined"+ && navigator.storage+ && typeof navigator.storage.getDirectory === "function";+ }+ return this.opfsAvailable;+ }++ private async ensureBackupDirectory(): Promise<FileSystemDirectoryHandle | null> {+ if (!this.isOpfsAvailable()) {+ return null;+ }++ if (!this.backupDir) {+ const root = await navigator.storage.getDirectory();+ this.backupDir = await root.getDirectoryHandle(BACKUP_DIR_NAME, { create: true });+ }+ return this.backupDir;+ }+}++/** Mirrors the server's listing filter, capitals and all: setup backups start with one. */+function isBackupFileName(name: string): boolean {+ return name.toLowerCase().includes("backup")+ && (name.endsWith(DATABASE_EXTENSION) || name.endsWith(CONTAINER_EXTENSION));+}++/**+ * What a container is, read from its own header rather than from today's options: a backup keeps+ * the shape it was written in, whatever the settings have since become. A file whose header does+ * not parse is listed as a plain one rather than not at all.+ */+async function describeContainer(file: Blob, fileName: string): Promise<Partial<DatabaseBackup>> {+ if (!fileName.endsWith(CONTAINER_EXTENSION)) {+ return {};+ }++ try {+ const head = new Uint8Array(await file.slice(0, FIXED_HEADER_BYTES).arrayBuffer());+ const info = peekBackupContainer(head);+ if (!info) {+ return {};+ }++ return {+ compressed: info.compressed,+ encrypted: info.encrypted,+ // Recorded as 0 when the writer did not know it, which reads the same as "not stated".+ plaintextSize: info.plaintextSize > 0 ? info.plaintextSize : undefined+ };+ } catch {+ return {};+ }+}++/** Every file in the directory, gathered so the listing can look names up while it walks them. */+async function fileEntriesIn(dir: FileSystemDirectoryHandle): Promise<[string, FileSystemFileHandle][]> {+ const entries: [string, FileSystemFileHandle][] = [];+ for await (const [ name, handle ] of dir.entries()) {+ if (handle.kind === "file") {+ entries.push([ name, handle as FileSystemFileHandle ]);+ }+ }+ return entries;+}++/** Sweeps out markers and the unfinished backups they disown, from runs that never got to. */+async function removeAbandonedPartials(dir: FileSystemDirectoryHandle): Promise<void> {+ for (const [ name ] of await fileEntriesIn(dir)) {+ if (name.endsWith(PARTIAL_SUFFIX)) {+ await removeEntryQuietly(dir, name.slice(0, -PARTIAL_SUFFIX.length));+ await removeEntryQuietly(dir, name);+ }+ }+}++/** One backup name, one file: a container retires the plain copy it replaces, and vice versa. */+async function removeCounterpart(dir: FileSystemDirectoryHandle, fileName: string): Promise<void> {+ const counterpart = fileName.endsWith(CONTAINER_EXTENSION)+ ? `${fileName.slice(0, -CONTAINER_EXTENSION.length)}${DATABASE_EXTENSION}`+ : `${fileName.slice(0, -DATABASE_EXTENSION.length)}${CONTAINER_EXTENSION}`;++ await removeEntryQuietly(dir, counterpart);+}++async function syncAccessTo(dir: FileSystemDirectoryHandle, name: string): Promise<SyncFileAccess> {+ const handle = await dir.getFileHandle(name, { create: true });+ return await handle.createSyncAccessHandle();+}++/** Adds slots when the pool is too full for a snapshot and the journal the vacuum gives it. */+async function reserveSnapshotSlots(pool: SnapshotPool): Promise<void> {+ const free = pool.getCapacity() - pool.getFileCount();+ if (free < SNAPSHOT_SLOTS) {+ await pool.addCapacity(SNAPSHOT_SLOTS - free);+ }+}++/** Removes the snapshot entry, if it is there at all. Never the reason a backup fails. */+function removeSnapshotQuietly(pool: SnapshotPool): void {+ try {+ pool.unlink(SNAPSHOT_NAME);+ } catch {+ // A leftover entry costs a pool slot, which the next backup reclaims here anyway.+ }+}++async function removeEntryQuietly(dir: FileSystemDirectoryHandle, name: string): Promise<void> {+ try {+ await dir.removeEntry(name);+ } catch {+ // Already absent, which is what removing it was for.+ }+}++/** Releases an unconsumed snapshot stream; one already consumed or errored refuses, done is done. */+async function cancelQuietly(stream: ReadableStream<Uint8Array>): Promise<void> {+ try {+ await stream.cancel();+ } catch {+ // Locked or errored: whoever consumed it has released it.+ }+}++/** Closes on the failure path, where a second error would only mask the one being reported. */+function closeQuietly(destination: BackupDestination | undefined): void {+ try {+ destination?.close();+ } catch {+ // The write failure being thrown past this is the story; a broken flush on top is not.+ }+}++function toMiB(bytes: number): number {+ return Math.round(bytes / (1024 * 1024));}diff --git a/apps/standalone/src/local-server-worker.ts b/apps/standalone/src/local-server-worker.tsindex a8b4fc5769..d2d25abc03 100644--- a/apps/standalone/src/local-server-worker.ts+++ b/apps/standalone/src/local-server-worker.ts@@ -269,7 +269,7 @@ async function initialize(): Promise<void> {request: useNativeHttp ? new BridgedRequestProvider() : new FetchRequestProvider(),platform: new StandalonePlatformProvider(queryString),log: logService,- backup: new StandaloneBackupService(coreModule!.options),+ backup: new StandaloneBackupService(coreModule!.options, () => sqlProvider ?? undefined),translations: translationProvider,schema: schemaModule.default,getDemoArchive: async () => {diff --git a/apps/standalone/src/opfs-sync-access.d.ts b/apps/standalone/src/opfs-sync-access.d.tsnew file mode 100644index 0000000000..ea916c494a--- /dev/null+++ b/apps/standalone/src/opfs-sync-access.d.ts@@ -0,0 +1,24 @@+/**+ * OPFS synchronous file access, which TypeScript keeps in `lib.webworker` — unusable here because+ * this project also compiles window-side code against `dom`, and the two libs cannot be mixed.+ * Declared by hand instead, mirroring `lib.webworker`, and only as much of it as the worker code+ * touches (the log service and the backup writer). The API itself exists only in dedicated+ * workers, which is where both run.+ */++interface FileSystemReadWriteOptions {+ at?: number;+}++interface FileSystemSyncAccessHandle {+ close(): void;+ flush(): void;+ getSize(): number;+ read(buffer: AllowSharedBufferSource, options?: FileSystemReadWriteOptions): number;+ truncate(newSize: number): void;+ write(buffer: AllowSharedBufferSource, options?: FileSystemReadWriteOptions): number;+}++interface FileSystemFileHandle {+ createSyncAccessHandle(): Promise<FileSystemSyncAccessHandle>;+}