fix(analytics): derive daysAgo from cached lastSeenAt per request

`lastSeenByType[type].daysAgo` was computed once inside the cached
60s envelope, so a body cached at 23:55 surfaced "vor 3d" until the
TTL refreshed at 00:55 instead of correctly flipping to "vor 4d" at
midnight. Store only the ISO `lastSeenAt` inside the cache and
derive `daysAgo` per call in the GET wrapper. The Map lookup stays
on the hot path; the per-call subtraction is a single Date.now()
per type.
This commit is contained in:
Marc-André Bombeck committed 2026-05-17 17:20:19 +02:00
1 parent ae637ce844
commit a86c6cf478
1 file changed
+57 -13
+57 -13
View File
@@ -83,13 +83,22 @@ export const GET = apiHandler(async (request?: Request) => {
// mount, and the Coach drawer all hit this endpoint within seconds
// of each other; the 60s TTL converts the 7.99s combined dashboard
// wait to a Map lookup on every subsequent caller.
const body = await cached(
const cachedBody = await cached(
caches.analytics as ServerCache<Awaited<ReturnType<typeof buildAnalyticsResponse>>>,
`${user.id}|default`,
() => buildAnalyticsResponse(user),
annotate,
);
// v1.4.38 — `lastSeenByType` lives inside the cached envelope as
// `{ lastSeenAt }` only; derive the `daysAgo` caption per call so
// the staleness label updates correctly across day boundaries.
// The cache TTL is 60s, but the day boundary it can straddle would
// otherwise leave the cached `daysAgo` off by one until the next
// refresh. Re-deriving on read is a single Date subtraction per
// type and stays on the hot path's Map-lookup side of the cache.
const body = enrichLastSeenDaysAgo(cachedBody);
const response = apiSuccess(body);
// v1.4.34 IW-B — bfcache-friendly directive so back-forward navigation
// restores the dashboard from memory. Per `src/lib/http/cache-headers.ts`:
@@ -104,6 +113,44 @@ export const GET = apiHandler(async (request?: Request) => {
type AuthedUser = Awaited<ReturnType<typeof requireAuth>>["user"];
/**
* v1.4.38 — derive `daysAgo` from the cached `lastSeenAt` ISO string
* per request. The cached envelope deliberately omits `daysAgo` so
* the dashboard tile staleness caption stays correct across day
* boundaries even when the body has been sitting in the 60s LRU.
*
* Returns a shallow-copied envelope with the enriched
* `lastSeenByType` map; everything else is passed through unchanged.
*/
function enrichLastSeenDaysAgo<
T extends {
lastSeenByType: Record<string, { lastSeenAt: string } | null>;
},
>(
body: T,
): Omit<T, "lastSeenByType"> & {
lastSeenByType: Record<
string,
{ lastSeenAt: string; daysAgo: number } | null
>;
} {
const nowMs = Date.now();
const enriched: Record<
string,
{ lastSeenAt: string; daysAgo: number } | null
> = {};
for (const [type, slot] of Object.entries(body.lastSeenByType)) {
if (slot === null) {
enriched[type] = null;
continue;
}
const lastMs = new Date(slot.lastSeenAt).getTime();
const daysAgo = Math.floor((nowMs - lastMs) / (24 * 60 * 60 * 1000));
enriched[type] = { lastSeenAt: slot.lastSeenAt, daysAgo };
}
return { ...body, lastSeenByType: enriched };
}
/**
* v1.4.34 IW-G — the heavy default-slice body, lifted out of the route
* handler so `cached()` can wrap it. Returns the raw JSON payload; the
@@ -163,13 +210,15 @@ async function buildAnalyticsResponse(user: AuthedUser) {
// tiles whose latest reading is older than a week. The series read
// already orders ascending (`fetchMeasurementSeriesChunked`'s stable
// `(measuredAt, id)` order); the last entry is the freshest sample.
// Surface as ISO + a server-computed `daysAgo` so the client never
// has to do tz-aware date math to colour the tile.
const nowForStaleness = new Date();
const lastSeenByType: Record<string, {
lastSeenAt: string;
daysAgo: number;
} | null> = {};
//
// v1.4.38 — the cached body now carries only `lastSeenAt` (ISO);
// `daysAgo` is derived in the GET wrapper per call. Storing the
// computed delta inside the cache let the value stale across day
// boundaries (60s TTL straddling midnight could surface a "vor 3d"
// caption that should read "vor 4d"). The ISO timestamp does not
// age, so re-deriving on read costs nothing and pins the caption
// to the real wall-clock at every request.
const lastSeenByType: Record<string, { lastSeenAt: string } | null> = {};
let totalRowsReadForAggregate = 0;
const measurementsByType = await Promise.all(
@@ -184,13 +233,8 @@ async function buildAnalyticsResponse(user: AuthedUser) {
// most-recent point without an extra pass.
const latest = measurements.at(-1);
if (latest) {
const daysAgo = Math.floor(
(nowForStaleness.getTime() - latest.measuredAt.getTime()) /
(24 * 60 * 60 * 1000),
);
lastSeenByType[type] = {
lastSeenAt: latest.measuredAt.toISOString(),
daysAgo,
};
} else {
lastSeenByType[type] = null;