Skip to content

Build your personal knowledge base with Trilium Notes

Merge branch 'main' of https://github.com/TriliumNext/Trilium into feat/backup-import-3

Adorian Doran3e2a40be7a17
diff --cc apps/standalone/src/lightweight/browser_routes.ts
index 73c2dfbbb1,f7bfb04359..79ef40ef2d
--- a/apps/standalone/src/lightweight/browser_routes.ts
+++ b/apps/standalone/src/lightweight/browser_routes.ts
@@@ -130,10 -131,12 +131,12 @@@ function createRoute(router: BrowserRou
* transactional() wrapper, which would commit an empty transaction immediately when
* passed an async callback.
*/
-function createAsyncRoute(router: BrowserRouter) {
+function createAsyncRoute(router: BrowserRouter, { transactional = true } = {}) {
return (method: HttpMethod, path: string, _middleware: any[], handler: (req: any, res: any) => Promise<unknown>, resultHandler?: ((req: any, res: any, result: unknown) => unknown) | null) => {
router.register(method, path, (req: BrowserRequest) => {
- return getContext().init(async () => {
+ // Exclusive: this transaction stays open across awaits, so no other
+ // route may touch the connection until it commits. See db_lock.ts.
+ return dbLock.runExclusive(() => getContext().init(async () => {
setContextFromHeaders(req);
const expressLikeReq = toExpressLikeReq(req);
const mockRes = createMockExpressResponse();
diff --cc apps/standalone/src/local-bridge.spec.ts
index bd696360bf,7418f878d0..25b3ad9937
--- a/apps/standalone/src/local-bridge.spec.ts
+++ b/apps/standalone/src/local-bridge.spec.ts
@@@ -47,8 -55,7 +55,9 @@@ function lastWorker(): MockWorker
afterEach(() => {
delete (navigator as unknown as NavServiceWorker).serviceWorker;
+ // Download frames pile up across tests otherwise: their removal timers never get to run.
+ document.querySelectorAll("iframe").forEach((frame) => frame.remove());
+ document.getElementById("trilium-error-overlay")?.remove();
vi.restoreAllMocks();
});
@@@ -513,4 -428,115 +529,142 @@@ describe("restoreBackup", () =>
expect(() => worker.onmessage?.({ data: { type: "RESTORE_PROGRESS", id: "other", progress: {} } }))
.not.toThrow();
});
+
+ it("refuses in a follower rather than opening a second database", async () => {
+ const bridge = await freshBridge();
+ leadership.isLeader = false;
+
+ await expect(bridge.restoreBackup({ backup: new File([ "bytes" ], "backup.db") }))
+ .rejects.toThrow(/tab that owns the database/);
+ expect(workerInstances).toHaveLength(0);
+ });
+ });
+
+ describe("leadership", () => {
+ it("a follower refuses to serve and never starts a worker", async () => {
+ const bridge = await freshBridge();
+ bridge.attachServiceWorkerBridge();
+ leadership.isLeader = false;
+
+ const port = { postMessage: vi.fn() };
+ await swHandler?.({
+ data: { type: "LOCAL_FETCH", id: "9", request: { method: "GET", url: "/api/x", headers: {} } },
+ ports: [port]
+ });
+
+ // Starting a worker here would open a second database against the same
+ // OPFS pool — the exact failure leadership exists to prevent.
+ expect(workerInstances).toHaveLength(0);
+ expect(port.postMessage).toHaveBeenCalledWith({ type: "NOT_LEADER", id: "9" });
+ });
+
+ it("answers the service worker's leader probe", async () => {
+ const bridge = await freshBridge();
+ bridge.attachServiceWorkerBridge();
+
+ const leaderPort = { postMessage: vi.fn() };
+ await swHandler?.({ data: { type: "WHO_IS_LEADER" }, ports: [leaderPort] });
+ expect(leaderPort.postMessage).toHaveBeenCalledWith({ type: "LEADER_REPLY", isLeader: true });
+
+ leadership.isLeader = false;
+ const followerPort = { postMessage: vi.fn() };
+ await swHandler?.({ data: { type: "WHO_IS_LEADER" }, ports: [followerPort] });
+ expect(followerPort.postMessage).toHaveBeenCalledWith({ type: "LEADER_REPLY", isLeader: false });
+ });
+
++ it("a follower refuses a backup stream rather than starting a worker for it", async () => {
++ const bridge = await freshBridge();
++ bridge.attachServiceWorkerBridge();
++ leadership.isLeader = false;
++
++ const port = { postMessage: vi.fn() };
++ await swHandler?.({ data: { type: "LOCAL_BACKUP_STREAM" }, ports: [port] });
++
++ expect(workerInstances).toHaveLength(0);
++ // Said on the port, so the download answers 503 instead of hanging on a stream
++ // no worker will ever produce.
++ expect(port.postMessage).toHaveBeenCalledWith(
++ expect.objectContaining({ type: "error" }));
++ });
++
++ it("a follower refuses to download a backup, since the passphrase never leaves its tab", async () => {
++ const bridge = await freshBridge();
++ leadership.isLeader = false;
++
++ const result = await bridge.downloadDatabase("Backup.tnbackup", "123456");
++
++ expect(result).toMatchObject({ status: "failed" });
++ expect(workerInstances).toHaveLength(0);
++ // Nothing was navigated either: a frame would have downloaded an unencrypted backup.
++ expect(document.querySelector("iframe")).toBeNull();
++ });
++
+ it("announceLeadership tells the controlling service worker", async () => {
+ const bridge = await freshBridge();
+ const controller = { postMessage: vi.fn() };
+ Object.defineProperty(navigator, "serviceWorker", {
+ value: { addEventListener: vi.fn(), controller },
+ configurable: true
+ });
+
+ bridge.announceLeadership();
+ expect(controller.postMessage).toHaveBeenCalledWith({ type: "LEADER_ANNOUNCE" });
+ });
+
+ it("survives announcing with no controlling service worker", async () => {
+ const bridge = await freshBridge(false);
+ expect(() => bridge.announceLeadership()).not.toThrow();
+ });
+ });
+
+ describe("cross-tab ws relay", () => {
+ it("relays the worker's ws messages to the other tabs", async () => {
+ const posted: unknown[] = [];
+ class MockBroadcastChannel {
+ onmessage: ((e: { data: unknown }) => void) | null = null;
+ postMessage = vi.fn((m: unknown) => { posted.push(m); });
+ close = vi.fn();
+ }
+ vi.stubGlobal("BroadcastChannel", MockBroadcastChannel);
+
+ const bridge = await freshBridge();
+ bridge.startLocalServerWorker();
+ lastWorker().onmessage?.({ data: { type: "WS_MESSAGE", message: { kind: "entity-change" } } });
+
+ // Only the leader has a worker, so without this relay a follower would
+ // never learn the entity changed.
+ expect(posted).toEqual([{ kind: "entity-change" }]);
+ vi.unstubAllGlobals();
+ });
+
+ it("dispatches a relayed message into this tab", async () => {
+ const channels: MockBroadcastChannel[] = [];
+ class MockBroadcastChannel {
+ onmessage: ((e: { data: unknown }) => void) | null = null;
+ postMessage = vi.fn();
+ close = vi.fn();
+ constructor() { channels.push(this); }
+ }
+ vi.stubGlobal("BroadcastChannel", MockBroadcastChannel);
+
+ const bridge = await freshBridge();
+ bridge.attachServiceWorkerBridge();
+ const dispatchSpy = vi.spyOn(window, "dispatchEvent");
+
+ channels.at(-1)?.onmessage?.({ data: { kind: "from-leader" } });
+
+ const event = dispatchSpy.mock.calls.at(-1)?.[0] as CustomEvent;
+ expect(event.type).toBe("trilium:ws-message");
+ expect(event.detail).toEqual({ kind: "from-leader" });
+ vi.unstubAllGlobals();
+ });
+
+ it("works when BroadcastChannel is unavailable", async () => {
+ vi.stubGlobal("BroadcastChannel", undefined);
+ const bridge = await freshBridge();
+ bridge.startLocalServerWorker();
+
+ expect(() => lastWorker().onmessage?.({ data: { type: "WS_MESSAGE", message: { kind: "x" } } })).not.toThrow();
+ vi.unstubAllGlobals();
+ });
});
diff --cc apps/standalone/src/local-bridge.ts
index e4a2d7ffbc,6354b59814..888305b4c6
--- a/apps/standalone/src/local-bridge.ts
+++ b/apps/standalone/src/local-bridge.ts
@@@ -1,9 -1,7 +1,11 @@@
-import type { StandaloneRestoreProgress, StandaloneRestoreResult } from "@triliumnext/commons";
+import type {
+ StandaloneDownloadResult,
+ StandaloneRestoreProgress,
+ StandaloneRestoreResult
+} from "@triliumnext/commons";
+ import { showErrorOverlay } from "./error-overlay.js";
+ import { isLeader } from "./leader_election.js";
import LocalServerWorker from "./local-server-worker?worker";
let localWorker: Worker | null = null;
const pending = new Map();
@@@ -45,99 -93,6 +97,111 @@@ export function restoreBackup(opts:
});
}
+/**
+ * How long the download's frame is kept in the page: comfortably past the service worker's own
+ * 30-second wait for the stream to open, after which the response has either been handed to the
+ * browser's download manager, which no longer needs the frame, or failed inside it invisibly.
+ */
+const DOWNLOAD_FRAME_LINGER_MS = 60_000;
+
+/** Well inside the ~30 seconds of eventlessness after which browsers reclaim a service worker. */
+const BACKUP_PING_INTERVAL_MS = 10_000;
+
+let backupPing: ReturnType<typeof setInterval> | null = null;
+
+/**
+ * Keeps the service worker alive while it streams a backup download, by fetching a no-op URL it
+ * answers: a fetch event is what resets the browser's idle clock on it. Runs for exactly as long
+ * as the local worker says a stream is running, and never twice at once.
+ */
+function setBackupPinging(active: boolean): void {
+ if (active && !backupPing) {
+ backupPing = setInterval(
+ () => void fetch("/local-backup-ping").catch(() => undefined),
+ BACKUP_PING_INTERVAL_MS
+ );
+ } else if (!active && backupPing) {
+ clearInterval(backupPing);
+ backupPing = null;
+ }
+}
+
+/** How long the chain gets to reach the worker and open the stream before it is called dead. */
+const DOWNLOAD_START_TIMEOUT_MS = 45_000;
+
+/** The one download in flight, waiting for the worker to say how the stream ended. */
+let pendingDownload: {
+ resolve: (result: StandaloneDownloadResult) => void;
+ startTimer: ReturnType<typeof setTimeout>;
+} | null = null;
+
+/** Carried from {@link downloadDatabase} to the stream relay, so it never rides the URL. */
+let pendingDownloadPassphrase: string | undefined;
+
+/**
+ * Hands the browser a download of the live database, streamed by the service worker.
+ *
+ * A navigation rather than a request: the URL is answered by the service worker with a response
+ * body it pulls from the local worker chunk by chunk, so the browser's own download manager
+ * receives, shows and stores the file, and nothing is staged in the origin's storage first.
+ * The worker is started here because the service worker's first act is to ask the page for it.
+ * The passphrase, when there is one, travels to the worker on the relayed message, never in the
+ * URL a browser would put in its history.
+ *
+ * The navigation is a hidden iframe rather than an anchor click: anchors with the `download`
+ * attribute are not routed through service workers everywhere (Firefox never sends them there),
+ * while a frame's navigation always is, and the response's `Content-Disposition` is what makes it
+ * a download either way. A failure renders invisibly inside the frame instead of navigating the
+ * application away.
+ *
+ * Resolves when the worker has finished producing the stream, one way or the other — which is as
+ * close to "the download finished" as anything on this side of the browser's download manager can
+ * see. A chain that dies silently inside the hidden frame (a stale service worker, say) resolves
+ * as failed after a timeout rather than never.
++ *
++ * Only the leader tab can do this, as for a restore: the worker that streams the database is the
++ * 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> {
++ if (!isLeader()) {
++ return Promise.resolve({
++ status: "failed",
++ message: "A backup can only be downloaded from the tab that owns the database. "
++ + "Close the other Trilium tabs and try again."
++ });
++ }
++
+ startLocalServerWorker();
+ // A newer download supersedes one still unaccounted for, rather than stacking behind it.
+ settlePendingDownload({ status: "cancelled" });
+ pendingDownloadPassphrase = passphrase;
+
+ const frame = document.createElement("iframe");
+ frame.hidden = true;
+ frame.src = `/local-backup-download?fileName=${encodeURIComponent(fileName)}`;
+ document.body.appendChild(frame);
+ setTimeout(() => frame.remove(), DOWNLOAD_FRAME_LINGER_MS);
+
+ return new Promise((resolve) => {
+ pendingDownload = {
+ resolve,
+ startTimer: setTimeout(
+ () => settlePendingDownload({ status: "failed", message: "The download did not start." }),
+ DOWNLOAD_START_TIMEOUT_MS
+ )
+ };
+ });
+}
+
+function settlePendingDownload(result: StandaloneDownloadResult): void {
+ if (pendingDownload) {
+ clearTimeout(pendingDownload.startTimer);
+ pendingDownload.resolve(result);
+ pendingDownload = null;
+ }
+}
+
export function isLocalApiRequest(url: URL): boolean {
return LOCAL_API_PREFIXES.some(p => url.pathname.startsWith(p));
}
@@@ -334,23 -284,13 +411,41 @@@ export function attachServiceWorkerBrid
navigator.serviceWorker.addEventListener("message", async (event) => {
const msg = event.data;
+ // The service worker lost track of the leader and is probing for it.
+ if (msg?.type === "WHO_IS_LEADER") {
+ const replyPort = event.ports && event.ports[0];
+ replyPort?.postMessage({ type: "LEADER_REPLY", isLeader: isLeader() });
+ return;
+ }
+
+ // A backup download's channel: handed straight through to the worker, which streams the
+ // database into it. The page is only the relay, because the service worker cannot reach
+ // the local worker itself.
+ if (msg?.type === "LOCAL_BACKUP_STREAM") {
+ const streamPort = event.ports && event.ports[0];
- if (streamPort) {
- startLocalServerWorker();
- localWorker?.postMessage({
- type: "BACKUP_STREAM",
- port: streamPort,
- passphrase: pendingDownloadPassphrase
- }, [ streamPort ]);
- pendingDownloadPassphrase = undefined;
++ if (!streamPort) {
++ return;
++ }
++
++ // As for any other request: only the leader has a worker, and starting one here
++ // would open a second database. The download is refused rather than served wrongly.
++ if (!isLeader()) {
++ streamPort.postMessage({
++ type: "error",
++ message: "This tab does not own the database."
++ });
++ return;
+ }
++
++ startLocalServerWorker().postMessage({
++ type: "BACKUP_STREAM",
++ port: streamPort,
++ passphrase: pendingDownloadPassphrase
++ }, [ streamPort ]);
++ pendingDownloadPassphrase = undefined;
+ return;
+ }
+
if (!msg || msg.type !== "LOCAL_FETCH") return;
const port = event.ports && event.ports[0];
diff --cc apps/standalone/src/local-server-worker.ts
index acbfdceccc,a53b8ebec9..b9973c7fb0
--- a/apps/standalone/src/local-server-worker.ts
+++ b/apps/standalone/src/local-server-worker.ts
@@@ -49,15 -49,6 +49,10 @@@ console.log("[Worker] Error handlers in
import type { BrowserRouter } from './lightweight/browser_router';
import type { StandaloneRestoreProgress, StandaloneRestoreResult } from "@triliumnext/commons";
- import {
- DEFAULT_DATABASE_NAME,
- readCurrentDatabaseName,
- RestoreFailure,
- restoreDatabase,
- writeCurrentDatabaseName
- } from './lightweight/database_restore';
- import { consumeSetupMarker, removeSetupMarker, writeSetupMarker } from './lightweight/setup_marker';
++// Nothing that opens a database or a backup is imported statically: both reach for the backup
++// container and the whole of core, and evaluating those at worker startup is what kept the iOS
++// worker from booting. Every use below loads its module when it is actually needed.
+
// Build-time constant injected by Vite (see `define` in vite.config.mts).
declare const __TRILIUM_INTEGRATION_TEST__: string;
@@@ -269,6 -251,6 +265,11 @@@ async function initialize(): Promise<vo
logService.info("[Worker] Loading @triliumnext/core...");
const schemaModule = await import("@triliumnext/core/src/assets/schema.sql?raw");
coreModule = await import("@triliumnext/core");
++ const {
++ consumeSetupMarker,
++ removeSetupMarker,
++ writeSetupMarker
++ } = await import('./lightweight/setup_marker.js');
await coreModule.initializeCore({
executionContext: new BrowserExecutionContext(),
@@@ -389,32 -363,6 +390,38 @@@ async function dispatch(request: LocalR
return appRouter.dispatch(request.method, request.url, request.body, request.headers);
}
+/**
+ * Erases the database the wizard was booted away from, and leaves an empty one in its place.
+ *
+ * The pool has no notion of "no database", and everything after this point in the wizard writes to
+ * one: creating a document, converging a sync. So the entry is unlinked and a fresh one opened under
+ * the name a first run uses, which is exactly the state a browser that had never run Trilium is in.
+ */
+async function removeStandaloneDatabase(): Promise<void> {
+ const pool = sqlProvider?.sahPool;
+ if (!sqlProvider || !pool) {
+ throw new Error("The database is not open, so there is nothing to erase.");
+ }
+
++ const {
++ DEFAULT_DATABASE_NAME,
++ readCurrentDatabaseName,
++ writeCurrentDatabaseName
++ } = await import('./lightweight/database_restore.js');
++
+ const live = await readCurrentDatabaseName();
+ sqlProvider.close();
+
+ try {
+ pool.unlink(live);
+ } catch {
+ // Already gone, which is the state the caller asked for.
+ }
+
+ await writeCurrentDatabaseName(DEFAULT_DATABASE_NAME);
+ sqlProvider.loadFromSahPool(DEFAULT_DATABASE_NAME);
+}
+
/**
* Restores the database from a backup handed straight to this worker.
*
diff --cc apps/standalone/src/main.spec.ts
index b81dcdae40,a945b3460e..c34bf4d932
--- a/apps/standalone/src/main.spec.ts
+++ b/apps/standalone/src/main.spec.ts
@@@ -5,7 -5,7 +5,8 @@@ const mocks = vi.hoisted(() => (
attachServiceWorkerBridge: vi.fn(),
registerNativeHttpHandler: vi.fn(),
restoreBackup: vi.fn(),
+ downloadDatabase: vi.fn(),
+ announceLeadership: vi.fn(),
capacitorHttpHandler: vi.fn()
}));
@@@ -14,7 -18,14 +19,15 @@@ vi.mock("./local-bridge.js", () => (
attachServiceWorkerBridge: mocks.attachServiceWorkerBridge,
registerNativeHttpHandler: mocks.registerNativeHttpHandler,
restoreBackup: mocks.restoreBackup,
- downloadDatabase: mocks.downloadDatabase
++ downloadDatabase: mocks.downloadDatabase,
+ announceLeadership: mocks.announceLeadership
+ }));
+ vi.mock("./leader_election.js", () => ({
+ claimLeadership: (onElected: () => void) => {
+ if (leadership.elected) {
+ onElected();
+ }
+ }
}));
vi.mock("./services/capacitor_http_handler.js", () => ({ capacitorHttpHandler: mocks.capacitorHttpHandler }));
// Avoid pulling the entire client bundle when loadScripts() runs.
diff --cc apps/standalone/src/main.ts
index 91fbde2264,e55434ba3d..2c1af48419
--- a/apps/standalone/src/main.ts
+++ b/apps/standalone/src/main.ts
@@@ -1,5 -1,7 +1,7 @@@
+ import { showErrorOverlay } from "./error-overlay.js";
import { installIosInterceptors } from "./ios-interceptors.js";
- import { attachServiceWorkerBridge, downloadDatabase, registerNativeHttpHandler, restoreBackup, startLocalServerWorker } from "./local-bridge.js";
+ import { claimLeadership } from "./leader_election.js";
-import { announceLeadership, attachServiceWorkerBridge, registerNativeHttpHandler, restoreBackup, startLocalServerWorker } from "./local-bridge.js";
++import { announceLeadership, attachServiceWorkerBridge, downloadDatabase, registerNativeHttpHandler, restoreBackup, startLocalServerWorker } from "./local-bridge.js";
async function waitForServiceWorkerControl(): Promise<void> {
if (!("serviceWorker" in navigator) || !navigator.serviceWorker) {
diff --cc apps/standalone/src/sw.ts
index 5e2723422b,158022e204..c16d12089f
--- a/apps/standalone/src/sw.ts
+++ b/apps/standalone/src/sw.ts
@@@ -92,26 -92,67 +92,78 @@@ async function networkFirst(request)
/* v8 ignore stop */
}
+ // Only one tab owns the database (it holds the Web Lock and is the only one with
+ // a worker), so every tab's API traffic has to reach that specific tab. This is
+ // a cache: the service worker is evicted when idle and loses it, so a miss falls
+ // back to probing the open tabs.
+ let leaderClientId = null;
+
+ self.addEventListener("message", (event) => {
+ if (event.data?.type === "LEADER_ANNOUNCE" && event.source) {
+ leaderClientId = event.source.id;
+ }
+ });
+
+ function isMainAppWindow(client) {
+ const url = new URL(client.url);
+ // Main app is at root or index.html, not in /pdfjs/ or other iframe paths,
+ // which have no local bridge of their own.
+ return !url.pathname.startsWith("/pdfjs/");
+ }
+
+ /**
+ * Ask each candidate tab whether it is the leader. Used when the cached id is
+ * missing or stale; the answer is cached again for subsequent requests.
+ */
+ async function findLeader(candidates) {
+ for (const candidate of candidates) {
+ const channel = new MessageChannel();
+ const replied = new Promise((resolve) => {
+ const timeout = setTimeout(() => resolve(null), 1_000);
+ channel.port1.onmessage = (event) => {
+ clearTimeout(timeout);
+ resolve(event.data);
+ };
+ });
+
+ candidate.postMessage({ type: "WHO_IS_LEADER" }, [channel.port2]);
+ const answer = await replied;
+ if (answer?.isLeader) {
+ leaderClientId = candidate.id;
+ return candidate;
+ }
+ }
+ return null;
+ }
+
-async function forwardToClientLocalServer(request, _clientId, retried = false) {
+/**
- * The main app window, which is the one carrying the local bridge — not an iframe like the
- * PDF.js viewer. Falls back to any window, and to null where there is none at all.
++ * The tab that owns the database, which is the only one that can answer for it: the cached leader
++ * while it is still open, otherwise whichever tab answers the probe, and failing both the first app
++ * window — which replies NOT_LEADER if it is not the one, leaving the caller to retry.
+ */
- async function findMainClient() {
++async function findLeaderClient() {
// @ts-expect-error - self.clients is valid in service worker context
const all = await self.clients.matchAll({ type: "window", includeUncontrolled: true });
+ const candidates = all.filter(isMainAppWindow);
- const client = all.find((c: { url: string }) => {
- const url = new URL(c.url);
- // Main app is at root or index.html, not in /pdfjs/ or other iframe paths
- return !url.pathname.startsWith("/pdfjs/");
- }) || null;
+ let client = candidates.find((c) => c.id === leaderClientId) || null;
+ if (!client) {
+ client = await findLeader(candidates);
+ }
- return client || all[0] || null;
+ // No leader answered (e.g. the old one is closing and the next has not been
+ // promoted yet). Fall back to the first app window rather than dropping the
+ // request; if it is not the leader it replies NOT_LEADER and we retry below.
+ if (!client) {
+ client = candidates[0] || all[0] || null;
+ }
+
++ return { client, candidates };
+}
+
- async function forwardToClientLocalServer(request, _clientId) {
- const client = await findMainClient();
++async function forwardToClientLocalServer(request, _clientId, retried = false) {
++ const { client, candidates } = await findLeaderClient();
+
// If no page is available, fall back to network
if (!client) return fetch(request);
@@@ -179,88 -232,6 +248,91 @@@
});
}
+/**
+ * Answers a backup download with the database streamed straight out of the local worker.
+ *
+ * The response body is fed through a message channel: this end asks for one chunk each time the
+ * download can take more, the page relays the channel to the worker, and the worker reads the
+ * database a batch of pages at a time. The download's backpressure is the only flow control, so
+ * nothing is ever buffered beyond a chunk or two, whatever the database weighs.
++ *
++ * The channel goes to the leader tab, since that is the one holding the database; a follower that
++ * receives it anyway says so on the port, and this answers 503 rather than a truncated file.
+ */
+async function streamBackupDownload(url) {
- const client = await findMainClient();
++ const { client } = await findLeaderClient();
+ if (!client) {
+ return new Response("The application page is not available.", { status: 503 });
+ }
+
+ const channel = new MessageChannel();
+ const port = channel.port1;
+ client.postMessage({ type: "LOCAL_BACKUP_STREAM" }, [channel.port2]);
+
+ // The worker opens with the exact size, which is what lets the download show a percentage.
+ const begin = await new Promise<{ type?: string; byteSize?: number; message?: unknown } | null>((resolve) => {
+ const timeout = setTimeout(() => resolve(null), 30_000);
+ port.onmessage = (event) => {
+ clearTimeout(timeout);
+ resolve(event.data);
+ };
+ });
+ if (!begin || begin.type !== "begin") {
+ port.postMessage({ type: "cancel" });
+ return new Response(
+ begin && begin.type === "error" ? String(begin.message) : "The backup stream did not start.",
+ { status: 503 }
+ );
+ }
+
+ // Several chunks travel at once: each pull round-trips through the page to the worker, and
+ // one-at-a-time would make that latency the download's speed limit.
+ const MAX_CHUNKS_IN_FLIGHT = 8;
+ let outstanding = 0;
+ let streamController: ReadableStreamDefaultController<Uint8Array> | null = null;
+ const requestMore = () => {
+ while (streamController && outstanding < MAX_CHUNKS_IN_FLIGHT
+ && (streamController.desiredSize ?? 0) > 0) {
+ outstanding++;
+ port.postMessage({ type: "pull" });
+ }
+ };
+
+ const stream = new ReadableStream({
+ start(controller) {
+ streamController = controller;
+ port.onmessage = (event) => {
+ const msg = event.data;
+ if (msg && msg.type === "chunk") {
+ outstanding--;
+ controller.enqueue(new Uint8Array(msg.data));
+ requestMore();
+ } else if (msg && msg.type === "end") {
+ controller.close();
+ } else {
+ controller.error(new Error(msg && msg.message ? String(msg.message) : "The backup failed."));
+ }
+ };
+ requestMore();
+ },
+ pull() {
+ requestMore();
+ },
+ cancel() {
+ port.postMessage({ type: "cancel" });
+ }
+ }, new CountQueuingStrategy({ highWaterMark: MAX_CHUNKS_IN_FLIGHT }));
+
+ const fileName = (url.searchParams.get("fileName") || "backup.db").replace(/["\\\r\n]/g, "-");
+ return new Response(stream, {
+ headers: {
+ "Content-Type": "application/octet-stream",
+ "Content-Disposition": `attachment; filename="${fileName}"`,
+ "Content-Length": String(begin.byteSize)
+ }
+ });
+}
+
self.addEventListener("fetch", (event) => {
const url = new URL(event.request.url);