Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(standalone): re-send request body when retrying a stale leader
Elian Dorand3268eb55064
diff --git a/apps/standalone/src/sw.spec.ts b/apps/standalone/src/sw.spec.tsindex 351c457bec..8a69969fa7 100644--- a/apps/standalone/src/sw.spec.ts+++ b/apps/standalone/src/sw.spec.ts@@ -38,14 +38,34 @@ async function awaitResponse(event: { _response?: Promise<Response> }): Promise<return res;}-function fetchEvent(url: string, init: { method?: string; mode?: string; headers?: [string, string][] } = {}): { request: unknown; clientId: string; respondWith(p: Promise<Response>): void; _response?: Promise<Response> } {- const request = {+type RequestInit = { method?: string; mode?: string; headers?: [string, string][] };++/**+ * Models the real `Request` body semantics: a body can be read once, and a+ * consumed request can neither be cloned nor re-read. Without this the mock+ * silently permits double reads, which hides retry bugs.+ */+function mockRequest(url: string, init: RequestInit = {}) {+ let bodyUsed = false;+ return {url,method: init.method ?? "GET",mode: init.mode ?? "cors",headers: { entries: () => (init.headers ?? [])[Symbol.iterator]() },- arrayBuffer: async () => new TextEncoder().encode("body").buffer+ arrayBuffer: async () => {+ if (bodyUsed) throw new TypeError("Body is unusable: Body has already been read");+ bodyUsed = true;+ return new TextEncoder().encode("body").buffer;+ },+ clone: () => {+ if (bodyUsed) throw new TypeError("Failed to clone: body already used");+ return mockRequest(url, init);+ }};+}++function fetchEvent(url: string, init: RequestInit = {}): { request: unknown; clientId: string; respondWith(p: Promise<Response>): void; _response?: Promise<Response> } {+ const request = mockRequest(url, init);const event = { request, clientId: "c1" } as ReturnType<typeof fetchEvent>;event.respondWith = (p: Promise<Response>) => { event._response = p; };return event;@@ -328,4 +348,51 @@ describe("forwardToClientLocalServer", () => {channels.at(-1)?.port1.onmessage?.({ data: { type: "LOCAL_FETCH_RESPONSE", id: "uuid-1", response: { status: 200, headers: {}, body: null } } } as unknown);expect((await awaitResponse(event)).status).toBe(200);});++ it("re-sends the body when a body-bearing mutation hits a stale leader", async () => {+ const stale = mainClient("c-stale", false);+ const leader = mainClient("c-leader", true);+ (self as unknown as SwGlobals).clients = {+ claim: vi.fn(),+ matchAll: vi.fn(async () => [stale, leader])+ };+ const handlers = await loadSw();+ handlers.message({ data: { type: "LEADER_ANNOUNCE" }, source: { id: "c-stale" } });++ const event = await dispatchLocal(handlers, "PUT");+ await vi.waitFor(() => expect(stale.postMessage).toHaveBeenCalledWith(expect.objectContaining({ type: "LOCAL_FETCH" }), expect.anything()));+ channels.at(-1)?.port1.onmessage?.({ data: { type: "NOT_LEADER", id: "uuid-1" } } as unknown);++ // The retry must carry the body, not fail on an already-consumed request.+ await vi.waitFor(() => expect(leader.postMessage).toHaveBeenCalledWith(expect.objectContaining({ type: "LOCAL_FETCH" }), expect.anything()));+ const forwarded = leader.postMessage.mock.calls.find(([msg]) => msg?.type === "LOCAL_FETCH")?.[0];+ expect(new TextDecoder().decode(forwarded?.request?.body)).toBe("body");++ channels.at(-1)?.port1.onmessage?.({ data: { type: "LOCAL_FETCH_RESPONSE", id: "uuid-1", response: { status: 200, headers: {}, body: null } } } as unknown);+ expect((await awaitResponse(event)).status).toBe(200);+ });++ it("gives up to the network rather than looping when the retry also refuses", 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);+ (self as unknown as SwGlobals).clients = {+ claim: vi.fn(),+ matchAll: vi.fn(async () => [a, 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);++ 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);++ expect((await awaitResponse(event)).status).toBe(200);+ expect(fetchMock).toHaveBeenCalled();+ });});diff --git a/apps/standalone/src/sw.ts b/apps/standalone/src/sw.tsindex 62e44ffc1f..158022e204 100644--- a/apps/standalone/src/sw.ts+++ b/apps/standalone/src/sw.ts@@ -136,7 +136,7 @@ async function findLeader(candidates) {return null;}-async function forwardToClientLocalServer(request, _clientId) {+async function forwardToClientLocalServer(request, _clientId, retried = false) {// @ts-expect-error - self.clients is valid in service worker contextconst all = await self.clients.matchAll({ type: "window", includeUncontrolled: true });const candidates = all.filter(isMainAppWindow);@@ -160,9 +160,13 @@ async function forwardToClientLocalServer(request, _clientId) {const headersObj = {};for (const [k, v] of request.headers.entries()) headersObj[k] = v;+ // Read from a clone: `request` itself must stay unconsumed so the NOT_LEADER+ // path below can forward it again (or hand it to fetch()). Reading it+ // directly makes any body-bearing retry fail with "Body has already been+ // read".const body = (request.method === "GET" || request.method === "HEAD")? null- : await request.arrayBuffer();+ : await request.clone().arrayBuffer();const id = crypto.randomUUID();const channel = new MessageChannel();@@ -197,12 +201,16 @@ async function forwardToClientLocalServer(request, _clientId) {const localResp = await responsePromise;// We picked a follower. It refused to open a second database; re-resolve the- // leader and try once more.+ // 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.if (localResp?.type === "NOT_LEADER") {leaderClientId = null;+ if (retried) return fetch(request);+const leader = await findLeader(candidates.filter((c) => c.id !== client.id));if (!leader) return fetch(request);- return forwardToClientLocalServer(request, _clientId);+ return forwardToClientLocalServer(request, _clientId, true);}if (!localResp || localResp.type !== "LOCAL_FETCH_RESPONSE" || localResp.id !== id) {