mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-19 00:12:18 +00:00
perf(dashboard): server-prefetch the Today hero + chart series into the dehydrated cache
Kill the above-the-fold first-load flash on `/`: the hero digest and the batched chart series still fired client-side after JS download + hydrate, so the hero and charts painted empty and filled in seconds later (LCP ~5.5 s mobile-throttled while the snapshot already dehydrated). Extend the existing `page.tsx` snapshot prefetch to also seed the daily digest and the chart series batch into the same dehydrated TanStack cache, under keys byte-identical to the client's: - Extract the series-batch route core into `readSeriesBatch(...)` so the RSC and the route share one code path (no HTTP-to-self); the route thins to auth + Zod + the shared reader, behaviour unchanged. - New client-safe pure module `batch-chart-types.ts`: `deriveBatchChartTypes` (the single implementation of the visible-with-data type-set derivation, order + resting-HR-vs-pulse pick preserved) and `computeBatchWindow` (profile-tz end-of-day minus the coverage window). Server and client run the same function over the same snapshot payload, and the window is computed once server-side and threaded to the client as a prop, so the `chartSeriesBatch` key matches on both sides by construction. - Render the hero data-first so the SSR HTML carries the populated hero (the LCP element) — hydration-safe because the digest is dehydrated and never restored from the IndexedDB persist allowlist; bound that invariant with comments on both the hero gate and the allowlist. - Warm the shared chart-runtime chunk during hydration. Both prefetches honour the `DASHBOARD_SSR_PREFETCH=false` escape and fail soft to the client-fetch path on any error; a ~400 ms soft budget bounds the cold-day digest cost. No contract change, no visual change.
This commit is contained in:
1 parent
427b5f0b7c
commit
271abd7b64
8 files changed
+691
-107
No files matched your search
@@ -22,28 +22,15 @@
|
||||
* client keeps sleep on the dedicated route.
|
||||
*/
|
||||
import { NextRequest } from "next/server";
|
||||
import pLimit from "p-limit";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { returnAllZodIssues } from "@/lib/api-response";
|
||||
import { apiSuccess } from "@/lib/api-response";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { loadUserSourcePriority } from "@/lib/rollups/measurement-read";
|
||||
import {
|
||||
readDailySeries,
|
||||
type DailySeriesRow,
|
||||
} from "@/lib/measurements/daily-series-read";
|
||||
import { readSeriesBatch } from "@/lib/measurements/series-batch-read";
|
||||
import {
|
||||
seriesBatchQuerySchema,
|
||||
SERIES_BATCH_MAX_TYPES,
|
||||
} from "@/lib/validations/series-batch";
|
||||
import type { MeasurementType } from "@/generated/prisma/client";
|
||||
|
||||
/**
|
||||
* Concurrency cap for the per-type rollup reads. Mirrors the W-POOL
|
||||
* `p-limit(4)` discipline applied across the analytics fan-out so a
|
||||
* wide dashboard never packs the shared Prisma pool.
|
||||
*/
|
||||
const SERIES_BATCH_CONCURRENCY = 4;
|
||||
|
||||
export const GET = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
@@ -55,49 +42,23 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
}
|
||||
|
||||
const { types, from, to } = parsed.data;
|
||||
// De-dupe while preserving order so a caller repeating a type doesn't
|
||||
// double-read it.
|
||||
const uniqueTypes = Array.from(new Set(types)) as MeasurementType[];
|
||||
|
||||
// Load the source-priority ladder ONCE and thread it across every type
|
||||
// so the batched reader doesn't re-query it per type.
|
||||
const priorityJson = await loadUserSourcePriority(user.id);
|
||||
|
||||
// Per-type isolation: a single type's transient DB reject degrades to an
|
||||
// empty slice for THAT type only, never a 500 that blanks every chart in
|
||||
// the row. The failing chart self-fetches through its existing fallback.
|
||||
const limit = pLimit(SERIES_BATCH_CONCURRENCY);
|
||||
let degradedTypes = 0;
|
||||
const entries = await Promise.all(
|
||||
uniqueTypes.map((type) =>
|
||||
limit(async (): Promise<readonly [MeasurementType, DailySeriesRow[]]> => {
|
||||
try {
|
||||
const rows = await readDailySeries({
|
||||
userId: user.id,
|
||||
type,
|
||||
from,
|
||||
to,
|
||||
priorityJson,
|
||||
});
|
||||
return [type, rows] as const;
|
||||
} catch {
|
||||
degradedTypes += 1;
|
||||
return [type, []] as const;
|
||||
}
|
||||
}),
|
||||
),
|
||||
// Shared core: priority ladder once, `p-limit(4)` per-type fan-out, per-type
|
||||
// fault isolation to `[]`. The RSC dashboard prefetch calls the same
|
||||
// function so the two paths never drift.
|
||||
const { series, degradedTypes } = await readSeriesBatch(
|
||||
user.id,
|
||||
types,
|
||||
from,
|
||||
to,
|
||||
);
|
||||
|
||||
const series: Record<string, DailySeriesRow[]> = {};
|
||||
for (const [type, rows] of entries) {
|
||||
series[type] = rows;
|
||||
}
|
||||
|
||||
const seriesLists = Object.values(series);
|
||||
annotate({
|
||||
action: { name: "measurement.series.batch" },
|
||||
meta: {
|
||||
type_count: uniqueTypes.length,
|
||||
total: entries.reduce((sum, [, rows]) => sum + rows.length, 0),
|
||||
type_count: seriesLists.length,
|
||||
total: seriesLists.reduce((sum, rows) => sum + rows.length, 0),
|
||||
degraded_types: degradedTypes,
|
||||
},
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user