Skip to content

Build your personal knowledge base with Trilium Notes

standalone/backup: improve the backup writing speed

Adorian Dorand90949ceb3b7
diff --git a/apps/standalone/src/lightweight/backup-download.spec.ts b/apps/standalone/src/lightweight/backup-download.spec.ts
index 349d8a528d..a5707a1731 100644
--- a/apps/standalone/src/lightweight/backup-download.spec.ts
+++ b/apps/standalone/src/lightweight/backup-download.spec.ts
@@ -15,10 +15,13 @@ 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);
- }
+ getColumn(_sql: string, params?: unknown[]) {
+ const [ first, last ] = params as [ number, number ];
+
+ return Array.from({ length: last - first + 1 }, (_unused, index) =>
+ new Uint8Array(PAGE_SIZE).fill((first + index) & 0xff));
+ },
+ getValue(sql: string) {
if (sql.includes("page_size")) {
return PAGE_SIZE;
}
@@ -172,7 +175,7 @@ describe("streamDatabaseDownload", () => {
it("reports a database that cannot even be sized, before any begin", async () => {
const port = fakePort();
- const outcome = await streamDatabaseDownload({ getValue: () => 0 }, port);
+ const outcome = await streamDatabaseDownload({ getValue: () => 0, getColumn: () => [] }, port);
expect(outcome).toMatchObject({ status: "failed" });
expect(port.sent).toHaveLength(1);
@@ -184,8 +187,9 @@ describe("streamDatabaseDownload", () => {
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)
+ getValue: (sql, params) => reader.getValue(sql, params),
+ getColumn: (sql, params) =>
+ (reader.getColumn(sql, params) as Uint8Array[]).map(() => new Uint8Array(3))
};
const port = fakePort();
const running = streamDatabaseDownload(broken, port);
diff --git a/apps/standalone/src/lightweight/backup-download.ts b/apps/standalone/src/lightweight/backup-download.ts
index b98e230744..3df12125b8 100644
--- a/apps/standalone/src/lightweight/backup-download.ts
+++ b/apps/standalone/src/lightweight/backup-download.ts
@@ -4,7 +4,11 @@ import {
writeBackupContainer
} from "@triliumnext/backup-container/web";
-import { type LiveDatabaseReader, streamLiveDatabasePages } from "./backup-stream.js";
+import {
+ type LiveDatabaseReader,
+ streamLiveDatabasePages,
+ type StreamTiming
+} from "./backup-stream.js";
/**
* Feeds a database backup into a download the service worker is holding open.
@@ -110,9 +114,21 @@ export async function streamDatabaseDownload(
return requests.shift() ?? "cancel";
};
+ /**
+ * How long was spent with a chunk ready and nowhere to put it.
+ *
+ * The one thing this side cannot make faster: the browser asks for the next piece as it commits
+ * the last one to disk, so a large figure here means the download itself is the limit and no
+ * amount of reading or hashing faster would show up in the total.
+ */
+ let waitedMs = 0;
+
/** Posts one chunk per granted pull, or throws the stop that was granted instead. */
const sendChunk = async (chunk: Uint8Array): Promise<void> => {
+ const waitingSince = Date.now();
const request = await nextRequest();
+ waitedMs += Date.now() - waitingSince;
+
if (request !== "pull") {
throw new DownloadStopped(request);
}
@@ -125,8 +141,9 @@ export async function streamDatabaseDownload(
};
let source: ReadableStream<Uint8Array> | undefined;
+ const startedAt = Date.now();
try {
- const { byteSize, stream } = streamLiveDatabasePages(db);
+ const { byteSize, stream, timing } = streamLiveDatabasePages(db);
source = stream;
// A container either way, so every backup this application writes has one shape and one
@@ -147,6 +164,8 @@ export async function streamDatabaseDownload(
}
);
port.postMessage({ type: "end" });
+ reportTiming(byteSize, timing, waitedMs, Date.now() - startedAt);
+
return { status: "done" };
} catch (e) {
if (e instanceof DownloadStopped) {
@@ -169,6 +188,34 @@ export async function streamDatabaseDownload(
}
}
+/**
+ * One line saying where a backup's time went, split three ways so a slow one can be acted on.
+ *
+ * `read` is the database coming out through SQLite, `waiting` is having a chunk ready and the
+ * download not yet asking for it, and what neither accounts for is the hashing and encryption in
+ * between. Only the first is worth optimising: waiting is the browser committing the file to disk,
+ * which is the floor, and the rest is a hash the format cannot do without.
+ */
+function reportTiming(
+ byteSize: number,
+ timing: StreamTiming,
+ waitedMs: number,
+ totalMs: number
+): void {
+ const mib = byteSize / (1024 * 1024);
+ const rate = (ms: number) => (ms > 0 ? mib / (ms / 1000) : 0).toFixed(1);
+ const share = (ms: number) => Math.round(100 * ms / Math.max(totalMs, 1));
+ const restMs = Math.max(0, totalMs - timing.readMs - waitedMs);
+
+ console.log(
+ `[Backup] ${mib.toFixed(0)} MiB in ${(totalMs / 1000).toFixed(1)}s (${rate(totalMs)} MiB/s). `
+ + `Reads ${(timing.readMs / 1000).toFixed(1)}s (${share(timing.readMs)}%, `
+ + `${rate(timing.readMs)} MiB/s over ${timing.pages} pages), `
+ + `waiting on the download ${(waitedMs / 1000).toFixed(1)}s (${share(waitedMs)}%), `
+ + `hashing and crypto ${(restMs / 1000).toFixed(1)}s (${share(restMs)}%).`
+ );
+}
+
/** 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 {
diff --git a/apps/standalone/src/lightweight/backup-stream.spec.ts b/apps/standalone/src/lightweight/backup-stream.spec.ts
index 0c1e7ff079..7ae0737e91 100644
--- a/apps/standalone/src/lightweight/backup-stream.spec.ts
+++ b/apps/standalone/src/lightweight/backup-stream.spec.ts
@@ -49,7 +49,10 @@ async function drain(stream: ReadableStream<Uint8Array>): Promise<Uint8Array> {
describe("streamLiveDatabasePages against the real engine", () => {
function readerFor(provider: BrowserSqlProvider): LiveDatabaseReader {
- return { getValue: (sql, params) => provider.prepare(sql).pluck().get(params ?? []) };
+ return {
+ getValue: (sql, params) => provider.prepare(sql).pluck().get(params ?? []),
+ getColumn: (sql, params) => provider.prepare(sql).pluck().all(params ?? []) as unknown[]
+ };
}
function populatedProvider(): BrowserSqlProvider {
@@ -98,11 +101,21 @@ describe("streamLiveDatabasePages against the real engine", () => {
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
+ getValue: (sql) =>
+ sql.includes("page_size") ? 512 : sql.includes("page_count") ? 4 : 0,
+ // A page short of what the page size says it must be, four times over.
+ getColumn: () => Array.from({ length: 4 }, () => new Uint8Array(3))
};
await expect(drain(streamLiveDatabasePages(reader).stream)).rejects.toThrow(/malformed/);
});
+
+ it("errors the stream when the range comes back short of the pages it asked for", async () => {
+ const reader: LiveDatabaseReader = {
+ getValue: (sql) =>
+ sql.includes("page_size") ? 512 : sql.includes("page_count") ? 4 : 0,
+ getColumn: () => [ new Uint8Array(512) ]
+ };
+ await expect(drain(streamLiveDatabasePages(reader).stream)).rejects.toThrow(/got 1 of 4/);
+ });
});
diff --git a/apps/standalone/src/lightweight/backup-stream.ts b/apps/standalone/src/lightweight/backup-stream.ts
index f595939507..2e8f9ad3eb 100644
--- a/apps/standalone/src/lightweight/backup-stream.ts
+++ b/apps/standalone/src/lightweight/backup-stream.ts
@@ -15,12 +15,29 @@
* @module
*/
-/** How many pages travel per stream chunk: 1 MiB at the default 8 KiB page size. */
-const BATCH_PAGES = 128;
+/**
+ * How many pages are fetched, and travel, per stream chunk.
+ *
+ * One statement covers the whole batch, so this is the number of rows a single query steps through
+ * rather than the number of queries. Larger batches therefore cost almost nothing extra in
+ * round trips and only buy fewer of them, while the memory held is one batch: 4 MiB at an 8 KiB
+ * page, 2 MiB at 4 KiB, which the container immediately re-cuts into its own 1 MiB frames.
+ */
+const BATCH_PAGES = 512;
/** 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;
+ /** One column of every row, which is how a whole batch of pages arrives in one statement. */
+ getColumn(sql: string, params?: unknown[]): unknown[];
+}
+
+/** What the read cost, for a caller that wants to say where a slow backup spent its time. */
+export interface StreamTiming {
+ /** Milliseconds spent inside the page reads, as against waiting on whatever consumes them. */
+ readMs: number;
+ /** Pages handed over so far. */
+ pages: number;
}
/** Thrown by {@link streamLiveDatabasePages} when a write lands mid-stream. The caller retries. */
@@ -35,6 +52,8 @@ export interface DatabaseStream {
/** Exact size of the streamed database, known before the first byte flows. */
byteSize: number;
stream: ReadableStream<Uint8Array>;
+ /** Updated as the stream runs, so a caller can report where the time went. */
+ timing: StreamTiming;
}
/**
@@ -56,11 +75,15 @@ export function streamLiveDatabasePages(db: LiveDatabaseReader): DatabaseStream
const pageCount = countOf(db.getValue("PRAGMA page_count"), "page_count");
const fingerprint = fingerprintOf(db);
+ const timing: StreamTiming = { readMs: 0, pages: 0 };
let nextPage = 1;
+
return {
byteSize: pageSize * pageCount,
+ timing,
stream: new ReadableStream<Uint8Array>({
pull(controller) {
+ const startedAt = Date.now();
try {
if (fingerprintOf(db) !== fingerprint) {
throw new DatabaseChangedError();
@@ -71,26 +94,54 @@ export function streamLiveDatabasePages(db: LiveDatabaseReader): 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(readLivePage(db, nextPage, pageSize), index * pageSize);
- }
+ const batch = readLivePages(db, nextPage, pages, pageSize);
+ nextPage += pages;
+ timing.pages += pages;
+
controller.enqueue(batch);
} catch (e) {
controller.error(e);
+ } finally {
+ timing.readMs += Date.now() - startedAt;
}
}
})
};
}
-/** 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.`);
+/**
+ * A run of pages, in one statement rather than one per page.
+ *
+ * This is the whole of what a backup costs to read, and the difference between the two shapes is
+ * not small: a page at a time means preparing, binding, stepping and finalising a query against a
+ * virtual table for every page in the database, which for a multi-gigabyte one is over a million
+ * round trips into WebAssembly. Stepping one statement across the range does the same work once.
+ */
+function readLivePages(
+ db: LiveDatabaseReader,
+ firstPage: number,
+ pages: number,
+ pageSize: number
+): Uint8Array {
+ const rows = db.getColumn(
+ "SELECT data FROM sqlite_dbpage WHERE pgno BETWEEN ? AND ? ORDER BY pgno",
+ [ firstPage, firstPage + pages - 1 ]
+ );
+
+ if (rows.length !== pages) {
+ throw new Error(`Pages ${firstPage} to ${firstPage + pages - 1}: got ${rows.length} of ${pages}.`);
}
- return data;
+
+ const batch = new Uint8Array(pages * pageSize);
+ for (let index = 0; index < pages; index++) {
+ const data = rows[index];
+ if (!(data instanceof Uint8Array) || data.byteLength !== pageSize) {
+ throw new Error(`Page ${firstPage + index} came back malformed.`);
+ }
+ batch.set(data, index * pageSize);
+ }
+
+ return batch;
}
/**
diff --git a/apps/standalone/src/local-server-worker.ts b/apps/standalone/src/local-server-worker.ts
index cca72c340c..5245afdc51 100644
--- a/apps/standalone/src/local-server-worker.ts
+++ b/apps/standalone/src/local-server-worker.ts
@@ -543,7 +543,10 @@ async function handleBackupStream(port: MessagePort, passphrase?: string): Promi
const { streamDatabaseDownload } = await import("./lightweight/backup-download.js");
const result = await streamDatabaseDownload(
- { getValue: (sql, params) => core.getSql().getValue(sql, params) },
+ {
+ getValue: (sql, params) => core.getSql().getValue(sql, params),
+ getColumn: (sql, params) => core.getSql().getColumn(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,