Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
🥅 Reload once and report chunk timings on Turbopack module factory errors (#3523)
Luke Vellacd77be796879
diff --git a/apps/web/instrumentation-client.ts b/apps/web/instrumentation-client.tsindex 97047450a..d33cc3c19 100644--- a/apps/web/instrumentation-client.ts+++ b/apps/web/instrumentation-client.ts@@ -5,6 +5,11 @@// Initializes the PostHog browser client (side-effect import).import "@rallly/posthog/client";import * as Sentry from "@sentry/nextjs";+import {+ getChunkRecoveryContext,+ isModuleFactoryError,+ reloadOnceForChunkError,+} from "@/lib/chunk-recovery";const SENTRY_DSN = process.env.SENTRY_DSN || process.env.NEXT_PUBLIC_SENTRY_DSN;@@ -26,8 +31,29 @@ Sentry.init({"The Internet connection appears to be offline",],+ beforeSend(event, hint) {+ if (isModuleFactoryError(hint.originalException)) {+ const context = getChunkRecoveryContext();+ event.tags = {+ ...event.tags,+ chunk_reloaded_recently: context.reloadedRecently,+ };+ event.contexts = { ...event.contexts, chunk_recovery: context };+ }+ return event;+ },+// Setting this option to true will print useful information to the console while you're setting up Sentry.debug: false,});+// Errors React catches in an error boundary reach the boundary instead; see+// app/[locale]/error.tsx and app/global-error.tsx.+window.addEventListener("error", (event) =>+ reloadOnceForChunkError(event.error),+);+window.addEventListener("unhandledrejection", (event) =>+ reloadOnceForChunkError(event.reason),+);+export const onRouterTransitionStart = Sentry.captureRouterTransitionStart;diff --git a/apps/web/src/app/[locale]/error.tsx b/apps/web/src/app/[locale]/error.tsxindex 870202851..3b080651e 100644--- a/apps/web/src/app/[locale]/error.tsx+++ b/apps/web/src/app/[locale]/error.tsx@@ -11,6 +11,7 @@ import { Link } from "@/components/link";import { DefaultLogo } from "@/features/branding/components/default-logo";import { Trans } from "@/i18n/client";import { signOut } from "@/lib/auth-client";+import { reloadOnceForChunkError } from "@/lib/chunk-recovery";import { githubRepoUrl } from "@/lib/constants";import { INVALID_SESSION } from "@/lib/errors/invalid-session-error";@@ -28,6 +29,7 @@ export default function LocaleErrorBoundary({React.useEffect(() => {if (!isInvalidSession) {Sentry.captureException(error);+ reloadOnceForChunkError(error);}}, [error, isInvalidSession]);diff --git a/apps/web/src/app/global-error.tsx b/apps/web/src/app/global-error.tsxindex 252fd1af2..9c34e03cf 100644--- a/apps/web/src/app/global-error.tsx+++ b/apps/web/src/app/global-error.tsx@@ -3,6 +3,7 @@import * as Sentry from "@sentry/nextjs";import NextError from "next/error";import { useEffect } from "react";+import { reloadOnceForChunkError } from "@/lib/chunk-recovery";export default function GlobalError({error,@@ -13,6 +14,7 @@ export default function GlobalError({}) {useEffect(() => {Sentry.captureException(error);+ reloadOnceForChunkError(error);}, [error]);return (diff --git a/apps/web/src/lib/chunk-recovery.test.ts b/apps/web/src/lib/chunk-recovery.test.tsnew file mode 100644index 000000000..b7e8eda3b--- /dev/null+++ b/apps/web/src/lib/chunk-recovery.test.ts@@ -0,0 +1,94 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ isModuleFactoryError,+ reloadOnceForChunkError,+ summarizeStaticAssets,+} from "./chunk-recovery";++const factoryError = new Error(+ "Module 304577 was instantiated because it was required from module 878939, but the module factory is not available.",+);++describe("isModuleFactoryError", () => {+ it("matches the Turbopack missing factory error", () => {+ expect(isModuleFactoryError(factoryError)).toBe(true);+ });++ it("ignores other errors", () => {+ expect(isModuleFactoryError(new Error("Load failed"))).toBe(false);+ expect(isModuleFactoryError(undefined)).toBe(false);+ });+});++describe("summarizeStaticAssets", () => {+ it("keeps only Next static assets and names them by file", () => {+ const entry = {+ initiatorType: "script",+ nextHopProtocol: "h3",+ transferSize: 0,+ encodedBodySize: 1200,+ decodedBodySize: 4800,+ duration: 12.4,+ responseStatus: 200,+ deliveryType: "cache",+ };+ expect(+ summarizeStaticAssets([+ {+ ...entry,+ name: "https://static.rallly.co/_next/static/immutable/chunks/2j4m7ciojig3r.js",+ },+ { ...entry, name: "https://b.rallly.co/decide" },+ ]),+ ).toEqual([+ {+ file: "2j4m7ciojig3r.js",+ initiator: "script",+ protocol: "h3",+ status: 200,+ delivery: "cache",+ transfer: 0,+ encoded: 1200,+ decoded: 4800,+ ms: 12,+ },+ ]);+ });+});++describe("reloadOnceForChunkError", () => {+ const reload = vi.fn();++ beforeEach(() => {+ vi.useFakeTimers();+ vi.stubGlobal("location", { ...window.location, reload });+ window.sessionStorage.clear();+ });++ afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+ reload.mockReset();+ });++ it("reloads once and not again within the cooldown", () => {+ reloadOnceForChunkError(factoryError);+ reloadOnceForChunkError(factoryError);+ vi.runAllTimers();+ expect(reload).toHaveBeenCalledTimes(1);+ });++ it("reloads again after the cooldown", () => {+ reloadOnceForChunkError(factoryError);+ vi.advanceTimersByTime(5 * 60 * 1000 + 1);+ reloadOnceForChunkError(factoryError);+ vi.runAllTimers();+ expect(reload).toHaveBeenCalledTimes(2);+ });++ it("does not reload for other errors", () => {+ reloadOnceForChunkError(new Error("boom"));+ vi.runAllTimers();+ expect(reload).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/lib/chunk-recovery.ts b/apps/web/src/lib/chunk-recovery.tsnew file mode 100644index 000000000..8512344f9--- /dev/null+++ b/apps/web/src/lib/chunk-recovery.ts@@ -0,0 +1,87 @@+// 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.++const RELOAD_KEY = "rallly:chunk-reload-at";+const RELOAD_COOLDOWN_MS = 5 * 60 * 1000;++export function isModuleFactoryError(error: unknown) {+ const message =+ error instanceof Error+ ? error.message+ : typeof error === "string"+ ? error+ : "";+ return message.includes("module factory is not available");+}++type StaticAssetEntry = Pick<+ PerformanceResourceTiming,+ | "name"+ | "initiatorType"+ | "nextHopProtocol"+ | "transferSize"+ | "encodedBodySize"+ | "decodedBodySize"+ | "duration"+> & { responseStatus?: number; deliveryType?: string };++export function summarizeStaticAssets(entries: StaticAssetEntry[]) {+ return entries+ .filter((entry) => entry.name.includes("/_next/static/"))+ .map((entry) => ({+ file: entry.name.slice(entry.name.lastIndexOf("/") + 1),+ initiator: entry.initiatorType,+ protocol: entry.nextHopProtocol,+ status: entry.responseStatus,+ delivery: entry.deliveryType,+ // transferSize 0 with a body means it came from the browser cache;+ // encoded and decoded sizes that disagree with other loads of the same+ // file point to a truncated or altered response.+ transfer: entry.transferSize,+ encoded: entry.encodedBodySize,+ decoded: entry.decodedBodySize,+ ms: Math.round(entry.duration),+ }));+}++function readReloadedAt() {+ try {+ return Number(window.sessionStorage.getItem(RELOAD_KEY)) || null;+ } catch {+ return null;+ }+}++export function getChunkRecoveryContext() {+ const navigation = performance.getEntriesByType("navigation")[0] as+ | PerformanceNavigationTiming+ | undefined;+ const reloadedAt = readReloadedAt();+ return {+ navigationType: navigation?.type,+ reloadedRecently:+ reloadedAt !== null && Date.now() - reloadedAt < RELOAD_COOLDOWN_MS,+ assets: summarizeStaticAssets(+ performance.getEntriesByType("resource") as PerformanceResourceTiming[],+ ),+ };+}++export function reloadOnceForChunkError(error: unknown) {+ if (!isModuleFactoryError(error)) return;+ const reloadedAt = readReloadedAt();+ if (reloadedAt !== null && Date.now() - reloadedAt < RELOAD_COOLDOWN_MS) {+ return;+ }+ try {+ window.sessionStorage.setItem(RELOAD_KEY, String(Date.now()));+ } catch {+ // Without storage there is no loop guard, so never reload.+ return;+ }+ // Let Sentry hand its event to the transport first; it uses keepalive, so+ // the request survives the navigation.+ setTimeout(() => window.location.reload(), 0);+}