mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-14 22:50:51 +00:00
Take the writes off three read routes
A GET must not have side effects — api-handler.ts says so next to READ_HTTP_METHODS, where an MCP-audience token is admitted on the safe methods precisely because they are assumed to write nothing. Three routes broke that: the sync handshake bumped User.lastSyncedAt, the achievements read inserted unlock rows, and the cycle calendar fired a discarded promise at the forecast cache so a failed write left no trace anywhere. Each write moves to the place that causes it. The sync checkpoint is now stamped by the batch ingest endpoints for measurements, mood and intakes. The handshake reports it. That also fixes the watermark: the checkpoint used to advance past a window the client had not drained, and a client trusting it would skip that window. It can only trail a real sync now. The unlock rows move to a nightly achievement-unlock-sweep. The badge grid never needed them — unlocked comes from the live metrics and the completion date is derived — so the payload is unchanged; the rows pin that date and carry it into the backup, and the sweep reaches accounts that never open the page. The cycle forecast moves to a nightly cycle-prediction-refresh. The CyclePrediction row is not a cache of a read: it is the index the reminder cron scans, so which reminders an account received depended on whether somebody had opened the calendar. persistPredictionCache no longer swallows its errors either — the job reports them.
This commit is contained in:
1 parent
eb641dcd7b
commit
6ac3a61829
27 files changed
+1365
-139
No files matched your search
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* `refreshPredictionCacheForUser` — the request-free recompute the nightly
|
||||
* job runs.
|
||||
*
|
||||
* Two things are load-bearing. It has to reach the persistence at all (the
|
||||
* job's whole purpose is that a forecast exists for an account that never
|
||||
* opened the calendar), and the write's failure has to escape: the previous
|
||||
* implementation caught everything and returned, so a cache that had not been
|
||||
* written for weeks looked exactly like one with nothing to write.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
cycleProfile: { findUnique: vi.fn() },
|
||||
user: { findUnique: vi.fn() },
|
||||
menstrualCycle: { findMany: vi.fn() },
|
||||
cycleDayLog: { findMany: vi.fn() },
|
||||
measurement: { findMany: vi.fn() },
|
||||
cyclePrediction: { findUnique: vi.fn(), upsert: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
import { prisma } from "@/lib/db";
|
||||
import { refreshPredictionCacheForUser } from "@/lib/cycle/prediction-refresh";
|
||||
|
||||
const NOW = new Date("2026-06-10T02:20:00.000Z");
|
||||
|
||||
function profile(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
userId: "user-1",
|
||||
goal: "GENERAL_HEALTH",
|
||||
typicalCycleLength: 28,
|
||||
typicalPeriodLength: 5,
|
||||
lutealPhaseLength: 14,
|
||||
predictionEnabled: true,
|
||||
rawChartMode: false,
|
||||
secondarySymptom: "MUCUS",
|
||||
cycleTrackingEnabled: true,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
/** Four period starts 28 days apart, the last one still open. */
|
||||
const CYCLE_STARTS = ["2026-03-05", "2026-04-02", "2026-04-30", "2026-05-28"];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(prisma.cycleProfile.findUnique).mockResolvedValue(
|
||||
profile() as never,
|
||||
);
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue({
|
||||
timezone: "Europe/Berlin",
|
||||
} as never);
|
||||
vi.mocked(prisma.menstrualCycle.findMany).mockResolvedValue(
|
||||
CYCLE_STARTS.map((startDate, i) => ({
|
||||
id: `cyc-${i}`,
|
||||
userId: "user-1",
|
||||
startDate,
|
||||
endDate: null,
|
||||
periodEndDate: null,
|
||||
ovulationDate: null,
|
||||
ovulationConfirmed: false,
|
||||
})) as never,
|
||||
);
|
||||
vi.mocked(prisma.cycleDayLog.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(prisma.measurement.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(prisma.cyclePrediction.findUnique).mockResolvedValue(null as never);
|
||||
vi.mocked(prisma.cyclePrediction.upsert).mockResolvedValue({} as never);
|
||||
});
|
||||
|
||||
describe("refreshPredictionCacheForUser", () => {
|
||||
it("writes the forecast for an account that never opened the calendar", async () => {
|
||||
const outcome = await refreshPredictionCacheForUser("user-1", NOW);
|
||||
|
||||
expect(outcome).toBe("persisted");
|
||||
expect(prisma.cyclePrediction.upsert).toHaveBeenCalledTimes(1);
|
||||
const call = vi.mocked(prisma.cyclePrediction.upsert).mock.calls[0]![0] as {
|
||||
where: { userId: string };
|
||||
create: { nextPeriodStart: string; generatedAt: Date };
|
||||
};
|
||||
expect(call.where.userId).toBe("user-1");
|
||||
// A real forecast, not a placeholder: four 28-day cycles put the next
|
||||
// period start 28 days after the last one.
|
||||
expect(call.create.nextPeriodStart).toBe("2026-06-25");
|
||||
expect(call.create.generatedAt).toEqual(NOW);
|
||||
});
|
||||
|
||||
it("writes nothing for an account with prediction turned off", async () => {
|
||||
vi.mocked(prisma.cycleProfile.findUnique).mockResolvedValue(
|
||||
profile({ predictionEnabled: false }) as never,
|
||||
);
|
||||
|
||||
const outcome = await refreshPredictionCacheForUser("user-1", NOW);
|
||||
|
||||
expect(outcome).toBe("no-prediction");
|
||||
expect(prisma.cyclePrediction.upsert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("writes nothing for an account that has no cycle profile", async () => {
|
||||
vi.mocked(prisma.cycleProfile.findUnique).mockResolvedValue(null as never);
|
||||
|
||||
const outcome = await refreshPredictionCacheForUser("user-1", NOW);
|
||||
|
||||
expect(outcome).toBe("no-profile");
|
||||
expect(prisma.cyclePrediction.upsert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("lets a failed write escape instead of swallowing it", async () => {
|
||||
vi.mocked(prisma.cyclePrediction.upsert).mockRejectedValue(
|
||||
new Error("write rejected"),
|
||||
);
|
||||
|
||||
await expect(
|
||||
refreshPredictionCacheForUser("user-1", NOW),
|
||||
).rejects.toThrowError("write rejected");
|
||||
});
|
||||
});
|
||||
@@ -2,13 +2,20 @@
|
||||
* Cycle prediction cache — debounced stale-while-revalidate (the v1.8.7
|
||||
* insight-assessment cache pattern, ios-contract §2.D).
|
||||
*
|
||||
* `GET /api/cycle/calendar` runs the pure engine synchronously (it is
|
||||
* cheap) for the live forecast it returns, AND persists that forecast to
|
||||
* the `CyclePrediction` cache row so the Coach snapshot + notifications
|
||||
* read a stable materialised value without re-running the engine. The
|
||||
* persist is debounced: a re-write only lands when the prior row is older
|
||||
* than the debounce window OR the forecast actually changed, so a tight
|
||||
* read loop never thrashes the row.
|
||||
* The `CyclePrediction` row is what the cycle-reminder cron scans to find
|
||||
* who is due a period-soon or fertile-soon push. It is written by the
|
||||
* `cycle-prediction-refresh` job (see `prediction-refresh.ts`), never by a
|
||||
* read: `GET /api/cycle/calendar` runs the same engine for the forecast it
|
||||
* returns and persists nothing.
|
||||
*
|
||||
* The persist is debounced: a re-write only lands when the prior row is
|
||||
* older than the debounce window OR the forecast actually changed, so a
|
||||
* repeated refresh never thrashes the row.
|
||||
*
|
||||
* Failures propagate. This used to swallow every error, which made a cache
|
||||
* that had not been written for weeks indistinguishable from one with
|
||||
* nothing to write; the caller is a job and puts the failure on the
|
||||
* operator's failing-jobs surface.
|
||||
*/
|
||||
import { prisma } from "@/lib/db";
|
||||
import type { CyclePredictionResult } from "@/lib/cycle/types";
|
||||
@@ -18,63 +25,58 @@ const PREDICTION_DEBOUNCE_MS = 6 * 60 * 60 * 1000; // 6h
|
||||
|
||||
/**
|
||||
* Persist (or refresh) the cached forecast for a user, debounced. A
|
||||
* no-op when a fresh-enough identical row already exists. Best-effort:
|
||||
* never throws into the read path.
|
||||
* no-op when a fresh-enough identical row already exists.
|
||||
*/
|
||||
export async function persistPredictionCache(
|
||||
userId: string,
|
||||
result: CyclePredictionResult,
|
||||
now: Date = new Date(),
|
||||
): Promise<void> {
|
||||
try {
|
||||
const existing = await prisma.cyclePrediction.findUnique({
|
||||
where: { userId },
|
||||
select: {
|
||||
method: true,
|
||||
nextPeriodStart: true,
|
||||
nextPeriodStartLow: true,
|
||||
nextPeriodStartHigh: true,
|
||||
confidence: true,
|
||||
cyclesObserved: true,
|
||||
generatedAt: true,
|
||||
},
|
||||
});
|
||||
const existing = await prisma.cyclePrediction.findUnique({
|
||||
where: { userId },
|
||||
select: {
|
||||
method: true,
|
||||
nextPeriodStart: true,
|
||||
nextPeriodStartLow: true,
|
||||
nextPeriodStartHigh: true,
|
||||
confidence: true,
|
||||
cyclesObserved: true,
|
||||
generatedAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
const unchanged =
|
||||
existing !== null &&
|
||||
existing.method === result.method &&
|
||||
existing.nextPeriodStart === result.nextPeriodStart &&
|
||||
existing.nextPeriodStartLow === result.nextPeriodStartLow &&
|
||||
existing.nextPeriodStartHigh === result.nextPeriodStartHigh &&
|
||||
existing.confidence === result.confidence &&
|
||||
existing.cyclesObserved === result.cyclesObserved;
|
||||
const unchanged =
|
||||
existing !== null &&
|
||||
existing.method === result.method &&
|
||||
existing.nextPeriodStart === result.nextPeriodStart &&
|
||||
existing.nextPeriodStartLow === result.nextPeriodStartLow &&
|
||||
existing.nextPeriodStartHigh === result.nextPeriodStartHigh &&
|
||||
existing.confidence === result.confidence &&
|
||||
existing.cyclesObserved === result.cyclesObserved;
|
||||
|
||||
const fresh =
|
||||
existing !== null &&
|
||||
now.getTime() - existing.generatedAt.getTime() < PREDICTION_DEBOUNCE_MS;
|
||||
const fresh =
|
||||
existing !== null &&
|
||||
now.getTime() - existing.generatedAt.getTime() < PREDICTION_DEBOUNCE_MS;
|
||||
|
||||
// Skip the write only when the row is BOTH unchanged AND fresh.
|
||||
if (unchanged && fresh) return;
|
||||
// Skip the write only when the row is BOTH unchanged AND fresh.
|
||||
if (unchanged && fresh) return;
|
||||
|
||||
const data = {
|
||||
method: result.method,
|
||||
nextPeriodStart: result.nextPeriodStart,
|
||||
nextPeriodStartLow: result.nextPeriodStartLow,
|
||||
nextPeriodStartHigh: result.nextPeriodStartHigh,
|
||||
fertileWindowStart: result.fertileWindowStart,
|
||||
fertileWindowEnd: result.fertileWindowEnd,
|
||||
predictedOvulation: result.predictedOvulation,
|
||||
confidence: result.confidence,
|
||||
cyclesObserved: result.cyclesObserved,
|
||||
generatedAt: now,
|
||||
};
|
||||
const data = {
|
||||
method: result.method,
|
||||
nextPeriodStart: result.nextPeriodStart,
|
||||
nextPeriodStartLow: result.nextPeriodStartLow,
|
||||
nextPeriodStartHigh: result.nextPeriodStartHigh,
|
||||
fertileWindowStart: result.fertileWindowStart,
|
||||
fertileWindowEnd: result.fertileWindowEnd,
|
||||
predictedOvulation: result.predictedOvulation,
|
||||
confidence: result.confidence,
|
||||
cyclesObserved: result.cyclesObserved,
|
||||
generatedAt: now,
|
||||
};
|
||||
|
||||
await prisma.cyclePrediction.upsert({
|
||||
where: { userId },
|
||||
create: { userId, ...data },
|
||||
update: data,
|
||||
});
|
||||
} catch {
|
||||
/* best-effort cache write — the live engine result is authoritative */
|
||||
}
|
||||
await prisma.cyclePrediction.upsert({
|
||||
where: { userId },
|
||||
create: { userId, ...data },
|
||||
update: data,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* Recompute the cached cycle forecast for one account from the persisted
|
||||
* rows, without a request.
|
||||
*
|
||||
* `CyclePrediction` is not a cache of a read — it is the index the
|
||||
* cycle-reminder cron scans to find who is due a period-soon or fertile-soon
|
||||
* push. Until v1.35.3 its only writer was `GET /api/cycle/calendar`, which
|
||||
* meant the reminders an account received depended on whether somebody had
|
||||
* opened the calendar recently, and the write itself was a discarded promise
|
||||
* inside a `try {} catch {}` that swallowed the failure. Both ends are fixed
|
||||
* here: the refresh runs on the schedule that consumes it, and a failed write
|
||||
* throws so the job reports it.
|
||||
*
|
||||
* The reads mirror the calendar route's default window so the forecast the
|
||||
* cron scans and the forecast the calendar renders come out of the same
|
||||
* inputs.
|
||||
*/
|
||||
import { prisma } from "@/lib/db";
|
||||
import { predictCycle } from "@/lib/cycle";
|
||||
import {
|
||||
toCycleInputs,
|
||||
toDayLogInputs,
|
||||
toProfileInput,
|
||||
} from "@/lib/cycle/engine-adapter";
|
||||
import { persistPredictionCache } from "@/lib/cycle/prediction-cache";
|
||||
import { addDays } from "@/lib/cycle/day-math";
|
||||
import { BBT_WINDOW } from "@/lib/cycle/types";
|
||||
import { DEFAULT_TIMEZONE, moodDateKey } from "@/lib/mood/date-key";
|
||||
|
||||
/** Day-log lookback: the calendar's default past span or the symptothermal
|
||||
* window, whichever reaches further back. */
|
||||
const LOOKBACK_DAYS = Math.max(90, BBT_WINDOW);
|
||||
|
||||
/** Wrist/skin-temperature lookback feeding the temperature-trend layer. */
|
||||
const TEMPERATURE_LOOKBACK_DAYS = 90;
|
||||
|
||||
export type PredictionRefreshOutcome =
|
||||
/** A forecast was computed and the cache row reflects it. */
|
||||
| "persisted"
|
||||
/** No profile row, so the account has never touched cycle tracking. */
|
||||
| "no-profile"
|
||||
/** Prediction is off for this account (raw-chart mode / explicit opt-out),
|
||||
* or the engine had nothing to forecast from. */
|
||||
| "no-prediction";
|
||||
|
||||
/**
|
||||
* Recompute and persist the forecast for one account. Throws if the write
|
||||
* fails — the caller is a job and owns the failure.
|
||||
*/
|
||||
export async function refreshPredictionCacheForUser(
|
||||
userId: string,
|
||||
now: Date = new Date(),
|
||||
): Promise<PredictionRefreshOutcome> {
|
||||
const [profile, user] = await Promise.all([
|
||||
prisma.cycleProfile.findUnique({ where: { userId } }),
|
||||
prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { timezone: true },
|
||||
}),
|
||||
]);
|
||||
if (!profile) return "no-profile";
|
||||
if (!profile.predictionEnabled || profile.rawChartMode) {
|
||||
return "no-prediction";
|
||||
}
|
||||
|
||||
const tz = user?.timezone ?? DEFAULT_TIMEZONE;
|
||||
const today = moodDateKey(now, tz);
|
||||
|
||||
const [cycles, dayLogs, nightlyTemps] = await Promise.all([
|
||||
prisma.menstrualCycle.findMany({
|
||||
where: { userId, deletedAt: null },
|
||||
orderBy: { startDate: "asc" },
|
||||
}),
|
||||
prisma.cycleDayLog.findMany({
|
||||
where: {
|
||||
userId,
|
||||
deletedAt: null,
|
||||
date: { gte: addDays(today, -LOOKBACK_DAYS) },
|
||||
},
|
||||
orderBy: { date: "asc" },
|
||||
select: {
|
||||
date: true,
|
||||
flow: true,
|
||||
basalBodyTempC: true,
|
||||
temperatureExcluded: true,
|
||||
ovulationTest: true,
|
||||
cervicalMucus: true,
|
||||
cervixPosition: true,
|
||||
cervixFirmness: true,
|
||||
cervixOpening: true,
|
||||
},
|
||||
}),
|
||||
prisma.measurement.findMany({
|
||||
where: {
|
||||
userId,
|
||||
deletedAt: null,
|
||||
type: "WRIST_TEMPERATURE",
|
||||
measuredAt: {
|
||||
gte: new Date(
|
||||
Date.parse(
|
||||
`${addDays(today, -TEMPERATURE_LOOKBACK_DAYS)}T00:00:00Z`,
|
||||
),
|
||||
),
|
||||
},
|
||||
},
|
||||
orderBy: { measuredAt: "asc" },
|
||||
select: { measuredAt: true, value: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
const nights = nightlyTemps.map((m) => ({
|
||||
date: moodDateKey(m.measuredAt, tz),
|
||||
valueC: m.value,
|
||||
}));
|
||||
|
||||
const prediction = predictCycle(
|
||||
toCycleInputs(cycles),
|
||||
toDayLogInputs(dayLogs),
|
||||
toProfileInput(profile),
|
||||
today,
|
||||
nights,
|
||||
);
|
||||
|
||||
await persistPredictionCache(userId, prediction, now);
|
||||
return "persisted";
|
||||
}
|
||||
Reference in new issue
Block a user