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 import: fix some issues
Adorian Dorand5116abb5768
diff --git a/apps/client/src/setup_restore.tsx b/apps/client/src/setup_restore.tsxindex 0d635c0a09..3e9bfd2509 100644--- a/apps/client/src/setup_restore.tsx+++ b/apps/client/src/setup_restore.tsx@@ -290,6 +290,7 @@ function headlineFor(reason: string | undefined): string {case "swap-failed": return t("setup.restore-error-swap-failed");case "migration-failed": return t("setup.restore-error-would-not-open");case "restore-refused": return t("setup.restore-error-refused");+ case "already-initialized": return t("setup.restore-error-already-initialized");default: return t("setup.restore-error-unusable");}}diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 186d432992..a548f13592 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3699,6 +3699,7 @@"restore-error-swap-failed": "The database could not be replaced. Your previous database is back in place.","restore-error-would-not-open": "The restored database could not be opened. Your previous database is back in place.","restore-error-refused": "Another setup step is already running.",+ "restore-error-already-initialized": "This instance already has a knowledge base, so it cannot be restored over. Reload the page.","restore-error-could-not-start": "The restore could not be started.","restore-error-upload-failed": "The backup could not be uploaded.","restore-passphrase": "Encryption password",diff --git a/apps/standalone/src/lightweight/backup_provider.spec.ts b/apps/standalone/src/lightweight/backup_provider.spec.tsindex 690e1f2ec2..af225e1294 100644--- a/apps/standalone/src/lightweight/backup_provider.spec.ts+++ b/apps/standalone/src/lightweight/backup_provider.spec.ts@@ -1,4 +1,4 @@-import { options } from "@triliumnext/core";+import { getSql, options } from "@triliumnext/core";import { afterEach, describe, expect, it, vi } from "vitest";import StandaloneBackupService from "./backup_provider.js";@@ -117,6 +117,23 @@ describe("StandaloneBackupService with OPFS", () => {expect(fs.files.get("backup-daily.db")?.data.byteLength).toBeGreaterThan(0);});+ it("leaves a database too large to hold in memory unbacked-up", 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");++ expect(await new StandaloneBackupService(options).backupNow("before-migration"))+ .toBe("/backups/backup-before-migration.db");++ expect(serialize).not.toHaveBeenCalled();+ expect(fs.files.size).toBe(0);+ expect(warn).toHaveBeenCalled();+ });+it("lists matching backups newest-first and ignores non-backup entries", async () => {const fs = makeOpfs({"backup-old.db": { data: new Uint8Array(3), lastModified: 100 },diff --git a/apps/standalone/src/lightweight/backup_provider.ts b/apps/standalone/src/lightweight/backup_provider.tsindex 44512c3034..bbe9dd8ec1 100644--- a/apps/standalone/src/lightweight/backup_provider.ts+++ b/apps/standalone/src/lightweight/backup_provider.ts@@ -4,6 +4,19 @@ import { BackupOptionsService, BackupService, getSql } from "@triliumnext/core";const BACKUP_DIR_NAME = "backups";const BACKUP_FILE_PATTERN = /^backup-.*\.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.+ */+const MAX_SERIALIZABLE_BYTES = 256 * 1024 * 1024;+/*** Standalone backup service using OPFS (Origin Private File System).* Stores database backups as serialized byte arrays in OPFS.@@ -58,6 +71,12 @@ export default class StandaloneBackupService extends BackupService {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 databaseconst data = getSql().serialize();@@ -76,6 +95,15 @@ export default class StandaloneBackupService extends BackupService {}}+ /** 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()"+ );++ return typeof size === "number" ? size : 0;+ }+override async getExistingBackups(): Promise<DatabaseBackup[]> {if (!this.isOpfsAvailable()) {return [];diff --git a/apps/standalone/src/lightweight/database_restore.spec.ts b/apps/standalone/src/lightweight/database_restore.spec.tsindex d4b7d78d7f..152520795f 100644--- a/apps/standalone/src/lightweight/database_restore.spec.ts+++ b/apps/standalone/src/lightweight/database_restore.spec.ts@@ -1,5 +1,5 @@-import { writeBackupContainer } from "@triliumnext/backup-container";import type { SAHPoolUtil } from "@sqlite.org/sqlite-wasm";+import { writeBackupContainer } from "@triliumnext/backup-container";import fs from "fs";import fsp from "fs/promises";import os from "os";@@ -9,12 +9,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import {DEFAULT_DATABASE_NAME,readCurrentDatabaseName,- type RestoreProgress,restoreDatabase,+ type RestoreProgress,type RestoreTarget} from "./database_restore.js";-const CANDIDATE_NAME = "/trilium.candidate.db";+/** The name a restore writes to while the default one is live: the two alternate. */+const CANDIDATE_NAME = "/trilium.alt.db";const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "trilium-standalone-restore-"));/**@@ -175,6 +176,21 @@ describe("which database is the live one", () => {await expect(readCurrentDatabaseName()).resolves.toBe(CANDIDATE_NAME);});++ it("alternates between the two names, so a restore never prepares over the live database", async () => {+ const { files, pool } = fakePool();+ const { target } = fakeTarget(pool);+ const second = databaseBytes(12288);++ await restoreDatabase(target, new Blob([ databaseBytes() ]));+ await restoreDatabase(target, new Blob([ second ]));++ await expect(readCurrentDatabaseName()).resolves.toBe(DEFAULT_DATABASE_NAME);+ // Only ever the one database: the name it went back to holds the newer backup, and the one+ // it came from was dropped once the swap was through.+ expect([ ...files.keys() ]).toEqual([ DEFAULT_DATABASE_NAME ]);+ expect(files.get(DEFAULT_DATABASE_NAME)).toEqual(second);+ });});describe("restoring from a picked backup", () => {diff --git a/apps/standalone/src/lightweight/database_restore.ts b/apps/standalone/src/lightweight/database_restore.tsindex d76d2cff26..6590010c5d 100644--- a/apps/standalone/src/lightweight/database_restore.ts+++ b/apps/standalone/src/lightweight/database_restore.ts@@ -1,3 +1,4 @@+import type { SAHPoolUtil } from "@sqlite.org/sqlite-wasm";import {FIXED_HEADER_BYTES,isBackupContainerError,@@ -11,7 +12,6 @@ import {looksLikeSqlite,validateDatabase} from "@triliumnext/core";-import type { SAHPoolUtil } from "@sqlite.org/sqlite-wasm";/*** Puts a backup in place of this instance's database, in the browser.@@ -34,11 +34,22 @@ import type { SAHPoolUtil } from "@sqlite.org/sqlite-wasm";/** Where the pointer to the live database is kept, in the origin's private filesystem. */const POINTER_FILE = "trilium-current-database";+/**+ * The two names a database is ever kept under.+ *+ * A restore writes the new database in beside the old one and then points at it, so the name it+ * writes to has to be the one that is *not* live. Alternating between two settles that: whichever is+ * live, the other is free, and a restore can never be preparing over the database it is replacing.+ */+const DATABASE_NAMES = [ "/trilium.db", "/trilium.alt.db" ] as const;+/** The database opened when nothing has ever been restored. */-export const DEFAULT_DATABASE_NAME = "/trilium.db";+export const DEFAULT_DATABASE_NAME = DATABASE_NAMES[0];-/** Where a backup is written while it is being checked, before it is anything to anyone. */-const CANDIDATE_NAME = "/trilium.candidate.db";+/** Where a backup is written while it is being checked, which is wherever the live one is not. */+function candidateNameFor(live: string): string {+ return DATABASE_NAMES.find((name) => name !== live) ?? DATABASE_NAMES[1];+}/** What the restore is doing, in the order it does it. Mirrors the server's own steps. */export type RestoreStage = "staging" | "validating" | "swapping" | "done" | "failed";@@ -90,26 +101,28 @@ export async function restoreDatabase(options: { passphrase?: string; report?: (progress: RestoreProgress) => void } = {}): Promise<void> {const report = options.report ?? (() => {});+ const live = await readCurrentDatabaseName();+ const candidate = candidateNameFor(live);try {report({ stage: "staging" });- await stageCandidate(target.pool, backup, options.passphrase, (fraction) =>+ await stageCandidate(target.pool, candidate, backup, options.passphrase, (fraction) =>report({ stage: "staging", fraction }));report({ stage: "validating" });- const validation = validate(target.pool);+ const validation = validate(target.pool, candidate);if (!validation.valid) {throw new RestoreFailure(validation.rejection, validation.message);}report({ stage: "swapping" });- await swapIn(target);+ await swapIn(target, live, candidate);report({ stage: "done" });} catch (e) {const failure = asFailure(e);// The candidate is no use to anyone now, and the pool's slots are finite.- await removeQuietly(target.pool, CANDIDATE_NAME);+ await removeQuietly(target.pool, candidate);report({ stage: "failed", error: failure.message, reason: failure.reason });throw failure;@@ -134,12 +147,13 @@ export class RestoreFailure extends Error {*/async function stageCandidate(pool: SAHPoolUtil,+ candidate: string,backup: Blob,passphrase: string | undefined,onProgress: ProgressCallback): Promise<void> {await makeRoomFor(pool);- await removeQuietly(pool, CANDIDATE_NAME);+ await removeQuietly(pool, candidate);const format = await readBackupFormat(backup);if (!format) {@@ -147,7 +161,7 @@ async function stageCandidate(}if (!format.container) {- await pool.importDb(CANDIDATE_NAME, pullFrom(backup.stream()));+ await pool.importDb(candidate, pullFrom(backup.stream()));onProgress(1);return;}@@ -160,15 +174,15 @@ async function stageCandidate(const relay = new TransformStream<Uint8Array, Uint8Array>();const unwrapped = readBackupContainer(backup.stream(), relay.writable, { passphrase, onProgress });- const imported = pool.importDb(CANDIDATE_NAME, pullFrom(relay.readable));+ const imported = pool.importDb(candidate, pullFrom(relay.readable));// Awaited together: either failing has to stop the other, which is what a rejected pipe does.await Promise.all([ unwrapped, imported ]);}/** Opens the candidate and puts it through the checks every platform shares. */-function validate(pool: SAHPoolUtil): DatabaseValidation {- const db = new pool.OpfsSAHPoolDb(CANDIDATE_NAME);+function validate(pool: SAHPoolUtil, candidate: string): DatabaseValidation {+ const db = new pool.OpfsSAHPoolDb(candidate);try {return validateDatabase(candidateOf(db));@@ -200,14 +214,12 @@ function candidateOf(db: InstanceType<SAHPoolUtil["OpfsSAHPoolDb"]>): CandidateD* changes, an interrupted restore leaves the old one live with an unused entry beside it, which the* next attempt overwrites.*/-async function swapIn(target: RestoreTarget): Promise<void> {- const previous = await readCurrentDatabaseName();-+async function swapIn(target: RestoreTarget, previous: string, candidate: string): Promise<void> {target.close();- await writeCurrentDatabaseName(CANDIDATE_NAME);+ await writeCurrentDatabaseName(candidate);try {- target.open(CANDIDATE_NAME);+ target.open(candidate);} catch (e) {// Put back what was live, so a candidate that will not open costs nothing.await writeCurrentDatabaseName(previous);@@ -217,9 +229,7 @@ async function swapIn(target: RestoreTarget): Promise<void> {}// Only once the restored database is open: until then the old one is what a restart needs.- if (previous !== CANDIDATE_NAME) {- await removeQuietly(target.pool, previous);- }+ await removeQuietly(target.pool, previous);}async function writeCurrentDatabaseName(dbName: string): Promise<void> {diff --git a/apps/standalone/src/local-server-worker.ts b/apps/standalone/src/local-server-worker.tsindex 24538852b6..abc2434916 100644--- a/apps/standalone/src/local-server-worker.ts+++ b/apps/standalone/src/local-server-worker.ts@@ -372,17 +372,40 @@ async function dispatch(request: LocalRequest) {* question, so it is reported as one and the same file can be offered again with an answer.*/async function handleRestoreBackup(id: string, backup: File, passphrase?: string): Promise<void> {- const report = (progress: StandaloneRestoreProgress) =>- (self as unknown as Worker).postMessage({ type: "RESTORE_PROGRESS", id, progress });const answer = (result: StandaloneRestoreResult) =>(self as unknown as Worker).postMessage({ type: "RESTORE_RESULT", id, result });+ const report = (progress: StandaloneRestoreProgress) =>+ (self as unknown as Worker).postMessage({ type: "RESTORE_PROGRESS", id, progress });++ const core = coreModule;+ const pool = sqlProvider?.sahPool;+ if (!core || !sqlProvider || !pool) {+ answer({ status: "error", reason: "swap-failed", message: "The database is not ready yet." });+ return;+ }++ // What `checkAppNotInitialized` is to the server's routes. A restore replaces the database+ // wholesale, so it is only ever offered by the setup screen; a tab left open on that screen+ // after another one finished setting up must not act on it.+ if (core.sql_init.isDbInitialized()) {+ answer({ status: "error", reason: "already-initialized", message: "The database is already set up." });+ return;+ }++ // Two restores would prepare over each other, since they write the same candidate.+ if (restoreInProgress) {+ answer({ status: "error", reason: "restore-refused", message: "A restore is already running." });+ return;+ }++ restoreInProgress = true;try {await restoreDatabase({- pool: sqlProvider!.sahPool!,- close: () => sqlProvider!.close(),- open: (dbName) => sqlProvider!.loadFromSahPool(dbName)+ pool,+ close: () => sqlProvider?.close(),+ open: (dbName) => sqlProvider?.loadFromSahPool(dbName)},backup,{ passphrase, report: ({ stage, fraction }) => report({ stage, fraction }) }@@ -390,8 +413,8 @@ async function handleRestoreBackup(id: string, backup: File, passphrase?: string// What the "create new document" path announces for the same reason: everything that waits// on a database being there starts from here.- await coreModule!.sql_init.initDbConnection();- coreModule!.events.emit(coreModule!.events.DB_INITIALIZED);+ await core.sql_init.initDbConnection();+ core.events.emit(core.events.DB_INITIALIZED);answer({ status: "restored" });} catch (e) {@@ -401,9 +424,14 @@ async function handleRestoreBackup(id: string, backup: File, passphrase?: stringanswer(reason === "passphrase-required"? { status: "needs-passphrase" }: { status: "error", reason, message });+ } finally {+ restoreInProgress = false;}}+/** Whether a restore is running, since a second one would prepare over the first one's work. */+let restoreInProgress = false;+// Wait for the INIT message before initializing so that queryString// (which may contain ?integrationTest=memory for e2e) is available.let initReceived = false;