Skip to content

Build your personal knowledge base with Trilium Notes

standalone/backup: swtitch from snapshots stored on OPFS to streamed downloads to avoid quota issues

Adorian Doran71daf29de243
diff --git a/apps/client/src/services/backup_download.ts b/apps/client/src/services/backup_download.ts
new file mode 100644
index 0000000000..2748e2b2d3
--- /dev/null
+++ b/apps/client/src/services/backup_download.ts
@@ -0,0 +1,46 @@
+import type { StandaloneDownloadResult } from "@triliumnext/commons";
+
+/**
+ * Backing up by download, which is the standalone platform's one and only backup.
+ *
+ * Standalone keeps no backups anywhere: the browser's storage holds the live database and could
+ * rarely hold a copy of it beside itself, so a backup is streamed straight off the live database
+ * into a browser download instead. The options screen and the setup screen both back up through
+ * here, so the naming and the passphrase live in exactly one place.
+ *
+ * @module
+ */
+
+/** Whether this platform backs up by streaming a download, which is the standalone build. */
+export function isBackupDownloadSupported(): boolean {
+ return !!window.standaloneApi;
+}
+
+/**
+ * How a downloaded backup is named: the same dated, readable shape the other platforms write
+ * their setup backups under, with the encrypted container's extension, which is what the download
+ * currently always carries.
+ */
+export function backupDownloadFileName(now: Date): string {
+ const stamp = (value: number) => String(value).padStart(2, "0");
+ const date = [ now.getFullYear(), stamp(now.getMonth() + 1), stamp(now.getDate()) ].join("-");
+ const time = [ stamp(now.getHours()), stamp(now.getMinutes()), stamp(now.getSeconds()) ].join("-");
+
+ return `Backup ${date} ${time}.tnbackup`;
+}
+
+/**
+ * Starts the download and resolves with how it ended, which is when the stream behind it has been
+ * fully produced — the closest thing to "finished" the application can see, with the browser's
+ * own download UI carrying the transfer itself.
+ */
+export async function startBackupDownload(fileName: string): Promise<StandaloneDownloadResult> {
+ const api = window.standaloneApi;
+ if (!api) {
+ return { status: "failed", message: "This platform does not back up by download." };
+ }
+
+ // TODO: ask the user for a passphrase instead; this fixed one exists only to test the
+ // encrypted download path end to end.
+ return await api.backup.downloadDatabase(fileName, "123456");
+}
diff --git a/apps/client/src/setup_existing.css b/apps/client/src/setup_existing.css
index 152ee6718a..4a62fa29b8 100644
--- a/apps/client/src/setup_existing.css
+++ b/apps/client/src/setup_existing.css
@@ -1,10 +1,26 @@
.page.existing-data,
-.page.existing-data-backed-up {
+.page.existing-data-backed-up,
+.page.existing-data-downloading {
.existing-data-warning {
margin-top: 16px;
}
}
+/* The download step: one action with its state under it, centred like the backing-up wait. */
+.page.existing-data-downloading .existing-data-download {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 1em;
+ margin-block: 3em;
+
+ .existing-data-progress-message {
+ display: flex;
+ align-items: center;
+ gap: 0.75em;
+ }
+}
+
.page.existing-data .existing-data-choices .tn-card-section {
padding-block: 12px;
}
diff --git a/apps/client/src/setup_existing.spec.tsx b/apps/client/src/setup_existing.spec.tsx
index b214457f97..4d30c1aec5 100644
--- a/apps/client/src/setup_existing.spec.tsx
+++ b/apps/client/src/setup_existing.spec.tsx
@@ -6,10 +6,10 @@ vi.mock("./services/i18n", () => ({ t: (key: string) => key }));
const serverMock = vi.hoisted(() => ({
get: vi.fn(async (url: string): Promise<unknown> =>
- (url === "setup/existing/status" ? { fraction: null } : url === "keyboard-actions" ? [] : {})),
- post: vi.fn(async (_url: string): Promise<unknown> => ({})),
- // The backup runs for minutes, so it asks for a timeout of its own rather than the default one.
- postWithTimeout: vi.fn(async (_url: string, _timeoutMs: number): Promise<unknown> => ({}))
+ (url === "setup/existing/status"
+ ? { state: "idle", fraction: null }
+ : url === "keyboard-actions" ? [] : {})),
+ post: vi.fn(async (_url: string): Promise<unknown> => ({}))
}));
vi.mock("./services/server", () => ({ default: serverMock }));
@@ -66,7 +66,6 @@ beforeEach(() => {
onProceed.mockReset();
onKept.mockReset();
serverMock.post.mockReset().mockResolvedValue(undefined);
- serverMock.postWithTimeout.mockReset().mockResolvedValue(undefined);
serverMock.get.mockClear();
openMock.download.mockClear();
electronMock.isElectron.mockReset().mockReturnValue(false);
@@ -139,7 +138,7 @@ describe("choosing what happens to the existing knowledge base", () => {
expect(serverMock.post).toHaveBeenCalledWith("setup/existing/delete");
expect(onProceed).toHaveBeenCalled();
// Nothing was backed up, since nothing was asked to be.
- expect(serverMock.postWithTimeout).not.toHaveBeenCalled();
+ expect(serverMock.post).not.toHaveBeenCalledWith("setup/existing/backup");
});
it("leaves everything alone and reopens the database on cancel", async () => {
@@ -155,17 +154,30 @@ describe("choosing what happens to the existing knowledge base", () => {
});
describe("backing it up first", () => {
- it("says what was written, and erases nothing until that is confirmed", async () => {
- serverMock.postWithTimeout.mockResolvedValue(BACKUP);
+ /** Answers the status polls with `status`, leaving every other GET as the default mock has it. */
+ function statusAnswers(status: unknown) {
+ serverMock.get.mockImplementation(async (url: string) =>
+ (url === "setup/existing/status" ? status : url === "keyboard-actions" ? [] : {}));
+ }
+
+ /** Chooses the backup, sets it going, and rides out one poll interval. */
+ async function backUpAndWait() {
renderScreens();
await settle();
choose("back-up");
await settle();
button("setup.continue")?.click();
+ // The answer arrives over a poll, one interval after the backup was set going.
+ await vi.advanceTimersByTimeAsync(1100);
await settle();
+ }
+
+ it("says what was written, and erases nothing until that is confirmed", async () => {
+ statusAnswers({ state: "done", fraction: 1, result: BACKUP });
+ await backUpAndWait();
- expect(serverMock.postWithTimeout).toHaveBeenCalledWith("setup/existing/backup", 3600000);
+ expect(serverMock.post).toHaveBeenCalledWith("setup/existing/backup");
// The path in full: the option holding a custom backup directory is in the database that is
// about to go, so this may be the last chance to read it.
expect(container.textContent).toContain(BACKUP.fileName);
@@ -182,11 +194,9 @@ describe("backing it up first", () => {
});
it("shows how far along the write is, once the writer has said anything", async () => {
- // The backup answers only when it is finished, so this screen would otherwise show a spinner
- // and nothing else for the minutes a large knowledge base takes.
- let resolveBackup: (value: unknown) => void = () => {};
- serverMock.postWithTimeout.mockImplementation(() => new Promise((resolve) => { resolveBackup = resolve; }));
- serverMock.get.mockResolvedValue({ fraction: 0.42 });
+ // The write runs for minutes, so this screen would otherwise show a spinner and nothing
+ // else for the whole of it.
+ statusAnswers({ state: "running", fraction: null });
renderScreens();
await settle();
@@ -198,26 +208,19 @@ describe("backing it up first", () => {
// Nothing to show yet, so the spinner stands in for the bar.
expect(container.querySelector(".spinner-border")).not.toBeNull();
+ statusAnswers({ state: "running", fraction: 0.42 });
await vi.advanceTimersByTimeAsync(1000);
expect(container.querySelector("progress")?.value).toBeCloseTo(0.42);
expect(container.textContent).toContain("42%");
// ...and steps aside once there is one, rather than the two competing.
expect(container.querySelector(".spinner-border")).toBeNull();
-
- resolveBackup(BACKUP);
});
it("saves a copy wherever the user says, and opens the folder on the desktop", async () => {
electronMock.isElectron.mockReturnValue(true);
window.electronApi = { shell: { openPath: electronMock.openPath } } as never;
- serverMock.postWithTimeout.mockResolvedValue(BACKUP);
- renderScreens();
- await settle();
-
- choose("back-up");
- await settle();
- button("setup.continue")?.click();
- await settle();
+ statusAnswers({ state: "done", fraction: 1, result: BACKUP });
+ await backUpAndWait();
container.querySelector<HTMLAnchorElement>(".existing-data-path-link")?.click();
expect(electronMock.openPath).toHaveBeenCalledWith(BACKUP.directoryPath);
@@ -228,7 +231,21 @@ describe("backing it up first", () => {
});
it("says to keep the backup password where the backup needs one", async () => {
- serverMock.postWithTimeout.mockResolvedValue({ ...BACKUP, encrypted: true });
+ statusAnswers({ state: "done", fraction: 1, result: { ...BACKUP, encrypted: true } });
+ await backUpAndWait();
+
+ expect(container.querySelector(".existing-data-warning")?.textContent)
+ .toContain("setup.existing-data-encrypted-warning");
+ });
+
+ it("goes back to the question when the backup cannot even start", async () => {
+ // Rejected the way the client's request layer rejects: the response body, not an Error.
+ serverMock.post.mockImplementation(async (url: string) => {
+ if (url === "setup/existing/backup") {
+ throw '{"message":"the disk is full"}';
+ }
+ return undefined;
+ });
renderScreens();
await settle();
@@ -237,23 +254,138 @@ describe("backing it up first", () => {
button("setup.continue")?.click();
await settle();
- expect(container.querySelector(".existing-data-warning")?.textContent)
- .toContain("setup.existing-data-encrypted-warning");
+ expect(container.querySelector(".page-error")?.textContent).toContain("the disk is full");
+ expect(container.querySelector("input[type=radio]")).not.toBeNull();
+ expect(onProceed).not.toHaveBeenCalled();
});
- it("goes back to the question when the backup fails, having erased nothing", async () => {
- // Rejected the way the client's request layer rejects: the response body, not an Error.
- serverMock.postWithTimeout.mockRejectedValue('{"message":"the disk is full"}');
+ it("goes back to the question when the backup fails along the way", async () => {
+ statusAnswers({ state: "failed", fraction: null, error: "the disk is full" });
+ await backUpAndWait();
+
+ expect(container.querySelector(".page-error")?.textContent).toContain("the disk is full");
+ expect(container.querySelector("input[type=radio]")).not.toBeNull();
+ expect(onProceed).not.toHaveBeenCalled();
+ });
+
+ it("keeps waiting through polls that fail, and takes the answer from the one that succeeds", async () => {
+ // The standalone worker answers nothing while it is deep inside the write itself; a poll
+ // that dies must read as "still going", not as the backup having failed.
+ let polls = 0;
+ serverMock.get.mockImplementation(async (url: string) => {
+ if (url === "setup/existing/status") {
+ polls++;
+ if (polls < 3) {
+ throw "rejected by browser";
+ }
+ return { state: "done", fraction: 1, result: BACKUP };
+ }
+ return url === "keyboard-actions" ? [] : {};
+ });
renderScreens();
await settle();
choose("back-up");
await settle();
button("setup.continue")?.click();
+ await vi.advanceTimersByTimeAsync(3500);
await settle();
- expect(container.querySelector(".page-error")?.textContent).toContain("the disk is full");
- expect(container.querySelector("input[type=radio]")).not.toBeNull();
+ expect(container.textContent).toContain(BACKUP.fileName);
expect(onProceed).not.toHaveBeenCalled();
});
});
+
+describe("backing up straight to a download on standalone", () => {
+ const downloadDatabase = vi.fn();
+
+ beforeEach(() => {
+ downloadDatabase.mockClear();
+ window.standaloneApi = {
+ backup: { downloadDatabase }
+ } as unknown as typeof window.standaloneApi;
+ });
+
+ afterEach(() => {
+ window.standaloneApi = undefined;
+ });
+
+ /**
+ * The button on the page that arrived, not the one that left: happy-dom never fires the
+ * animation events that let SlidePages drop the leaving page, so after one transition both
+ * pages are in the DOM and the arriving one renders second.
+ */
+ function arrivingButton(label: string): HTMLButtonElement | undefined {
+ return [ ...container.querySelectorAll("button") ]
+ .filter((element) => element.textContent?.includes(label))
+ .at(-1);
+ }
+
+ /** Chooses the backup and arrives at the download screen, with nothing started yet. */
+ async function reachDownloadScreen() {
+ renderScreens();
+ await settle();
+
+ choose("back-up");
+ await settle();
+ button("setup.continue")?.click();
+ await settle();
+ }
+
+ it("shows the download step without starting anything, and gates Continue on it", async () => {
+ let finish: (result: unknown) => void = () => {};
+ downloadDatabase.mockImplementation(() => new Promise((resolve) => {
+ finish = resolve;
+ }));
+ await reachDownloadScreen();
+
+ // Arrived, but nothing downloads until the user says so, and Continue is not on offer.
+ expect(container.textContent).toContain("setup.existing-data-downloading");
+ expect(downloadDatabase).not.toHaveBeenCalled();
+ expect(arrivingButton("setup.continue")?.disabled).toBe(true);
+ expect(serverMock.post).not.toHaveBeenCalledWith("setup/existing/backup");
+
+ arrivingButton("setup.existing-data-download")?.click();
+ await settle();
+ expect(downloadDatabase).toHaveBeenCalledWith(
+ expect.stringMatching(/^Backup \d{4}-\d{2}-\d{2} \d{2}-\d{2}-\d{2}\.tnbackup$/),
+ "123456");
+ expect(container.textContent).toContain("setup.existing-data-downloading-in-progress");
+ expect(arrivingButton("setup.continue")?.disabled).toBe(true);
+
+ finish({ status: "done" });
+ await settle();
+ expect(container.textContent).toContain("setup.existing-data-downloading-done");
+ expect(arrivingButton("setup.continue")?.disabled).toBe(false);
+
+ arrivingButton("setup.continue")?.click();
+ await settle();
+ expect(serverMock.post).toHaveBeenCalledWith("setup/existing/delete");
+ expect(onProceed).toHaveBeenCalled();
+ });
+
+ it("shows what stopped a failed download, and keeps Continue out of reach", async () => {
+ downloadDatabase.mockResolvedValue({ status: "failed", message: "the stream broke" });
+ await reachDownloadScreen();
+
+ arrivingButton("setup.existing-data-download")?.click();
+ await settle();
+
+ expect(container.textContent).toContain("the stream broke");
+ expect(arrivingButton("setup.continue")?.disabled).toBe(true);
+ // The button is back, because trying again is the way out.
+ expect(arrivingButton("setup.existing-data-download")?.disabled).toBe(false);
+ expect(serverMock.post).not.toHaveBeenCalledWith("setup/existing/delete");
+ });
+
+ it("cancel leaves everything alone and reopens the database", async () => {
+ await reachDownloadScreen();
+
+ arrivingButton("setup.existing-data-cancel")?.click();
+ await settle();
+
+ expect(serverMock.post).toHaveBeenCalledWith("setup/existing/keep");
+ expect(serverMock.post).not.toHaveBeenCalledWith("setup/existing/delete");
+ expect(onKept).toHaveBeenCalled();
+ });
+});
diff --git a/apps/client/src/setup_existing.tsx b/apps/client/src/setup_existing.tsx
index 1348575a35..5a1d5045f8 100644
--- a/apps/client/src/setup_existing.tsx
+++ b/apps/client/src/setup_existing.tsx
@@ -1,8 +1,13 @@
import "./setup_existing.css";
-import type { SetupExistingBackup } from "@triliumnext/commons";
+import type { SetupExistingBackup, SetupExistingBackupStatus } from "@triliumnext/commons";
import { useEffect, useState } from "preact/hooks";
+import {
+ backupDownloadFileName,
+ isBackupDownloadSupported,
+ startBackupDownload
+} from "./services/backup_download";
import { t } from "./services/i18n";
import open from "./services/open";
import server from "./services/server";
@@ -37,9 +42,17 @@ const CHOICES: { value: Choice; label: string }[] = [
{ value: "delete", label: "setup.existing-data-delete" }
];
-/** The three screens, in the order they can be reached, which is also the order they slide in. */
-type Step = "choice" | "backing-up" | "backed-up";
-const STEP_ORDER: Step[] = [ "choice", "backing-up", "backed-up" ];
+/** The screens, in the order they can be reached, which is also the order they slide in. */
+type Step = "choice" | "backing-up" | "downloading" | "backed-up";
+const STEP_ORDER: Step[] = [ "choice", "backing-up", "downloading", "backed-up" ];
+
+/** Where the standalone platform's backup download stands, as its screen shows it. */
+interface DownloadStatus {
+ fileName: string;
+ state: "idle" | "running" | "done" | "failed";
+ /** What stopped it, shown when `state` is `failed`. */
+ error?: string;
+}
/**
* The whole question, as one step of the wizard.
@@ -54,6 +67,7 @@ const STEP_ORDER: Step[] = [ "choice", "backing-up", "backed-up" ];
export default function ExistingData({ onProceed, onKept }: { onProceed: () => void; onKept: () => void }) {
const [ step, setStep ] = useState<Step>("choice");
const [ backup, setBackup ] = useState<SetupExistingBackup | null>(null);
+ const [ download, setDownload ] = useState<DownloadStatus | null>(null);
const [ error, setError ] = useState<string>();
const [ errorId, setErrorId ] = useState(0);
@@ -74,6 +88,16 @@ export default function ExistingData({ onProceed, onKept }: { onProceed: () => v
}
async function backUp() {
+ // Standalone streams the backup straight into a browser download: the browser's own
+ // storage may not have room for a second copy of the database, but the disk does. The
+ // screen comes first and the download starts from its own button, so nothing lands in
+ // the downloads bar unannounced.
+ if (isBackupDownloadSupported()) {
+ setDownload({ fileName: backupDownloadFileName(new Date()), state: "idle" });
+ setStep("downloading");
+ return;
+ }
+
setStep("backing-up");
try {
@@ -87,6 +111,18 @@ export default function ExistingData({ onProceed, onKept }: { onProceed: () => v
}
}
+ async function startDownload() {
+ if (!download) {
+ return;
+ }
+
+ setDownload({ ...download, state: "running", error: undefined });
+ const result = await startBackupDownload(download.fileName);
+ setDownload((current) => current && (result.status === "done"
+ ? { ...current, state: "done", error: undefined }
+ : { ...current, state: "failed", error: result.message }));
+ }
+
async function keep() {
try {
await keepExistingData();
@@ -111,6 +147,16 @@ export default function ExistingData({ onProceed, onKept }: { onProceed: () => v
/>
)}
{shown === "backing-up" && <ExistingDataBackingUp />}
+ {shown === "downloading" && download && (
+ <ExistingDataDownloading
+ fileName={download.fileName}
+ state={download.state}
+ error={download.error}
+ onDownload={() => void startDownload()}
+ onContinue={() => void erase()}
+ onCancel={() => void keep()}
+ />
+ )}
{shown === "backed-up" && backup && (
<ExistingDataBackedUp
backup={backup}
@@ -229,7 +275,7 @@ export function ExistingDataBackingUp() {
useEffect(() => {
const interval = setInterval(async () => {
try {
- const { fraction } = await server.get<{ fraction: number | null }>("setup/existing/status");
+ const { fraction } = await server.get<SetupExistingBackupStatus>("setup/existing/status");
setFraction(fraction);
} catch {
// The backup is what matters here; a missed reading is worth nothing being said about.
@@ -268,6 +314,71 @@ export function ExistingDataBackingUp() {
/** How often the screen asks how far along the backup is. */
const PROGRESS_INTERVAL_MS = 1000;
+/**
+ * The download step of the standalone platform, where the backup goes straight into a browser
+ * download rather than into the browser's own storage.
+ *
+ * The download starts from its own button rather than on arrival, so nothing appears in the
+ * downloads bar unannounced, and Continue stays disabled until the stream behind the download has
+ * been fully produced — the closest thing to "finished" the application can see, with the
+ * browser's own download UI carrying the transfer itself.
+ */
+export function ExistingDataDownloading({ fileName, state, error, onDownload, onContinue, onCancel }: {
+ fileName: string;
+ state: DownloadStatus["state"];
+ error?: string;
+ onDownload: () => void;
+ onContinue: () => void;
+ onCancel: () => void;
+}) {
+ return (
+ <SetupPage
+ className="existing-data-downloading top-aligned"
+ title={t("setup.existing-data-downloading")}
+ description={t("setup.existing-data-downloading-description", { fileName })}
+ illustration={<Icon icon="bx bx-download" className="illustration-icon" />}
+ footer={
+ <>
+ <Button text={t("setup.existing-data-cancel")} onClick={onCancel} />
+ <Button
+ text={t("setup.continue")}
+ kind="primary"
+ disabled={state !== "done"}
+ onClick={onContinue}
+ />
+ </>
+ }
+ >
+ <div class="existing-data-download">
+ <Button
+ text={t("setup.existing-data-download")}
+ icon="bx bx-download"
+ kind="primary"
+ disabled={state === "running"}
+ onClick={onDownload}
+ />
+
+ {state === "running" && (
+ <div class="existing-data-progress-message">
+ <span class="spinner-border" role="status" aria-hidden="true" />
+ <span>{t("setup.existing-data-downloading-in-progress")}</span>
+ </div>
+ )}
+ {state === "done" && <span>{t("setup.existing-data-downloading-done")}</span>}
+ {state === "failed" && (
+ <Admonition type="warning" className="existing-data-download-error">
+ {error ?? t("setup.existing-data-download-failed")}
+ </Admonition>
+ )}
+ </div>
+
+ <Admonition type="caution" className="existing-data-warning">
+ {t("setup.existing-data-downloading-warning")}
+ </Admonition>
+ </SetupPage>
+ );
+}
+
/**
* What was written, before the database it was written from is erased.
*
@@ -325,7 +436,7 @@ export function ExistingDataBackedUp({ backup, onContinue, onCancel }: {
}
/**
- * How long the backup is given before the client stops waiting for its answer.
+ * How long the backup is given before the client stops asking after it.
*
* The default minute is nothing next to what this takes: a large knowledge base is copied, and
* compressed and encrypted where the instance is set up for that, which runs into minutes. Giving up
@@ -367,9 +478,42 @@ function downloadBackup(filePath: string) {
`api/database/backup/download?filePath=${encodeURIComponent(filePath)}`));
}
-/** Backs the existing database up, answering with what was written. */
-export function backUpExistingData(): Promise<SetupExistingBackup> {
- return server.postWithTimeout<SetupExistingBackup>("setup/existing/backup", BACKUP_TIMEOUT_MS);
+/**
+ * Backs the existing database up, answering with what was written.
+ *
+ * Started with one request and followed through the status endpoint rather than waited for on the
+ * request itself: on the standalone platform a request rides the service worker, and the browser
+ * reclaims a fetch held open for the minutes a large database needs. A poll that fails is retried
+ * rather than believed, because the write blocks the standalone worker for long stretches in which
+ * it answers nothing, and the backup is running all the while.
+ */
+export async function backUpExistingData(): Promise<SetupExistingBackup> {
+ await server.post("setup/existing/backup");
+
+ const deadline = Date.now() + BACKUP_TIMEOUT_MS;
+ while (Date.now() < deadline) {
+ await sleep(PROGRESS_INTERVAL_MS);
+
+ let status: SetupExistingBackupStatus;
+ try {
+ status = await server.get<SetupExistingBackupStatus>("setup/existing/status");
+ } catch {
+ continue;
+ }
+
+ if (status.state === "done" && status.result) {
+ return status.result;
+ }
+ if (status.state === "failed") {
+ throw new Error(status.error ?? t("setup.existing-data-backup-failed"));
+ }
+ }
+
+ throw new Error(t("setup.existing-data-backup-failed"));
+}
+
+function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
}
/** Erases it, which is the point of no return. */
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index e1bbbe85cd..0dcb3e818b 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2078,6 +2078,9 @@
"date-and-time": "Date & time",
"path": "Path",
"database_backed_up_to": "Database has been backed up to {{- backupFilePath}}",
+ "download_only_summary": "Backups are downloaded straight to your device; nothing is stored in the browser.",
+ "download_finished": "The backup was downloaded as {{- fileName}}.",
+ "download_failed": "The backup download did not finish.",
"no_backup_yet": "no backup yet",
"download": "Download",
"options_title": "Backup options",
@@ -3702,6 +3705,12 @@
"existing-data-file-size": "Size",
"existing-data-encrypted-warning": "This backup is encrypted with the backup password you set in the options, which is not your Trilium password. If you no longer have that password, press Cancel now: nothing has been deleted yet, and you can change the password before trying again. Without it the backup cannot be restored.",
"existing-data-backup-failed": "The backup could not be created.",
+ "existing-data-downloading": "Download a backup",
+ "existing-data-downloading-description": "Your knowledge base will be saved as a download named {{- fileName}}. Your browser shows its progress among your downloads.",
+ "existing-data-downloading-in-progress": "Downloading...",
+ "existing-data-downloading-done": "The download has finished.",
+ "existing-data-download-failed": "The download did not finish.",
+ "existing-data-downloading-warning": "Once the download has finished and you press Continue, the knowledge base it was taken from is permanently erased. Keep the downloaded file somewhere safe.",
"existing-data-delete-failed": "The existing knowledge base could not be deleted.",
"existing-data-keep-failed": "The existing knowledge base could not be reopened.",
"restore-from-backup": "Restore from backup",
diff --git a/apps/client/src/widgets/type_widgets/options/backup.tsx b/apps/client/src/widgets/type_widgets/options/backup.tsx
index a4382f3786..89004e64b6 100644
--- a/apps/client/src/widgets/type_widgets/options/backup.tsx
+++ b/apps/client/src/widgets/type_widgets/options/backup.tsx
@@ -9,6 +9,11 @@ import {
} from "@triliumnext/commons";
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
+import {
+ backupDownloadFileName,
+ isBackupDownloadSupported,
+ startBackupDownload
+} from "../../../services/backup_download";
import { describeDatabaseFormat } from "../../../services/database_files";
import dialogService from "../../../services/dialog";
import { t } from "../../../services/i18n";
@@ -30,6 +35,13 @@ import DatabaseFileList from "./components/DatabaseFileList";
import OptionsPageHeader from "./components/OptionsPageHeader";
export default function BackupSettings() {
+ // Standalone keeps no backups anywhere: its one backup is a manual download, streamed straight
+ // off the live database, so the page reduces to that action and the way back in.
+ return isBackupDownloadSupported() ? <StandaloneBackupSettings /> : <StoredBackupSettings />;
+}
+
+/** The page everywhere backups are kept as files: the server, the desktop. */
+function StoredBackupSettings() {
const [backups, setBackups] = useState<DatabaseBackup[]>([]);
const [backupFolderPath, setBackupFolderPath] = useState<string | null>(null);
@@ -57,6 +69,60 @@ export default function BackupSettings() {
);
}
+/**
+ * The whole backup page on the standalone platform: the summary says how backups work there, the
+ * same "Backup now" button as everywhere else hands one to the browser as a download, and restore
+ * boots to the setup screen the way it does on the other platforms. There is no list, location,
+ * schedule or format to configure, because nothing is ever stored.
+ */
+function StandaloneBackupSettings() {
+ const [downloading, setDownloading] = useState(false);
+
+ async function download() {
+ setDownloading(true);
+ try {
+ const fileName = backupDownloadFileName(new Date());
+ const result = await startBackupDownload(fileName);
+
+ if (result.status === "done") {
+ toast.showMessage(t("backup.download_finished", { fileName }), 10000);
+ } else if (result.status === "failed") {
+ toast.showError(result.message ?? t("backup.download_failed"));
+ }
+ // A cancelled download needs no telling: the user did it themselves, in the browser.
+ } finally {
+ setDownloading(false);
+ }
+ }
+
+ return (
+ <OptionsPageHeader
+ below={
+ <div className="backup-status">
+ <span className="backup-status-summary">{t("backup.download_only_summary")}</span>
+
+ {canBootToSetup() && (
+ <Button
+ name="restore-backup-button"
+ text={t("backup.restore_backup")}
+ size="micro"
+ onClick={() => bootToSetup({ targetScreen: "restore-backup" })}
+ />
+ )}
+
+ <Button
+ name="backup-database-now-button"
+ text={t("backup.backup_now")}
+ size="micro"
+ disabled={downloading}
+ onClick={() => void download()}
+ />
+ </div>
+ }
+ />
+ );
+}
+
interface BackupStatusProps {
backups: DatabaseBackup[];
refreshCallback: () => void;
diff --git a/apps/standalone/src/lightweight/backup-download.spec.ts b/apps/standalone/src/lightweight/backup-download.spec.ts
new file mode 100644
index 0000000000..92567dd3c0
--- /dev/null
+++ b/apps/standalone/src/lightweight/backup-download.spec.ts
@@ -0,0 +1,187 @@
+import { readBackupContainer } from "@triliumnext/backup-container";
+import { streamedContainerSize } from "@triliumnext/backup-container/web";
+import { Readable, Writable } from "stream";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { type DownloadPort, streamDatabaseDownload } from "./backup-download.js";
+import type { LiveDatabaseReader } from "./backup-stream.js";
+
+const PAGE_SIZE = 512;
+const PAGE_COUNT = 300;
+
+/** Cheap scrypt cost, so the suite is not dominated by key derivation. */
+const FAST_SCRYPT = { log2N: 10, r: 8, p: 1 };
+
+/** A reader serving `PAGE_COUNT` constant-filled pages, with steady write counters. */
+function fakeReader(): LiveDatabaseReader {
+ return {
+ getValue(sql: string, params?: unknown[]) {
+ if (sql.includes("sqlite_dbpage")) {
+ return new Uint8Array(PAGE_SIZE).fill((params?.[0] as number) & 0xff);
+ }
+ if (sql.includes("page_size")) {
+ return PAGE_SIZE;
+ }
+ if (sql.includes("page_count")) {
+ return PAGE_COUNT;
+ }
+ return 7;
+ }
+ };
+}
+
+/** The bytes the fake reader's database consists of, for comparing an unwrapped download against. */
+function fakeDatabaseBytes(): Uint8Array {
+ const bytes = new Uint8Array(PAGE_SIZE * PAGE_COUNT);
+ for (let page = 1; page <= PAGE_COUNT; page++) {
+ bytes.fill(page & 0xff, (page - 1) * PAGE_SIZE, page * PAGE_SIZE);
+ }
+ return bytes;
+}
+
+/** A port whose far end is the test: what was sent piles up, and the test delivers the replies. */
+function fakePort() {
+ const sent: { type?: string; byteSize?: number; data?: ArrayBuffer; message?: string }[] = [];
+ const port = {
+ sent,
+ closed: false,
+ // Faithful to a real port where it matters most: a transferred buffer is DETACHED on the
+ // sending side, so a producer still holding a view into it breaks here as in production.
+ postMessage: (message: unknown, transfer?: Transferable[]) => {
+ sent.push(structuredClone(message, transfer ? { transfer } : undefined) as (typeof sent)[number]);
+ },
+ onmessage: null as DownloadPort["onmessage"],
+ close: () => {
+ port.closed = true;
+ },
+ deliver(message: unknown) {
+ port.onmessage?.({ data: message });
+ },
+ chunks(): ArrayBuffer[] {
+ return sent.filter((message) => message.type === "chunk")
+ .map((message) => message.data as ArrayBuffer);
+ }
+ };
+ return port;
+}
+
+describe("streamDatabaseDownload", () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ });
+
+ it("announces the size, sends one chunk per pull, and ends done", async () => {
+ const port = fakePort();
+ const running = streamDatabaseDownload(fakeReader(), port);
+
+ for (let i = 0; i < 4; i++) {
+ port.deliver({ type: "pull" });
+ }
+ const outcome = await running;
+
+ expect(outcome).toEqual({ status: "done" });
+ expect(port.sent[0]).toEqual({ type: "begin", byteSize: PAGE_SIZE * PAGE_COUNT });
+ expect(port.chunks().map((chunk) => chunk.byteLength))
+ .toEqual([ 128 * PAGE_SIZE, 128 * PAGE_SIZE, 44 * PAGE_SIZE ]);
+ expect(port.sent.at(-1)).toEqual({ type: "end" });
+ expect(port.closed).toBe(true);
+ expect(port.onmessage).toBeNull();
+ });
+
+ it("wraps the stream in an encrypted container, sized exactly as its begin announces", async () => {
+ const port = fakePort();
+ const running = streamDatabaseDownload(fakeReader(), port, {
+ passphrase: "123456",
+ scrypt: FAST_SCRYPT
+ });
+
+ for (let i = 0; i < 10; i++) {
+ port.deliver({ type: "pull" });
+ }
+ const outcome = await running;
+
+ expect(outcome).toEqual({ status: "done" });
+ // The announced size is what the download's Content-Length becomes, so it must be exact.
+ const announced = port.sent[0].byteSize;
+ expect(announced).toBe(streamedContainerSize(PAGE_SIZE * PAGE_COUNT));
+ const streamed = port.chunks().reduce((total, chunk) => total + chunk.byteLength, 0);
+ expect(streamed).toBe(announced);
+
+ // What went down the wire reads back as the database, through the other runtime's reader.
+ const container = Buffer.concat(port.chunks().map((chunk) => Buffer.from(chunk)));
+ const unwrapped: Buffer[] = [];
+ const sink = new Writable({
+ write(chunk: Buffer, _encoding, callback) {
+ unwrapped.push(chunk);
+ callback();
+ }
+ });
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- a Node stream over the bytes.
+ await readBackupContainer(Readable.from([ container ]) as any, sink, {
+ passphrase: "123456",
+ requireSqliteHeader: false
+ });
+ expect(new Uint8Array(Buffer.concat(unwrapped))).toEqual(fakeDatabaseBytes());
+ });
+
+ it("stops quietly when the download is cancelled", async () => {
+ const port = fakePort();
+ const running = streamDatabaseDownload(fakeReader(), port);
+
+ port.deliver({ type: "pull" });
+ port.deliver({ type: "cancel" });
+ const outcome = await running;
+
+ expect(outcome).toEqual({ status: "cancelled" });
+ expect(port.chunks()).toHaveLength(1);
+ expect(port.sent.some((message) => message.type === "end")).toBe(false);
+ expect(port.closed).toBe(true);
+ });
+
+ it("abandons a stream nothing asks after, which is what a reclaimed service worker leaves", async () => {
+ vi.useFakeTimers();
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const port = fakePort();
+ const running = streamDatabaseDownload(fakeReader(), port);
+
+ // One chunk flows, then the far end goes silent forever.
+ port.deliver({ type: "pull" });
+ await vi.advanceTimersByTimeAsync(11 * 60 * 1000);
+ const outcome = await running;
+
+ expect(outcome).toMatchObject({ status: "failed" });
+ expect(port.sent.some((message) => message.type === "end")).toBe(false);
+ expect(port.closed).toBe(true);
+ expect(warn.mock.calls.join("\n")).toMatch(/abandoning/);
+ });
+
+ it("reports a database that cannot even be sized, before any begin", async () => {
+ const port = fakePort();
+ const outcome = await streamDatabaseDownload({ getValue: () => 0 }, port);
+
+ expect(outcome).toMatchObject({ status: "failed" });
+ expect(port.sent).toHaveLength(1);
+ expect(port.sent[0].type).toBe("error");
+ expect(port.sent[0].message).toMatch(/page_size/);
+ expect(port.closed).toBe(true);
+ });
+
+ it("reports a failure mid-stream through the port rather than throwing", async () => {
+ const reader = fakeReader();
+ const broken: LiveDatabaseReader = {
+ getValue: (sql, params) =>
+ sql.includes("sqlite_dbpage") ? new Uint8Array(3) : reader.getValue(sql, params)
+ };
+ const port = fakePort();
+ const running = streamDatabaseDownload(broken, port);
+
+ port.deliver({ type: "pull" });
+ const outcome = await running;
+
+ expect(outcome).toMatchObject({ status: "failed", message: expect.stringMatching(/malformed/) });
+ expect(port.sent[0].type).toBe("begin");
+ expect(port.sent.at(-1)?.type).toBe("error");
+ expect(port.closed).toBe(true);
+ });
+});
diff --git a/apps/standalone/src/lightweight/backup-download.ts b/apps/standalone/src/lightweight/backup-download.ts
new file mode 100644
index 0000000000..55ef549cc1
--- /dev/null
+++ b/apps/standalone/src/lightweight/backup-download.ts
@@ -0,0 +1,184 @@
+import {
+ type ScryptParams,
+ streamedContainerSize,
+ writeBackupContainer
+} from "@triliumnext/backup-container/web";
+
+import { type LiveDatabaseReader, streamLiveDatabasePages } from "./backup-stream.js";
+
+/**
+ * Feeds a database backup into a download the service worker is holding open.
+ *
+ * The worker end of a three-party relay: the service worker answers a download navigation with a
+ * streamed `Response`, the page passes one end of a message channel through to this worker, and
+ * this module pulls pages off the live database and pushes them down the channel. Nothing lands in
+ * the origin's own storage on the way, which is the point: a quota that cannot hold a second copy
+ * of the database never has to.
+ *
+ * The stream is pull-driven, which is what carries the browser's backpressure all the way here:
+ * the service worker asks for a chunk each time the download can take more, so a slow disk slows
+ * the database reads rather than piling chunks up in a message queue.
+ *
+ * The payload is the plain database, or, given a passphrase, a streamed encrypted container: the
+ * format's forward-only shape, whose GCM frames carry the integrity a patched-in digest cannot on
+ * a destination already streamed away. Compression is never used here — at these sizes it is more
+ * than a low-end device can afford — and either shape's exact size is known up front, which is
+ * what gives the download its `Content-Length` and the browser its progress bar.
+ *
+ * Protocol, from the service worker's side: it receives `begin` (with the exact byte size), then
+ * one `chunk` per `pull` it sends, then `end`; `error` may arrive at any point, and `cancel` may
+ * be sent at any point.
+ *
+ * @module
+ */
+
+/** The slice of `MessagePort` the stream needs, kept structural for tests. */
+export interface DownloadPort {
+ postMessage(message: unknown, transfer?: Transferable[]): void;
+ onmessage: ((event: { data: unknown }) => void) | null;
+ close?(): void;
+}
+
+/** How the download ended, for the screen that gates its Continue on it. */
+export interface DownloadOutcome {
+ status: "done" | "cancelled" | "failed";
+ /** What stopped it, when `failed`. */
+ message?: string;
+}
+
+export interface DownloadOptions {
+ /** Wraps the stream in an encrypted, streamed container. Plain database bytes otherwise. */
+ passphrase?: string;
+ /** scrypt cost override, for tests that cannot afford the production one. */
+ scrypt?: ScryptParams;
+}
+
+/**
+ * How long the stream waits to be asked for more before giving the download up for dead.
+ *
+ * A living download asks many times a second, and even one the user paused sits behind a service
+ * worker the page keeps pinging alive. What this catches is the far end having died without a
+ * word — a reclaimed service worker cannot say goodbye — so the wait is generous enough that no
+ * plausible pause trips it, and its expiry means cleanup, never a failed backup that was working.
+ */
+const PULL_TIMEOUT_MS = 10 * 60 * 1000;
+
+/** How the far end ended the stream mid-payload, carried out of the sink as an exception. */
+class DownloadStopped extends Error {
+ constructor(readonly why: "cancel" | "abandoned") {
+ super(`The download was ${why === "cancel" ? "cancelled" : "abandoned"}.`);
+ this.name = "DownloadStopped";
+ }
+}
+
+/**
+ * Streams the live database into `port` until it is done, cancelled, or fails.
+ *
+ * Never rejects: failures are reported through the port for the download's sake, and the outcome
+ * is returned for the screen that is waiting to enable its Continue.
+ */
+export async function streamDatabaseDownload(
+ db: LiveDatabaseReader,
+ port: DownloadPort,
+ options: DownloadOptions = {}
+): Promise<DownloadOutcome> {
+ const requests: ("pull" | "cancel")[] = [];
+ let wake: (() => void) | null = null;
+
+ port.onmessage = (event) => {
+ const type = (event.data as { type?: unknown } | null)?.type;
+ if (type === "pull" || type === "cancel") {
+ requests.push(type);
+ wake?.();
+ }
+ };
+
+ const nextRequest = async (): Promise<"pull" | "cancel" | "abandoned"> => {
+ while (requests.length === 0) {
+ const woke = await new Promise<boolean>((resolve) => {
+ const timer = setTimeout(() => resolve(false), PULL_TIMEOUT_MS);
+ wake = () => {
+ clearTimeout(timer);
+ resolve(true);
+ };
+ });
+ wake = null;
+ if (!woke) {
+ return "abandoned";
+ }
+ }
+ return requests.shift() ?? "cancel";
+ };
+
+ /** Posts one chunk per granted pull, or throws the stop that was granted instead. */
+ const sendChunk = async (chunk: Uint8Array): Promise<void> => {
+ const request = await nextRequest();
+ if (request !== "pull") {
+ throw new DownloadStopped(request);
+ }
+
+ // Fresh, whole buffers are handed over rather than copied; anything else is copied first.
+ const data = chunk.byteOffset === 0 && chunk.byteLength === chunk.buffer.byteLength
+ ? chunk.buffer
+ : chunk.slice().buffer;
+ port.postMessage({ type: "chunk", data }, [ data ]);
+ };
+
+ let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
+ try {
+ const { byteSize, stream } = streamLiveDatabasePages(db);
+
+ if (options.passphrase === undefined) {
+ reader = stream.getReader();
+ port.postMessage({ type: "begin", byteSize });
+
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) {
+ port.postMessage({ type: "end" });
+ return { status: "done" };
+ }
+ await sendChunk(value);
+ }
+ }
+
+ port.postMessage({ type: "begin", byteSize: streamedContainerSize(byteSize) });
+ await writeBackupContainer(
+ stream,
+ new WritableStream<Uint8Array>({ write: sendChunk }),
+ {
+ passphrase: options.passphrase,
+ streamed: true,
+ plaintextSize: byteSize,
+ scrypt: options.scrypt
+ }
+ );
+ port.postMessage({ type: "end" });
+ return { status: "done" };
+ } catch (e) {
+ if (e instanceof DownloadStopped) {
+ if (e.why === "abandoned") {
+ console.warn("[Backup] The download stopped asking for data; abandoning the stream.");
+ return { status: "failed", message: "The download stopped." };
+ }
+ return { status: "cancelled" };
+ }
+
+ const message = e instanceof Error ? e.message : String(e);
+ post(port, { type: "error", message });
+ return { status: "failed", message };
+ } finally {
+ await reader?.cancel().catch(() => undefined);
+ port.onmessage = null;
+ port.close?.();
+ }
+}
+
+/** A best-effort message: the port may already be gone, and this report is all that would say so. */
+function post(port: DownloadPort, message: unknown): void {
+ try {
+ port.postMessage(message);
+ } catch {
+ // Nobody left to tell.
+ }
+}
diff --git a/apps/standalone/src/lightweight/backup-stream.spec.ts b/apps/standalone/src/lightweight/backup-stream.spec.ts
index 1ffa81ee90..0c1e7ff079 100644
--- a/apps/standalone/src/lightweight/backup-stream.spec.ts
+++ b/apps/standalone/src/lightweight/backup-stream.spec.ts
@@ -2,23 +2,18 @@ import { getSql } from "@triliumnext/core";
import { describe, expect, it } from "vitest";
import {
- openBackupDestination,
- type SnapshotConnection,
- type SnapshotStatement,
- streamDatabasePages,
- type SyncFileAccess
+ DatabaseChangedError,
+ type LiveDatabaseReader,
+ streamLiveDatabasePages
} 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 };
- };
+ sqlite3: { capi: { sqlite3_js_db_export(db: unknown): Uint8Array } };
};
-type WithDb = { db: SnapshotConnection };
+type WithDb = { db: unknown };
function newProviderWithModule(): BrowserSqlProvider {
const provider = new BrowserSqlProvider();
@@ -28,7 +23,7 @@ function newProviderWithModule(): BrowserSqlProvider {
return provider;
}
-function rawConnection(provider: BrowserSqlProvider): SnapshotConnection {
+function rawConnection(provider: BrowserSqlProvider): unknown {
return (provider as unknown as WithDb).db;
}
@@ -52,201 +47,62 @@ async function drain(stream: ReadableStream<Uint8Array>): Promise<Uint8Array> {
return whole;
}
-describe("streamDatabasePages against the real engine", () => {
- it("streams a database as its exact file bytes", async () => {
+describe("streamLiveDatabasePages against the real engine", () => {
+ function readerFor(provider: BrowserSqlProvider): LiveDatabaseReader {
+ return { getValue: (sql, params) => provider.prepare(sql).pluck().get(params ?? []) };
+ }
+
+ function populatedProvider(): BrowserSqlProvider {
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.
+ // Enough rows to span several batches, and deletions so a freelist is streamed too.
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)");
+ provider.exec("DELETE FROM t WHERE id % 5 = 0");
+ return provider;
+ }
- const connection = rawConnection(provider);
+ it("streams the live database as its exact bytes, without taking the connection over", async () => {
+ const provider = populatedProvider();
const exported = (provider as unknown as WithSqlite3).sqlite3.capi
- .sqlite3_js_db_export(connection);
+ .sqlite3_js_db_export(rawConnection(provider));
- const { byteSize, stream } = streamDatabasePages(connection);
+ const { byteSize, stream } = streamLiveDatabasePages(readerFor(provider));
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();
+ // Not taken over: the connection answers as before, because it is the live one.
+ expect(provider.prepare("SELECT count(*) FROM t").pluck().get([])).toBe(400);
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);
+ it("errors the stream when a write lands mid-stream, so a caller can start over", async () => {
+ const provider = populatedProvider();
+ const { stream } = streamLiveDatabasePages(readerFor(provider));
const reader = stream.getReader();
await reader.read();
- await reader.cancel();
- expect(connection.closed).toBe(1);
- expect(connection.finalized).toBe(1);
- });
-});
+ provider.exec("INSERT INTO t (payload) VALUES (randomblob(10))");
-/** 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);
+ await expect(reader.read()).rejects.toBeInstanceOf(DatabaseChangedError);
+ provider.close();
});
- 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("refuses a reader that reports no usable page size", () => {
+ const reader: LiveDatabaseReader = { getValue: () => 0 };
+ expect(() => streamLiveDatabasePages(reader)).toThrow(/page_size/);
});
- 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();
+ it("errors the stream when a page comes back the wrong size", async () => {
+ const reader: LiveDatabaseReader = {
+ getValue: (sql) => sql.includes("sqlite_dbpage")
+ ? new Uint8Array(3)
+ : sql.includes("page_size") ? 512 : sql.includes("page_count") ? 4 : 0
+ };
+ await expect(drain(streamLiveDatabasePages(reader).stream)).rejects.toThrow(/malformed/);
});
});
+
diff --git a/apps/standalone/src/lightweight/backup-stream.ts b/apps/standalone/src/lightweight/backup-stream.ts
index 6b846ed6e1..f595939507 100644
--- a/apps/standalone/src/lightweight/backup-stream.ts
+++ b/apps/standalone/src/lightweight/backup-stream.ts
@@ -1,17 +1,16 @@
/**
- * Streams a database between the SAH pool and a plain OPFS file without ever holding it whole.
+ * Streams the database out of the browser without ever holding it whole, or copying it first.
*
- * 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 SAH pool has no streaming read, and staging a copy of the database beside itself needs
+ * storage a browser quota may simply not have. What the pool does have is SQLite, 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. The pages come straight off the live database,
+ * and consistency is watched rather than arranged: the database's write counters are checked as
+ * the stream goes, and a write landing mid-stream errors it so the caller can start over.
*
- * 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.
+ * Deliberately a dumb pipe: {@link streamLiveDatabasePages} turns the live database into a
+ * `ReadableStream` of page batches, and where they flow is the caller's story — today that is the
+ * backup download, which relays them through the service worker to the browser's disk.
*
* @module
*/
@@ -19,20 +18,17 @@
/** 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;
+/** Reads the live database through the core SQL layer, which fronts the one connection there is. */
+export interface LiveDatabaseReader {
+ getValue(sql: string, params?: unknown[]): unknown;
}
-/** 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;
+/** Thrown by {@link streamLiveDatabasePages} when a write lands mid-stream. The caller retries. */
+export class DatabaseChangedError extends Error {
+ constructor() {
+ super("The database changed while it was being backed up.");
+ this.name = "DatabaseChangedError";
+ }
}
export interface DatabaseStream {
@@ -42,47 +38,34 @@ export interface DatabaseStream {
}
/**
- * Streams the database open on `db` as its exact file bytes, a batch of pages at a time.
+ * Streams the live database as its exact logical bytes, without any copy of it anywhere.
*
- * 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.
+ * The database is in use while it is being read, and there is only the one connection, so nothing
+ * can hold the content in place across the stream's yields. Consistency comes from detection
+ * instead: the write counters are fingerprinted at the start and checked before every batch and
+ * once more before the stream closes, and any write anywhere in between errors the stream with
+ * {@link DatabaseChangedError} rather than sealing a backup that is part before and part after.
+ * Every write in this process goes through the one connection the counters watch, so nothing can
+ * slip past them.
*
* @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;
- }
+export function streamLiveDatabasePages(db: LiveDatabaseReader): DatabaseStream {
+ const pageSize = countOf(db.getValue("PRAGMA page_size"), "page_size");
+ const pageCount = countOf(db.getValue("PRAGMA page_count"), "page_count");
+ const fingerprint = fingerprintOf(db);
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 (fingerprintOf(db) !== fingerprint) {
+ throw new DatabaseChangedError();
+ }
if (nextPage > pageCount) {
- release();
controller.close();
return;
}
@@ -90,96 +73,36 @@ export function streamDatabasePages(db: SnapshotConnection): DatabaseStream {
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);
+ batch.set(readLivePage(db, 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;
+/** One page, checked to be exactly a page: anything else means the file is not what it claims. */
+function readLivePage(db: LiveDatabaseReader, pageNumber: number, pageSize: number): Uint8Array {
+ const data = db.getValue("SELECT data FROM sqlite_dbpage WHERE pgno = ?", [ pageNumber ]);
+ if (!(data instanceof Uint8Array) || data.byteLength !== pageSize) {
+ throw new Error(`Page ${pageNumber} came back malformed.`);
+ }
+ return data;
}
/**
- * 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.
+ * What must not have moved between two looks for the pages to belong to one database: rows changed
+ * on this connection, the schema's own version, and the file's page count.
*/
-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();
- }
+function fingerprintOf(db: LiveDatabaseReader): string {
+ return [
+ db.getValue("SELECT total_changes()"),
+ db.getValue("PRAGMA schema_version"),
+ db.getValue("PRAGMA page_count")
+ ].join("/");
}
/** A pragma answer as the positive integer it must be, or the reason it is not a database. */
@@ -190,23 +113,3 @@ function countOf(value: unknown, name: string): number {
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.ts
index f11d05f9fb..869df8b547 100644
--- a/apps/standalone/src/lightweight/backup_provider.spec.ts
+++ b/apps/standalone/src/lightweight/backup_provider.spec.ts
@@ -1,486 +1,60 @@
-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, {
- type BackupSqlAccess,
+ removeBackupLeftovers,
type SnapshotPool
} from "./backup_provider.js";
-interface NavWithStorage {
- storage?: {
- getDirectory?: () => Promise<unknown>;
- estimate?: () => Promise<{ quota?: number; usage?: number }>;
- };
-}
-
-const realStorageDescriptor = Object.getOwnPropertyDescriptor(navigator, "storage");
-
-/**
- * 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 data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
- }
- };
- },
- async createSyncAccessHandle() {
- if (failures.syncAccess) {
- throw new Error("file is locked");
- }
- return {
- 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() {}
- };
- }
- };
- }
-
- const dir = {
- async getFileHandle(name: string, opts?: { create?: boolean }) {
- if (!files.has(name)) {
- if (!opts?.create) {
- throw new Error(`missing ${name}`);
- }
- files.set(name, { data: new Uint8Array(), lastModified: clock++ });
- }
- return fileHandle(name);
- },
- async removeEntry(name: string) {
- if (!files.delete(name)) {
- throw new Error(`missing ${name}`);
- }
- },
- async *entries(): AsyncGenerator<[string, unknown]> {
- // 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, 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
- });
-}
-
-/** 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(() => {
- if (realStorageDescriptor) {
- Object.defineProperty(navigator, "storage", realStorageDescriptor);
- } else {
- delete (navigator as unknown as NavWithStorage).storage;
- }
vi.restoreAllMocks();
});
-describe("StandaloneBackupService without OPFS", () => {
- function serviceWithoutOpfs() {
- delete (navigator as unknown as NavWithStorage).storage;
- return service(makeSqlAccess().access);
+describe("StandaloneBackupService", () => {
+ function service() {
+ return new StandaloneBackupService(options);
}
- it("scheduleBackups is a no-op", () => {
- expect(() => serviceWithoutOpfs().scheduleBackups()).not.toThrow();
+ it("schedules nothing, since nothing is ever stored", () => {
+ expect(() => service().scheduleBackups()).not.toThrow();
});
- it("backupNow warns and returns the nominal path", async () => {
+ it("declines a stored backup with a warning, and without blocking the caller", async () => {
+ // The pre-migration backup goes through here, and a migration must not be stopped by a
+ // backup this platform simply does not have.
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
- expect(await serviceWithoutOpfs().backupNow("now")).toBe("/backups/backup-now.db");
- expect(warn).toHaveBeenCalled();
- });
- it("backupAs refuses outright, because its caller shows the result to the user", async () => {
- await expect(serviceWithoutOpfs().backupAs("Backup 1")).rejects.toThrow(/OPFS/);
+ await expect(service().backupNow("before-migration")).resolves.toBe("");
+ expect(warn.mock.calls.join("\n")).toMatch(/before-migration/);
});
- 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();
+ it("has no backups to list and none to serve", async () => {
+ expect(await service().getExistingBackups()).toEqual([]);
+ expect(await service().getBackupContent()).toBeNull();
});
});
-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");
-
- expect(path).toBe("/backups/backup-daily.db");
- 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("sanitizes the backup name the way the server does", async () => {
- const fs = makeOpfs();
- installOpfs(async () => fs.root);
- 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
- );
-
- const path = await service(makeSqlAccess().access).backupNow("daily");
- expect(path).toBe("/backups/backup-daily.tnbackup");
-
- 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(error.mock.calls.join("\n")).toMatch(/browser storage/);
-
- await expect(service(sql.access).backupAs("Backup 1")).rejects.toThrow(/browser storage/);
- });
-
- 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
- };
+describe("removeBackupLeftovers", () => {
+ it("unlinks both of the old snapshot machinery's leftovers", () => {
+ const unlinked: string[] = [];
+ const pool: SnapshotPool = {
+ unlink: (name: string) => {
+ unlinked.push(name);
+ return true;
}
- 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 },
- "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 service(makeSqlAccess().access).getExistingBackups();
- expect(backups.map((backup) => backup.fileName)).toEqual([ "backup-good.db" ]);
- });
-
- 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 svc = service(makeSqlAccess().access);
- const content = await svc.getBackupContent("/backups/backup-keep.tnbackup");
- expect(content && Array.from(content)).toEqual([ 1, 2, 3 ]);
-
- 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);
- expect(await service(makeSqlAccess().access).getBackupContent("/backups/secrets.txt"))
- .toBeNull();
- });
-
- it("handles a missing backup directory handle gracefully", async () => {
- // root.getDirectoryHandle resolves to undefined → every operation degrades quietly.
- const root = { async getDirectoryHandle() { return undefined; } };
- installOpfs(async () => root);
- vi.spyOn(console, "error").mockImplementation(() => {});
+ };
- 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();
+ removeBackupLeftovers(pool);
+ expect(unlinked).toEqual([ "/backup-snapshot.db", "/backup-snapshot.db-journal" ]);
});
- it("swallows OPFS errors on every operation but backupAs", async () => {
- const boom = async () => {
- throw new Error("opfs down");
+ it("never throws past a pool that refuses", () => {
+ const refusing: SnapshotPool = {
+ unlink: () => {
+ throw new Error("in use");
+ }
};
- installOpfs(boom);
- vi.spyOn(console, "error").mockImplementation(() => {});
- 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");
+ expect(() => removeBackupLeftovers(refusing)).not.toThrow();
});
});
diff --git a/apps/standalone/src/lightweight/backup_provider.ts b/apps/standalone/src/lightweight/backup_provider.ts
index 782893843b..19410b8c2c 100644
--- a/apps/standalone/src/lightweight/backup_provider.ts
+++ b/apps/standalone/src/lightweight/backup_provider.ts
@@ -1,489 +1,66 @@
-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";
-
-/** Backups that are compressed are containers rather than plain database copies, as on the server. */
-const CONTAINER_EXTENSION = ".tnbackup";
-const DATABASE_EXTENSION = ".db";
+import type { DatabaseBackup } from "@triliumnext/commons";
+import { BackupService } from "@triliumnext/core";
/**
- * 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.
+ * Pool entries earlier versions could leave behind: they vacuumed a snapshot into the pool, and a
+ * backup interrupted mid-vacuum left the snapshot, up to the database's own size, or its journal
+ * sitting there. Swept for as long as such pools may still be around.
*/
-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;
-}
+const SNAPSHOT_LEFTOVERS = [ "/backup-snapshot.db", "/backup-snapshot.db-journal" ];
-/** The slice of the SAH pool used here, kept structural so tests need not build a real one. */
+/** The slice of the SAH pool the leftover sweep needs. `SAHPoolUtil` matches it as it stands. */
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: streams the database into a file under OPFS `/backups`.
+ * Standalone backup service: a stub, deliberately.
*
- * 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.
+ * The platform keeps no backups anywhere. Its one backup is manual: the options screen and the
+ * setup screen stream the live database straight into a browser download, through the service
+ * worker, without a byte of it landing in the browser's own storage — which is the point, since
+ * that storage holds the live database and can rarely hold a copy of it beside itself. So nothing
+ * here schedules, stores, lists or serves anything.
*
- * 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.
+ * The pre-migration backup is skipped with a warning rather than refused: the only backup this
+ * platform has needs a user at a screen, and blocking a migration on a backup nobody can take
+ * would leave the application unable to start at all.
*/
export default class StandaloneBackupService extends BackupService {
- private backupDir: FileSystemDirectoryHandle | null = null;
- private opfsAvailable: boolean | null = null;
-
- constructor(
- options: BackupOptionsService,
- private readonly sqlAccess: () => BackupSqlAccess | undefined = () => undefined
- ) {
- super(options);
- }
override scheduleBackups(): void {
- // No scheduled backups on standalone/mobile
+ // Nothing is ever stored, so there is nothing to schedule.
}
override async backupNow(name: string): Promise<string> {
- // 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}`;
-
- if (!this.isOpfsAvailable()) {
- console.warn(`[Backup] OPFS not available, skipping backup: ${fileName}`);
- return nominalPath;
- }
-
- try {
- 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);
- }
- return nominalPath;
- }
-
- 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.");
- }
-
- // 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
- };
+ console.warn(`[Backup] Stored backups are not supported on this platform, so "${name}" `
+ + "was not created. The options screen backs up by downloading a copy instead.");
+ return "";
}
override async getExistingBackups(): Promise<DatabaseBackup[]> {
- if (!this.isOpfsAvailable()) {
- return [];
- }
-
- try {
- const dir = await this.ensureBackupDirectory();
- if (!dir) {
- return [];
- }
-
- const entries = await fileEntriesIn(dir);
- const names = new Set(entries.map(([ name ]) => name));
- const backups: DatabaseBackup[] = [];
-
- 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.getFile();
- backups.push({
- fileName: name,
- filePath: `/${BACKUP_DIR_NAME}/${name}`,
- mtime: new Date(file.lastModified),
- fileSize: file.size,
- ...await describeContainer(file, name)
- });
- }
-
- // Sort by modification time, newest first
- backups.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
- return backups;
- } catch (error) {
- console.error("[Backup] Failed to list backups:", error);
- return [];
- }
+ return [];
}
- /**
- * Delete a backup by filename.
- */
- async deleteBackup(fileName: string): Promise<void> {
- if (!this.isOpfsAvailable()) {
- return;
- }
-
- try {
- const dir = await this.ensureBackupDirectory();
- if (!dir) {
- 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);
- }
+ override async getBackupContent(): Promise<Uint8Array | null> {
+ return null;
}
- override async getBackupContent(filePath: string): Promise<Uint8Array | null> {
- if (!this.isOpfsAvailable()) {
- return null;
- }
-
- try {
- const dir = await this.ensureBackupDirectory();
- if (!dir) {
- return null;
- }
-
- // Extract fileName from filePath (e.g. "/backups/backup-now.db" -> "backup-now.db")
- const fileName = filePath.split("/").pop();
- if (!fileName || !isBackupFileName(fileName)) {
- return null;
- }
-
- const fileHandle = await dir.getFileHandle(fileName);
- const file = await fileHandle.getFile();
- const data = await file.arrayBuffer();
- return new Uint8Array(data);
- } catch (error) {
- console.error(`[Backup] Failed to get backup content ${filePath}:`, error);
- 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.
+ * Removes whatever an earlier version's snapshot machinery left in the pool. Unlinking truncates
+ * the pool's physical file, so the quota comes back with it.
+ *
+ * Called by the worker at startup: the space should not stay lost just because the machinery that
+ * would have reclaimed it is gone. Never the reason anything fails.
*/
-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);
+export function removeBackupLeftovers(pool: SnapshotPool): void {
+ for (const name of SNAPSHOT_LEFTOVERS) {
+ try {
+ pool.unlink(name);
+ } catch {
+ // A leftover entry costs a pool slot and its bytes, which the next sweep tries again.
}
}
}
-
-/** 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-bridge.spec.ts b/apps/standalone/src/local-bridge.spec.ts
index 746c0e39f6..bd696360bf 100644
--- a/apps/standalone/src/local-bridge.spec.ts
+++ b/apps/standalone/src/local-bridge.spec.ts
@@ -47,6 +47,8 @@ function lastWorker(): MockWorker {
afterEach(() => {
delete (navigator as unknown as NavServiceWorker).serviceWorker;
+ // Download frames pile up across tests otherwise: their removal timers never get to run.
+ document.querySelectorAll("iframe").forEach((frame) => frame.remove());
vi.restoreAllMocks();
});
@@ -196,6 +198,37 @@ describe("attachServiceWorkerBridge", () => {
expect(() => swHandler?.({ data: { type: "LOCAL_FETCH", id: "1", request: {} }, ports: [] })).not.toThrow();
});
+ it("relays a backup download's port straight to the worker, transferred", async () => {
+ const bridge = await freshBridge();
+ bridge.attachServiceWorkerBridge();
+
+ const port = { postMessage: vi.fn() };
+ await swHandler?.({ data: { type: "LOCAL_BACKUP_STREAM" }, ports: [port] });
+
+ expect(lastWorker().postMessage)
+ .toHaveBeenCalledWith(expect.objectContaining({ type: "BACKUP_STREAM", port }), [ port ]);
+
+ // Without a port there is nothing to relay, and nothing to trip over either.
+ expect(() => swHandler?.({ data: { type: "LOCAL_BACKUP_STREAM" }, ports: [] })).not.toThrow();
+ });
+
+ it("hands the passphrase to the worker on the relayed message, and only once", async () => {
+ const bridge = await freshBridge();
+ bridge.attachServiceWorkerBridge();
+ void bridge.downloadDatabase("Backup.tnbackup", "123456");
+
+ const port = { postMessage: vi.fn() };
+ await swHandler?.({ data: { type: "LOCAL_BACKUP_STREAM" }, ports: [port] });
+ expect(lastWorker().postMessage).toHaveBeenCalledWith(
+ expect.objectContaining({ type: "BACKUP_STREAM", passphrase: "123456" }), [ port ]);
+
+ // A stream that arrives with no download of its own gets no leftover passphrase.
+ const secondPort = { postMessage: vi.fn() };
+ await swHandler?.({ data: { type: "LOCAL_BACKUP_STREAM" }, ports: [secondPort] });
+ expect(lastWorker().postMessage).toHaveBeenLastCalledWith(
+ expect.objectContaining({ type: "BACKUP_STREAM", passphrase: undefined }), [ secondPort ]);
+ });
+
it("replies without a transferable body when the worker omits one", async () => {
const bridge = await freshBridge();
bridge.attachServiceWorkerBridge();
@@ -351,6 +384,74 @@ describe("isLocalApiRequest", () => {
});
});
+describe("backup download keepalive", () => {
+ it("pings the service worker for exactly as long as the worker says a stream runs", async () => {
+ vi.useFakeTimers();
+ const fetchSpy = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(null));
+ const bridge = await freshBridge();
+ bridge.startLocalServerWorker();
+
+ lastWorker().onmessage?.({ data: { type: "BACKUP_STREAM_ACTIVE", active: true } });
+ await vi.advanceTimersByTimeAsync(25_000);
+ expect(fetchSpy).toHaveBeenCalledWith("/local-backup-ping");
+ expect(fetchSpy).toHaveBeenCalledTimes(2);
+
+ lastWorker().onmessage?.({ data: { type: "BACKUP_STREAM_ACTIVE", active: false } });
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(fetchSpy).toHaveBeenCalledTimes(2);
+
+ vi.useRealTimers();
+ });
+});
+
+describe("downloadDatabase", () => {
+ it("navigates a hidden frame at the download URL, and starts the worker for it", async () => {
+ vi.useFakeTimers();
+ const bridge = await freshBridge();
+
+ void bridge.downloadDatabase("Backup 2026-08-08 10-00-00.db");
+
+ // A frame rather than an anchor: anchor downloads bypass the service worker in Firefox.
+ const frame = document.querySelector("iframe");
+ expect(frame?.hidden).toBe(true);
+ expect(frame?.src).toContain(
+ `/local-backup-download?fileName=${encodeURIComponent("Backup 2026-08-08 10-00-00.db")}`);
+ expect(workerInstances.length).toBe(1);
+
+ // The frame outlives the service worker's whole wait for the stream, then goes.
+ await vi.advanceTimersByTimeAsync(59_000);
+ expect(document.querySelector("iframe")).not.toBeNull();
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(document.querySelector("iframe")).toBeNull();
+
+ vi.useRealTimers();
+ });
+
+ it("resolves with the outcome the worker reports when the stream ends", async () => {
+ const bridge = await freshBridge();
+ const pending = bridge.downloadDatabase("Backup.tnbackup");
+
+ lastWorker().onmessage?.({ data: { type: "BACKUP_STREAM_ACTIVE", active: true } });
+ lastWorker().onmessage?.({
+ data: { type: "BACKUP_STREAM_ACTIVE", active: false, result: { status: "done" } }
+ });
+
+ expect(await pending).toEqual({ status: "done" });
+ });
+
+ it("resolves as failed when nothing ever picks the download up", async () => {
+ vi.useFakeTimers();
+ const bridge = await freshBridge();
+ const pending = bridge.downloadDatabase("Backup.tnbackup");
+
+ // The chain died silently inside the hidden frame; no worker message ever arrives.
+ await vi.advanceTimersByTimeAsync(46_000);
+
+ expect(await pending).toMatchObject({ status: "failed" });
+ vi.useRealTimers();
+ });
+});
+
describe("restoreBackup", () => {
/** The message the bridge sent to the worker to start a restore. */
function restoreMessage(worker: MockWorker) {
diff --git a/apps/standalone/src/local-bridge.ts b/apps/standalone/src/local-bridge.ts
index 56cde72555..e4a2d7ffbc 100644
--- a/apps/standalone/src/local-bridge.ts
+++ b/apps/standalone/src/local-bridge.ts
@@ -1,4 +1,8 @@
-import type { StandaloneRestoreProgress, StandaloneRestoreResult } from "@triliumnext/commons";
+import type {
+ StandaloneDownloadResult,
+ StandaloneRestoreProgress,
+ StandaloneRestoreResult
+} from "@triliumnext/commons";
import LocalServerWorker from "./local-server-worker?worker";
let localWorker: Worker | null = null;
@@ -41,6 +45,99 @@ export function restoreBackup(opts: {
});
}
+/**
+ * How long the download's frame is kept in the page: comfortably past the service worker's own
+ * 30-second wait for the stream to open, after which the response has either been handed to the
+ * browser's download manager, which no longer needs the frame, or failed inside it invisibly.
+ */
+const DOWNLOAD_FRAME_LINGER_MS = 60_000;
+
+/** Well inside the ~30 seconds of eventlessness after which browsers reclaim a service worker. */
+const BACKUP_PING_INTERVAL_MS = 10_000;
+
+let backupPing: ReturnType<typeof setInterval> | null = null;
+
+/**
+ * Keeps the service worker alive while it streams a backup download, by fetching a no-op URL it
+ * answers: a fetch event is what resets the browser's idle clock on it. Runs for exactly as long
+ * as the local worker says a stream is running, and never twice at once.
+ */
+function setBackupPinging(active: boolean): void {
+ if (active && !backupPing) {
+ backupPing = setInterval(
+ () => void fetch("/local-backup-ping").catch(() => undefined),
+ BACKUP_PING_INTERVAL_MS
+ );
+ } else if (!active && backupPing) {
+ clearInterval(backupPing);
+ backupPing = null;
+ }
+}
+
+/** How long the chain gets to reach the worker and open the stream before it is called dead. */
+const DOWNLOAD_START_TIMEOUT_MS = 45_000;
+
+/** The one download in flight, waiting for the worker to say how the stream ended. */
+let pendingDownload: {
+ resolve: (result: StandaloneDownloadResult) => void;
+ startTimer: ReturnType<typeof setTimeout>;
+} | null = null;
+
+/** Carried from {@link downloadDatabase} to the stream relay, so it never rides the URL. */
+let pendingDownloadPassphrase: string | undefined;
+
+/**
+ * Hands the browser a download of the live database, streamed by the service worker.
+ *
+ * A navigation rather than a request: the URL is answered by the service worker with a response
+ * body it pulls from the local worker chunk by chunk, so the browser's own download manager
+ * receives, shows and stores the file, and nothing is staged in the origin's storage first.
+ * The worker is started here because the service worker's first act is to ask the page for it.
+ * The passphrase, when there is one, travels to the worker on the relayed message, never in the
+ * URL a browser would put in its history.
+ *
+ * The navigation is a hidden iframe rather than an anchor click: anchors with the `download`
+ * attribute are not routed through service workers everywhere (Firefox never sends them there),
+ * while a frame's navigation always is, and the response's `Content-Disposition` is what makes it
+ * a download either way. A failure renders invisibly inside the frame instead of navigating the
+ * application away.
+ *
+ * Resolves when the worker has finished producing the stream, one way or the other — which is as
+ * close to "the download finished" as anything on this side of the browser's download manager can
+ * see. A chain that dies silently inside the hidden frame (a stale service worker, say) resolves
+ * as failed after a timeout rather than never.
+ */
+export function downloadDatabase(fileName: string, passphrase?: string): Promise<StandaloneDownloadResult> {
+ startLocalServerWorker();
+ // A newer download supersedes one still unaccounted for, rather than stacking behind it.
+ settlePendingDownload({ status: "cancelled" });
+ pendingDownloadPassphrase = passphrase;
+
+ const frame = document.createElement("iframe");
+ frame.hidden = true;
+ frame.src = `/local-backup-download?fileName=${encodeURIComponent(fileName)}`;
+ document.body.appendChild(frame);
+ setTimeout(() => frame.remove(), DOWNLOAD_FRAME_LINGER_MS);
+
+ return new Promise((resolve) => {
+ pendingDownload = {
+ resolve,
+ startTimer: setTimeout(
+ () => settlePendingDownload({ status: "failed", message: "The download did not start." }),
+ DOWNLOAD_START_TIMEOUT_MS
+ )
+ };
+ });
+}
+
+function settlePendingDownload(result: StandaloneDownloadResult): void {
+ if (pendingDownload) {
+ clearTimeout(pendingDownload.startTimer);
+ pendingDownload.resolve(result);
+ pendingDownload = null;
+ }
+}
+
export function isLocalApiRequest(url: URL): boolean {
return LOCAL_API_PREFIXES.some(p => url.pathname.startsWith(p));
}
@@ -166,6 +263,24 @@ export function startLocalServerWorker() {
return;
}
+ // A backup download is streaming through the service worker, which receives no events of
+ // its own while a response body streams: browsers reclaim such "idle" workers within a
+ // minute or so, killing the download mid-file. A real fetch is a functional event that
+ // resets that clock, so one is sent for as long as the worker says the stream is running.
+ // The end of the stream also carries its outcome, which is what the caller of
+ // downloadDatabase() has been waiting on.
+ if (msg?.type === "BACKUP_STREAM_ACTIVE") {
+ setBackupPinging(msg.active === true);
+ if (msg.active === true) {
+ if (pendingDownload) {
+ clearTimeout(pendingDownload.startTimer);
+ }
+ } else {
+ settlePendingDownload(msg.result ?? { status: "done" });
+ }
+ return;
+ }
+
// Handle WebSocket-like messages from the worker (for frontend updates)
if (msg?.type === "WS_MESSAGE" && msg.message) {
// Dispatch a custom event that ws.ts listens to in standalone mode
@@ -218,6 +333,24 @@ export function attachServiceWorkerBridge() {
navigator.serviceWorker.addEventListener("message", async (event) => {
const msg = event.data;
+
+ // A backup download's channel: handed straight through to the worker, which streams the
+ // database into it. The page is only the relay, because the service worker cannot reach
+ // the local worker itself.
+ if (msg?.type === "LOCAL_BACKUP_STREAM") {
+ const streamPort = event.ports && event.ports[0];
+ if (streamPort) {
+ startLocalServerWorker();
+ localWorker?.postMessage({
+ type: "BACKUP_STREAM",
+ port: streamPort,
+ passphrase: pendingDownloadPassphrase
+ }, [ streamPort ]);
+ pendingDownloadPassphrase = undefined;
+ }
+ return;
+ }
+
if (!msg || msg.type !== "LOCAL_FETCH") return;
const port = event.ports && event.ports[0];
diff --git a/apps/standalone/src/local-server-worker.ts b/apps/standalone/src/local-server-worker.ts
index d2d25abc03..acbfdceccc 100644
--- a/apps/standalone/src/local-server-worker.ts
+++ b/apps/standalone/src/local-server-worker.ts
@@ -74,6 +74,7 @@ let BridgedRequestProvider: typeof import('./lightweight/bridged_request_provide
let StandalonePlatformProvider: typeof import('./lightweight/platform_provider').default;
let StandaloneLogService: typeof import('./lightweight/log_provider').default;
let StandaloneBackupService: typeof import('./lightweight/backup_provider').default;
+let removeBackupLeftovers: typeof import('./lightweight/backup_provider').removeBackupLeftovers;
let StandaloneInAppHelpProvider: typeof import('./lightweight/in_app_help_provider').default;
let translationProvider: typeof import('./lightweight/translation_provider').default;
let createConfiguredRouter: typeof import('./lightweight/browser_routes').createConfiguredRouter;
@@ -179,6 +180,7 @@ async function loadModules(): Promise<void> {
StandalonePlatformProvider = platformModule.default;
StandaloneLogService = logModule.default;
StandaloneBackupService = backupModule.default;
+ removeBackupLeftovers = backupModule.removeBackupLeftovers;
translationProvider = translationModule.default;
createConfiguredRouter = routesModule.createConfiguredRouter;
@@ -256,6 +258,14 @@ async function initialize(): Promise<void> {
logService.info("[Worker] Database loaded");
+ // A backup interrupted by the page going away leaves its snapshot in the pool, up to
+ // the database's own size. Reclaimed here so the space is back whether or not another
+ // backup is ever taken.
+ const backupPool = sqlProvider?.sahPool;
+ if (backupPool) {
+ removeBackupLeftovers(backupPool);
+ }
+
logService.info("[Worker] Loading @triliumnext/core...");
const schemaModule = await import("@triliumnext/core/src/assets/schema.sql?raw");
coreModule = await import("@triliumnext/core");
@@ -269,7 +279,7 @@ async function initialize(): Promise<void> {
request: useNativeHttp ? new BridgedRequestProvider() : new FetchRequestProvider(),
platform: new StandalonePlatformProvider(queryString),
log: logService,
- backup: new StandaloneBackupService(coreModule!.options, () => sqlProvider ?? undefined),
+ backup: new StandaloneBackupService(coreModule!.options),
translations: translationProvider,
schema: schemaModule.default,
getDemoArchive: async () => {
@@ -477,6 +487,40 @@ async function handleRestoreBackup(id: string, backup: File, passphrase?: string
/** Whether a restore is running, since a second one would prepare over the first one's work. */
let restoreInProgress = false;
+/**
+ * Streams the database into a download the service worker is holding open on the other end of
+ * `port`. Every way this ends is reported twice over: through the port for the download's sake,
+ * and to the page, which keeps the service worker alive while the stream runs and whose screen
+ * gates its Continue on the outcome.
+ */
+async function handleBackupStream(port: MessagePort, passphrase?: string): Promise<void> {
+ const announce = (active: boolean, result?: { status: string; message?: string }) =>
+ (self as unknown as Worker).postMessage({ type: "BACKUP_STREAM_ACTIVE", active, result });
+
+ const core = coreModule;
+ if (!core || !sqlProvider?.isOpen()) {
+ port.postMessage({ type: "error", message: "The database is not ready yet." });
+ port.close();
+ announce(false, { status: "failed", message: "The database is not ready yet." });
+ return;
+ }
+
+ console.log("[Worker] Streaming a backup download...");
+ announce(true);
+
+ const { streamDatabaseDownload } = await import("./lightweight/backup-download.js");
+ const result = await streamDatabaseDownload(
+ { getValue: (sql, params) => core.getSql().getValue(sql, params) },
+ // A MessagePort satisfies the seam at runtime; only the `onmessage` property's event
+ // parameter is typed wider here than the seam's, which a cast is the whole cost of.
+ port as unknown as import("./lightweight/backup-download.js").DownloadPort,
+ { passphrase }
+ );
+
+ announce(false, result);
+ console.log(`[Worker] Backup download stream ended: ${result.status}.`);
+}
+
// Wait for the INIT message before initializing so that queryString
// (which may contain ?integrationTest=memory for e2e) is available.
let initReceived = false;
@@ -510,6 +554,11 @@ self.onmessage = async (event) => {
return;
}
+ if (msg.type === "BACKUP_STREAM") {
+ await handleBackupStream(msg.port, msg.passphrase);
+ return;
+ }
+
if (msg.type !== "LOCAL_REQUEST") return;
const { id, request } = msg;
diff --git a/apps/standalone/src/main.spec.ts b/apps/standalone/src/main.spec.ts
index 72d4f3b250..b81dcdae40 100644
--- a/apps/standalone/src/main.spec.ts
+++ b/apps/standalone/src/main.spec.ts
@@ -5,6 +5,7 @@ const mocks = vi.hoisted(() => ({
attachServiceWorkerBridge: vi.fn(),
registerNativeHttpHandler: vi.fn(),
restoreBackup: vi.fn(),
+ downloadDatabase: vi.fn(),
capacitorHttpHandler: vi.fn()
}));
@@ -12,7 +13,8 @@ vi.mock("./local-bridge.js", () => ({
startLocalServerWorker: mocks.startLocalServerWorker,
attachServiceWorkerBridge: mocks.attachServiceWorkerBridge,
registerNativeHttpHandler: mocks.registerNativeHttpHandler,
- restoreBackup: mocks.restoreBackup
+ restoreBackup: mocks.restoreBackup,
+ downloadDatabase: mocks.downloadDatabase
}));
vi.mock("./services/capacitor_http_handler.js", () => ({ capacitorHttpHandler: mocks.capacitorHttpHandler }));
// Avoid pulling the entire client bundle when loadScripts() runs.
diff --git a/apps/standalone/src/main.ts b/apps/standalone/src/main.ts
index 892624921a..91fbde2264 100644
--- a/apps/standalone/src/main.ts
+++ b/apps/standalone/src/main.ts
@@ -1,5 +1,5 @@
import { installIosInterceptors } from "./ios-interceptors.js";
-import { attachServiceWorkerBridge, registerNativeHttpHandler, restoreBackup, startLocalServerWorker } from "./local-bridge.js";
+import { attachServiceWorkerBridge, downloadDatabase, registerNativeHttpHandler, restoreBackup, startLocalServerWorker } from "./local-bridge.js";
async function waitForServiceWorkerControl(): Promise<void> {
if (!("serviceWorker" in navigator) || !navigator.serviceWorker) {
@@ -46,7 +46,10 @@ async function bootstrap() {
// The client's way to the worker for the few things that carry a file, which the request path
// would serialise whole and time out on. The desktop's `window.electronApi` is the same idea.
- window.standaloneApi = { restore: { importBackup: restoreBackup } };
+ window.standaloneApi = {
+ restore: { importBackup: restoreBackup },
+ backup: { downloadDatabase }
+ };
try {
// When running inside a Capacitor WebView, register the native HTTP
diff --git a/apps/standalone/src/sw.spec.ts b/apps/standalone/src/sw.spec.ts
index b29da63141..a32dddf554 100644
--- a/apps/standalone/src/sw.spec.ts
+++ b/apps/standalone/src/sw.spec.ts
@@ -248,8 +248,9 @@ describe("forwardToClientLocalServer", () => {
(self as unknown as SwGlobals).clients = { claim: vi.fn(), matchAll: vi.fn(async () => [client]) };
const event = await dispatchLocal(handlers, "GET");
const rejection = expect(event._response).rejects.toThrow("Local server timeout");
- // Flushes the pending matchAll microtask, then fires the 30s timeout.
- await vi.advanceTimersByTimeAsync(30_000);
+ // Flushes the pending matchAll microtask, then fires the timeout, which sits just under
+ // the ~5 minutes the browser gives a fetch event.
+ await vi.advanceTimersByTimeAsync(270_000);
await rejection;
vi.useRealTimers();
});
diff --git a/apps/standalone/src/sw.ts b/apps/standalone/src/sw.ts
index f2ebfb9b61..5e2723422b 100644
--- a/apps/standalone/src/sw.ts
+++ b/apps/standalone/src/sw.ts
@@ -92,24 +92,25 @@ async function networkFirst(request) {
/* v8 ignore stop */
}
-async function forwardToClientLocalServer(request, _clientId) {
- // Find the main app window to handle the request
- // We must route to the main app (which has the local bridge), not iframes like PDF.js viewer
+/**
+ * The main app window, which is the one carrying the local bridge — not an iframe like the
+ * PDF.js viewer. Falls back to any window, and to null where there is none at all.
+ */
+async function findMainClient() {
// @ts-expect-error - self.clients is valid in service worker context
const all = await self.clients.matchAll({ type: "window", includeUncontrolled: true });
- // Find the main app window - it's the one NOT serving pdfjs or other embedded content
- // The main app has the local bridge handler for LOCAL_FETCH messages
- let client = all.find((c: { url: string }) => {
+ const client = all.find((c: { url: string }) => {
const url = new URL(c.url);
// Main app is at root or index.html, not in /pdfjs/ or other iframe paths
return !url.pathname.startsWith("/pdfjs/");
}) || null;
- // If no main app window found, fall back to any available client
- if (!client) {
- client = all[0] || null;
- }
+ return client || all[0] || null;
+}
+
+async function forwardToClientLocalServer(request, _clientId) {
+ const client = await findMainClient();
// If no page is available, fall back to network
if (!client) return fetch(request);
@@ -126,9 +127,14 @@ async function forwardToClientLocalServer(request, _clientId) {
const channel = new MessageChannel();
const responsePromise = new Promise((resolve, reject) => {
+ // Long enough for a request the worker answers late because it is deep inside one
+ // synchronous stretch of work (a VACUUM of a multi-gigabyte database blocks it for well
+ // over a minute), and just short of the ~5 minutes Chromium gives a fetch event before
+ // reclaiming it regardless. Anything legitimately longer must not ride a single request:
+ // the setup backup starts with one request and is followed over a status poll.
const timeout = setTimeout(() => {
reject(new Error("Local server timeout"));
- }, 30_000);
+ }, 270_000);
channel.port1.onmessage = (event) => {
clearTimeout(timeout);
@@ -173,6 +179,88 @@ async function forwardToClientLocalServer(request, _clientId) {
});
}
+/**
+ * Answers a backup download with the database streamed straight out of the local worker.
+ *
+ * The response body is fed through a message channel: this end asks for one chunk each time the
+ * download can take more, the page relays the channel to the worker, and the worker reads the
+ * database a batch of pages at a time. The download's backpressure is the only flow control, so
+ * nothing is ever buffered beyond a chunk or two, whatever the database weighs.
+ */
+async function streamBackupDownload(url) {
+ const client = await findMainClient();
+ if (!client) {
+ return new Response("The application page is not available.", { status: 503 });
+ }
+
+ const channel = new MessageChannel();
+ const port = channel.port1;
+ client.postMessage({ type: "LOCAL_BACKUP_STREAM" }, [channel.port2]);
+
+ // The worker opens with the exact size, which is what lets the download show a percentage.
+ const begin = await new Promise<{ type?: string; byteSize?: number; message?: unknown } | null>((resolve) => {
+ const timeout = setTimeout(() => resolve(null), 30_000);
+ port.onmessage = (event) => {
+ clearTimeout(timeout);
+ resolve(event.data);
+ };
+ });
+ if (!begin || begin.type !== "begin") {
+ port.postMessage({ type: "cancel" });
+ return new Response(
+ begin && begin.type === "error" ? String(begin.message) : "The backup stream did not start.",
+ { status: 503 }
+ );
+ }
+
+ // Several chunks travel at once: each pull round-trips through the page to the worker, and
+ // one-at-a-time would make that latency the download's speed limit.
+ const MAX_CHUNKS_IN_FLIGHT = 8;
+ let outstanding = 0;
+ let streamController: ReadableStreamDefaultController<Uint8Array> | null = null;
+ const requestMore = () => {
+ while (streamController && outstanding < MAX_CHUNKS_IN_FLIGHT
+ && (streamController.desiredSize ?? 0) > 0) {
+ outstanding++;
+ port.postMessage({ type: "pull" });
+ }
+ };
+
+ const stream = new ReadableStream({
+ start(controller) {
+ streamController = controller;
+ port.onmessage = (event) => {
+ const msg = event.data;
+ if (msg && msg.type === "chunk") {
+ outstanding--;
+ controller.enqueue(new Uint8Array(msg.data));
+ requestMore();
+ } else if (msg && msg.type === "end") {
+ controller.close();
+ } else {
+ controller.error(new Error(msg && msg.message ? String(msg.message) : "The backup failed."));
+ }
+ };
+ requestMore();
+ },
+ pull() {
+ requestMore();
+ },
+ cancel() {
+ port.postMessage({ type: "cancel" });
+ }
+ }, new CountQueuingStrategy({ highWaterMark: MAX_CHUNKS_IN_FLIGHT }));
+
+ const fileName = (url.searchParams.get("fileName") || "backup.db").replace(/["\\\r\n]/g, "-");
+ return new Response(stream, {
+ headers: {
+ "Content-Type": "application/octet-stream",
+ "Content-Disposition": `attachment; filename="${fileName}"`,
+ "Content-Length": String(begin.byteSize)
+ }
+ });
+}
+
self.addEventListener("fetch", (event) => {
const url = new URL(event.request.url);
@@ -185,6 +273,21 @@ self.addEventListener("fetch", (event) => {
// worker, which the interceptor never sees. See capacitor_http_handler.ts.
if (url.pathname.startsWith("/_trilium_native_http/")) return;
+ // The keepalive the page sends while a backup download streams: a streaming response body
+ // generates no events of its own, and a service worker with no events is one the browser
+ // reclaims mid-download. Answering a fetch is what resets that clock.
+ if (url.pathname === "/local-backup-ping") {
+ event.respondWith(new Response(null, { status: 204 }));
+ return;
+ }
+
+ // A backup download: streamed straight from the local worker, before navigate handling for
+ // the same reason as the API routes — the download arrives as a navigation.
+ if (url.pathname === "/local-backup-download") {
+ event.respondWith(streamBackupDownload(url));
+ return;
+ }
+
// API-ish: local-first via bridge (must be checked before navigate handling,
// because export triggers a navigation to an /api/ URL)
if (isLocalFirst(url)) {
diff --git a/packages/commons/src/lib/setup_marker.ts b/packages/commons/src/lib/setup_marker.ts
index a5bb093885..4e78b745d6 100644
--- a/packages/commons/src/lib/setup_marker.ts
+++ b/packages/commons/src/lib/setup_marker.ts
@@ -41,6 +41,25 @@ export interface SetupExistingBackup {
encrypted: boolean;
}
+/**
+ * Where the setup backup stands, polled by the screen waiting on it.
+ *
+ * The backup is started with one request and watched through this one, rather than answered on a
+ * request held open for however long the write takes: on the standalone platform a request rides
+ * the service worker, and the browser does not let a fetch stay open for the minutes a large
+ * database needs.
+ */
+export interface SetupExistingBackupStatus {
+ /** `idle` before any backup this boot; what became of the latest one after that. */
+ state: "idle" | "running" | "done" | "failed";
+ /** How far through the write, from 0 to 1, while running and once the writer can say. */
+ fraction: number | null;
+ /** What was written, once `done`. */
+ result?: SetupExistingBackup;
+ /** What stopped it, once `failed`. */
+ error?: string;
+}
+
/** What a start reads out of {@link SETUP_MARKER_FILE_NAME}. */
export interface SetupMarker {
/** The language the instance was using, so the wizard is in it rather than asking again. */
diff --git a/packages/commons/src/lib/standalone_api_interface.ts b/packages/commons/src/lib/standalone_api_interface.ts
index f25c77ea3f..4e371d8db5 100644
--- a/packages/commons/src/lib/standalone_api_interface.ts
+++ b/packages/commons/src/lib/standalone_api_interface.ts
@@ -42,7 +42,34 @@ export interface StandaloneRestoreApi {
}): Promise<StandaloneRestoreResult>;
}
+/** How a database download ended, for the screen that gates its Continue on it. */
+export interface StandaloneDownloadResult {
+ status: "done" | "cancelled" | "failed";
+ /** What stopped it, when `status` is `failed`. */
+ message?: string;
+}
+
+export interface StandaloneBackupApi {
+ /**
+ * Streams a copy of the live database straight into a browser download.
+ *
+ * Straight through: nothing is staged in the origin's own storage, which may not have room
+ * for a second copy of a large database, and nothing is ever compressed, which a low-end
+ * device cannot afford at these sizes. The bytes go from the database to the disk a page at a
+ * time, and the browser's own download UI shows the transfer itself.
+ *
+ * Given a passphrase, the download is a streamed encrypted container (`.tnbackup`); without
+ * one it is the plain database (`.db`). The file name should carry the matching extension.
+ *
+ * Resolves when the stream has been fully produced, one way or the other, which is as close
+ * to "the download finished" as the application can see: the browser's download manager may
+ * still be settling the last bytes to disk for a moment after.
+ */
+ downloadDatabase(fileName: string, passphrase?: string): Promise<StandaloneDownloadResult>;
+}
+
/** The complete surface the standalone build exposes to the client. */
export interface StandaloneApi {
restore: StandaloneRestoreApi;
+ backup: StandaloneBackupApi;
}
diff --git a/packages/trilium-backup-container/src/container.spec.ts b/packages/trilium-backup-container/src/container.spec.ts
index ef0e25f545..da3f33b5dd 100644
--- a/packages/trilium-backup-container/src/container.spec.ts
+++ b/packages/trilium-backup-container/src/container.spec.ts
@@ -8,6 +8,7 @@ import {
FRAME_SIZE,
HEADER_BYTES_ENCRYPTED,
HEADER_BYTES_PLAIN,
+ streamedContainerSize,
TAG_BYTES
} from "./format.js";
import { readBackupContainer, writeBackupContainer } from "./node-streams.js";
@@ -21,6 +22,7 @@ import {
MemorySink,
reasonOf,
readFromBuffer,
+ readFromBufferWeb,
type WriteOptions,
writeToBuffer
} from "./test-helpers.js";
@@ -322,6 +324,7 @@ describe("peeking at a container", () => {
expect(peekBackupContainer(written.bytes.subarray(0, FIXED_HEADER_BYTES))).toEqual({
version: 1,
plaintextSize: 9_000,
+ streamed: false,
...expected
});
});
@@ -490,3 +493,57 @@ describe("errors", () => {
await expect(read).rejects.toThrow(/ENOSPC/);
});
});
+
+describe("streamed containers", () => {
+ const STREAMED: WriteOptions = { streamed: true, passphrase: PASSPHRASE, scrypt: FAST_SCRYPT };
+
+ it("writes front to back, sized exactly as stated, and reads back on both runtimes", async () => {
+ const database = fakeDatabase(64 * 1024);
+ const written = await writeToBuffer(database, { ...STREAMED, plaintextSize: database.length });
+
+ // No patch was asked of the destination, and none was needed.
+ expect(written.patchedAt).toEqual([]);
+ expect(written.bytes.length).toBe(streamedContainerSize(database.length));
+ // The digest field stays zeros, which is what "no digest" looks like in the header.
+ expect(written.bytes.subarray(HEADER_BYTES_ENCRYPTED - 32, HEADER_BYTES_ENCRYPTED)
+ .every((byte) => byte === 0)).toBe(true);
+ expect(peekBackupContainer(written.bytes.subarray(0, FIXED_HEADER_BYTES)))
+ .toMatchObject({ encrypted: true, streamed: true, compressed: false });
+
+ const read = await readFromBuffer(written.bytes, { passphrase: PASSPHRASE });
+ expect(read.bytes.equals(database)).toBe(true);
+
+ const readWeb = await readFromBufferWeb(written.bytes, { passphrase: PASSPHRASE });
+ expect(readWeb.bytes.equals(database)).toBe(true);
+ });
+
+ it("sizes a payload that is an exact multiple of the frame size, empty final frame included", async () => {
+ const database = fakeDatabase(FRAME_SIZE);
+ const written = await writeToBuffer(database, STREAMED);
+
+ expect(written.bytes.length).toBe(streamedContainerSize(FRAME_SIZE));
+ const read = await readFromBuffer(written.bytes, { passphrase: PASSPHRASE });
+ expect(read.bytes.equals(database)).toBe(true);
+ });
+
+ it("still catches tampering: the frames authenticate what the digest no longer covers", async () => {
+ const database = fakeDatabase(64 * 1024);
+ const written = await writeToBuffer(database, STREAMED);
+
+ const tampered = flipByte(written.bytes, HEADER_BYTES_ENCRYPTED + 4 + 100);
+ expect(await failureOf(tampered, { passphrase: PASSPHRASE })).toBe("damaged-payload");
+ });
+
+ it("refuses to write a streamed container without encryption", async () => {
+ expect(await reasonOf(writeToBuffer(fakeDatabase(), { streamed: true })))
+ .toBe("invalid-options");
+ });
+
+ it("refuses to read a streamed flag on an unencrypted container", async () => {
+ const written = await writeToBuffer(fakeDatabase());
+ const forged = Buffer.from(written.bytes);
+ forged[21] |= 0b100;
+
+ expect(await failureOf(forged)).toBe("unsupported-flags");
+ });
+});
diff --git a/packages/trilium-backup-container/src/format.ts b/packages/trilium-backup-container/src/format.ts
index 4141a62f00..61d83a4b65 100644
--- a/packages/trilium-backup-container/src/format.ts
+++ b/packages/trilium-backup-container/src/format.ts
@@ -18,7 +18,14 @@ export const FORMAT_VERSION = 1;
export const FLAG_COMPRESSED = 0b0000_0001;
export const FLAG_ENCRYPTED = 0b0000_0010;
-export const FLAG_RESERVED = 0b1111_1100;
+/**
+ * Written front to back, with no payload digest: the destination could not be revisited to patch
+ * one in — a download already on its way to the user, for instance. Only ever valid together with
+ * {@link FLAG_ENCRYPTED}: the frame tags then authenticate every payload byte, which is what the
+ * digest was for, while on an unencrypted payload the digest is the only integrity there is.
+ */
+export const FLAG_STREAMED = 0b0000_0100;
+export const FLAG_RESERVED = 0b1111_1000;
export const FIXED_HEADER_BYTES = 32;
export const DIGEST_BYTES = 32;
@@ -84,6 +91,8 @@ export interface ContainerHeader {
version: number;
compressed: boolean;
encrypted: boolean;
+ /** Written front to back, so the digest field holds zeros. See {@link FLAG_STREAMED}. */
+ streamed: boolean;
/**
* Size of the wrapped database before compression, or 0 when unknown. A hint, never an
* instruction.
@@ -139,7 +148,8 @@ export function encodeHeader(header: ContainerHeader): Uint8Array {
buffer[MAGIC.length] = header.version;
const compressed = header.compressed ? FLAG_COMPRESSED : 0;
const encrypted = header.encrypted ? FLAG_ENCRYPTED : 0;
- buffer[21] = compressed | encrypted;
+ const streamed = header.streamed ? FLAG_STREAMED : 0;
+ buffer[21] = compressed | encrypted | streamed;
writeU16LE(buffer, 22, header.headerLength);
writeU64LE(buffer, 24, BigInt(header.plaintextSize));
@@ -163,6 +173,7 @@ export interface FixedHeader {
version: number;
compressed: boolean;
encrypted: boolean;
+ streamed: boolean;
plaintextSize: number;
headerLength: number;
}
@@ -201,6 +212,15 @@ export function decodeFixedHeader(buffer: Uint8Array, maxHeaderBytes: number): F
);
}
const encrypted = (flags & FLAG_ENCRYPTED) !== 0;
+ const streamed = (flags & FLAG_STREAMED) !== 0;
+ if (streamed && !encrypted) {
+ // Without a digest and without frame tags there would be no integrity at all, so no
+ // writer produces this and no reader trusts it.
+ throw new BackupContainerError(
+ "unsupported-flags",
+ "A streamed container without encryption is never valid."
+ );
+ }
const headerLength = readU16LE(buffer, 22);
if (headerLength > maxHeaderBytes) {
@@ -225,11 +245,24 @@ export function decodeFixedHeader(buffer: Uint8Array, maxHeaderBytes: number): F
version,
compressed: (flags & FLAG_COMPRESSED) !== 0,
encrypted,
+ streamed,
plaintextSize: plaintextSize > BigInt(Number.MAX_SAFE_INTEGER) ? 0 : Number(plaintextSize),
headerLength
};
}
+/**
+ * Exact byte length of a streamed, encrypted, uncompressed container wrapping `plaintextSize`
+ * bytes: the header, the payload, and the length field and tag around every frame — including the
+ * final frame, which is empty when the payload is an exact multiple of the frame size. Exactness
+ * is the point: a download that states its size correctly is one the browser gives a progress bar.
+ */
+export function streamedContainerSize(plaintextSize: number): number {
+ const frames = Math.floor(plaintextSize / FRAME_SIZE) + 1;
+
+ return HEADER_BYTES_ENCRYPTED + plaintextSize + frames * (4 + TAG_BYTES);
+}
+
/**
* Parses the fields after the fixed header. `buffer` is the whole header, `headerLength` bytes
* long.
diff --git a/packages/trilium-backup-container/src/index.ts b/packages/trilium-backup-container/src/index.ts
index 6458cc5e41..538db6af49 100644
--- a/packages/trilium-backup-container/src/index.ts
+++ b/packages/trilium-backup-container/src/index.ts
@@ -56,7 +56,8 @@ export {
FRAME_SIZE,
SCRYPT_BOUNDS,
SCRYPT_DEFAULTS,
- type ScryptParams
+ type ScryptParams,
+ streamedContainerSize
} from "./format.js";
export { readBackupContainer, writeBackupContainer } from "./node-streams.js";
export {
diff --git a/packages/trilium-backup-container/src/read.ts b/packages/trilium-backup-container/src/read.ts
index 1d660e2c90..e6db63bdb9 100644
--- a/packages/trilium-backup-container/src/read.ts
+++ b/packages/trilium-backup-container/src/read.ts
@@ -62,6 +62,8 @@ export interface BackupContainerInfo {
version: number;
compressed: boolean;
encrypted: boolean;
+ /** Written front to back with no payload digest; the frames alone carry the integrity. */
+ streamed: boolean;
/** Size of the wrapped database before compression, or 0 when the writer did not record it. */
plaintextSize: number;
}
@@ -82,12 +84,12 @@ export function peekBackupContainer(
}
try {
- const { version, compressed, encrypted, plaintextSize } = decodeFixedHeader(
+ const { version, compressed, encrypted, streamed, plaintextSize } = decodeFixedHeader(
head.subarray(0, FIXED_HEADER_BYTES),
maxHeaderBytes
);
- return { version, compressed, encrypted, plaintextSize };
+ return { version, compressed, encrypted, streamed, plaintextSize };
} catch {
return null;
}
@@ -326,7 +328,8 @@ async function* readFrames(
backend: ContainerBackend
): AsyncGenerator<Uint8Array> {
const aad = aadOf(header);
- const hash = backend.createSha256();
+ // A streamed container records no digest, so hashing towards one would only slow the restore.
+ const hash = header.streamed ? null : backend.createSha256();
let counter = 0;
for (;;) {
@@ -346,9 +349,11 @@ async function* readFrames(
const ciphertext = await reader.readExactly(length);
const tag = await reader.readExactly(TAG_BYTES);
- hash.update(lengthField);
- hash.update(ciphertext);
- hash.update(tag);
+ if (hash) {
+ hash.update(lengthField);
+ hash.update(ciphertext);
+ hash.update(tag);
+ }
const plaintext = await backend.gcmOpen(
key,
@@ -378,7 +383,9 @@ async function* readFrames(
);
}
- verifyDigest(hash.digest(), header.digest);
+ if (hash) {
+ verifyDigest(hash.digest(), header.digest);
+ }
}
/** Yields the payload of an unencrypted container, which runs to end of file. */
diff --git a/packages/trilium-backup-container/src/web.ts b/packages/trilium-backup-container/src/web.ts
index aa6117a444..a520b2ead1 100644
--- a/packages/trilium-backup-container/src/web.ts
+++ b/packages/trilium-backup-container/src/web.ts
@@ -34,7 +34,8 @@ export {
FRAME_SIZE,
SCRYPT_BOUNDS,
SCRYPT_DEFAULTS,
- type ScryptParams
+ type ScryptParams,
+ streamedContainerSize
} from "./format.js";
export {
DEFAULT_PROGRESS_INTERVAL_MS,
diff --git a/packages/trilium-backup-container/src/write.ts b/packages/trilium-backup-container/src/write.ts
index c6d46acbfd..48df1cb861 100644
--- a/packages/trilium-backup-container/src/write.ts
+++ b/packages/trilium-backup-container/src/write.ts
@@ -42,8 +42,18 @@ const EMPTY = new Uint8Array(0);
export type PatchHeader = (offset: number, data: Uint8Array) => Promise<void> | void;
export interface WriteBackupContainerOptions extends ProgressOptions {
- /** Patches the payload digest into the header once the payload is complete. Required. */
- patchHeader: PatchHeader;
+ /**
+ * Patches the payload digest into the header once the payload is complete. Required, except
+ * for a {@link streamed} container, which records no digest and never writes backwards.
+ */
+ patchHeader?: PatchHeader;
+ /**
+ * Write front to back, recording no payload digest — for a destination that cannot be
+ * revisited, such as a download already on its way to the user. Requires `passphrase`: the
+ * GCM frame tags then authenticate every payload byte, which is what the digest was for,
+ * while on an unencrypted payload the digest is the only integrity there is.
+ */
+ streamed?: boolean;
/** Compress the payload with gzip. */
compress?: boolean;
/** Encrypt the payload. Encryption is on exactly when a passphrase is given. */
@@ -94,7 +104,15 @@ export async function writeContainer(
backend: ContainerBackend,
options: WriteBackupContainerOptions
): Promise<WriteBackupContainerResult> {
- if (typeof options.patchHeader !== "function") {
+ const streamed = options.streamed === true;
+ if (streamed && options.passphrase === undefined) {
+ throw new BackupContainerError(
+ "invalid-options",
+ "A streamed container must be encrypted: without a digest, the frame tags are the "
+ + "only integrity it has."
+ );
+ }
+ if (!streamed && typeof options.patchHeader !== "function") {
throw new BackupContainerError(
"invalid-options",
"patchHeader is required to write the payload digest."
@@ -119,6 +137,7 @@ export async function writeContainer(
version: FORMAT_VERSION,
compressed,
encrypted,
+ streamed,
plaintextSize,
headerLength: headerLengthFor(encrypted),
encryption: null,
@@ -141,7 +160,10 @@ export async function writeContainer(
}
const headerBytes = encodeHeader(header);
- const aad = headerBytes.subarray(0, authenticatedHeaderEnd(header.headerLength));
+ // A copy rather than a view: the header is about to be handed to the sink, and a sink is free
+ // to transfer the buffer away (the streamed download does), which would detach any view still
+ // held here while every frame's authentication still needs it.
+ const aad = headerBytes.slice(0, authenticatedHeaderEnd(header.headerLength));
if (header.encryption && key !== null) {
const verifier = await backend.gcmSeal(
@@ -177,7 +199,11 @@ export async function writeContainer(
await output.end();
const digest = hash.digest();
- await options.patchHeader(digestOffset(header.headerLength), digest);
+ // A streamed container keeps the zeros: its frames authenticate themselves, and there is no
+ // going back to the header of a destination already streamed away.
+ if (!streamed) {
+ await options.patchHeader?.(digestOffset(header.headerLength), digest);
+ }
// After the patch rather than after the payload: the container is not written until the digest
// is in its header.
diff --git a/packages/trilium-core/src/routes/api/setup.ts b/packages/trilium-core/src/routes/api/setup.ts
index 7b2f3aed82..caf78a6800 100644
--- a/packages/trilium-core/src/routes/api/setup.ts
+++ b/packages/trilium-core/src/routes/api/setup.ts
@@ -2,10 +2,10 @@ import sqlInit from "../../services/sql_init.js";
import setupService from "../../services/setup.js";
import { getRunningSetupOperation, withSetupLock } from "../../services/setup_lock.js";
import {
- backUpExistingData,
deleteExistingData,
- getExistingBackupProgress,
- keepExistingData
+ getExistingBackupStatus,
+ keepExistingData,
+ startBackUpExistingData
} from "../../services/setup_existing.js";
import { asSetupTargetScreen, getSetupPlatform } from "../../services/setup_mode.js";
import { getLog } from "../../services/log.js";
@@ -57,23 +57,26 @@ async function bootToSetup(req: Request) {
}
/**
- * Backs up the database the wizard was booted away from, and says where it went.
+ * Starts backing up the database the wizard was booted away from.
*
- * Answers only once the file is written, which for a large database is minutes: the screen that
- * calls this shows a spinner for exactly that long, and has nothing useful to say in between.
+ * Answers as soon as the write is underway rather than once it is done: the write runs for minutes
+ * on a large database, and on standalone a request rides the service worker, whose fetches the
+ * browser reclaims after a few minutes no matter how patient the caller is. The screen follows the
+ * write, and learns where it went, through {@link existingBackupStatus}.
*/
-async function backUpExisting() {
- return await backUpExistingData(new Date());
+function backUpExisting() {
+ startBackUpExistingData(new Date());
}
/**
- * How far through the backup is, for the screen waiting on it.
+ * Where the backup stands, for the screen waiting on it: how far along, and once it is over, what
+ * was written or what stopped it.
*
- * Polled rather than pushed: the answer is one number, the screen is the only thing asking, and a
- * push would need a channel that setup does not otherwise have.
+ * Polled rather than pushed: the screen is the only thing asking, and a push would need a channel
+ * that setup does not otherwise have.
*/
function existingBackupStatus() {
- return { fraction: getExistingBackupProgress() };
+ return getExistingBackupStatus();
}
/** Erases that database. Everything else in the data directory, backups included, stays. */
diff --git a/packages/trilium-core/src/services/setup_existing.spec.ts b/packages/trilium-core/src/services/setup_existing.spec.ts
index f3fb1999bd..acd9634c83 100644
--- a/packages/trilium-core/src/services/setup_existing.spec.ts
+++ b/packages/trilium-core/src/services/setup_existing.spec.ts
@@ -6,7 +6,9 @@ import {
backupNameFor,
deleteExistingData,
getExistingBackupProgress,
- keepExistingData
+ getExistingBackupStatus,
+ keepExistingData,
+ startBackUpExistingData
} from "./setup_existing.js";
import { enterSetupMode, initSetupPlatform, leaveSetupMode } from "./setup_mode.js";
@@ -97,5 +99,59 @@ describe("what becomes of the existing database", () => {
await expect(deleteExistingData()).rejects.toThrow(/first time/);
await expect(keepExistingData()).rejects.toThrow(/first time/);
expect(platform.removeDatabase).not.toHaveBeenCalled();
+ expect(() => startBackUpExistingData(new Date())).toThrow(/first time/);
+ });
+});
+
+describe("the started backup, followed through its status", () => {
+ /** Puts a controllable backupAs in place and gives back the strings to pull. */
+ function stubBackup(behaviour: (onProgress?: (fraction: number) => void) => Promise<unknown>) {
+ const backup = getBackup() as { backupAs?: unknown };
+ const previous = backup.backupAs;
+ backup.backupAs = (_name: string, onProgress?: (fraction: number) => void) =>
+ behaviour(onProgress);
+
+ return () => {
+ backup.backupAs = previous;
+ };
+ }
+
+ it("runs with a live fraction, joins a second start, and ends holding what was written", async () => {
+ const written = { fileName: "b", filePath: "/b", fileSize: 1, encrypted: false };
+ let report: ((fraction: number) => void) | undefined;
+ let finish!: (value: typeof written) => void;
+ const restore = stubBackup((onProgress) => new Promise((resolve) => {
+ report = onProgress;
+ finish = resolve;
+ }));
+
+ startBackUpExistingData(new Date());
+ await vi.waitFor(() => expect(getExistingBackupStatus().state).toBe("running"));
+
+ report?.(0.25);
+ expect(getExistingBackupStatus()).toMatchObject({ state: "running", fraction: 0.25 });
+
+ // Asked to start again while running: joined, not doubled, so the fraction survives.
+ startBackUpExistingData(new Date());
+ expect(getExistingBackupStatus()).toMatchObject({ state: "running", fraction: 0.25 });
+
+ finish(written);
+ await vi.waitFor(() => expect(getExistingBackupStatus().state).toBe("done"));
+ expect(getExistingBackupStatus()).toEqual({ state: "done", fraction: 1, result: written });
+
+ restore();
+ });
+
+ it("ends failed with the reason, and lets the next attempt start over", async () => {
+ const restore = stubBackup(async () => {
+ throw new Error("disk full");
+ });
+
+ // The previous test left a done state behind, which a new start must replace.
+ startBackUpExistingData(new Date());
+ await vi.waitFor(() => expect(getExistingBackupStatus().state).toBe("failed"));
+ expect(getExistingBackupStatus()).toEqual({ state: "failed", fraction: null, error: "disk full" });
+
+ restore();
});
});
diff --git a/packages/trilium-core/src/services/setup_existing.ts b/packages/trilium-core/src/services/setup_existing.ts
index 31c281afdf..7c161e6b20 100644
--- a/packages/trilium-core/src/services/setup_existing.ts
+++ b/packages/trilium-core/src/services/setup_existing.ts
@@ -1,4 +1,4 @@
-import type { SetupExistingBackup } from "@triliumnext/commons";
+import type { SetupExistingBackup, SetupExistingBackupStatus } from "@triliumnext/commons";
import { getBackup } from "./backup.js";
import eventService from "./events.js";
@@ -56,6 +56,46 @@ export async function backUpExistingData(now: Date): Promise<SetupExistingBackup
}
}
+/**
+ * Starts the backup and answers at once, leaving the outcome to be polled for.
+ *
+ * The write itself runs for minutes on a large knowledge base, and a request held open that long
+ * does not survive every platform: on standalone it rides the service worker, whose fetches the
+ * browser reclaims after a few minutes however patient the caller is. So the caller that would have
+ * waited on {@link backUpExistingData} starts it here and follows it through
+ * {@link getExistingBackupStatus} instead.
+ *
+ * A backup already running is joined rather than doubled. What can be refused outright (no
+ * existing database, a platform with nowhere to write) still throws from here, so the starting
+ * request carries the reason.
+ */
+export function startBackUpExistingData(now: Date): void {
+ if (status.state === "running") {
+ return;
+ }
+
+ requireExistingData();
+ if (!getBackup().backupAs) {
+ throw new Error("This platform cannot write a backup of the existing database.");
+ }
+
+ status = { state: "running", fraction: null };
+ backUpExistingData(now)
+ .then((written) => {
+ status = { state: "done", fraction: 1, result: written };
+ })
+ .catch((e) => {
+ status = { state: "failed", fraction: null, error: messageOf(e) };
+ });
+}
+
+/** Where the latest backup stands, for the screen polling its way through it. */
+export function getExistingBackupStatus(): SetupExistingBackupStatus {
+ return status.state === "running" ? { ...status, fraction: progress } : status;
+}
+
+let status: SetupExistingBackupStatus = { state: "idle", fraction: null };
+
/**
* How far through the backup is, from 0 to 1, or `null` when none is running.
*
@@ -144,3 +184,7 @@ function requireExistingData(): void {
throw new Error("There is no existing database: this instance is being set up for the first time.");
}
}
+
+function messageOf(e: unknown): string {
+ return e instanceof Error ? e.message : String(e);
+}