Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
🥅 Refetch static assets past the cache before the chunk error reload (#3543)
Luke Vellab6814320a884
diff --git a/apps/web/src/lib/chunk-recovery.test.ts b/apps/web/src/lib/chunk-recovery.test.tsindex b7e8eda3b..d82f4fb1a 100644--- a/apps/web/src/lib/chunk-recovery.test.ts+++ b/apps/web/src/lib/chunk-recovery.test.ts@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import {isModuleFactoryError,reloadOnceForChunkError,+ staticAssetUrls,summarizeStaticAssets,} from "./chunk-recovery";@@ -56,39 +57,80 @@ describe("summarizeStaticAssets", () => {});});+describe("staticAssetUrls", () => {+ it("keeps each Next static asset once", () => {+ const chunk =+ "https://static.rallly.co/_next/static/immutable/chunks/2dixsi-13gzup.js";+ expect(+ staticAssetUrls([+ { name: chunk },+ { name: chunk },+ { name: "https://b.rallly.co/decide" },+ ]),+ ).toEqual([chunk]);+ });+});+describe("reloadOnceForChunkError", () => {const reload = vi.fn();+ const fetch = vi.fn();+ const chunk =+ "https://static.rallly.co/_next/static/immutable/chunks/2dixsi-13gzup.js";beforeEach(() => {vi.useFakeTimers();vi.stubGlobal("location", { ...window.location, reload });+ vi.stubGlobal("fetch", fetch.mockResolvedValue(new Response()));+ vi.spyOn(performance, "getEntriesByType").mockReturnValue([+ { name: chunk } as PerformanceEntry,+ ]);window.sessionStorage.clear();});afterEach(() => {vi.useRealTimers();vi.unstubAllGlobals();+ vi.restoreAllMocks();reload.mockReset();+ fetch.mockReset();+ });++ it("refetches static assets past the cache before reloading", async () => {+ reloadOnceForChunkError(factoryError);+ await vi.runAllTimersAsync();+ expect(fetch).toHaveBeenCalledWith(+ chunk,+ expect.objectContaining({ cache: "reload", mode: "no-cors" }),+ );+ expect(reload).toHaveBeenCalledTimes(1);+ });++ it("still reloads when a refetch fails", async () => {+ fetch.mockRejectedValue(new TypeError("Load failed"));+ reloadOnceForChunkError(factoryError);+ await vi.runAllTimersAsync();+ expect(reload).toHaveBeenCalledTimes(1);});- it("reloads once and not again within the cooldown", () => {+ it("reloads once and not again within the cooldown", async () => {reloadOnceForChunkError(factoryError);reloadOnceForChunkError(factoryError);- vi.runAllTimers();+ await vi.runAllTimersAsync();expect(reload).toHaveBeenCalledTimes(1);});- it("reloads again after the cooldown", () => {+ it("reloads again after the cooldown", async () => {reloadOnceForChunkError(factoryError);- vi.advanceTimersByTime(5 * 60 * 1000 + 1);+ await vi.advanceTimersByTimeAsync(5 * 60 * 1000 + 1);reloadOnceForChunkError(factoryError);- vi.runAllTimers();+ await vi.runAllTimersAsync();expect(reload).toHaveBeenCalledTimes(2);});- it("does not reload for other errors", () => {+ it("does not reload for other errors", async () => {reloadOnceForChunkError(new Error("boom"));- vi.runAllTimers();+ await vi.runAllTimersAsync();expect(reload).not.toHaveBeenCalled();+ expect(fetch).not.toHaveBeenCalled();});});diff --git a/apps/web/src/lib/chunk-recovery.ts b/apps/web/src/lib/chunk-recovery.tsindex 8512344f9..3ae66ce59 100644--- a/apps/web/src/lib/chunk-recovery.ts+++ b/apps/web/src/lib/chunk-recovery.ts@@ -1,10 +1,13 @@// Turbopack throws this when a chunk has registered but lacks a module the// page expects. WebKit browsers hit it since static assets moved to a separate-// host, and a fresh load usually works, so recover by reloading once and send-// Sentry what the browser actually received for each chunk.+// host. Failures stick to a visitor across deploys and a plain reload fails+// the same way from cache, which points to a bad cached copy of an immutable+// chunk. So recover by refetching every static asset past the cache, then+// reloading once, and send Sentry what the browser received for each chunk.const RELOAD_KEY = "rallly:chunk-reload-at";const RELOAD_COOLDOWN_MS = 5 * 60 * 1000;+const REFETCH_TIMEOUT_MS = 3000;export function isModuleFactoryError(error: unknown) {const message =@@ -83,5 +86,39 @@ export function reloadOnceForChunkError(error: unknown) {}// Let Sentry hand its event to the transport first; it uses keepalive, so// the request survives the navigation.- setTimeout(() => window.location.reload(), 0);+ setTimeout(() => {+ void refetchStaticAssets(+ staticAssetUrls(performance.getEntriesByType("resource")),+ ).finally(() => window.location.reload());+ }, 0);+}++export function staticAssetUrls(entries: Pick<PerformanceEntry, "name">[]) {+ return [+ ...new Set(+ entries+ .map((entry) => entry.name)+ .filter((name) => name.includes("/_next/static/")),+ ),+ ];+}++// cache: "reload" skips the HTTP cache and stores the fresh response, which+// overwrites a bad copy. Chunk script tags carry no crossorigin attribute, so+// the request mirrors theirs (no-cors, credentials included) to hit the same+// cache entry.+async function refetchStaticAssets(urls: string[]) {+ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), REFETCH_TIMEOUT_MS);+ await Promise.allSettled(+ urls.map((url) =>+ fetch(url, {+ cache: "reload",+ mode: "no-cors",+ credentials: "include",+ signal: controller.signal,+ }),+ ),+ );+ clearTimeout(timeout);}