fix(charts): degrade chart failures to one card and heal stale shells per version

The update poller and the chunk-error reload guard key on the target
version instead of disarming for the whole session, so a second deploy
re-arms the self-heal and a stale shell can no longer strand with
404ing chunks. Lazy chart imports retry once and mount inside a
per-card error boundary with a reload affordance — a failed chunk
degrades to one card instead of replacing the page. The JSON API
client attaches a fifteen-second timeout unless the caller brings its
own signal (the raw streaming path is exempt), chart queries surface
errors with a retry instead of rendering as an empty period, per-type
fetch failures reject instead of caching an empty series as fresh, and
the session and snapshot queries retry once on transient network or
server errors.
This commit is contained in:
Marc-André Bombeck committed 2026-06-11 21:17:27 +02:00
1 parent b346e78cc7
commit b5e799c2d6
27 files changed
+892 -89

No files matched your search

@@ -0,0 +1,41 @@
/**
* Unit tests for the chunk-error auto-reload guard in `src/app/error.tsx`.
*
* The guard is keyed on the running shell's build version: one reload
* attempt per BROKEN SHELL, not one per session. After a successful
* heal the reloaded page carries the new version and the guard re-arms
* by construction; the pre-v1.16.8 once-per-session key exhausted on
* multi-deploy days and stranded the user on the error page.
*/
import { describe, expect, it } from "vitest";
import { chunkReloadGuardValue, shouldAttemptChunkReload } from "../error";
describe("shouldAttemptChunkReload", () => {
it("reloads when no attempt is recorded", () => {
expect(shouldAttemptChunkReload(null, "1.16.8")).toBe(true);
});
it("suppresses a second reload for the SAME shell version", () => {
const stored = chunkReloadGuardValue("1.16.8");
expect(shouldAttemptChunkReload(stored, "1.16.8")).toBe(false);
});
it("re-arms after a deploy — the reloaded shell carries a NEW version", () => {
const stored = chunkReloadGuardValue("1.16.8");
expect(shouldAttemptChunkReload(stored, "1.16.9")).toBe(true);
});
it("treats a legacy timestamp guard value as no attempt", () => {
// Pre-v1.16.8 sessions stored `String(Date.now())`; it never matches
// a guard value, so a stranded session heals on its next chunk error.
expect(shouldAttemptChunkReload("1765400000000", "1.16.8")).toBe(true);
});
it("degrades to once-per-shell-lifetime when no version is injected", () => {
expect(chunkReloadGuardValue("")).toBe("unversioned");
expect(shouldAttemptChunkReload(null, "")).toBe(true);
expect(shouldAttemptChunkReload("unversioned", "")).toBe(false);
});
});
+39 -5
View File
@@ -4,6 +4,7 @@ import { useEffect } from "react";
import { ErrorDetails } from "@/components/error-details";
const CHUNK_RELOAD_KEY = "healthlog:chunk-reload-attempted";
const SHELL_VERSION = process.env.NEXT_PUBLIC_APP_VERSION ?? "";
function isChunkLoadError(err: Error & { digest?: string }): boolean {
if (err.name === "ChunkLoadError") return true;
@@ -16,6 +17,33 @@ function isChunkLoadError(err: Error & { digest?: string }): boolean {
);
}
/**
* Guard value recorded per auto-reload attempt — the running shell's
* build version, so the suppression is scoped to ONE shell. After a
* successful heal the reloaded page carries the NEW version and the
* guard re-arms by construction; only a shell that reloaded and is
* STILL broken (the new build is also missing the chunk) stays
* suppressed. Builds without an injected version degrade to the legacy
* once-per-session behaviour via the "unversioned" sentinel.
*/
export function chunkReloadGuardValue(shellVersion: string): string {
return shellVersion || "unversioned";
}
/**
* Pure reload decision so the guard semantics carry direct unit
* coverage. `stored` is the sessionStorage value from the last attempt
* (`null` when none happened); legacy guard values (the pre-v1.16.8
* timestamp) never match a version string, so a session stuck from
* before the change heals on its next chunk error.
*/
export function shouldAttemptChunkReload(
stored: string | null,
shellVersion: string,
): boolean {
return stored !== chunkReloadGuardValue(shellVersion);
}
export default function AppError({
error,
reset,
@@ -36,13 +64,19 @@ export default function AppError({
// After a deploy the cached shell still references old chunk
// filenames; they 404 and Next.js surfaces them as `ChunkLoadError`.
// A single hard reload fetches the new shell + chunk graph.
// sessionStorage gates the auto-reload so an error we can't recover
// from (e.g. the new build is also missing the chunk) doesn't loop.
// The sessionStorage guard is keyed on the shell version (see
// `chunkReloadGuardValue`) so it suppresses a loop within ONE
// broken shell but re-arms after every deploy — the pre-v1.16.8
// once-per-session guard exhausted on multi-deploy days and left
// the user on the error page with no automatic way out.
if (typeof window !== "undefined" && isChunkLoadError(error)) {
try {
const already = window.sessionStorage.getItem(CHUNK_RELOAD_KEY);
if (!already) {
window.sessionStorage.setItem(CHUNK_RELOAD_KEY, String(Date.now()));
const stored = window.sessionStorage.getItem(CHUNK_RELOAD_KEY);
if (shouldAttemptChunkReload(stored, SHELL_VERSION)) {
window.sessionStorage.setItem(
CHUNK_RELOAD_KEY,
chunkReloadGuardValue(SHELL_VERSION),
);
window.location.reload();
}
} catch {
+27 -8
View File
@@ -28,8 +28,10 @@ import type { DashboardAnalyticsData as AnalyticsData } from "@/types/analytics"
import dynamic from "next/dynamic";
import { Button } from "@/components/ui/button";
import { EmptyState } from "@/components/ui/empty-state";
import { ChartErrorBoundary } from "@/components/charts/chart-error-state";
import { ChartSkeleton } from "@/components/charts/chart-skeleton";
import { HealthChartDynamic } from "@/components/charts/health-chart-dynamic";
import { importWithRetry } from "@/lib/retry-import";
import {
DashboardChartCell,
useDashboardChartReveal,
@@ -64,20 +66,37 @@ const DASHBOARD_QUERY_OPTS = {
refetchOnWindowFocus: false,
} as const;
const MoodChart = dynamic(
// v1.16.8 — the loaders retry a rejected chunk import once (a lazy
// import caches its rejection permanently, so a transient 404 from a
// stale shell used to brick the card for the session) and each mount
// wraps in `<ChartErrorBoundary>` so a chunk that still fails degrades
// to ONE error card instead of bubbling to the route-level `error.tsx`.
const MoodChartLazy = dynamic(
() =>
import("@/components/charts/mood-chart").then((mod) => ({
default: mod.MoodChart,
})),
importWithRetry(() => import("@/components/charts/mood-chart")).then(
(mod) => ({ default: mod.MoodChart }),
),
{ ssr: false, loading: () => <ChartSkeleton /> },
);
const MedicationComplianceChart = dynamic(
const MoodChart = (props: React.ComponentProps<typeof MoodChartLazy>) => (
<ChartErrorBoundary>
<MoodChartLazy {...props} />
</ChartErrorBoundary>
);
const MedicationComplianceChartLazy = dynamic(
() =>
import("@/components/charts/medication-compliance-chart").then((mod) => ({
default: mod.MedicationComplianceChart,
})),
importWithRetry(
() => import("@/components/charts/medication-compliance-chart"),
).then((mod) => ({ default: mod.MedicationComplianceChart })),
{ ssr: false, loading: () => <ChartSkeleton /> },
);
const MedicationComplianceChart = (
props: React.ComponentProps<typeof MedicationComplianceChartLazy>,
) => (
<ChartErrorBoundary>
<MedicationComplianceChartLazy {...props} />
</ChartErrorBoundary>
);
import { useTranslations, useFormatters } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { useAnalyticsQuery } from "@/lib/queries/use-analytics-query";