Skip to content

Build your personal knowledge base with Trilium Notes

packages/backup container: add progress reporting

Adorian Doranb5dc81480aaa
diff --git a/packages/trilium-backup-container/README.md b/packages/trilium-backup-container/README.md
index 00e127e754..d3047a2b14 100644
--- a/packages/trilium-backup-container/README.md
+++ b/packages/trilium-backup-container/README.md
@@ -60,6 +60,30 @@ Write to a temporary name and rename on success. Do not hand the payload stream
with `autoClose: false` and patch through that same handle: its `close()` then waits forever on a
stream that never emits `close`.
+## Reporting progress
+
+Both directions accept `onProgress`, which is called with a number from 0 to 1 at most once every
+`progressIntervalMs` (250 by default), and once more with exactly 1 when the container is finished.
+
+```ts
+await readBackupContainer(input, output, {
+ passphrase,
+ onProgress: (progress) => report(Math.round(progress * 100))
+});
+```
+
+Progress is measured on the database and never on the payload: the writer reports how much of the
+database has gone in, and the reader reports how much has come out, so a compressed container does not
+report a fraction of the progress along with a fraction of the size. A fraction needs a total, which is
+the `plaintextSize` the writer records in the header, so a container written without one is read back
+reporting nothing but the final 1.
+
+Reports are throttled rather than debounced, since a container streams from beginning to end without
+ever pausing. Two things are outside them: key derivation, which is the slow part of opening an
+encrypted container and happens before the first byte is read, and success. A report of 1 says the
+payload has gone past, not that the destination took it, and the resolved promise is what says the
+container is written or unwrapped.
+
## Catching errors
Every failure is a `BackupContainerError` carrying a `reason`. The message is fixed English for logs;
diff --git a/packages/trilium-backup-container/src/index.ts b/packages/trilium-backup-container/src/index.ts
index eaeaa5640f..2c7dc1e4ce 100644
--- a/packages/trilium-backup-container/src/index.ts
+++ b/packages/trilium-backup-container/src/index.ts
@@ -28,12 +28,12 @@
* await rename(partial, final);
* ```
*
- * @example Reading one back
+ * @example Reading one back, reporting how far along it is
* ```ts
* const info = await readBackupContainer(
* fs.createReadStream(container),
* fs.createWriteStream(database),
- * { passphrase }
+ * { passphrase, onProgress: (progress) => report(Math.round(progress * 100)) }
* );
* ```
*
@@ -53,6 +53,11 @@ export {
SCRYPT_DEFAULTS,
type ScryptParams
} from "./format.js";
+export {
+ DEFAULT_PROGRESS_INTERVAL_MS,
+ type ProgressCallback,
+ type ProgressOptions
+} from "./progress.js";
export {
type BackupContainerInfo,
DEFAULT_MAX_OUTPUT_BYTES,
diff --git a/packages/trilium-backup-container/src/progress.spec.ts b/packages/trilium-backup-container/src/progress.spec.ts
new file mode 100644
index 0000000000..2e9c07c63d
--- /dev/null
+++ b/packages/trilium-backup-container/src/progress.spec.ts
@@ -0,0 +1,302 @@
+import { Readable } from "node:stream";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { FRAME_SIZE } from "./format.js";
+import { readBackupContainer, type ReadBackupContainerOptions } from "./read.js";
+import {
+ chunked,
+ fakeDatabase,
+ FAST_SCRYPT,
+ MemorySink,
+ reasonOf,
+ readFromBuffer,
+ writeToBuffer
+} from "./test-helpers.js";
+import type { WriteBackupContainerOptions } from "./write.js";
+
+type WriteOptions = Omit<WriteBackupContainerOptions, "patchHeader">;
+
+const PASSPHRASE = "correct horse battery staple";
+
+/** Every format combination, since progress is measured on the plaintext side of all of them. */
+const FORMATS: [string, WriteOptions][] = [
+ [ "plain", {} ],
+ [ "compressed", { compress: true } ],
+ [ "encrypted", { passphrase: PASSPHRASE, scrypt: FAST_SCRYPT } ],
+ [ "compressed and encrypted", { compress: true, passphrase: PASSPHRASE, scrypt: FAST_SCRYPT } ]
+];
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe("writing", () => {
+ it("reports each chunk of the database, up to and including a final 1", async () => {
+ const { reports, onProgress } = collector();
+ const database = fakeDatabase(64 * 1024);
+
+ await writeToBuffer(chunked(database, 4096), {
+ plaintextSize: database.length,
+ onProgress,
+ progressIntervalMs: 0
+ });
+
+ // Sixteen equal chunks, then completion once the digest has been patched in.
+ expect(reports).toEqual([ ...sixteenths(), 1 ]);
+ });
+
+ it.each(FORMATS)("measures the database going in, not the %s payload coming out", async (
+ _label,
+ options
+ ) => {
+ const { reports, onProgress } = collector();
+ const database = fakeDatabase(64 * 1024);
+
+ await writeToBuffer(chunked(database, 4096), {
+ ...options,
+ plaintextSize: database.length,
+ onProgress,
+ progressIntervalMs: 0
+ });
+
+ // A compressed payload is a fraction of the size, so measuring it would report a fraction
+ // of the progress: the sequence has to be the same one whatever the payload is doing.
+ expect(reports).toEqual([ ...sixteenths(), 1 ]);
+ });
+
+ it("reports completion alone when no size was given to measure against", async () => {
+ const { reports, onProgress } = collector();
+
+ await writeToBuffer(chunked(fakeDatabase(64 * 1024), 4096), {
+ onProgress,
+ progressIntervalMs: 0
+ });
+
+ expect(reports).toEqual([ 1 ]);
+ });
+
+ it("never reports past 1, even when the database outgrew the size it was measured at", async () => {
+ const { reports, onProgress } = collector();
+ const database = fakeDatabase(64 * 1024);
+
+ await writeToBuffer(chunked(database, 4096), {
+ plaintextSize: database.length / 2,
+ onProgress,
+ progressIntervalMs: 0
+ });
+
+ // Chunks eight to sixteen are all past the stated size, and then completion.
+ expect(Math.max(...reports)).toBe(1);
+ expect(reports.filter((progress) => progress === 1)).toHaveLength(10);
+ });
+
+ it("writes the backup anyway when the callback throws", async () => {
+ const database = fakeDatabase(64 * 1024);
+ let calls = 0;
+
+ const written = await writeToBuffer(chunked(database, 4096), {
+ compress: true,
+ plaintextSize: database.length,
+ progressIntervalMs: 0,
+ onProgress: () => {
+ calls++;
+ throw new Error("the caller cannot cope with its own progress");
+ }
+ });
+
+ expect(calls).toBe(17);
+ const read = await readFromBuffer(written.bytes);
+ expect(read.bytes.equals(database)).toBe(true);
+ });
+});
+
+describe("reading", () => {
+ it("reports each chunk of the database coming out, up to and including a final 1", async () => {
+ const { reports, onProgress } = collector();
+ const database = fakeDatabase(2 * FRAME_SIZE);
+ const written = await writeToBuffer(database, { plaintextSize: database.length });
+
+ await readFromBuffer(written.bytes, { onProgress, progressIntervalMs: 0 });
+
+ expect(reports).toEqual([ 0.5, 1, 1 ]);
+ });
+
+ it.each(FORMATS)("measures the database coming out of a %s container", async (
+ _label,
+ options
+ ) => {
+ const { reports, onProgress } = collector();
+ const database = fakeDatabase(2 * FRAME_SIZE);
+ const written = await writeToBuffer(database, {
+ ...options,
+ plaintextSize: database.length
+ });
+
+ const read = await readFromBuffer(written.bytes, {
+ passphrase: PASSPHRASE,
+ onProgress,
+ progressIntervalMs: 0
+ });
+
+ expect(read.result.bytesWritten).toBe(database.length);
+ expectRisesToOne(reports);
+ });
+
+ it("reports completion alone when the container recorded no size", async () => {
+ const { reports, onProgress } = collector();
+ const written = await writeToBuffer(fakeDatabase(2 * FRAME_SIZE), { compress: true });
+
+ await readFromBuffer(written.bytes, { onProgress, progressIntervalMs: 0 });
+
+ expect(reports).toEqual([ 1 ]);
+ });
+
+ it.each([
+ [
+ "the passphrase is refused, which happens before a byte is unwrapped",
+ { passphrase: "wrong" },
+ "wrong-passphrase-or-damaged-header"
+ ],
+ [
+ "the output would exceed the ceiling",
+ { passphrase: PASSPHRASE, maxOutputBytes: 1_000 },
+ "output-too-large"
+ ]
+ ])("reports nothing when %s", async (_label, options, reason) => {
+ const { reports, onProgress } = collector();
+ const database = fakeDatabase(2 * FRAME_SIZE);
+ const written = await writeToBuffer(database, {
+ passphrase: PASSPHRASE,
+ scrypt: FAST_SCRYPT,
+ plaintextSize: database.length
+ });
+
+ const failure = await reasonOf(readFromBuffer(written.bytes, {
+ ...options as ReadBackupContainerOptions,
+ onProgress,
+ progressIntervalMs: 0
+ }));
+
+ expect(failure).toBe(reason);
+ expect(reports).toEqual([]);
+ });
+
+ it("reports nothing for output that is not a database, which is checked first", async () => {
+ const { reports, onProgress } = collector();
+ const payload = Buffer.from("this is not a database, it is a note");
+ const written = await writeToBuffer(payload, { plaintextSize: payload.length });
+
+ const failure = await reasonOf(
+ readFromBuffer(written.bytes, { onProgress, progressIntervalMs: 0 })
+ );
+
+ expect(failure).toBe("not-a-database");
+ expect(reports).toEqual([]);
+ });
+
+ it("does not report completion when the unwrapped database is the wrong size", async () => {
+ const { reports, onProgress } = collector();
+ const database = fakeDatabase(2 * FRAME_SIZE);
+ const written = await writeToBuffer(database, { plaintextSize: database.length });
+
+ // Claim a third more than the container actually holds, which is only caught at the end.
+ const lying = Buffer.from(written.bytes);
+ lying.writeBigUInt64LE(BigInt(3 * FRAME_SIZE), 24);
+
+ const failure = await reasonOf(
+ readFromBuffer(lying, { onProgress, progressIntervalMs: 0 })
+ );
+
+ expect(failure).toBe("size-mismatch");
+ expect(reports).toEqual([ 1 / 3, 2 / 3 ]);
+ });
+
+ it("stops reporting when the destination fails, without reporting completion after it", async () => {
+ const { reports, onProgress } = collector();
+ const database = fakeDatabase(2 * FRAME_SIZE);
+ const written = await writeToBuffer(database, { plaintextSize: database.length });
+
+ const failing = new MemorySink();
+ failing._write = (_chunk, _encoding, callback) => callback(new Error("ENOSPC"));
+
+ await expect(readBackupContainer(
+ Readable.from([ written.bytes ]),
+ failing,
+ { onProgress, progressIntervalMs: 0 }
+ )).rejects.toThrow(/ENOSPC/);
+
+ // A report of 1 can be the last chunk on its way to a destination that then refuses it, so
+ // what a failure rules out is a report *after* the last one the payload accounts for.
+ expect(reports.length).toBeLessThanOrEqual(2);
+ expect(reports.every((progress) => progress <= 1)).toBe(true);
+ });
+});
+
+describe("throttling", () => {
+ it("reports at most once per interval, whatever the clock does in between", async () => {
+ const { reports, onProgress } = collector();
+ const database = fakeDatabase(64 * 1024);
+ const clock = mockedClock();
+
+ // A hundred milliseconds per chunk against the default interval, so two chunks in three go
+ // unreported.
+ await writeToBuffer(ticking(chunked(database, 4096), clock, 100), {
+ plaintextSize: database.length,
+ onProgress
+ });
+
+ expect(reports).toEqual([ 1, 4, 7, 10, 13, 16 ].map((chunk) => chunk / 16).concat(1));
+ });
+
+ it("reports the first chunk and the last, however little time passes", async () => {
+ const { reports, onProgress } = collector();
+ const database = fakeDatabase(64 * 1024);
+ const clock = mockedClock();
+
+ // A clock that never moves: everything between the leading report and completion is held
+ // back, and neither of those two is.
+ await writeToBuffer(ticking(chunked(database, 4096), clock, 0), {
+ plaintextSize: database.length,
+ onProgress,
+ progressIntervalMs: 250
+ });
+
+ expect(reports).toEqual([ 1 / 16, 1 ]);
+ });
+});
+
+function collector(): { reports: number[]; onProgress: (progress: number) => void } {
+ const reports: number[] = [];
+
+ return { reports, onProgress: (progress) => reports.push(progress) };
+}
+
+/** The sequence a sixteen chunk database produces, which most of these tests write. */
+function sixteenths(): number[] {
+ return Array.from({ length: 16 }, (_value, index) => (index + 1) / 16);
+}
+
+function expectRisesToOne(reports: number[]): void {
+ expect(reports.length).toBeGreaterThan(2);
+ expect(reports.at(-1)).toBe(1);
+ expect(reports.every((progress) => progress > 0 && progress <= 1)).toBe(true);
+ expect([ ...reports ].sort((first, second) => first - second)).toEqual(reports);
+}
+
+/** A clock the test moves itself, so a throttle can be observed without waiting on a real one. */
+function mockedClock(): { now: number } {
+ const clock = { now: 1_000 };
+ vi.spyOn(Date, "now").mockImplementation(() => clock.now);
+
+ return clock;
+}
+
+/** Advances `clock` by `step` before each chunk, so the throttle sees time pass between them. */
+function ticking(source: Readable, clock: { now: number }, step: number): Readable {
+ return Readable.from((async function* () {
+ for await (const chunk of source) {
+ clock.now += step;
+ yield chunk as Buffer;
+ }
+ })());
+}
diff --git a/packages/trilium-backup-container/src/progress.ts b/packages/trilium-backup-container/src/progress.ts
new file mode 100644
index 0000000000..d6fdd845c2
--- /dev/null
+++ b/packages/trilium-backup-container/src/progress.ts
@@ -0,0 +1,91 @@
+/** Called with how far along an operation is, from 0 (nothing done) to 1 (complete). */
+export type ProgressCallback = (progress: number) => void;
+
+/** Shortest gap between two progress reports, unless the caller asks for a different one. */
+export const DEFAULT_PROGRESS_INTERVAL_MS = 250;
+
+/** The progress options every entry point in this module accepts. */
+export interface ProgressOptions {
+ /**
+ * Called with the progress of the payload, from 0 to 1, at most once every
+ * {@link ProgressOptions.progressIntervalMs}, and always once more with exactly 1 once the
+ * operation has finished.
+ *
+ * A position needs something to be a fraction of, so progress below 1 is only reported when the
+ * size of the database is known. A callback that throws is ignored: reporting on a backup is
+ * never a reason to fail one.
+ *
+ * A report of 1 is not itself a report of success. It says the last of the payload has gone
+ * past, which on both paths happens before the destination has taken it, so a failure can still
+ * follow one. The resolved promise is what says the container is written or unwrapped.
+ */
+ onProgress?: ProgressCallback;
+ /** Shortest gap between reports. Defaults to {@link DEFAULT_PROGRESS_INTERVAL_MS}. */
+ progressIntervalMs?: number;
+}
+
+/**
+ * Rate-limits progress reports to at most one per interval.
+ *
+ * Throttled rather than debounced: a container streams from beginning to end without ever pausing,
+ * so a debounce would hold every report back until there was nothing left to report. The interval is
+ * measured against the clock as the bytes go past rather than driven by a timer, so an operation
+ * that fails leaves nothing behind holding the event loop open.
+ */
+export class ProgressReporter {
+
+ #reportedAt = Number.NEGATIVE_INFINITY;
+
+ constructor(
+ /** What the position is a fraction of, or 0 when the size is not known. */
+ private readonly total: number,
+ private readonly callback: ProgressCallback,
+ private readonly intervalMs: number
+ ) {}
+
+ /** Reports being `bytes` into the total, unless the last report was too recent for another. */
+ at(bytes: number): void {
+ if (this.total <= 0) {
+ return;
+ }
+
+ const now = Date.now();
+ if (now - this.#reportedAt < this.intervalMs) {
+ return;
+ }
+
+ this.#reportedAt = now;
+ // Clamped: an input can have grown past the size that was measured before it was opened.
+ this.#emit(Math.min(1, bytes / this.total));
+ }
+
+ /** Reports completion, whatever was reported before it and however recently. */
+ complete(): void {
+ this.#emit(1);
+ }
+
+ #emit(progress: number): void {
+ try {
+ this.callback(progress);
+ } catch {
+ // Deliberately swallowed, see `onProgress`.
+ }
+ }
+
+}
+
+/** Builds the reporter for one operation, or `null` when the caller asked for no progress. */
+export function createProgressReporter(
+ total: number,
+ options: ProgressOptions
+): ProgressReporter | null {
+ if (!options.onProgress) {
+ return null;
+ }
+
+ return new ProgressReporter(
+ total,
+ options.onProgress,
+ options.progressIntervalMs ?? DEFAULT_PROGRESS_INTERVAL_MS
+ );
+}
diff --git a/packages/trilium-backup-container/src/read.ts b/packages/trilium-backup-container/src/read.ts
index e2479abf1e..e9f6bd9a18 100644
--- a/packages/trilium-backup-container/src/read.ts
+++ b/packages/trilium-backup-container/src/read.ts
@@ -23,12 +23,13 @@ import {
TAG_BYTES,
validateScryptParams
} from "./format.js";
+import { createProgressReporter, type ProgressOptions } from "./progress.js";
import { OutputGuard } from "./streams.js";
/** Ceiling on unwrapped output when the container does not record a smaller size. */
export const DEFAULT_MAX_OUTPUT_BYTES = 64 * 1024 * 1024 * 1024;
-export interface ReadBackupContainerOptions {
+export interface ReadBackupContainerOptions extends ProgressOptions {
/** Required when the container is encrypted. */
passphrase?: string;
/**
@@ -148,7 +149,10 @@ export async function readBackupContainer(
options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES,
header.plaintextSize > 0 ? header.plaintextSize : Number.POSITIVE_INFINITY
);
- const guard = new OutputGuard(ceiling, options.requireSqliteHeader !== false);
+ // The recorded size is the only total there is: the container's own length measures the payload
+ // as stored, which for a compressed one is not what comes out the other end.
+ const progress = createProgressReporter(header.plaintextSize, options);
+ const guard = new OutputGuard(ceiling, options.requireSqliteHeader !== false, progress);
const payload = header.encryption && key
? readFrames(reader, header, header.encryption, key)
@@ -173,6 +177,8 @@ export async function readBackupContainer(
);
}
+ progress?.complete();
+
return {
version: header.version,
compressed: header.compressed,
diff --git a/packages/trilium-backup-container/src/streams.ts b/packages/trilium-backup-container/src/streams.ts
index 6110823a51..bd3db84ffb 100644
--- a/packages/trilium-backup-container/src/streams.ts
+++ b/packages/trilium-backup-container/src/streams.ts
@@ -10,6 +10,7 @@ import {
SQLITE_HEADER_BYTES,
validateSqliteHeader
} from "./format.js";
+import type { ProgressReporter } from "./progress.js";
import { sealFrame } from "./crypto.js";
/** Passes bytes through untouched while hashing them, so the digest costs no extra pass. */
@@ -39,6 +40,33 @@ export class DigestTap extends Transform {
}
+/**
+ * Passes bytes through untouched while reporting how many of them have gone past.
+ *
+ * Sits at the head of the writer's pipeline, where the bytes are still the ones the recorded
+ * plaintext size counted: further down they are compressed, encrypted, or both, and a fraction of
+ * those is a fraction of a total nobody knows in advance.
+ */
+export class ProgressTap extends Transform {
+
+ #bytes = 0;
+
+ constructor(private readonly progress: ProgressReporter) {
+ super();
+ }
+
+ override _transform(
+ chunk: Buffer,
+ _encoding: BufferEncoding,
+ callback: TransformCallback
+ ): void {
+ this.#bytes += chunk.length;
+ this.progress.at(this.#bytes);
+ callback(null, chunk);
+ }
+
+}
+
/**
* Forces the gzip OS byte to "unknown".
*
@@ -156,6 +184,9 @@ export class FrameEncryptor extends Transform {
/**
* Guards the unwrapped output: enforces the ceiling before bytes reach the destination, checks the
* SQLite header as soon as enough of it has passed, and counts what was written.
+ *
+ * The count it already keeps is what the reader's progress is a fraction of, so the reporting is
+ * done from here rather than from a tap of its own.
*/
export class OutputGuard extends Transform {
@@ -166,7 +197,8 @@ export class OutputGuard extends Transform {
constructor(
private readonly ceiling: number,
- private readonly requireSqliteHeader: boolean
+ private readonly requireSqliteHeader: boolean,
+ private readonly progress: ProgressReporter | null = null
) {
super();
}
@@ -205,6 +237,10 @@ export class OutputGuard extends Transform {
}
}
+ // Reported only once the chunk has passed every check, so a rejected output never reports
+ // having got anywhere.
+ this.progress?.at(this.#written);
+
callback(null, chunk);
}
diff --git a/packages/trilium-backup-container/src/write.ts b/packages/trilium-backup-container/src/write.ts
index 453b45c495..df4ba7e24b 100644
--- a/packages/trilium-backup-container/src/write.ts
+++ b/packages/trilium-backup-container/src/write.ts
@@ -22,7 +22,8 @@ import {
TAG_BYTES,
validateScryptParams
} from "./format.js";
-import { DigestTap, FrameEncryptor, GzipHeaderNormaliser } from "./streams.js";
+import { createProgressReporter, type ProgressOptions } from "./progress.js";
+import { DigestTap, FrameEncryptor, GzipHeaderNormaliser, ProgressTap } from "./streams.js";
/** The stream shapes `pipeline` accepts, so a built array needs no cast at the call. */
type PipelineStage = NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream;
@@ -35,14 +36,17 @@ type PipelineStage = NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.Read
*/
export type PatchHeader = (offset: number, data: Buffer) => Promise<void> | void;
-export interface WriteBackupContainerOptions {
+export interface WriteBackupContainerOptions extends ProgressOptions {
/** Patches the payload digest into the header once the payload is complete. Required. */
patchHeader: PatchHeader;
/** Compress the payload with gzip. */
compress?: boolean;
/** Encrypt the payload. Encryption is on exactly when a passphrase is given. */
passphrase?: string;
- /** Size of the wrapped database, recorded as a hint for restore progress. Omit when unknown. */
+ /**
+ * Size of the wrapped database, recorded as a hint for restore progress and used as the total
+ * this write reports its own progress against. Omit when unknown.
+ */
plaintextSize?: number;
/** scrypt cost. Defaults to {@link SCRYPT_DEFAULTS}. */
scrypt?: ScryptParams;
@@ -96,6 +100,7 @@ export async function writeBackupContainer(
const compressed = options.compress === true;
const encrypted = options.passphrase !== undefined;
+ const progress = createProgressReporter(plaintextSize, options);
// Build the header first: the verifier tag authenticates the bytes before it, so those must be
// final.
@@ -140,6 +145,9 @@ export async function writeBackupContainer(
const digestTap = new DigestTap();
// Typed as the streams `pipeline` accepts, so the built array needs no cast at the call.
const stages: PipelineStage[] = [ input ];
+ if (progress) {
+ stages.push(new ProgressTap(progress));
+ }
if (compressed) {
stages.push(
createGzip({ level: options.compressionLevel ?? 6 }),
@@ -156,6 +164,10 @@ export async function writeBackupContainer(
const digest = digestTap.digest();
await options.patchHeader(digestOffset(header.headerLength), digest);
+ // After the patch rather than after the pipeline: the container is not written until the digest
+ // is in its header.
+ progress?.complete();
+
return {
headerLength: header.headerLength,
compressed,