Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
standalone/backup: show the progress for downloading a backup
Adorian Doran496b3f0bb28f
diff --git a/apps/client/src/services/backup_download.ts b/apps/client/src/services/backup_download.tsindex a611959284..536d255750 100644--- a/apps/client/src/services/backup_download.ts+++ b/apps/client/src/services/backup_download.ts@@ -41,12 +41,13 @@ export function backupFileName(name: string): string {*/export async function startBackupDownload(fileName: string,- passphrase?: string+ passphrase?: string,+ onProgress?: (sentBytes: number, totalBytes: number) => void): Promise<StandaloneDownloadResult> {const api = window.standaloneApi;if (!api) {return { status: "failed", message: "This platform does not back up by download." };}- return await api.backup.downloadDatabase(fileName, passphrase || undefined);+ return await api.backup.downloadDatabase(fileName, passphrase || undefined, onProgress);}diff --git a/apps/client/src/services/utils.spec.ts b/apps/client/src/services/utils.spec.tsindex d56457d83e..95f34d117a 100644--- a/apps/client/src/services/utils.spec.ts+++ b/apps/client/src/services/utils.spec.ts@@ -109,6 +109,24 @@ describe("formatSize", () => {expect(formatSize(5 * 1024 * 1024)).toBe("5 MiB");expect(formatSize(3 * 1024 * 1024 * 1024)).toBe("3 GiB");});++ it("stays in the largest unit it knows rather than running off the end of them", () => {+ // Past the last unit this used to name it "undefined", since it indexed straight into the+ // list with whatever power of 1024 the size came to.+ expect(formatSize(3 * 1024 ** 4)).toBe("3 TiB");+ expect(formatSize(5 * 1024 ** 5)).toBe("5120 TiB");+ });++ it("keeps the places it is given, trailing zeros and all", () => {+ // For a counter that is still climbing: dropping the zero shortens the text on every other+ // update, and the line shifts about while it is being read.+ expect(formatSize(1.5 * 1024 ** 3, 2)).toBe("1.50 GiB");+ expect(formatSize(1.55 * 1024 ** 3, 2)).toBe("1.55 GiB");+ expect(formatSize(2 * 1024 ** 3, 2)).toBe("2.00 GiB");+ expect(formatSize(10 * 1024 ** 2, 1)).toBe("10.0 MiB");+ // Nothing below a byte to show, however many places were asked for.+ expect(formatSize(512, 2)).toBe("512 B");+ });});describe("formatDateTime / date helpers", () => {diff --git a/apps/client/src/services/utils.ts b/apps/client/src/services/utils.tsindex f58559468a..0a0e8b302a 100644--- a/apps/client/src/services/utils.ts+++ b/apps/client/src/services/utils.ts@@ -247,20 +247,32 @@ export function escapeQuotes(value: string) {return value.replaceAll('"', """);}-export function formatSize(size: number | null | undefined) {+/** The units a size is shown in, largest last, each 1024 of the one before it. */+const SIZE_UNITS = ["B", "KiB", "MiB", "GiB", "TiB"];++/**+ * A byte count in the largest unit it fits in.+ *+ * @param decimals places to keep, trailing zeros and all. Omit it to round to at most two and drop+ * what is not needed, which reads best for a size at rest. Pass a number for a counter that is+ * still climbing: there, dropping a trailing zero shortens the text on every other update and the+ * line shifts about while it is being read.+ */+export function formatSize(size: number | null | undefined, decimals?: number) {if (size === null || size === undefined) {return "";}- if (size === 0) {+ if (size <= 0) {return "0 B";}- const k = 1024;- const sizes = ["B", "KiB", "MiB", "GiB"];- const i = Math.floor(Math.log(size) / Math.log(k));+ const unit = Math.min(Math.floor(Math.log(size) / Math.log(1024)), SIZE_UNITS.length - 1);+ const value = size / Math.pow(1024, unit);+ // Nothing below a byte to show, however many places were asked for.+ const places = decimals !== undefined && unit === 0 ? 0 : decimals;- return `${Math.round((size / Math.pow(k, i)) * 100) / 100} ${sizes[i]}`;+ return `${places === undefined ? Math.round(value * 100) / 100 : value.toFixed(places)} ${SIZE_UNITS[unit]}`;}function toObject<T, R>(array: T[], fn: (arg0: T) => [key: string, value: R]) {diff --git a/apps/client/src/setup_backup.css b/apps/client/src/setup_backup.cssindex 8ffe49fb5b..71a2e2dc35 100644--- a/apps/client/src/setup_backup.css+++ b/apps/client/src/setup_backup.css@@ -13,10 +13,38 @@text-align: center;}- .backup-download-message {- display: flex;+ /* The spinner beside the words rather than above them, with the label and its count stacked in+ the second column. Left-aligned, so a percentage does not shift the line about as it grows+ from one digit to two, and the panel's own centring places the block as a whole. */+ .backup-download-status {+ display: grid;+ grid-template-columns: auto 1fr;align-items: center;gap: 0.75em;+ text-align: start;+ }++ .backup-download-text {+ display: flex;+ flex-direction: column;+ gap: 0.15em;+ }++ .backup-download-progress {+ display: flex;+ gap: 0.4em;+ font-size: 0.85em;+ color: var(--muted-text-color);+ /* Every digit the same width, so a count that climbs does not jitter the line under it. */+ font-variant-numeric: tabular-nums;++ /* Held open for the widest it will ever be, so the sizes beside it start at the same place+ whether the count reads 9% or 100%. Filled from the start, not the end: the reserved+ space belongs after the number, or a short one would sit indented from the label above+ it. With tabular figures a digit is exactly 1ch, so five covers "100%". */+ .backup-download-percent {+ min-width: 5ch;+ }}.backup-download-hint {diff --git a/apps/client/src/setup_backup.spec.tsx b/apps/client/src/setup_backup.spec.tsxindex bd4dc45c7e..e620431567 100644--- a/apps/client/src/setup_backup.spec.tsx+++ b/apps/client/src/setup_backup.spec.tsx@@ -6,7 +6,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";vi.mock("./services/i18n", () => ({ t: (key: string) => key }));const mocks = vi.hoisted(() => ({- startBackupDownload: vi.fn(async () => ({ status: "done" }) as { status: string; message?: string })+ startBackupDownload: vi.fn(+ async (+ _fileName: string,+ _passphrase?: string,+ _onProgress?: (sentBytes: number, totalBytes: number) => void+ ) => ({ status: "done" }) as { status: string; message?: string }+ )}));vi.mock("./services/backup_download", async (importOriginal) => ({@@ -162,7 +168,7 @@ describe("choosing what the backup is called and whether it is locked", () => {await settle();expect(mocks.startBackupDownload)- .toHaveBeenCalledWith("Before the big import.tnbackup", "hunter2");+ .toHaveBeenCalledWith("Before the big import.tnbackup", "hunter2", expect.any(Function));});it("downloads under the suggested name, without a password, when neither was touched", async () => {@@ -173,7 +179,8 @@ describe("choosing what the backup is called and whether it is locked", () => {await settle();// Empty, not absent: the service turns that into an unencrypted container.- expect(mocks.startBackupDownload).toHaveBeenCalledWith(`${chosen}.tnbackup`, "");+ expect(mocks.startBackupDownload)+ .toHaveBeenCalledWith(`${chosen}.tnbackup`, "", expect.any(Function));});});@@ -333,6 +340,31 @@ describe("backing up from the setup screen", () => {expect(button("setup.backup-finish")?.disabled).toBe(false);});+ it("counts the download as it goes, since the browser's own progress is out of sight on a phone", async () => {+ let report: ((sent: number, total: number) => void) | undefined;+ mocks.startBackupDownload.mockImplementation((_name, _passphrase, onProgress) => {+ report = onProgress;++ return new Promise(() => {});+ });+ await reachDownload();++ button("setup.backup-download")?.click();+ await settle();+ // Nothing yet: a total of nothing has no percentage, and the spinner already says "working".+ expect(container.querySelector(".backup-download-progress")).toBeNull();++ report?.(512 * 1024 * 1024, 1024 * 1024 * 1024);+ await settle();+ expect(container.querySelector(".backup-download-progress")?.textContent)+ .toContain("setup.backup-downloading-size");+ // Its own element, which is what lets a width be held for it.+ expect(container.querySelector(".backup-download-percent")?.textContent)+ .toBe("setup.backup-downloading-percent");+ expect(mocks.startBackupDownload).toHaveBeenCalledWith(+ expect.any(String), "", expect.any(Function));+ });+it("shows what stopped a failed download, and offers another go", async () => {mocks.startBackupDownload.mockResolvedValue({ status: "failed", message: "the stream broke" });await reachDownload();diff --git a/apps/client/src/setup_backup.tsx b/apps/client/src/setup_backup.tsxindex a2bb0ea746..a6bf88199c 100644--- a/apps/client/src/setup_backup.tsx+++ b/apps/client/src/setup_backup.tsx@@ -10,6 +10,7 @@ import { useMemo, useState } from "preact/hooks";import { backupFileName, startBackupDownload } from "./services/backup_download";import { t } from "./services/i18n";+import { formatSize } from "./services/utils";import Admonition from "./widgets/react/Admonition";import Button from "./widgets/react/Button";import { Card, CardOption, CardSection } from "./widgets/react/Card";@@ -39,6 +40,8 @@ export interface BackupDownload {state: "idle" | "running" | "done" | "failed";/** What stopped it, once `failed`. */error?: string;+ /** How far it has got, once the first bytes have gone. */+ progress?: { sentBytes: number; totalBytes: number };start: () => void;}@@ -54,15 +57,22 @@ export function useBackupDownload(settings: SetupBackupSettings): BackupDownloadconst fileName = useMemo(() => backupFileName(settings.name), [ settings.name ]);const [ state, setState ] = useState<BackupDownload["state"]>("idle");const [ error, setError ] = useState<string>();+ const [ progress, setProgress ] = useState<BackupDownload["progress"]>();return {fileName,state,error,+ progress,start: () => {setState("running");setError(undefined);- void startBackupDownload(fileName, settings.passphrase).then((result) => {+ setProgress(undefined);++ const onProgress = (sentBytes: number, totalBytes: number) =>+ setProgress({ sentBytes, totalBytes });++ void startBackupDownload(fileName, settings.passphrase, onProgress).then((result) => {setState(result.status === "done" ? "done" : "failed");setError(result.status === "done" ? undefined : result.message);});@@ -200,9 +210,15 @@ export function BackupDownloadPanel({ download }: { download: BackupDownload })if (download.state === "running") {return (<div class="backup-download">- <div class="backup-download-message">+ {/* The count sits with the spinner rather than apart from it: on a phone the+ browser's own download UI is behind the notification shade, so this is the only+ sign the application is doing anything, and a spinner alone reads as stuck. */}+ <div class="backup-download-status"><span class="spinner-border" role="status" aria-hidden="true" />- <span>{t("setup.backup-downloading")}</span>+ <div class="backup-download-text">+ <span>{t("setup.backup-downloading")}</span>+ <DownloadProgress progress={download.progress} />+ </div></div><div class="backup-download-hint">{t("setup.backup-do-not-close")}</div></div>@@ -238,6 +254,40 @@ export function BackupDownloadPanel({ download }: { download: BackupDownload }));}+/**+ * How much of the download has gone, in the two forms a waiting user reads differently: the+ * percentage answers "how much longer", the sizes answer "is it moving at all".+ *+ * Absent until the first bytes are handed over, since a total of nothing has no percentage and+ * "0 B of 0 B" says less than the spinner does on its own.+ */+function DownloadProgress({ progress }: { progress?: BackupDownload["progress"] }) {+ if (!progress || progress.totalBytes <= 0) {+ return null;+ }++ return (+ <div class="backup-download-progress">+ {/* Its own element so a width can be held for it: the count grows from one digit to+ three, and without that the sizes beside it would be shoved along twice. */}+ <span class="backup-download-percent">+ {t("setup.backup-downloading-percent", {+ // Rounded down, so it never reads 100% while there is still something to write.+ percent: Math.floor(100 * progress.sentBytes / progress.totalBytes)+ })}+ </span>+ <span>+ {/* Fixed places, since these are still counting: dropping a trailing zero would+ shorten the line on every other update. */}+ {t("setup.backup-downloading-size", {+ done: formatSize(progress.sentBytes, 2),+ total: formatSize(progress.totalBytes, 2)+ })}+ </span>+ </div>+ );+}+/*** Taking the backup, once its settings are known.*diff --git a/apps/client/src/setup_existing.spec.tsx b/apps/client/src/setup_existing.spec.tsxindex 514ea2c4e7..1ae084bfe3 100644--- a/apps/client/src/setup_existing.spec.tsx+++ b/apps/client/src/setup_existing.spec.tsx@@ -414,7 +414,8 @@ describe("backing up straight to a download on standalone", () => {// The suggested name, and no password, which is what the parameters screen was left at.expect(downloadDatabase).toHaveBeenCalledWith(expect.stringMatching(/^Trilium data \(\d{4}-\d{2}-\d{2} \d{2}-\d{2}-\d{2}\)\.tnbackup$/),- undefined);+ undefined,+ expect.any(Function));expect(container.textContent).toContain("setup.backup-downloading");expect(arrivingButton("setup.continue")?.disabled).toBe(true);diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 64ee585127..f11e9e5e26 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3723,6 +3723,8 @@"backup-file": "Backup will be saved as","backup-download": "Generate and download backup","backup-downloading": "Downloading...",+ "backup-downloading-percent": "{{percent}}%",+ "backup-downloading-size": "({{done}} of {{total}})","backup-do-not-close": "Please do not switch away or close this screen until the download completes.","backup-downloaded": "The download has completed. Press \"Finish\" to return to the application.","backup-download-failed": "The download did not finish.",diff --git a/apps/standalone/src/lightweight/backup-download.ts b/apps/standalone/src/lightweight/backup-download.tsindex 3df12125b8..e95683c9fa 100644--- a/apps/standalone/src/lightweight/backup-download.ts+++ b/apps/standalone/src/lightweight/backup-download.ts@@ -55,8 +55,24 @@ export interface DownloadOptions {passphrase?: string;/** scrypt cost override, for tests that cannot afford the production one. */scrypt?: ScryptParams;+ /**+ * How much of the download has been handed over, for a screen to show.+ *+ * Called no more often than {@link PROGRESS_INTERVAL_MS}, and once at the end. Bytes rather+ * than a fraction, because the screen shows both, and this is the only place that knows the+ * total before the browser does.+ */+ onProgress?: (sentBytes: number, totalBytes: number) => void;}+/**+ * How often progress is worth reporting.+ *+ * A backup hands over thousands of chunks, and a message per chunk would be thousands of renders+ * for a number that a person reads a few times a minute.+ */+const PROGRESS_INTERVAL_MS = 250;+/*** How long the stream waits to be asked for more before giving the download up for dead.*@@ -122,6 +138,9 @@ export async function streamDatabaseDownload(* amount of reading or hashing faster would show up in the total.*/let waitedMs = 0;+ let sentBytes = 0;+ let totalBytes = 0;+ let reportedAt = 0;/** Posts one chunk per granted pull, or throws the stop that was granted instead. */const sendChunk = async (chunk: Uint8Array): Promise<void> => {@@ -133,11 +152,20 @@ export async function streamDatabaseDownload(throw new DownloadStopped(request);}+ const length = chunk.byteLength;// 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 ]);++ // Counted after the hand-over, so what is reported is what has actually gone.+ sentBytes += length;+ const now = Date.now();+ if (now - reportedAt >= PROGRESS_INTERVAL_MS) {+ reportedAt = now;+ options.onProgress?.(sentBytes, totalBytes);+ }};let source: ReadableStream<Uint8Array> | undefined;@@ -150,7 +178,8 @@ export async function streamDatabaseDownload(// extension. Without a passphrase it is the database between a header and a trailer, the// trailer's digest vouching for it; with one, every frame is authenticated as well.const encrypted = !!options.passphrase;- port.postMessage({ type: "begin", byteSize: containerSize(byteSize, encrypted) });+ totalBytes = containerSize(byteSize, encrypted);+ port.postMessage({ type: "begin", byteSize: totalBytes });await writeBackupContainer(stream,new WritableStream<Uint8Array>({ write: sendChunk }),@@ -164,6 +193,9 @@ export async function streamDatabaseDownload(});port.postMessage({ type: "end" });+ // The last one is unconditional: a throttled report would otherwise leave the screen a+ // chunk short of the total it is about to be told is finished.+ options.onProgress?.(sentBytes, totalBytes);reportTiming(byteSize, timing, waitedMs, Date.now() - startedAt);return { status: "done" };diff --git a/apps/standalone/src/local-bridge.ts b/apps/standalone/src/local-bridge.tsindex af0830bb59..d50632713e 100644--- a/apps/standalone/src/local-bridge.ts+++ b/apps/standalone/src/local-bridge.ts@@ -133,6 +133,7 @@ const DOWNLOAD_START_TIMEOUT_MS = 45_000;let pendingDownload: {resolve: (result: StandaloneDownloadResult) => void;startTimer: ReturnType<typeof setTimeout>;+ onProgress?: (sentBytes: number, totalBytes: number) => void;} | null = null;/** Carried from {@link downloadDatabase} to the stream relay, so it never rides the URL. */@@ -163,7 +164,11 @@ let pendingDownloadPassphrase: string | undefined;* leader's, and the passphrase asked for here never leaves this tab, so a follower would produce* either no backup or an unencrypted one under the belief it was encrypted.*/-export function downloadDatabase(fileName: string, passphrase?: string): Promise<StandaloneDownloadResult> {+export function downloadDatabase(+ fileName: string,+ passphrase?: string,+ onProgress?: (sentBytes: number, totalBytes: number) => void+): Promise<StandaloneDownloadResult> {if (!isLeader()) {return Promise.resolve({status: "failed",@@ -186,6 +191,7 @@ export function downloadDatabase(fileName: string, passphrase?: string): Promisereturn new Promise((resolve) => {pendingDownload = {resolve,+ onProgress,startTimer: setTimeout(() => settlePendingDownload({ status: "failed", message: "The download did not start." }),DOWNLOAD_START_TIMEOUT_MS@@ -344,6 +350,13 @@ export function startLocalServerWorker() {// 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.+ // How far the download has got, which the screen shows because a phone hides its own+ // download UI behind the notification shade.+ if (msg?.type === "BACKUP_STREAM_PROGRESS") {+ pendingDownload?.onProgress?.(Number(msg.sentBytes), Number(msg.totalBytes));+ return;+ }+if (msg?.type === "BACKUP_STREAM_ACTIVE") {setBackupPinging(msg.active === true);if (msg.active === true) {diff --git a/apps/standalone/src/local-server-worker.ts b/apps/standalone/src/local-server-worker.tsindex 5245afdc51..84c50cebf5 100644--- a/apps/standalone/src/local-server-worker.ts+++ b/apps/standalone/src/local-server-worker.ts@@ -550,7 +550,16 @@ async function handleBackupStream(port: MessagePort, passphrase?: string): Promi// 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 }+ {+ passphrase,+ // To the page rather than the port: the browser's own download UI is out of reach on+ // a phone until the notification shade is pulled down, so the screen says it itself.+ onProgress: (sentBytes, totalBytes) => (self as unknown as Worker).postMessage({+ type: "BACKUP_STREAM_PROGRESS",+ sentBytes,+ totalBytes+ })+ });announce(false, result);diff --git a/packages/commons/src/lib/standalone_api_interface.ts b/packages/commons/src/lib/standalone_api_interface.tsindex 4e371d8db5..5582ff3f0c 100644--- a/packages/commons/src/lib/standalone_api_interface.ts+++ b/packages/commons/src/lib/standalone_api_interface.ts@@ -65,7 +65,11 @@ export interface StandaloneBackupApi {* 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>;+ downloadDatabase(+ fileName: string,+ passphrase?: string,+ onProgress?: (sentBytes: number, totalBytes: number) => void+ ): Promise<StandaloneDownloadResult>;}/** The complete surface the standalone build exposes to the client. */