Skip to content

Commit 150f380

Browse files
committed
fix(web): key the chunk reload guard by build instead of a time window
A five-minute window still let a chunk that always fails reload the page again every five minutes. The guard now stores the build that reloaded the tab: the same build never reloads twice, and a deploy re-arms it.
1 parent 3fa0ab7 commit 150f380

3 files changed

Lines changed: 79 additions & 78 deletions

File tree

Lines changed: 25 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { describe, expect, it, vi } from "vite-plus/test";
22

3-
import { CHUNK_RELOAD_GUARD_WINDOW_MS, reloadOnceForChunkLoadError } from "./chunkReloadGuard";
3+
import { reloadOnceForChunkLoadError } from "./chunkReloadGuard";
44

55
function createStorageStub(initial: Record<string, string> = {}): Storage {
66
const store = new Map(Object.entries(initial));
@@ -20,73 +20,37 @@ function createStorageStub(initial: Record<string, string> = {}): Storage {
2020
};
2121
}
2222

23-
function createClock(start = 1_800_000_000_000) {
24-
let time = start;
25-
return {
26-
now: () => time,
27-
advance: (ms: number) => {
28-
time += ms;
29-
},
30-
};
31-
}
32-
3323
describe("reloadOnceForChunkLoadError", () => {
34-
it("reloads on the first failure and lets a repeat within the window surface", () => {
24+
it("reloads on the first failure and lets every later one on the same build surface", () => {
3525
const storage = createStorageStub();
36-
const clock = createClock();
3726
const reload = vi.fn();
3827

39-
expect(reloadOnceForChunkLoadError(() => storage, reload, clock.now)).toBe(true);
40-
expect(reload).toHaveBeenCalledTimes(1);
41-
42-
clock.advance(1_000);
43-
expect(reloadOnceForChunkLoadError(() => storage, reload, clock.now)).toBe(false);
28+
expect(reloadOnceForChunkLoadError(() => storage, reload, "1.0.0")).toBe(true);
4429
expect(reload).toHaveBeenCalledTimes(1);
45-
});
46-
47-
it("keeps refusing repeated failures for the whole window", () => {
48-
const storage = createStorageStub();
49-
const clock = createClock();
50-
const reload = vi.fn();
5130

52-
const reloads = Array.from({ length: 10 }, () => {
53-
clock.advance(2_000);
54-
return reloadOnceForChunkLoadError(() => storage, reload, clock.now);
55-
});
56-
57-
expect(reloads.filter(Boolean)).toHaveLength(1);
31+
for (let attempt = 0; attempt < 5; attempt += 1) {
32+
expect(reloadOnceForChunkLoadError(() => storage, reload, "1.0.0")).toBe(false);
33+
}
5834
expect(reload).toHaveBeenCalledTimes(1);
5935
});
6036

61-
it("reloads again once the window has passed, so a later deploy still recovers", () => {
37+
it("reloads again once a deploy changed the build", () => {
6238
const storage = createStorageStub();
63-
const clock = createClock();
6439
const reload = vi.fn();
6540

66-
reloadOnceForChunkLoadError(() => storage, reload, clock.now);
67-
clock.advance(CHUNK_RELOAD_GUARD_WINDOW_MS);
41+
reloadOnceForChunkLoadError(() => storage, reload, "1.0.0");
6842

69-
expect(reloadOnceForChunkLoadError(() => storage, reload, clock.now)).toBe(true);
43+
expect(reloadOnceForChunkLoadError(() => storage, reload, "1.0.1")).toBe(true);
44+
expect(reload).toHaveBeenCalledTimes(2);
45+
expect(reloadOnceForChunkLoadError(() => storage, reload, "1.0.1")).toBe(false);
7046
expect(reload).toHaveBeenCalledTimes(2);
7147
});
7248

73-
it("treats a guard written by an older version as expired", () => {
49+
it("treats a guard written by an older version as another build", () => {
7450
const storage = createStorageStub({ "t3code:chunk-load-reloaded": "1" });
7551
const reload = vi.fn();
7652

77-
expect(reloadOnceForChunkLoadError(() => storage, reload, createClock().now)).toBe(true);
78-
expect(reload).toHaveBeenCalledTimes(1);
79-
});
80-
81-
it("doesn't reload when the clock moved backwards since the last reload", () => {
82-
const storage = createStorageStub();
83-
const clock = createClock();
84-
const reload = vi.fn();
85-
86-
reloadOnceForChunkLoadError(() => storage, reload, clock.now);
87-
clock.advance(-60_000);
88-
89-
expect(reloadOnceForChunkLoadError(() => storage, reload, clock.now)).toBe(false);
53+
expect(reloadOnceForChunkLoadError(() => storage, reload, "1.0.0")).toBe(true);
9054
expect(reload).toHaveBeenCalledTimes(1);
9155
});
9256

@@ -96,7 +60,18 @@ describe("reloadOnceForChunkLoadError", () => {
9660
throw new DOMException("blocked", "SecurityError");
9761
};
9862

99-
expect(reloadOnceForChunkLoadError(blocked, reload)).toBe(false);
63+
expect(reloadOnceForChunkLoadError(blocked, reload, "1.0.0")).toBe(false);
64+
expect(reload).not.toHaveBeenCalled();
65+
});
66+
67+
it("never reloads when the guard can't be written", () => {
68+
const storage = createStorageStub();
69+
storage.setItem = () => {
70+
throw new DOMException("full", "QuotaExceededError");
71+
};
72+
const reload = vi.fn();
73+
74+
expect(reloadOnceForChunkLoadError(() => storage, reload, "1.0.0")).toBe(false);
10075
expect(reload).not.toHaveBeenCalled();
10176
});
10277
});
Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,24 @@
11
// Deploys and desktop server swaps can invalidate lazy chunks; one reload fetches the fresh index.
2-
// The guard expires after a delay instead of being cleared once the app boots. A successful boot
3-
// doesn't prove that every lazy chunk loads, so clearing it there let a chunk that fails on each
4-
// visit, such as the code highlighter blocked by a proxy, reload the page forever.
2+
// Keyed by build, not cleared at boot: a lazy chunk can fail after every successful boot, so a
3+
// build reloads the tab at most once and a new deploy re-arms the guard.
54
const CHUNK_RELOAD_GUARD_KEY = "t3code:chunk-load-reloaded";
6-
export const CHUNK_RELOAD_GUARD_WINDOW_MS = 5 * 60 * 1000;
5+
const CURRENT_BUILD = import.meta.env.APP_VERSION || "0.0.0";
76

87
export function reloadOnceForChunkLoadError(
98
getStorage: () => Storage = () => window.sessionStorage,
109
reload: () => void = () => window.location.reload(),
11-
now: () => number = Date.now,
10+
build: string = CURRENT_BUILD,
1211
): boolean {
13-
let reloadedRecently: boolean;
12+
let alreadyReloaded: boolean;
1413
try {
1514
const storage = getStorage();
16-
const lastReloadAt = Number(storage.getItem(CHUNK_RELOAD_GUARD_KEY));
17-
const elapsed = now() - lastReloadAt;
18-
// A clock that moved backwards counts as recent, so it can't turn into a loop either.
19-
reloadedRecently = lastReloadAt > 0 && elapsed < CHUNK_RELOAD_GUARD_WINDOW_MS;
20-
if (!reloadedRecently) storage.setItem(CHUNK_RELOAD_GUARD_KEY, String(now()));
15+
alreadyReloaded = storage.getItem(CHUNK_RELOAD_GUARD_KEY) === build;
16+
if (!alreadyReloaded) storage.setItem(CHUNK_RELOAD_GUARD_KEY, build);
2117
} catch {
2218
// Without storage, the reload guard cannot prevent an infinite loop.
2319
return false;
2420
}
25-
if (reloadedRecently) return false;
21+
if (alreadyReloaded) return false;
2622
reload();
2723
return true;
2824
}

‎apps/web/src/main.test.ts‎

Lines changed: 46 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,22 @@
11
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
22

3-
const mocks = vi.hoisted(() => ({ render: vi.fn().mockName("root.render") }));
3+
const mocks = vi.hoisted(() => ({
4+
render: vi.fn().mockName("root.render"),
5+
// Runs while the router loads, before main decides whether to render.
6+
duringRouterLoad: (): void => {},
7+
}));
48

59
vi.mock("@fontsource-variable/inter", () => ({}));
610
vi.mock("./index.css", () => ({}));
711
vi.mock("./cloud/publicConfig", () => ({ hasCloudPublicConfig: () => false }));
812
vi.mock("./env", () => ({ isElectron: false }));
9-
vi.mock("./appInit", () => ({ startAppServices: () => ({ load: () => Promise.resolve() }) }));
13+
vi.mock("./appInit", () => ({
14+
startAppServices: () => ({
15+
load: async () => {
16+
mocks.duringRouterLoad();
17+
},
18+
}),
19+
}));
1020
vi.mock("./AppRoot", () => ({ AppRoot: () => null }));
1121
vi.mock("react-dom/client", () => ({
1222
default: { createRoot: () => ({ render: mocks.render }) },
@@ -30,28 +40,30 @@ function createStorageStub(): Storage {
3040
};
3141
}
3242

43+
function failChunk(page: EventTarget) {
44+
const event = Object.assign(new Event("vite:preloadError", { cancelable: true }), {
45+
payload: new TypeError("Failed to fetch dynamically imported module: /assets/highlights.js"),
46+
});
47+
page.dispatchEvent(event);
48+
return event;
49+
}
50+
3351
// Boots main in a fresh page that shares the tab's sessionStorage, as a reload does.
34-
async function bootPage(storage: Storage) {
52+
async function bootPage(storage: Storage, { failDuringBoot = false } = {}) {
3553
vi.resetModules();
3654
mocks.render.mockClear();
3755
const reload = vi.fn().mockName("location.reload");
3856
const page = Object.assign(new EventTarget(), {
3957
sessionStorage: storage,
4058
location: { reload },
4159
});
60+
mocks.duringRouterLoad = failDuringBoot ? () => void failChunk(page) : () => {};
4261
vi.unstubAllGlobals();
4362
vi.stubGlobal("window", page);
4463
vi.stubGlobal("document", { getElementById: () => ({}) });
4564
const { startup } = await import("./main");
4665
await startup;
47-
const failLazyChunk = () => {
48-
const event = Object.assign(new Event("vite:preloadError", { cancelable: true }), {
49-
payload: new TypeError("Failed to fetch dynamically imported module: /assets/highlights.js"),
50-
});
51-
page.dispatchEvent(event);
52-
return event;
53-
};
54-
return { reload, failLazyChunk };
66+
return { reload, failLazyChunk: () => failChunk(page) };
5567
}
5668

5769
describe("main chunk reload guard", () => {
@@ -67,11 +79,29 @@ describe("main chunk reload guard", () => {
6779
expect(firstVisit.failLazyChunk().defaultPrevented).toBe(true);
6880
expect(firstVisit.reload).toHaveBeenCalledTimes(1);
6981

70-
const afterReload = await bootPage(storage);
82+
for (let visit = 0; visit < 3; visit += 1) {
83+
const nextVisit = await bootPage(storage);
84+
expect(mocks.render).toHaveBeenCalledTimes(1);
85+
// Not prevented: the failed import rejects and the caller's error handling takes over.
86+
expect(nextVisit.failLazyChunk().defaultPrevented).toBe(false);
87+
expect(nextVisit.reload).not.toHaveBeenCalled();
88+
}
89+
});
90+
91+
it("skips rendering when a chunk fails during boot and a reload is on its way", async () => {
92+
const { reload } = await bootPage(createStorageStub(), { failDuringBoot: true });
93+
94+
expect(reload).toHaveBeenCalledTimes(1);
95+
expect(mocks.render).not.toHaveBeenCalled();
96+
});
97+
98+
it("renders when a chunk fails during boot after the build already reloaded", async () => {
99+
const storage = createStorageStub();
100+
await bootPage(storage, { failDuringBoot: true });
101+
102+
const { reload } = await bootPage(storage, { failDuringBoot: true });
103+
104+
expect(reload).not.toHaveBeenCalled();
71105
expect(mocks.render).toHaveBeenCalledTimes(1);
72-
const repeat = afterReload.failLazyChunk();
73-
expect(afterReload.reload).not.toHaveBeenCalled();
74-
// Not prevented, so the import rejects and the code block falls back to plain text.
75-
expect(repeat.defaultPrevented).toBe(false);
76106
});
77107
});

0 commit comments

Comments
 (0)