Skip to content

Build your personal knowledge base with Trilium Notes

standalone/backup: read the backup file in slices instead of a single stream

Adorian Dorana3865495bfbf
diff --git a/apps/client/src/setup_restore.tsx b/apps/client/src/setup_restore.tsx
index 03f81d2896..b2d0533bab 100644
--- a/apps/client/src/setup_restore.tsx
+++ b/apps/client/src/setup_restore.tsx
@@ -321,6 +321,7 @@ function headlineFor(reason: string | undefined): string {
case "swap-failed-reload": return t("setup.restore-error-swap-failed-reload");
case "check-failed": return t("setup.restore-error-check-failed");
case "restore-failed": return t("setup.restore-error-failed");
+ case "backup-incomplete": return t("setup.restore-error-incomplete");
case "migration-failed": return t("setup.restore-error-would-not-open");
case "restore-refused": return t("setup.restore-error-refused");
case "already-initialized": return t("setup.restore-error-already-initialized");
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index f9b1ba23c5..64ee585127 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -3749,6 +3749,7 @@
"restore-error-swap-failed-reload": "The database could not be replaced. Your previous database is back in place, but Trilium could not reopen it. Reload this page to continue.",
"restore-error-check-failed": "The backup could not be checked. This may be a problem on this device rather than with the backup itself, so it is worth trying again.",
"restore-error-failed": "The restore could not be completed. Nothing was replaced, so your knowledge base is as it was.",
+ "restore-error-incomplete": "This backup file is incomplete. It was probably not copied or downloaded in full, so try transferring it again.",
"restore-error-would-not-open": "The restored database could not be opened. Your previous database is back in place.",
"restore-error-refused": "Another setup step is already running.",
"restore-error-already-initialized": "This instance already has a knowledge base, so it cannot be restored over. Reload the page.",
diff --git a/apps/standalone/src/lightweight/database_restore.spec.ts b/apps/standalone/src/lightweight/database_restore.spec.ts
index 7724a47073..60e4dd8d7f 100644
--- a/apps/standalone/src/lightweight/database_restore.spec.ts
+++ b/apps/standalone/src/lightweight/database_restore.spec.ts
@@ -9,6 +9,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
DEFAULT_DATABASE_NAME,
readCurrentDatabaseName,
+ readInSlices,
restoreDatabase,
type RestoreProgress,
type RestoreTarget
@@ -65,6 +66,29 @@ async function containerOf(payload: Uint8Array, options: { passphrase?: string;
return new Blob([ fs.readFileSync(filePath) ]);
}
+/**
+ * The same, written front to back the way the standalone download writes one: no digest patched in
+ * afterwards, and the plaintext size recorded, which is what makes its total length predictable.
+ */
+async function streamedContainerOf(payload: Uint8Array, options: { passphrase?: string } = {}) {
+ const filePath = path.join(tempRoot, `streamed-${Math.random().toString(36).slice(2)}.tnbackup`);
+
+ await writeBackupContainer(
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- a Node stream over the bytes.
+ (await import("stream")).Readable.from([ Buffer.from(payload) ]) as any,
+ fs.createWriteStream(filePath),
+ {
+ streamed: true,
+ compress: false,
+ passphrase: options.passphrase,
+ scrypt: { log2N: 10, r: 8, p: 1 },
+ plaintextSize: payload.length
+ }
+ );
+
+ return new Blob([ fs.readFileSync(filePath) ]);
+}
+
/** A pool that keeps its databases in memory and answers the checks however the test says. */
function fakePool() {
const files = new Map<string, Uint8Array>();
@@ -259,6 +283,23 @@ describe("restoring from a picked backup", () => {
expect(pointer).toBe(CANDIDATE_NAME);
});
+ it("reads the file in slices rather than as one read for the whole of it", async () => {
+ const { files, pool } = fakePool();
+ const { target } = fakeTarget(pool);
+ const original = databaseBytes();
+ const backup = new Blob([ original ]);
+ const sliced = vi.spyOn(backup, "slice");
+ const streamed = vi.spyOn(backup, "stream");
+
+ await restoreDatabase(target, backup);
+
+ expect(files.get(CANDIDATE_NAME)).toEqual(original);
+ // One read living for the whole file is what a low-memory WebView was seen ending early,
+ // with nothing to say it had; bounded reads are what the chunked upload has always used.
+ expect(streamed).not.toHaveBeenCalled();
+ expect(sliced.mock.calls.length).toBeGreaterThan(1);
+ });
+
it("unwraps a container back into the database it was made from", async () => {
const { files, pool } = fakePool();
const { target } = fakeTarget(pool);
@@ -307,6 +348,43 @@ describe("restoring from a picked backup", () => {
});
});
+describe("reading a file in slices", () => {
+ /** Drains a stream the way the readers here do, a chunk at a time. */
+ async function collect(stream: ReadableStream<Uint8Array>): Promise<Uint8Array> {
+ const reader = stream.getReader();
+ const chunks: Uint8Array[] = [];
+ for (let next = await reader.read(); !next.done; next = await reader.read()) {
+ chunks.push(next.value);
+ }
+
+ return concat(chunks);
+ }
+
+ it("hands back exactly the file, whatever the slices fall across", async () => {
+ const bytes = Uint8Array.from({ length: 1000 }, (_, at) => at % 251);
+
+ // A size that divides the file evenly, one that leaves a remainder, and one larger than
+ // the file: the boundaries are the only thing this has to get right.
+ for (const sliceSize of [ 100, 128, 4096 ]) {
+ await expect(collect(readInSlices(new Blob([ bytes ]), sliceSize))).resolves.toEqual(bytes);
+ }
+ });
+
+ it("refuses to end quietly where the file gives less than it claims", async () => {
+ const real = Uint8Array.from({ length: 256 }, (_, at) => at);
+ const backup = {
+ size: 1024,
+ slice: (start: number, end: number) =>
+ new Blob([ real.slice(start, Math.min(end, real.length)) ])
+ } as unknown as Blob;
+
+ await expect(collect(readInSlices(backup, 64))).rejects.toMatchObject({
+ reason: "backup-incomplete",
+ message: expect.stringContaining("256")
+ });
+ });
+});
+
describe("a backup that cannot be restored", () => {
it("asks for a passphrase before reading an encrypted container, and imports nothing", async () => {
const { files, pool } = fakePool();
@@ -320,6 +398,37 @@ describe("a backup that cannot be restored", () => {
expect(pointer).toBeUndefined();
});
+ it("says a file that ends early is incomplete, in the bytes it had and the bytes it needed", async () => {
+ const { pool } = fakePool();
+ const { target } = fakeTarget(pool);
+ const real = databaseBytes();
+ // A file whose size claims more than it can give, which is the shape the Android WebView
+ // presented: the read stops and the reader can only take that at its word.
+ const backup = {
+ size: real.length * 4,
+ slice: (start: number, end: number) =>
+ new Blob([ real.slice(start, Math.min(end, real.length)) ])
+ } as unknown as Blob;
+
+ await expect(restoreDatabase(target, backup)).rejects.toMatchObject({
+ reason: "backup-incomplete",
+ message: expect.stringContaining(String(real.length))
+ });
+ });
+
+ it("refuses a streamed container the file is too small to hold, without reading it", async () => {
+ const { pool, files } = fakePool();
+ const { target } = fakeTarget(pool);
+ const whole = await streamedContainerOf(databaseBytes());
+
+ await expect(restoreDatabase(target, whole.slice(0, whole.size - 64)))
+ .rejects.toMatchObject({ reason: "backup-incomplete" });
+
+ // Settled from the header alone: a container states the size it should be, so an
+ // incomplete one costs a second rather than however long its payload would have taken.
+ expect(files.size).toBe(0);
+ });
+
it("refuses a file that is neither a database nor a backup", async () => {
const { pool } = fakePool();
const { target } = fakeTarget(pool);
diff --git a/apps/standalone/src/lightweight/database_restore.ts b/apps/standalone/src/lightweight/database_restore.ts
index 26ad136d24..636d44edf0 100644
--- a/apps/standalone/src/lightweight/database_restore.ts
+++ b/apps/standalone/src/lightweight/database_restore.ts
@@ -1,10 +1,12 @@
import type { SAHPoolUtil } from "@sqlite.org/sqlite-wasm";
import {
+ type BackupContainerInfo,
FIXED_HEADER_BYTES,
isBackupContainerError,
peekBackupContainer,
type ProgressCallback,
- readBackupContainer
+ readBackupContainer,
+ streamedContainerSize
} from "@triliumnext/backup-container/web";
import {
type CandidateDatabase,
@@ -167,7 +169,7 @@ async function stageCandidate(
}
if (!format.container) {
- await pool.importDb(candidate, pullFrom(backup.stream()));
+ await pool.importDb(candidate, pullFrom(readInSlices(backup)));
onProgress(1);
return;
}
@@ -179,7 +181,7 @@ async function stageCandidate(
}
const relay = new TransformStream<Uint8Array, Uint8Array>();
- const unwrapped = readBackupContainer(backup.stream(), relay.writable, { passphrase, onProgress });
+ const unwrapped = readBackupContainer(readInSlices(backup), relay.writable, { passphrase, onProgress });
const imported = pool.importDb(candidate, pullFrom(relay.readable));
// Awaited together: either failing has to stop the other, which is what a rejected pipe does.
@@ -400,12 +402,82 @@ async function readBackupFormat(backup: Blob): Promise<{ container: boolean; enc
const container = peekBackupContainer(head);
if (container) {
+ requireWholeContainer(container, backup.size);
+
return { container: true, encrypted: container.encrypted };
}
return looksLikeSqlite(head) ? { container: false, encrypted: false } : null;
}
+/**
+ * Refuses a container the file is too small to hold, before a minute of work goes into it.
+ *
+ * Only a streamed one can be measured this way: it is written front to back with no compression, so
+ * its length follows from the size it records. Anything else is compressed, or was written by a
+ * writer that could revisit its own header, and its length says nothing in advance.
+ */
+function requireWholeContainer(container: BackupContainerInfo, size: number): void {
+ if (!container.streamed || container.plaintextSize <= 0) {
+ return;
+ }
+
+ const expected = streamedContainerSize(container.plaintextSize, container.encrypted);
+ if (size < expected) {
+ throw incompleteBackup(size, expected);
+ }
+}
+
+/**
+ * Reads a file a slice at a time, rather than as one read that lives for the whole of it.
+ *
+ * `Blob.stream()` is that one long read, and a browser is free to end it early. A low-memory Android
+ * WebView was seen doing exactly that with a complete 4.8 GB backup: the same byte every time, no
+ * error, just an end of input that a reader can only take at its word — which surfaced as a container
+ * that had run out of frames. Asking for a bounded range at a time is what the chunked upload has
+ * always done with files this size on the same hardware, and it is how the header below is read.
+ *
+ * Reaching the end before the file says it should is a failure here rather than silence, so a file
+ * that really is short says so in its own terms instead of through whatever was parsing it.
+ */
+export function readInSlices(blob: Blob, sliceSize = SLICE_BYTES): ReadableStream<Uint8Array> {
+ let offset = 0;
+
+ return new ReadableStream<Uint8Array>({
+ async pull(controller) {
+ if (offset >= blob.size) {
+ controller.close();
+ return;
+ }
+
+ const end = Math.min(offset + sliceSize, blob.size);
+ const slice = new Uint8Array(await blob.slice(offset, end).arrayBuffer());
+ if (slice.length === 0) {
+ throw incompleteBackup(offset, blob.size);
+ }
+
+ offset += slice.length;
+ controller.enqueue(slice);
+ }
+ });
+}
+
+/**
+ * How much is asked for at once: large enough that the per-read cost is lost against the work done
+ * with it, small enough that a device with very little memory never holds much. The container reads
+ * in frames a quarter of this size, and the stream keeps one slice queued.
+ */
+const SLICE_BYTES = 4 * 1024 * 1024;
+
+/** A file that stops before it should have, said in bytes because that is what makes it checkable. */
+function incompleteBackup(read: number, expected: number): RestoreFailure {
+ return new RestoreFailure(
+ "backup-incomplete",
+ `The backup file ends after ${read} bytes, short of the ${expected} it should hold. `
+ + "It was probably not copied or downloaded in full."
+ );
+}
+
/** Turns a stream into the pull `importDb` asks for: a chunk each call, nothing at the end. */
function pullFrom(stream: ReadableStream<Uint8Array>): () => Promise<Uint8Array | undefined> {
const reader = stream.getReader();