Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions apps/web/src/bootstrap.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,12 @@ function createStorageStub(initial: Record<string, string> = {}): Storage {
};
}

const NOW = 1_700_000_000_000;

async function bootWithFailingMainChunk(storage: Storage) {
vi.resetModules();
vi.useFakeTimers();
vi.setSystemTime(NOW);
mocks.showBootError.mockClear();
const reload = vi.fn().mockName("location.reload");
vi.stubGlobal(
Expand All @@ -43,23 +47,31 @@ async function bootWithFailingMainChunk(storage: Storage) {
try {
const { boot } = await import("./bootstrap");
await boot;
// The reload waits a moment for the network to settle.
await vi.advanceTimersByTimeAsync(5_000);
return { reload, showBootError: mocks.showBootError };
} finally {
vi.unstubAllGlobals();
vi.useRealTimers();
}
}

describe("bootstrap", () => {
it("reloads once instead of showing the boot error when the main chunk fails to load", async () => {
it("reloads, once for the whole failed load, instead of showing the boot error when the main chunk fails", async () => {
const { reload, showBootError } = await bootWithFailingMainChunk(createStorageStub());

expect(reload).toHaveBeenCalledTimes(1);
expect(showBootError).not.toHaveBeenCalled();
});

it("shows the boot error when the main chunk fails again after the reload", async () => {
it("shows the boot error once the reloads are used up and the main chunk still fails", async () => {
const { reload, showBootError } = await bootWithFailingMainChunk(
createStorageStub({ "t3code:chunk-load-reloaded": import.meta.env.APP_VERSION }),
createStorageStub({
"t3code:chunk-load-reloaded": JSON.stringify({
build: import.meta.env.APP_VERSION,
at: [NOW - 3_000, NOW - 2_000, NOW - 1_000],
}),
}),
);

expect(reload).not.toHaveBeenCalled();
Expand Down
95 changes: 83 additions & 12 deletions apps/web/src/lib/chunkReloadGuard.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { describe, expect, it, vi } from "vite-plus/test";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";

import { isChunkLoadError, reloadOnceForChunkLoadError } from "./chunkReloadGuard";
import {
chunkLoadState,
handleChunkLoadErrors,
isChunkLoadError,
reloadForChunkLoadError,
} from "./chunkReloadGuard";

function createStorageStub(): Storage {
const store = new Map<string, string>();
Expand All @@ -20,26 +25,64 @@ function createStorageStub(): Storage {
};
}

describe("reloadOnceForChunkLoadError", () => {
it("reloads on the first failure and lets the second one surface", () => {
describe("reloadForChunkLoadError", () => {
it("retries with growing delays, then lets the failure surface", () => {
const storage = createStorageStub();
const reload = vi.fn();
const reloadAt = (now: number) => reloadForChunkLoadError(() => storage, reload, "1.0.0", now);

expect(reloadOnceForChunkLoadError(() => storage, reload, "1.0.0")).toBe(true);
expect(reload).toHaveBeenCalledTimes(1);
expect(reloadAt(0)).toBe(true);
expect(reloadAt(5_000)).toBe(true);
expect(reloadAt(10_000)).toBe(true);
expect(reloadAt(15_000)).toBe(false);
expect(reload.mock.calls.map(([delay]) => delay)).toEqual([750, 1500, 2250]);
});

expect(reloadOnceForChunkLoadError(() => storage, reload, "1.0.0")).toBe(false);
expect(reload).toHaveBeenCalledTimes(1);
it("keeps a load that fails slowly, every 20 seconds, from reloading forever", () => {
const storage = createStorageStub();
const reload = vi.fn();
const outcomes = [0, 20_000, 40_000, 60_000, 80_000].map((now) =>
reloadForChunkLoadError(() => storage, reload, "1.0.0", now),
);

expect(outcomes).toEqual([true, true, true, false, false]);
});

it("reloads again once the window has passed", () => {
const storage = createStorageStub();
const reload = vi.fn();
for (const now of [0, 1_000, 2_000])
reloadForChunkLoadError(() => storage, reload, "1.0.0", now);

expect(reloadForChunkLoadError(() => storage, reload, "1.0.0", 11 * 60_000)).toBe(true);
expect(reload).toHaveBeenCalledTimes(4);
});

it("ignores stamps from a clock that has since moved back", () => {
const storage = createStorageStub();
storage.setItem(
"t3code:chunk-load-reloaded",
JSON.stringify({ build: "1.0.0", at: [1_000_000, 1_001_000, 1_002_000] }),
);

expect(reloadForChunkLoadError(() => storage, vi.fn(), "1.0.0", 0)).toBe(true);
});

it("reloads again once a deploy changed the build", () => {
const storage = createStorageStub();
const reload = vi.fn();
for (const now of [0, 1_000, 2_000])
reloadForChunkLoadError(() => storage, reload, "1.0.0", now);

reloadOnceForChunkLoadError(() => storage, reload, "1.0.0");
expect(reloadForChunkLoadError(() => storage, reload, "1.0.1", 3_000)).toBe(true);
});

it("treats the bare build string an older tab stored as no record", () => {
const storage = createStorageStub();
storage.setItem("t3code:chunk-load-reloaded", "1.0.0");
const reload = vi.fn();

expect(reloadOnceForChunkLoadError(() => storage, reload, "1.0.1")).toBe(true);
expect(reload).toHaveBeenCalledTimes(2);
expect(reloadForChunkLoadError(() => storage, reload, "1.0.0", 0)).toBe(true);
});

it("never reloads when storage is blocked, so a persistent failure cannot loop", () => {
Expand All @@ -48,11 +91,39 @@ describe("reloadOnceForChunkLoadError", () => {
throw new DOMException("blocked", "SecurityError");
};

expect(reloadOnceForChunkLoadError(blocked, reload)).toBe(false);
expect(reloadForChunkLoadError(blocked, reload)).toBe(false);
expect(reload).not.toHaveBeenCalled();
});
});

describe("handleChunkLoadErrors", () => {
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
chunkLoadState.reloadScheduled = false;
});

it("spends one reload on the many preload errors one failed load raises", () => {
vi.useFakeTimers();
const storage = createStorageStub();
const reload = vi.fn();
const page = Object.assign(new EventTarget(), {
sessionStorage: storage,
location: { reload },
});
vi.stubGlobal("window", page);
handleChunkLoadErrors();

const events = [1, 2, 3, 4].map(() => new Event("vite:preloadError", { cancelable: true }));
for (const event of events) page.dispatchEvent(event);
vi.advanceTimersByTime(5_000);

expect(events.every((event) => event.defaultPrevented)).toBe(true);
expect(reload).toHaveBeenCalledTimes(1);
expect(JSON.parse(storage.getItem("t3code:chunk-load-reloaded") ?? "{}").at).toHaveLength(1);
});
});

describe("isChunkLoadError", () => {
it.each([
["Failed to fetch dynamically imported module: t3code://app/assets/a.js", true],
Expand Down
44 changes: 35 additions & 9 deletions apps/web/src/lib/chunkReloadGuard.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,48 @@
// Deploys and desktop server swaps can invalidate lazy chunks; one reload fetches the fresh index.
// A failed chunk is only retried by a reload, so a few spaced-out reloads ride out a flapping network.
// The cap stops a chunk that is gone, or a load that hangs and then fails, from looping.
// Keyed by build and kept across boots: a chunk loaded after boot can fail on every visit.
const CHUNK_RELOAD_GUARD_KEY = "t3code:chunk-load-reloaded";
const MAX_RELOADS = 3;
const RELOAD_WINDOW_MS = 10 * 60_000;
const RELOAD_DELAY_MS = 750;

export function reloadOnceForChunkLoadError(
interface ReloadRecord {
readonly build: string;
readonly at: ReadonlyArray<number>;
}

// A tab opened before this format holds the bare build string, which is not a record.
function readRecord(raw: string | null): Partial<ReloadRecord> | undefined {
try {
return raw === null ? undefined : (JSON.parse(raw) as Partial<ReloadRecord>);
} catch {
return undefined;
}
}

export function reloadForChunkLoadError(
getStorage: () => Storage = () => window.sessionStorage,
reload: () => void = () => window.location.reload(),
reload: (delayMs: number) => void = (delayMs) =>
void setTimeout(() => window.location.reload(), delayMs),
build = import.meta.env.APP_VERSION,
now = Date.now(),
): boolean {
let alreadyReloaded: boolean;
let recent: ReadonlyArray<number> = [];
try {
const storage = getStorage();
alreadyReloaded = storage.getItem(CHUNK_RELOAD_GUARD_KEY) === build;
if (!alreadyReloaded) storage.setItem(CHUNK_RELOAD_GUARD_KEY, build);
const record = readRecord(storage.getItem(CHUNK_RELOAD_GUARD_KEY));
const stamps = record !== undefined && record.build === build ? record.at : undefined;
if (Array.isArray(stamps)) {
// A stamp from the future (the clock moved back) would hold the cap shut, so it does not count.
recent = stamps.filter((at) => at <= now && now - at < RELOAD_WINDOW_MS);
}
if (recent.length >= MAX_RELOADS) return false;
storage.setItem(CHUNK_RELOAD_GUARD_KEY, JSON.stringify({ build, at: [...recent, now] }));
} catch {
// Without storage, the reload guard cannot prevent an infinite loop.
return false;
}
if (alreadyReloaded) return false;
reload();
reload(RELOAD_DELAY_MS * (recent.length + 1));
return true;
}

Expand All @@ -40,7 +65,8 @@ export const chunkLoadState = { reloadScheduled: false };
// Registered from the entry before main loads, so main-chunk and route-chunk failures share one decision.
export function handleChunkLoadErrors() {
window.addEventListener("vite:preloadError", (event) => {
if (reloadOnceForChunkLoadError()) {
// One failed load raises this event for every chunk it lost; they share one reload.
if (chunkLoadState.reloadScheduled || reloadForChunkLoadError()) {
chunkLoadState.reloadScheduled = true;
event.preventDefault();
}
Expand Down
10 changes: 8 additions & 2 deletions apps/web/src/main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ vi.mock("react-dom/client", () => ({ default: { createRoot: () => ({ render: ()
// Boots the entry in a fresh page that shares the tab's sessionStorage, as a reload does.
async function bootThenFailLazyChunk(sessionStorage: Map<string, string>) {
vi.resetModules();
vi.useFakeTimers();
const reload = vi.fn().mockName("location.reload");
const page = Object.assign(new EventTarget(), {
sessionStorage: {
Expand All @@ -23,15 +24,20 @@ async function bootThenFailLazyChunk(sessionStorage: Map<string, string>) {
const { boot } = await import("./bootstrap");
await boot;
page.dispatchEvent(new Event("vite:preloadError", { cancelable: true }));
// The reload waits a moment for the network to settle.
await vi.advanceTimersByTimeAsync(5_000);
return reload;
} finally {
vi.unstubAllGlobals();
vi.useRealTimers();
}
}

it("reloads only once when a lazy chunk fails after every boot", async () => {
it("stops reloading after three tries when a lazy chunk fails after every boot", async () => {
const sessionStorage = new Map<string, string>();

expect(await bootThenFailLazyChunk(sessionStorage)).toHaveBeenCalledTimes(1);
for (let boot = 0; boot < 3; boot++) {
expect(await bootThenFailLazyChunk(sessionStorage)).toHaveBeenCalledTimes(1);
}
expect(await bootThenFailLazyChunk(sessionStorage)).not.toHaveBeenCalled();
});
Loading