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

+72 -3
View File
@@ -48,7 +48,9 @@ describe("apiFetch", () => {
const data = await apiFetch<{ id: string }>("/api/measurements/m1");
expect(data).toEqual({ id: "m1" });
expect(fetchMock).toHaveBeenCalledWith("/api/measurements/m1", undefined);
expect(fetchMock).toHaveBeenCalledWith("/api/measurements/m1", {
signal: expect.any(AbortSignal),
});
});
it("passes init through to fetch (signal, cache, headers)", async () => {
@@ -171,6 +173,67 @@ describe("apiFetchRaw", () => {
await expect(apiFetchRaw("/api/foo")).resolves.toBe(res);
});
it("applies NO default timeout — SSE streams outlive any fixed window", async () => {
fetchMock.mockResolvedValueOnce(new Response("stream", { status: 200 }));
await apiFetchRaw("/api/insights/chat", { method: "POST" });
const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
expect(init.signal).toBeUndefined();
});
});
describe("default timeout", () => {
it("attaches a default AbortSignal when the caller passes no signal", async () => {
fetchMock.mockResolvedValueOnce(jsonResponse({ data: null, error: null }));
await apiFetch("/api/foo", { cache: "no-store" });
const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
expect(init.cache).toBe("no-store");
expect(init.signal).toBeInstanceOf(AbortSignal);
});
it("a caller-supplied signal replaces the default", async () => {
fetchMock.mockResolvedValueOnce(jsonResponse({ data: null, error: null }));
const controller = new AbortController();
await apiFetch("/api/foo", { signal: controller.signal });
const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
expect(init.signal).toBe(controller.signal);
});
it("signal: null opts out of the default entirely", async () => {
fetchMock.mockResolvedValueOnce(jsonResponse({ data: null, error: null }));
await apiFetch("/api/foo", { signal: null });
const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
expect(init.signal).toBeNull();
});
it("apiFetchEnvelope carries the same default", async () => {
fetchMock.mockResolvedValueOnce(
jsonResponse({ data: [], error: null, meta: {} }),
);
await apiFetchEnvelope("/api/items");
const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
expect(init.signal).toBeInstanceOf(AbortSignal);
});
it("the default signal carries through the verb helpers' body merge", async () => {
fetchMock.mockResolvedValueOnce(jsonResponse({ data: null, error: null }));
await apiPost("/api/foo", { a: 1 });
const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
expect(init.method).toBe("POST");
expect(init.signal).toBeInstanceOf(AbortSignal);
});
});
describe("verb helpers", () => {
@@ -179,7 +242,10 @@ describe("verb helpers", () => {
await apiGet("/api/foo");
expect(fetchMock).toHaveBeenCalledWith("/api/foo", { method: "GET" });
expect(fetchMock).toHaveBeenCalledWith("/api/foo", {
method: "GET",
signal: expect.any(AbortSignal),
});
});
it.each([
@@ -206,7 +272,10 @@ describe("verb helpers", () => {
await apiPost("/api/foo");
expect(fetchMock).toHaveBeenCalledWith("/api/foo", { method: "POST" });
expect(fetchMock).toHaveBeenCalledWith("/api/foo", {
method: "POST",
signal: expect.any(AbortSignal),
});
});
it("merges caller headers with the JSON Content-Type", async () => {
+23 -4
View File
@@ -28,6 +28,11 @@
* callers can branch on `err.status === 429` for cooldown UX.
* - No toast / no global side effect ever originates here. Surfacing
* errors stays the call site's responsibility.
* - Every request carries a default 15 s `AbortSignal.timeout` so a
* stalled response can never hold a query in `isLoading` forever.
* Passing `init.signal` (any value, including `null` to opt out)
* replaces the default entirely — callers that need a longer
* window or their own cancellation own the signal then.
*
* Verb helpers `apiGet` / `apiPost` / `apiPut` / `apiPatch` /
* `apiDelete` JSON-encode an optional body and set `Content-Type:
@@ -39,7 +44,9 @@
* few callers that read success-side `meta` (pagination totals).
* - `apiFetchRaw` is a plain same-origin `fetch` passthrough for call
* sites that need the `Response` itself — blob downloads, SSE
* streams, manual status branching. No `.ok` check, no unwrap.
* streams, manual status branching. No `.ok` check, no unwrap, and
* deliberately NO default timeout: the Coach chat stream and other
* long-lived responses ride this path with their own signals.
*/
import { readError } from "./read-error";
@@ -91,6 +98,17 @@ async function parseEnvelope<T, M>(
return JSON.parse(text) as Envelope<T, M>;
}
/** Default per-request timeout for the envelope helpers. */
export const DEFAULT_TIMEOUT_MS = 15_000;
function withDefaultTimeout(init?: RequestInit): RequestInit {
// An explicit caller signal wins — including `null`, which opts out
// of any timeout. Only the absent case gets the default so a stalled
// response cannot park a TanStack query in `isLoading` forever.
if (init?.signal !== undefined) return init;
return { ...init, signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS) };
}
/**
* Same-origin API fetch — resolves with the unwrapped `data` payload,
* throws {@link ApiError} on a non-OK response.
@@ -99,7 +117,7 @@ export async function apiFetch<T = unknown>(
path: string,
init?: RequestInit,
): Promise<T> {
const res = await fetch(path, init);
const res = await fetch(path, withDefaultTimeout(init));
if (!res.ok) await throwApiError(res);
const envelope = await parseEnvelope<T, unknown>(res);
return (envelope === undefined ? undefined : envelope.data) as T;
@@ -113,7 +131,7 @@ export async function apiFetchEnvelope<
T = unknown,
M = Record<string, unknown>,
>(path: string, init?: RequestInit): Promise<{ data: T; meta: M | undefined }> {
const res = await fetch(path, init);
const res = await fetch(path, withDefaultTimeout(init));
if (!res.ok) await throwApiError(res);
const envelope = await parseEnvelope<T, M>(res);
return {
@@ -125,7 +143,8 @@ export async function apiFetchEnvelope<
/**
* Plain same-origin `fetch` passthrough for call sites that need the raw
* `Response` — blob downloads, SSE streams, manual status branching.
* Performs no `.ok` check and no envelope unwrap.
* Performs no `.ok` check, no envelope unwrap, and applies no default
* timeout (SSE streams legitimately outlive any fixed window).
*/
export function apiFetchRaw(
path: string,