mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 15:23:29 +00:00
perf(dashboard,insights): reserve the cold-paint footprint and cache the slow overview reads
The dashboard reserves chart-row skeleton cells from the saved layout before the snapshot resolves, so a cold load paints close to its final footprint instead of growing by a screen when data lands; the tile silhouettes count only tile-capable widgets with blood pressure as two, the greeting line keeps its box through name personalisation, and the getting-started checklist moves below the charts where its arrival shifts nothing. On the insights overview the targets build runs its eight reads in parallel with a one-year floor on the glucose scan instead of strictly in sequence over an unbounded history, the derived batch gains a server cache where it previously recomputed sixteen metrics on every read, both serve stale-while-revalidate, and the health-score column reserves its exact footprint while the analytics payload is pending.
This commit is contained in:
1 parent
b5e799c2d6
commit
242d2514ee
13 files changed
+784
-159
No files matched your search
@@ -51,6 +51,11 @@ import { GET } from "../route";
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { computeDerivedMetric } from "@/lib/insights/derived";
|
||||
import { __resetAllCachesForTests } from "@/lib/cache/server-cache";
|
||||
import {
|
||||
invalidateUserMeasurements,
|
||||
invalidateUserMood,
|
||||
} from "@/lib/cache/invalidate";
|
||||
|
||||
const SESSION_OK = {
|
||||
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
|
||||
@@ -66,6 +71,9 @@ function makeReq(metrics?: string): NextRequest {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
// v1.16.8 — the route reads through the module-scope `insightsDerived`
|
||||
// server cache; reset it so every test starts on a cold cell.
|
||||
__resetAllCachesForTests();
|
||||
vi.mocked(prisma.appSettings.findUnique).mockResolvedValue(null as never);
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue({
|
||||
dateOfBirth: new Date("1986-01-01"),
|
||||
@@ -144,3 +152,75 @@ describe("GET /api/insights/derived/batch", () => {
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/insights/derived/batch — server cache (v1.16.8)", () => {
|
||||
it("serves a warm repeat from the per-user cache without recomputing", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
const first = await callGet(makeReq("READINESS,BMI"));
|
||||
expect(first.status).toBe(200);
|
||||
expect(computeDerivedMetric).toHaveBeenCalledTimes(2);
|
||||
|
||||
const second = await callGet(makeReq("READINESS,BMI"));
|
||||
expect(second.status).toBe(200);
|
||||
// Cache hit — no second profile read, no second compute fan-out.
|
||||
expect(computeDerivedMetric).toHaveBeenCalledTimes(2);
|
||||
expect(prisma.user.findUnique).toHaveBeenCalledTimes(1);
|
||||
|
||||
const body = (await second.json()) as {
|
||||
data: { metrics: Record<string, { status: string }> };
|
||||
};
|
||||
expect(Object.keys(body.data.metrics).sort()).toEqual([
|
||||
"BMI",
|
||||
"READINESS",
|
||||
]);
|
||||
});
|
||||
|
||||
it("hits the same cell regardless of token order", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
await callGet(makeReq("READINESS,BMI"));
|
||||
await callGet(makeReq("BMI,READINESS"));
|
||||
// The key sorts the tokens, so the reordered request is a hit.
|
||||
expect(computeDerivedMetric).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("never serves one user's cell to another user", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
await callGet(makeReq("BMI"));
|
||||
expect(computeDerivedMetric).toHaveBeenCalledTimes(1);
|
||||
|
||||
vi.mocked(getSession).mockResolvedValue({
|
||||
...SESSION_OK,
|
||||
user: { ...SESSION_OK.user, id: "user-2" },
|
||||
} as never);
|
||||
await callGet(makeReq("BMI"));
|
||||
// Different userId prefix → cold cell → fresh compute.
|
||||
expect(computeDerivedMetric).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("recomputes after an interactive measurement write evicts the bucket", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
await callGet(makeReq("BMI"));
|
||||
expect(computeDerivedMetric).toHaveBeenCalledTimes(1);
|
||||
|
||||
invalidateUserMeasurements("user-1", { evict: true });
|
||||
await callGet(makeReq("BMI"));
|
||||
expect(computeDerivedMetric).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("serves stale-while-revalidate after a background write marks the bucket stale", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
await callGet(makeReq("BMI"));
|
||||
expect(computeDerivedMetric).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Background sync posture (no evict): the entry is marked stale, so
|
||||
// the next read serves the prior body immediately AND kicks off one
|
||||
// background recompute.
|
||||
invalidateUserMood("user-1");
|
||||
const res = await callGet(makeReq("BMI"));
|
||||
expect(res.status).toBe(200);
|
||||
// The background rebuild runs detached; give the microtask queue a
|
||||
// tick so the recompute lands before asserting.
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
expect(computeDerivedMetric).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@@ -26,6 +26,11 @@ import pLimit from "p-limit";
|
||||
import { apiSuccess, apiError, returnAllZodIssues } from "@/lib/api-response";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import {
|
||||
cachedSwr,
|
||||
caches,
|
||||
type ServerCache,
|
||||
} from "@/lib/cache/server-cache";
|
||||
import { requireAssistantSurface } from "@/lib/feature-flags";
|
||||
import { prisma } from "@/lib/db";
|
||||
import {
|
||||
@@ -139,10 +144,70 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
);
|
||||
}
|
||||
|
||||
// The deterministic per-score assessment is locale-dependent, so the
|
||||
// locale joins the cache key below — a de / en pair never shares a cell.
|
||||
const locale = await resolveServerLocale({
|
||||
request,
|
||||
userLocale: user.locale ?? null,
|
||||
override: request.nextUrl.searchParams.get("locale"),
|
||||
});
|
||||
const assessmentLocale = locale === "de" ? "de" : "en";
|
||||
|
||||
// v1.16.8 — read-through the per-user derived cache with
|
||||
// stale-while-revalidate. The cold build below walks the rollup tier
|
||||
// once per metric (1–2 s wall-clock for the overview's ~16-token
|
||||
// grid); the production trace showed the full recompute re-paid on
|
||||
// every read past the client's 60 s staleTime. Tokens sort into the
|
||||
// key so request order never splits cells; measurement writes evict /
|
||||
// mark the `${userId}|` prefix stale via `invalidateUserMeasurements`
|
||||
// and mood writes mark it stale (READINESS reads the mood series).
|
||||
const cacheKey = `${user.id}|batch|${items
|
||||
.map((item) => item.key)
|
||||
.sort()
|
||||
.join(",")}|${assessmentLocale}`;
|
||||
const map = await cachedSwr(
|
||||
caches.insightsDerived as ServerCache<
|
||||
Awaited<ReturnType<typeof buildDerivedBatch>>
|
||||
>,
|
||||
cacheKey,
|
||||
() =>
|
||||
buildDerivedBatch({
|
||||
userId: user.id,
|
||||
items,
|
||||
assessmentLocale,
|
||||
}),
|
||||
annotate,
|
||||
);
|
||||
|
||||
annotate({
|
||||
action: { name: "insights.derived.batch" },
|
||||
meta: {
|
||||
requested: items.length,
|
||||
ok: Object.values(map).filter((entry) => entry.status === "ok").length,
|
||||
},
|
||||
});
|
||||
|
||||
// `metrics` is a map keyed by the per-request token so the client reads
|
||||
// back exactly what it asked for (`VITALS_BASELINE:WEIGHT`, `READINESS`).
|
||||
return apiSuccess({ metrics: map });
|
||||
});
|
||||
|
||||
/**
|
||||
* The cacheable batch body — profile load + bounded per-metric fan-out.
|
||||
* Lifted out of the handler so `cachedSwr` can wrap it; everything here
|
||||
* is pure compute over the rollup tier (no provider call).
|
||||
*/
|
||||
async function buildDerivedBatch(input: {
|
||||
userId: string;
|
||||
items: BatchItem[];
|
||||
assessmentLocale: "de" | "en";
|
||||
}) {
|
||||
const { userId, items, assessmentLocale } = input;
|
||||
|
||||
// Profile read ONCE — the pool-contention mitigation; the same shared
|
||||
// loader the nightly score jobs use, so the batch never re-reads the
|
||||
// User row per metric.
|
||||
const profile = await loadBaselineProfile(prisma, user.id);
|
||||
const profile = await loadBaselineProfile(prisma, userId);
|
||||
|
||||
// Fan out under a bounded limiter so a 17-item dashboard read resolves
|
||||
// four computes at a time against the shared pool, not seventeen.
|
||||
@@ -156,12 +221,6 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
// null for non-assessable ids / non-`ok` status, so a non-score item still
|
||||
// gets `assessment: null`. A best-effort grid extra must NEVER fail the
|
||||
// whole batch, so each call is guarded → null on any unexpected shape.
|
||||
const locale = await resolveServerLocale({
|
||||
request,
|
||||
userLocale: user.locale ?? null,
|
||||
override: request.nextUrl.searchParams.get("locale"),
|
||||
});
|
||||
const assessmentLocale = locale === "de" ? "de" : "en";
|
||||
const safeAssessment = (
|
||||
metric: DerivedMetricId,
|
||||
derived: Parameters<typeof resolveDeterministicAssessment>[1],
|
||||
@@ -182,7 +241,7 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
limit(async () => {
|
||||
const derived = await computeDerivedMetric({
|
||||
metric: item.metric,
|
||||
userId: user.id,
|
||||
userId,
|
||||
profile,
|
||||
type: item.type,
|
||||
now,
|
||||
@@ -210,16 +269,5 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
|
||||
const map: Record<string, (typeof results)[number]["payload"]> = {};
|
||||
for (const r of results) map[r.key] = r.payload;
|
||||
|
||||
annotate({
|
||||
action: { name: "insights.derived.batch" },
|
||||
meta: {
|
||||
requested: items.length,
|
||||
ok: results.filter((r) => r.payload.status === "ok").length,
|
||||
},
|
||||
});
|
||||
|
||||
// `metrics` is a map keyed by the per-request token so the client reads
|
||||
// back exactly what it asked for (`VITALS_BASELINE:WEIGHT`, `READINESS`).
|
||||
return apiSuccess({ metrics: map });
|
||||
});
|
||||
return map;
|
||||
}
|
||||
@@ -277,4 +277,37 @@ describe("GET /api/insights/targets — mood-rollup tier swap", () => {
|
||||
expect(ageMs).toBeGreaterThan(oneYearMs - 3_600_000);
|
||||
expect(ageMs).toBeLessThan(oneYearMs + 3_600_000);
|
||||
});
|
||||
|
||||
it("bounds the glucose read with the same one-year floor (v1.16.8)", async () => {
|
||||
// The glucose section used to scan the user's entire BLOOD_GLUCOSE
|
||||
// history on every cold build (no `measuredAt` filter at all) just
|
||||
// to read the latest value per context. The read now carries the
|
||||
// same 365-day floor as the latest-ever-per-type query.
|
||||
await callGet(makeReq());
|
||||
|
||||
const calls = (
|
||||
prisma.measurement.findMany as ReturnType<typeof vi.fn>
|
||||
).mock.calls.map((c) => c[0]);
|
||||
const glucoseCall = calls.find((c) => c?.where?.type === "BLOOD_GLUCOSE");
|
||||
expect(glucoseCall).toBeDefined();
|
||||
expect(glucoseCall?.where?.measuredAt?.gte).toBeInstanceOf(Date);
|
||||
});
|
||||
|
||||
it("serves a warm repeat from the server cache without re-querying (v1.16.8)", async () => {
|
||||
const first = await callGet(makeReq());
|
||||
expect(first.status).toBe(200);
|
||||
const queriesAfterFirst = (
|
||||
prisma.measurement.findMany as ReturnType<typeof vi.fn>
|
||||
).mock.calls.length;
|
||||
expect(queriesAfterFirst).toBeGreaterThan(0);
|
||||
|
||||
const second = await callGet(makeReq());
|
||||
expect(second.status).toBe(200);
|
||||
// Same user, warm cell — the SWR read serves the cached body and
|
||||
// issues no further measurement queries inside the fresh TTL.
|
||||
expect(
|
||||
(prisma.measurement.findMany as ReturnType<typeof vi.fn>).mock.calls
|
||||
.length,
|
||||
).toBe(queriesAfterFirst);
|
||||
});
|
||||
});
|
||||
@@ -35,7 +35,7 @@ import type {
|
||||
} from "@/generated/prisma/client";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { cached, caches, type ServerCache } from "@/lib/cache/server-cache";
|
||||
import { cachedSwr, caches, type ServerCache } from "@/lib/cache/server-cache";
|
||||
import { NO_STORE_BUT_BFCACHE } from "@/lib/http/cache-headers";
|
||||
import {
|
||||
getEffectiveRange,
|
||||
@@ -133,7 +133,14 @@ type AuthedUser = Awaited<ReturnType<typeof requireAuth>>["user"];
|
||||
|
||||
export const GET = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
const body = await cached(
|
||||
// v1.16.8 — stale-while-revalidate read. The cold build is the
|
||||
// multi-query walk below; past the 60 s fresh TTL the prior body now
|
||||
// serves immediately while ONE background rebuild warms the cell,
|
||||
// instead of every Insights mount more than a minute apart re-paying
|
||||
// the >1 s compute inline. Writes still hard-evict the bucket
|
||||
// (`invalidateUser*` → `deleteByPrefix`), so user actions always
|
||||
// reflect on the next read.
|
||||
const body = await cachedSwr(
|
||||
caches.insightsTargets as ServerCache<
|
||||
Awaited<ReturnType<typeof buildTargetsResponse>>
|
||||
>,
|
||||
@@ -158,25 +165,6 @@ async function buildTargetsResponse(user: AuthedUser) {
|
||||
const userTz = user.timezone ?? DEFAULT_TIMEZONE;
|
||||
const dayKey = (d: Date): string => userDayKey(d, userTz);
|
||||
|
||||
// Fetch user profile
|
||||
const dbUser = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: {
|
||||
heightCm: true,
|
||||
dateOfBirth: true,
|
||||
gender: true,
|
||||
glucoseUnit: true,
|
||||
thresholdsJson: true,
|
||||
// v1.11.5 — needed to collapse a dual-source sleep night to one
|
||||
// canonical source before reconstructing per-night asleep totals.
|
||||
sourcePriorityJson: true,
|
||||
},
|
||||
});
|
||||
|
||||
const age = dbUser?.dateOfBirth ? getAge(new Date(dbUser.dateOfBirth)) : null;
|
||||
const gender = (dbUser?.gender as "MALE" | "FEMALE" | null) ?? null;
|
||||
const heightCm = dbUser?.heightCm ?? null;
|
||||
|
||||
// Fetch latest measurements for each type
|
||||
// v1.11.5 — SLEEP_DURATION is handled by a dedicated per-night
|
||||
// reconstruction read below (the generic per-type average treats each
|
||||
@@ -198,47 +186,166 @@ async function buildTargetsResponse(user: AuthedUser) {
|
||||
];
|
||||
|
||||
const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
|
||||
|
||||
// Fetch all measurements in the last 30 days + the latest for each type
|
||||
// Soft-delete filter mirrors the W-DELETED pattern: tombstoned rows
|
||||
// must not contribute to tile averages / latest values once iOS sync
|
||||
// starts emitting deletions.
|
||||
const recentMeasurements = await prisma.measurement.findMany({
|
||||
where: {
|
||||
userId,
|
||||
type: { in: types },
|
||||
measuredAt: { gte: thirtyDaysAgo },
|
||||
deletedAt: null,
|
||||
},
|
||||
orderBy: { measuredAt: "desc" },
|
||||
select: { type: true, value: true, measuredAt: true },
|
||||
});
|
||||
|
||||
// Absolute latest measurement per type within a one-year floor.
|
||||
//
|
||||
// Prisma's `distinct` does not compile to Postgres `DISTINCT ON` — the
|
||||
// driver dedups after pulling the rows, so an unbounded scan on a
|
||||
// 347 k-row tenant pulls every measurement back to Node only to drop
|
||||
// all but seven (audit Critical Finding #2, v1.4.40). The 365-day
|
||||
// floor caps the planner-side walk to the existing
|
||||
// `(user_id, type, measured_at)` index range; the trade-off is that a
|
||||
// user who hasn't measured a metric in over a year sees the tile's
|
||||
// `current` value as null instead of pulling a stale year-old reading
|
||||
// forward — which is the correct behaviour for the consistency strip
|
||||
// (the strip already gates on "fewer than 3 readings in 30 days" →
|
||||
// insufficientData).
|
||||
const oneYearAgo = new Date(Date.now() - 365 * 24 * 60 * 60 * 1000);
|
||||
const latestEverByType = await prisma.measurement.findMany({
|
||||
where: {
|
||||
userId,
|
||||
type: { in: types },
|
||||
measuredAt: { gte: oneYearAgo },
|
||||
deletedAt: null,
|
||||
},
|
||||
orderBy: { measuredAt: "desc" },
|
||||
distinct: ["type"],
|
||||
select: { type: true, value: true },
|
||||
});
|
||||
|
||||
// Mood-rollup warm-up fires before the parallel read below so a legacy
|
||||
// account converges onto the rollup tier on a subsequent request; the
|
||||
// read itself never blocks on the warm-up (fire-and-forget).
|
||||
void ensureUserMoodRollupsFresh(userId);
|
||||
// Five-year window mirrors `/api/mood/analytics` so existing rollup
|
||||
// coverage is consulted; the trailing 30-day filter happens in JS
|
||||
// because the consistency strip already walks per-day buckets.
|
||||
const moodRollupWindowMs = 5 * 365 * 24 * 60 * 60 * 1000;
|
||||
const moodSince = new Date(Date.now() - moodRollupWindowMs);
|
||||
|
||||
// v1.16.8 — ONE parallel round of every independent read. The cold
|
||||
// build used to await eight queries strictly in sequence (profile →
|
||||
// measurements → latest-per-type → sleep → medications → intakes →
|
||||
// mood → glucose), stacking their round-trip latencies into the >1 s
|
||||
// wall-clock the production trace showed. All of them are independent
|
||||
// (the intake read depends only on the medication ids, so the pair
|
||||
// chains inside its own slot); fan them out together and the cold
|
||||
// build pays roughly the slowest query instead of the sum.
|
||||
const [
|
||||
dbUser,
|
||||
recentMeasurements,
|
||||
latestEverByType,
|
||||
sleepStageRows,
|
||||
medicationBundle,
|
||||
moodRollups,
|
||||
latestMoodEntry,
|
||||
glucoseRows,
|
||||
] = await Promise.all([
|
||||
// User profile (height / age / gender / thresholds / source priority).
|
||||
prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: {
|
||||
heightCm: true,
|
||||
dateOfBirth: true,
|
||||
gender: true,
|
||||
glucoseUnit: true,
|
||||
thresholdsJson: true,
|
||||
// v1.11.5 — needed to collapse a dual-source sleep night to one
|
||||
// canonical source before reconstructing per-night asleep totals.
|
||||
sourcePriorityJson: true,
|
||||
},
|
||||
}),
|
||||
// All measurements in the last 30 days for the generic type set.
|
||||
// Soft-delete filter mirrors the W-DELETED pattern: tombstoned rows
|
||||
// must not contribute to tile averages / latest values once iOS sync
|
||||
// starts emitting deletions.
|
||||
prisma.measurement.findMany({
|
||||
where: {
|
||||
userId,
|
||||
type: { in: types },
|
||||
measuredAt: { gte: thirtyDaysAgo },
|
||||
deletedAt: null,
|
||||
},
|
||||
orderBy: { measuredAt: "desc" },
|
||||
select: { type: true, value: true, measuredAt: true },
|
||||
}),
|
||||
// Absolute latest measurement per type within a one-year floor.
|
||||
//
|
||||
// Prisma's `distinct` does not compile to Postgres `DISTINCT ON` — the
|
||||
// driver dedups after pulling the rows, so an unbounded scan on a
|
||||
// 347 k-row tenant pulls every measurement back to Node only to drop
|
||||
// all but seven (audit Critical Finding #2, v1.4.40). The 365-day
|
||||
// floor caps the planner-side walk to the existing
|
||||
// `(user_id, type, measured_at)` index range; the trade-off is that a
|
||||
// user who hasn't measured a metric in over a year sees the tile's
|
||||
// `current` value as null instead of pulling a stale year-old reading
|
||||
// forward — which is the correct behaviour for the consistency strip
|
||||
// (the strip already gates on "fewer than 3 readings in 30 days" →
|
||||
// insufficientData).
|
||||
prisma.measurement.findMany({
|
||||
where: {
|
||||
userId,
|
||||
type: { in: types },
|
||||
measuredAt: { gte: oneYearAgo },
|
||||
deletedAt: null,
|
||||
},
|
||||
orderBy: { measuredAt: "desc" },
|
||||
distinct: ["type"],
|
||||
select: { type: true, value: true },
|
||||
}),
|
||||
// Sleep stage rows for the per-night reconstruction (section 4).
|
||||
prisma.measurement.findMany({
|
||||
where: {
|
||||
userId,
|
||||
type: "SLEEP_DURATION",
|
||||
measuredAt: { gte: thirtyDaysAgo },
|
||||
deletedAt: null,
|
||||
},
|
||||
orderBy: { measuredAt: "asc" },
|
||||
select: { value: true, measuredAt: true, sleepStage: true, source: true },
|
||||
}),
|
||||
// Active medications + their 30-day intake events (section 8). The
|
||||
// intake read depends on the medication ids, so the pair chains
|
||||
// inside this slot while riding the outer fan-out.
|
||||
(async () => {
|
||||
const activeMedications = await prisma.medication.findMany({
|
||||
where: { userId, active: true },
|
||||
// v1.15.20 — schedules through the shared compliance select so the
|
||||
// configured per-dose windows reach this surface like every other.
|
||||
include: {
|
||||
schedules: { select: SCHEDULE_COMPLIANCE_SELECT },
|
||||
// v1.16.3 — archived schedule eras for era-aware compliance.
|
||||
scheduleRevisions: { orderBy: { validFrom: "asc" } },
|
||||
},
|
||||
orderBy: { name: "asc" },
|
||||
});
|
||||
if (activeMedications.length === 0) {
|
||||
return { activeMedications, intakeEvents: [] };
|
||||
}
|
||||
const intakeEvents = await prisma.medicationIntakeEvent.findMany({
|
||||
where: {
|
||||
userId,
|
||||
// v1.7.0 sync — exclude tombstoned rows.
|
||||
deletedAt: null,
|
||||
medicationId: {
|
||||
in: activeMedications.map((medication) => medication.id),
|
||||
},
|
||||
scheduledFor: { gte: thirtyDaysAgo },
|
||||
},
|
||||
orderBy: { scheduledFor: "desc" },
|
||||
select: {
|
||||
medicationId: true,
|
||||
takenAt: true,
|
||||
skipped: true,
|
||||
scheduledFor: true,
|
||||
},
|
||||
});
|
||||
return { activeMedications, intakeEvents };
|
||||
})(),
|
||||
// Mood day rollups (section 9).
|
||||
readMoodDayRollups(userId, moodSince),
|
||||
// Latest raw mood entry — bounded `take: 1` via the index.
|
||||
prisma.moodEntry.findFirst({
|
||||
// v1.7.0 sync — exclude tombstoned rows.
|
||||
where: { userId, deletedAt: null },
|
||||
orderBy: { moodLoggedAt: "desc" },
|
||||
select: { score: true, moodLoggedAt: true },
|
||||
}),
|
||||
// Glucose rows (section 10). Same one-year floor as the
|
||||
// latest-per-type read above — the previous unbounded scan pulled a
|
||||
// heavy logger's full history back to Node on every cold build; a
|
||||
// context whose newest reading is over a year old now reports no
|
||||
// card, matching the per-type tile posture.
|
||||
prisma.measurement.findMany({
|
||||
where: {
|
||||
userId,
|
||||
type: "BLOOD_GLUCOSE",
|
||||
measuredAt: { gte: oneYearAgo },
|
||||
deletedAt: null,
|
||||
},
|
||||
orderBy: { measuredAt: "desc" },
|
||||
select: { value: true, measuredAt: true, glucoseContext: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
const age = dbUser?.dateOfBirth ? getAge(new Date(dbUser.dateOfBirth)) : null;
|
||||
const gender = (dbUser?.gender as "MALE" | "FEMALE" | null) ?? null;
|
||||
const heightCm = dbUser?.heightCm ?? null;
|
||||
|
||||
const latestByType: Record<string, number | null> = {};
|
||||
const avg30ByType: Record<string, number | null> = {};
|
||||
@@ -813,16 +920,7 @@ async function buildTargetsResponse(user: AuthedUser) {
|
||||
// overview headline.
|
||||
const sleepRange = getSleepDurationRange();
|
||||
{
|
||||
const sleepStageRows = await prisma.measurement.findMany({
|
||||
where: {
|
||||
userId,
|
||||
type: "SLEEP_DURATION",
|
||||
measuredAt: { gte: thirtyDaysAgo },
|
||||
deletedAt: null,
|
||||
},
|
||||
orderBy: { measuredAt: "asc" },
|
||||
select: { value: true, measuredAt: true, sleepStage: true, source: true },
|
||||
});
|
||||
// `sleepStageRows` resolved in the parallel read at the top.
|
||||
const nights = reconstructSleepNights(
|
||||
sleepStageRows as SleepStageRow[],
|
||||
userTz,
|
||||
@@ -1002,40 +1100,12 @@ async function buildTargetsResponse(user: AuthedUser) {
|
||||
});
|
||||
}
|
||||
|
||||
// 8. Medication Compliance (average across active medications)
|
||||
const activeMedications = await prisma.medication.findMany({
|
||||
where: { userId, active: true },
|
||||
// v1.15.20 — schedules through the shared compliance select so the
|
||||
// configured per-dose windows reach this surface like every other.
|
||||
include: {
|
||||
schedules: { select: SCHEDULE_COMPLIANCE_SELECT },
|
||||
// v1.16.3 — archived schedule eras for era-aware compliance.
|
||||
scheduleRevisions: { orderBy: { validFrom: "asc" } },
|
||||
},
|
||||
orderBy: { name: "asc" },
|
||||
});
|
||||
// 8. Medication Compliance (average across active medications) —
|
||||
// `activeMedications` + their 30-day `intakeEvents` resolved in the
|
||||
// parallel read at the top.
|
||||
const { activeMedications, intakeEvents } = medicationBundle;
|
||||
|
||||
if (activeMedications.length > 0) {
|
||||
const thirtyDaysAgoIntake = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
|
||||
const intakeEvents = await prisma.medicationIntakeEvent.findMany({
|
||||
where: {
|
||||
userId,
|
||||
// v1.7.0 sync — exclude tombstoned rows.
|
||||
deletedAt: null,
|
||||
medicationId: {
|
||||
in: activeMedications.map((medication) => medication.id),
|
||||
},
|
||||
scheduledFor: { gte: thirtyDaysAgoIntake },
|
||||
},
|
||||
orderBy: { scheduledFor: "desc" },
|
||||
select: {
|
||||
medicationId: true,
|
||||
takenAt: true,
|
||||
skipped: true,
|
||||
scheduledFor: true,
|
||||
},
|
||||
});
|
||||
|
||||
const medicationStats = activeMedications.map((medication) => {
|
||||
const medicationEvents = intakeEvents.filter(
|
||||
(event) => event.medicationId === medication.id,
|
||||
@@ -1187,21 +1257,9 @@ async function buildTargetsResponse(user: AuthedUser) {
|
||||
// rows yet (legacy account before the boot-time backfill caught up)
|
||||
// we run the legacy live walk once and fire the warm-up so the next
|
||||
// request lands on the rollup tier. Same posture as
|
||||
// `/api/mood/analytics`.
|
||||
void ensureUserMoodRollupsFresh(userId);
|
||||
// `/api/mood/analytics`. The warm-up trigger + the `moodRollups` /
|
||||
// `latestMoodEntry` reads moved into the parallel round at the top.
|
||||
const thirtyDaysAgoMood = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
|
||||
// Five-year window mirrors `/api/mood/analytics` so existing rollup
|
||||
// coverage is consulted; the trailing 30-day filter happens in JS
|
||||
// because the consistency strip already walks per-day buckets.
|
||||
const moodRollupWindowMs = 5 * 365 * 24 * 60 * 60 * 1000;
|
||||
const moodSince = new Date(Date.now() - moodRollupWindowMs);
|
||||
const moodRollups = await readMoodDayRollups(userId, moodSince);
|
||||
const latestMoodEntry = await prisma.moodEntry.findFirst({
|
||||
// v1.7.0 sync — exclude tombstoned rows.
|
||||
where: { userId, deletedAt: null },
|
||||
orderBy: { moodLoggedAt: "desc" },
|
||||
select: { score: true, moodLoggedAt: true },
|
||||
});
|
||||
|
||||
// Build a per-day event list for the consistency strip + 30-day stats.
|
||||
// Use the rollup tier when populated; fall back to a bounded raw walk
|
||||
@@ -1357,12 +1415,8 @@ async function buildTargetsResponse(user: AuthedUser) {
|
||||
dateOfBirth: dbUser?.dateOfBirth ?? null,
|
||||
gender: dbUser?.gender ?? null,
|
||||
};
|
||||
// `glucoseRows` resolved (one-year floor) in the parallel read at the top.
|
||||
const thirtyDaysAgoGlucose = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
|
||||
const glucoseRows = await prisma.measurement.findMany({
|
||||
where: { userId, type: "BLOOD_GLUCOSE", deletedAt: null },
|
||||
orderBy: { measuredAt: "desc" },
|
||||
select: { value: true, measuredAt: true, glucoseContext: true },
|
||||
});
|
||||
|
||||
const labelKeyByContext: Record<GlucoseContext, string> = {
|
||||
FASTING: "targets.glucoseFasting",
|
||||
|
||||
Reference in new issue
Block a user