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
client/backup import: report the processing progress for backup containers
Adorian Dorane7699c0fb852
diff --git a/apps/client/src/setup_restore.css b/apps/client/src/setup_restore.cssindex cd545281c7..9746a0db61 100644--- a/apps/client/src/setup_restore.css+++ b/apps/client/src/setup_restore.css@@ -106,6 +106,28 @@}}+ /* Takes the rest of the row, so the bar does not depend on how long the step is named. */+ .restore-stage-progress {+ display: flex;+ flex: 1;+ align-items: center;+ gap: 0.5em;+ margin-left: auto;++ progress {+ flex: 1;+ min-width: 4em;+ }++ span {+ min-width: 3em;+ font-size: 0.85em;+ font-variant-numeric: tabular-nums;+ text-align: right;+ opacity: 0.7;+ }+ }+.restore-banner {margin-top: 1em;}diff --git a/apps/client/src/setup_restore.spec.tsx b/apps/client/src/setup_restore.spec.tsxindex 7a7a601573..4a846d818b 100644--- a/apps/client/src/setup_restore.spec.tsx+++ b/apps/client/src/setup_restore.spec.tsx@@ -23,7 +23,7 @@ const BACKUPS = [];let container: HTMLDivElement;-let restore: { stage: string; error?: string; reason?: string } | null;+let restore: { stage: string; fraction?: number; error?: string; reason?: string } | null;function renderRestore(props: Partial<{ onBack: () => void; onRestored: () => void }> = {}) {container = document.createElement("div");@@ -261,6 +261,34 @@ describe("following the restore", () => {expect(active?.textContent).toContain("setup.restore-stage-validating");});+ it("shows how far the running step has got, and only on that step", async () => {+ await startRestore();++ restore = { stage: "staging", fraction: 0.42 };+ await nextPoll();++ const bar = container.querySelector<HTMLProgressElement>(".restore-stages .active progress");+ expect(bar?.value).toBe(0.42);+ expect(container.querySelector(".restore-stages .active .restore-stage-progress")?.textContent).toContain("42%");+ // One bar, on the step that is running.+ expect(container.querySelectorAll(".restore-stages progress")).toHaveLength(1);+ });++ it("drops the bar for a step that cannot say how far it has got", async () => {+ await startRestore();++ restore = { stage: "staging", fraction: 0.9 };+ await nextPoll();+ expect(container.querySelector(".restore-stages progress")).toBeTruthy();++ // Checking a database reads it from end to end with nothing to report along the way; the+ // previous step's bar must not be left sitting under it.+ restore = { stage: "validating" };+ await nextPoll();++ expect(container.querySelector(".restore-stages progress")).toBeFalsy();+ });+it("finishes setup once the restore is done", async () => {await startRestore();diff --git a/apps/client/src/setup_restore.tsx b/apps/client/src/setup_restore.tsxindex 55302342d9..4d19ebee29 100644--- a/apps/client/src/setup_restore.tsx+++ b/apps/client/src/setup_restore.tsx@@ -354,14 +354,24 @@ function AskPassphrase({ fileName, wrong, onSubmit }: { fileName: string; wrong:/** The stages the server works through, and which one it is on. */const STAGES = [ "staging", "validating", "swapping", "migrating" ] as const;+/** What the server says about the restore it is running. */+interface RestoreStatus {+ stage: string;+ /** How far through the current stage, where that stage can say; absent where it cannot. */+ fraction?: number;+ error?: string;+ reason?: string;+}+function RestoreProgress({ onRestored, onFailed }: { onRestored: () => void; onFailed: (failure: { error?: string; reason?: string }) => void }) {const [ stage, setStage ] = useState<string>("staging");+ const [ fraction, setFraction ] = useState<number | null>(null);useEffect(() => {const interval = setInterval(async () => {let restore;try {- ({ restore } = await server.get<{ restore: { stage: string; error?: string; reason?: string } | null }>("setup/restore/status"));+ ({ restore } = await server.get<{ restore: RestoreStatus | null }>("setup/restore/status"));} catch {// The database is detached for the moment it takes to exchange the files, which any// request landing in that moment cannot be answered through. The next one can.@@ -383,6 +393,7 @@ function RestoreProgress({ onRestored, onFailed }: { onRestored: () => void; onF}setStage(restore.stage);+ setFraction(restore.fraction ?? null);}, 1000);return () => clearInterval(interval);@@ -397,6 +408,15 @@ function RestoreProgress({ onRestored, onFailed }: { onRestored: () => void; onF<CardSection key={name} className={index < currentIndex ? "completed" : index === currentIndex ? "active" : ""}><Icon icon={index < currentIndex ? "bx bx-check-circle" : index === currentIndex ? "bx bx-loader-circle bx-spin" : "bx bx-circle"} />{" "}{t(`setup.restore-stage-${name}`)}++ {/* Only the step that is running, and only where it can say how far it has+ got. The steps that cannot show nothing rather than an empty bar. */}+ {index === currentIndex && fraction !== null && (+ <div class="restore-stage-progress">+ <progress value={fraction} max={1} />+ <span>{Math.floor(fraction * 100)}%</span>+ </div>+ )}</CardSection>))}</Card>diff --git a/apps/server/src/services/database_restore.spec.ts b/apps/server/src/services/database_restore.spec.tsindex cd6d93dbf3..fd5e614519 100644--- a/apps/server/src/services/database_restore.spec.ts+++ b/apps/server/src/services/database_restore.spec.ts@@ -13,6 +13,7 @@ import {getRestoreProgress,logRestore,logRestoreError,+ reportStepProgress,readBackupFormat,removeQuietly,reportRestoreFailure,@@ -222,6 +223,63 @@ describe("what the log is told", () => {expect(log).not.toContain("holidays-in-crete");});+ it("reports how far a long step has got, in brackets, once per tenth of the way", () => {+ const said: string[] = [];+ vi.spyOn(getLog(), "info").mockImplementation((message) => said.push(String(message)));+ const report = reportStepProgress("unwrapping the backup");++ // What the container module sends: a position at whatever rate its own throttle allows.+ for (const fraction of [ 0, 0.02, 0.05, 0.09, 0.1, 0.15, 0.2, 0.99, 1 ]) {+ report(fraction);+ }++ expect(said).toEqual([+ "Backup restore: unwrapping the backup [0%]",+ "Backup restore: unwrapping the backup [10%]",+ "Backup restore: unwrapping the backup [20%]",+ "Backup restore: unwrapping the backup [99%]",+ "Backup restore: unwrapping the backup [100%]"+ ]);+ });++ it("says nothing more while a step is not getting anywhere, however often it is asked", () => {+ const said: string[] = [];+ vi.spyOn(getLog(), "info").mockImplementation((message) => said.push(String(message)));+ const report = reportStepProgress("unwrapping the backup");++ report(0.42);+ for (let i = 0; i < 50; i++) {+ report(0.42);+ }++ // A stall is told apart from slow going by the log not growing, which it cannot do if every+ // report writes a line.+ expect(said).toEqual([ "Backup restore: unwrapping the backup [42%]" ]);+ });++ it("reports the progress of a real unwrap", async () => {+ const said: string[] = [];+ vi.spyOn(getLog(), "info").mockImplementation((message) => said.push(String(message)));+ const backup = await containerOf(validDatabase());++ await stageBackup({ path: backup, fileName: "backup.tnbackup", consumable: false });++ expect(transcript(said)).toContain("unwrapping the backup [100%]");+ });++ it("puts the position where the screen can see it, every time rather than every tenth", () => {+ vi.spyOn(getLog(), "info").mockImplementation(() => {});+ reportRestoreFailure("backup.db", new Error("so that there is a progress to carry it"));+ const report = reportStepProgress("unwrapping the backup");++ report(0.42);+ expect(getRestoreProgress()?.fraction).toBe(0.42);++ // Between two logged tenths, and still the latest thing the screen is told.+ report(0.47);+ expect(getRestoreProgress()?.fraction).toBe(0.47);+ });+it("says which steps a restore got through, so one that stops says where", async () => {const said: string[] = [];vi.spyOn(getLog(), "info").mockImplementation((message) => said.push(String(message)));@@ -233,6 +291,9 @@ describe("what the log is told", () => {await expect(restoreDatabase({ path: validDatabase(), fileName: "backup.db", consumable: false })).rejects.toBeInstanceOf(RestoreFailure);+ // A step's position belongs to that step, so it is not left showing under the next one.+ expect(getRestoreProgress()?.fraction).toBeUndefined();+const log = transcript(said);expect(detach).toHaveBeenCalled();expect(log).toContain("the backup is a plain database");diff --git a/apps/server/src/services/database_restore.ts b/apps/server/src/services/database_restore.tsindex 2b8aa96d94..534f03a913 100644--- a/apps/server/src/services/database_restore.ts+++ b/apps/server/src/services/database_restore.ts@@ -3,6 +3,7 @@ import {FIXED_HEADER_BYTES,isBackupContainerError,peekBackupContainer,+ type ProgressCallback,readBackupContainer} from "@triliumnext/backup-container";import {@@ -85,6 +86,50 @@ function withoutPaths(text: string): string {return scrubbed;}+/**+ * How much of the way through a step has to pass before it is worth another line.+ *+ * A log is read after the fact, so what it needs from a step that runs for minutes is a trail+ * proving it was moving, not a running total. Every tenth is ten or eleven lines however long the+ * step takes, which is enough to tell a slow unwrap from a stalled one.+ */+const PROGRESS_LOG_STEP = 10;++/**+ * How often the container module is asked to report.+ *+ * Half the rate the screen polls at, so what it is shown is never much older than it is, and far+ * below the rate the module would report at left alone.+ */+const PROGRESS_INTERVAL_MS = 500;++/**+ * Passes the container module's progress on to both places that want it, each at its own rate.+ *+ * The screen is polled about once a second and wants the latest position every time, so every report+ * reaches it. The log wants the opposite: its reader comes to it afterwards and needs a trail, not a+ * running total, so a line is written only when the position has actually moved on a tenth. Writing+ * every report to both would make a stall indistinguishable from progress in the one place where+ * that distinction is all there is.+ */+export function reportStepProgress(activity: string): ProgressCallback {+ let lastLogged = -1;++ return (fraction) => {+ if (progress) {+ progress = { ...progress, fraction };+ }++ const percent = Math.floor(fraction * 100);+ const step = Math.floor(percent / PROGRESS_LOG_STEP);++ if (step > lastLogged) {+ lastLogged = step;+ logRestore(`${activity} [${percent}%]`);+ }+ };+}+/** How big a file is, counting one that cannot be measured as nothing rather than failing over it. */export function sizeOf(filePath: string): number {return fs.statSync(filePath, { throwIfNoEntry: false })?.size ?? 0;@@ -137,6 +182,14 @@ export interface RestoreProgress {stage: RestoreStage;/** The name of the backup being restored, so a reloaded page can say what is going on. */fileName: string;+ /**+ * How far through the current step, from 0 to 1.+ *+ * Absent for the steps that cannot say — checking a database reads it from beginning to end with+ * nothing to report along the way, and exchanging the files is over in moments. It belongs to the+ * step rather than to the restore, and starts again with each one.+ */+ fraction?: number;/** Set when `stage` is `failed`. */error?: string;/** Set when `stage` is `failed`. */@@ -389,7 +442,14 @@ export async function stageBackup(request: RestoreRequest): Promise<string> {const unwrappedAt = Date.now();try {- const unwrapped = await readBackupContainer(source, destination, { passphrase: request.passphrase });+ const unwrapped = await readBackupContainer(source, destination, {+ passphrase: request.passphrase,+ // The step that runs for minutes on a large backup, and the only one that can say how far+ // through it is. Without this the log jumps from the format to the finished size, which+ // reads the same whether it took a moment or is still going.+ onProgress: reportStepProgress("unwrapping the backup"),+ progressIntervalMs: PROGRESS_INTERVAL_MS+ });logRestore(`unwrapped a version ${unwrapped.version} container in ${describeElapsed(unwrappedAt)}`+ `: ${describeSize(unwrapped.bytesWritten)} of database`+ `${unwrapped.compressed ? `, from ${describeSize(sourceBytes)} compressed` : ""}`);@@ -508,7 +568,9 @@ function markerFor(document: string): string {*/function report(stage: RestoreStage): void {if (progress) {- progress = { ...progress, stage };+ // The position belonged to the step that has just ended, and would otherwise be read as this+ // one's — a step with nothing to report showing the last one's bar, frozen where it stopped.+ progress = { ...progress, stage, fraction: undefined };}logRestore(`step '${stage}'`);