Skip to content

Build your personal knowledge base with Trilium Notes

fix(standalone): wait for the database tab instead of asking the static host

Claude9d7d47bce950
diff --git a/apps/client/src/index.ts b/apps/client/src/index.ts
index f405f55223..10c1e561e3 100644
--- a/apps/client/src/index.ts
+++ b/apps/client/src/index.ts
@@ -68,6 +68,9 @@ async function setupGlob() {
const response = localFetch
? await withTimeout(localFetch(new Request(url)), LOCAL_BOOTSTRAP_TIMEOUT_MS)
: await fetch(url);
+ if (!response.ok) {
+ throw new Error(await readErrorMessage(response));
+ }
const json = await response.json();
if (import.meta.env.DEV && localFetch) {
// The worker answers this one only once it has finished starting up, so the time it
@@ -84,6 +87,19 @@ async function setupGlob() {
window.glob.getThemeStyle = getThemeStyle;
}
+/** The `message` of a JSON error body, or the status line when the body has none. */
+async function readErrorMessage(response: Response): Promise<string> {
+ try {
+ const body = await response.json();
+ if (typeof body?.message === "string") {
+ return body.message;
+ }
+ } catch {
+ // Not JSON: fall through to the status line.
+ }
+ return `the server answered ${response.status} ${response.statusText}`.trim();
+}
+
/**
* Rejects once `timeoutMs` has passed without `promise` settling, so a worker that never answers
* reaches `bootstrap()`'s error handler and the splash states the failure.
diff --git a/apps/standalone/src/sw.spec.ts b/apps/standalone/src/sw.spec.ts
index af63b2845f..0e6ff70462 100644
--- a/apps/standalone/src/sw.spec.ts
+++ b/apps/standalone/src/sw.spec.ts
@@ -274,12 +274,14 @@ describe("forwardToClientLocalServer", () => {
expect(res.status).toBe(200);
});
- it("falls back to the network when there are no clients", async () => {
+ it("answers 503 rather than asking the static host when there are no clients", async () => {
(self as unknown as SwGlobals).clients = { claim: vi.fn(), matchAll: vi.fn(async () => []) };
const handlers = await loadSw();
const event = await dispatchLocal(handlers, "GET");
- await event._response;
- expect(fetch).toHaveBeenCalled();
+ const res = await awaitResponse(event);
+ expect(res.status).toBe(503);
+ expect(await res.json()).toEqual({ message: expect.stringContaining("No Trilium tab") });
+ expect(fetch).not.toHaveBeenCalled();
});
it("defaults status and omits headers when the response is sparse", async () => {
@@ -294,15 +296,15 @@ describe("forwardToClientLocalServer", () => {
expect(res.status).toBe(200);
});
- it("falls back to the network on a protocol mismatch", async () => {
+ it("answers 503 rather than asking the static host on a protocol mismatch", async () => {
const client = mainClient();
(self as unknown as SwGlobals).clients = { claim: vi.fn(), matchAll: vi.fn(async () => [client]) };
const handlers = await loadSw();
const event = await dispatchLocal(handlers, "GET");
await vi.waitFor(() => expect(client.postMessage).toHaveBeenCalledWith(expect.objectContaining({ type: "LOCAL_FETCH" }), expect.anything()));
channels.at(-1)?.port1.onmessage?.({ data: { type: "WRONG", id: "uuid-1" } } as unknown);
- await event._response;
- expect(fetch).toHaveBeenCalled();
+ expect((await awaitResponse(event)).status).toBe(503);
+ expect(fetch).not.toHaveBeenCalled();
});
it("rejects on a message error", async () => {
@@ -413,27 +415,72 @@ describe("forwardToClientLocalServer", () => {
expect((await awaitResponse(event)).status).toBe(200);
});
- it("gives up to the network rather than looping when the retry also refuses", async () => {
+ it("waits for a reloaded tab that is promoted to leader after its request went out", async () => {
+ // The reloaded page requests /bootstrap while the previous page still holds the Web Lock.
+ let promoted = false;
+ const page = {
+ id: "c-page",
+ url: `${origin}/`,
+ postMessage: vi.fn((msg: { type?: string; id?: string }) => {
+ const port = channels.at(-1)?.port1;
+ if (msg?.type === "WHO_IS_LEADER") {
+ port?.onmessage?.({ data: { type: "LEADER_REPLY", isLeader: promoted } } as unknown);
+ } else if (msg?.type === "LOCAL_FETCH") {
+ port?.onmessage?.({
+ data: promoted
+ ? { type: "LOCAL_FETCH_RESPONSE", id: msg.id, response: { status: 200, headers: {}, body: null } }
+ : { type: "NOT_LEADER", id: msg.id }
+ } as unknown);
+ }
+ })
+ };
+ (self as unknown as SwGlobals).clients = { claim: vi.fn(), matchAll: vi.fn(async () => [page]) };
+ const handlers = await loadSw();
+ vi.useFakeTimers();
+
+ const event = await dispatchLocal(handlers, "GET");
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(event._response).toBeDefined();
+ promoted = true;
+ await vi.advanceTimersByTimeAsync(1_000);
+
+ expect((await awaitResponse(event)).status).toBe(200);
+ expect(fetch).not.toHaveBeenCalled();
+ vi.useRealTimers();
+ });
+
+ it("answers 503 once no tab has become leader by the deadline", async () => {
// Both tabs claim leadership when probed but refuse when asked to serve.
- const a = mainClient("c-a", true);
- const b = mainClient("c-b", true);
+ const refuse = (id: string) => ({
+ id,
+ url: `${origin}/`,
+ postMessage: vi.fn((msg: { type?: string; id?: string }) => {
+ const port = channels.at(-1)?.port1;
+ port?.onmessage?.({
+ data: msg?.type === "WHO_IS_LEADER"
+ ? { type: "LEADER_REPLY", isLeader: true }
+ : { type: "NOT_LEADER", id: msg.id }
+ } as unknown);
+ })
+ });
(self as unknown as SwGlobals).clients = {
claim: vi.fn(),
- matchAll: vi.fn(async () => [a, b])
+ matchAll: vi.fn(async () => [refuse("c-a"), refuse("c-b")])
};
- const fetchMock = vi.fn(async () => new Response("network", { status: 200 }));
- vi.stubGlobal("fetch", fetchMock);
-
const handlers = await loadSw();
- const event = await dispatchLocal(handlers, "PUT");
-
- await vi.waitFor(() => expect(a.postMessage).toHaveBeenCalledWith(expect.objectContaining({ type: "LOCAL_FETCH" }), expect.anything()));
- channels.at(-1)?.port1.onmessage?.({ data: { type: "NOT_LEADER", id: "uuid-1" } } as unknown);
+ vi.useFakeTimers();
- await vi.waitFor(() => expect(b.postMessage).toHaveBeenCalledWith(expect.objectContaining({ type: "LOCAL_FETCH" }), expect.anything()));
- channels.at(-1)?.port1.onmessage?.({ data: { type: "NOT_LEADER", id: "uuid-1" } } as unknown);
+ const event = await dispatchLocal(handlers, "PUT");
+ let settled = false;
+ void event._response?.then(() => { settled = true; });
+ await vi.advanceTimersByTimeAsync(29_000);
+ expect(settled).toBe(false);
+ await vi.advanceTimersByTimeAsync(2_000);
- expect((await awaitResponse(event)).status).toBe(200);
- expect(fetchMock).toHaveBeenCalled();
+ const res = await awaitResponse(event);
+ expect(res.status).toBe(503);
+ expect(await res.json()).toEqual({ message: expect.stringContaining("in time") });
+ expect(fetch).not.toHaveBeenCalled();
+ vi.useRealTimers();
});
});
diff --git a/apps/standalone/src/sw.ts b/apps/standalone/src/sw.ts
index ab359cddf1..9a0b3d41d8 100644
--- a/apps/standalone/src/sw.ts
+++ b/apps/standalone/src/sw.ts
@@ -198,11 +198,29 @@ async function answerShareRequest(request, clientId) {
return forwardToClientLocalServer(request, clientId);
}
-async function forwardToClientLocalServer(request, _clientId, retried = false) {
- const { client, candidates } = await findLeaderClient();
+/**
+ * How long a request waits for a tab to own the database. A reloaded leader page requests
+ * `/bootstrap` before the browser has released the previous page's Web Lock and promoted it, so
+ * for a moment no tab answers as leader.
+ */
+const LEADER_WAIT_MS = 30_000;
+const LEADER_RETRY_DELAY_MS = 250;
- // If no page is available, fall back to network
- if (!client) return fetch(request);
+/**
+ * Answers a local API request that no tab can serve. The static host has no API of its own: a
+ * network request for one returns `index.html`, which the client fails to parse as JSON.
+ */
+function noLeaderResponse(reason) {
+ return new Response(JSON.stringify({ message: reason }), {
+ status: 503,
+ headers: { "content-type": "application/json; charset=utf-8" }
+ });
+}
+
+async function forwardToClientLocalServer(request, _clientId, deadline = Date.now() + LEADER_WAIT_MS) {
+ const { client } = await findLeaderClient();
+
+ if (!client) return noLeaderResponse("No Trilium tab is open to answer this request.");
const reqUrl = request.url;
const headersObj = {};
@@ -253,22 +271,21 @@ async function forwardToClientLocalServer(request, _clientId, retried = false) {
const localResp = await responsePromise;
- // We picked a follower. It refused to open a second database; re-resolve the
- // leader and try once more. Only once: leadership can flip between a tab
- // answering WHO_IS_LEADER and that same tab serving the fetch, so an
- // unbounded retry could ping-pong between two tabs indefinitely.
+ // We picked a follower, which refuses to open a second database. Re-resolve the leader until
+ // `deadline`: a tab can be waiting for the Web Lock, and leadership can flip between a tab
+ // answering WHO_IS_LEADER and that same tab serving the fetch.
if (localResp?.type === "NOT_LEADER") {
leaderClientId = null;
- if (retried) return fetch(request);
+ if (Date.now() >= deadline) {
+ return noLeaderResponse("No Trilium tab took ownership of the database in time.");
+ }
- const leader = await findLeader(candidates.filter((c) => c.id !== client.id));
- if (!leader) return fetch(request);
- return forwardToClientLocalServer(request, _clientId, true);
+ await new Promise((resolve) => setTimeout(resolve, LEADER_RETRY_DELAY_MS));
+ return forwardToClientLocalServer(request, _clientId, deadline);
}
if (!localResp || localResp.type !== "LOCAL_FETCH_RESPONSE" || localResp.id !== id) {
- // Protocol mismatch; fall back
- return fetch(request);
+ return noLeaderResponse("The Trilium tab sent an unexpected reply.");
}
// localResp.response: { status, headers, body }