mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-09 21:10:59 +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,92 @@
|
||||
/**
|
||||
* `GET /api/sync/state` is a read.
|
||||
*
|
||||
* It used to bump `User.lastSyncedAt` on every call, which is the exact
|
||||
* side-effecting GET the MCP-audience note in `api-handler.ts` warns against,
|
||||
* and it advanced the checkpoint past a window the client had not drained.
|
||||
* The checkpoint is now owned by the ingest boundaries; this route reports it.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("@/lib/api-handler", () => ({
|
||||
apiHandler: <T extends (...args: unknown[]) => unknown>(fn: T) => fn,
|
||||
requireAuth: vi.fn(async () => ({ user: { id: "u1" } })),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
measurement: { findFirst: vi.fn(), count: vi.fn() },
|
||||
moodEntry: { findFirst: vi.fn(), count: vi.fn() },
|
||||
medicationIntakeEvent: { findFirst: vi.fn(), count: vi.fn() },
|
||||
user: { findUnique: vi.fn(), update: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/logging/context", () => ({ annotate: vi.fn() }));
|
||||
|
||||
vi.mock("@/lib/api-response", () => ({
|
||||
apiSuccess: (data: unknown) => ({ data, error: null }),
|
||||
}));
|
||||
|
||||
import { GET } from "../route";
|
||||
import { prisma } from "@/lib/db";
|
||||
|
||||
const CHECKPOINT = new Date("2026-07-30T08:15:00.000Z");
|
||||
|
||||
type SyncStateBody = {
|
||||
lastSyncedAt: string | null;
|
||||
serverNow: string;
|
||||
timezone: string;
|
||||
};
|
||||
|
||||
async function callGet(): Promise<SyncStateBody> {
|
||||
const res = (await (
|
||||
GET as unknown as (req: unknown) => Promise<{ data: SyncStateBody }>
|
||||
)({})) as { data: SyncStateBody };
|
||||
return res.data;
|
||||
}
|
||||
|
||||
describe("GET /api/sync/state", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(prisma.measurement.findFirst).mockResolvedValue(null as never);
|
||||
vi.mocked(prisma.moodEntry.findFirst).mockResolvedValue(null as never);
|
||||
vi.mocked(prisma.medicationIntakeEvent.findFirst).mockResolvedValue(
|
||||
null as never,
|
||||
);
|
||||
vi.mocked(prisma.measurement.count).mockResolvedValue(0 as never);
|
||||
vi.mocked(prisma.moodEntry.count).mockResolvedValue(0 as never);
|
||||
vi.mocked(prisma.medicationIntakeEvent.count).mockResolvedValue(0 as never);
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue({
|
||||
lastSyncedAt: CHECKPOINT,
|
||||
timezone: "Europe/Berlin",
|
||||
} as never);
|
||||
});
|
||||
|
||||
it("writes nothing — the handshake never touches the user row", async () => {
|
||||
await callGet();
|
||||
expect(prisma.user.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reports the stored checkpoint rather than the previous handshake", async () => {
|
||||
const body = await callGet();
|
||||
expect(body.lastSyncedAt).toBe(CHECKPOINT.toISOString());
|
||||
});
|
||||
|
||||
it("keeps reporting the same checkpoint across repeated calls", async () => {
|
||||
const first = await callGet();
|
||||
const second = await callGet();
|
||||
expect(second.lastSyncedAt).toBe(first.lastSyncedAt);
|
||||
expect(prisma.user.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reports a never-synced account as null so the client re-pairs full", async () => {
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue({
|
||||
lastSyncedAt: null,
|
||||
timezone: "Europe/Berlin",
|
||||
} as never);
|
||||
const body = await callGet();
|
||||
expect(body.lastSyncedAt).toBeNull();
|
||||
expect(prisma.user.update).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -12,7 +12,9 @@
|
||||
* {
|
||||
* userId,
|
||||
* timezone,
|
||||
* lastSyncedAt, — User.lastSyncedAt (ISO string or null)
|
||||
* lastSyncedAt, — User.lastSyncedAt (ISO string or null).
|
||||
* Set by the ingest boundaries, not here:
|
||||
* this route is a read and writes nothing.
|
||||
* serverNow, — `new Date().toISOString()` for clock skew
|
||||
* measurements: { lastUpdatedAt, liveCount, tombstonedCount },
|
||||
* mood: { lastUpdatedAt, liveCount, tombstonedCount },
|
||||
@@ -45,10 +47,10 @@ import {
|
||||
export const GET = apiHandler(async (_request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
// Per-domain aggregate reads + one user-side bump. Each runs against
|
||||
// indexed columns (userId, deleted_at / updated_at) so it stays
|
||||
// O(rows-for-user) and not O(rows-across-tenants). v1.7.0 adds the
|
||||
// mood + intake blocks now that both carry the sync columns.
|
||||
// Per-domain aggregate reads. Each runs against indexed columns (userId,
|
||||
// deleted_at / updated_at) so it stays O(rows-for-user) and not
|
||||
// O(rows-across-tenants). v1.7.0 adds the mood + intake blocks now that
|
||||
// both carry the sync columns.
|
||||
const [
|
||||
measurementLatest,
|
||||
measurementLive,
|
||||
@@ -96,16 +98,14 @@ export const GET = apiHandler(async (_request: NextRequest) => {
|
||||
}),
|
||||
]);
|
||||
|
||||
// The handshake also bumps the user's lastSyncedAt — the call IS
|
||||
// the handshake. iOS reads the OLD lastSyncedAt from the response
|
||||
// and then trusts that subsequent server writes after the new
|
||||
// checkpoint will round-trip via the standard read paths.
|
||||
const previous = currentUser?.lastSyncedAt ?? null;
|
||||
const nextCheckpoint = new Date();
|
||||
await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: { lastSyncedAt: nextCheckpoint },
|
||||
});
|
||||
// The handshake reports the checkpoint; it does not set it. The column is
|
||||
// stamped by the ingest boundaries that actually move data (see
|
||||
// `markSyncCheckpoint`), so `lastSyncedAt` answers "when did this account
|
||||
// last push a batch" rather than "when did a client last ask". NULL still
|
||||
// means never synced, and the value can now only trail the truth — the
|
||||
// handshake used to advance it past a window the client had not drained.
|
||||
const lastSyncedAt = currentUser?.lastSyncedAt ?? null;
|
||||
const serverNow = new Date();
|
||||
|
||||
annotate({
|
||||
action: { name: "sync.state" },
|
||||
@@ -114,15 +114,15 @@ export const GET = apiHandler(async (_request: NextRequest) => {
|
||||
tombstonedCount: measurementTomb,
|
||||
moodLiveCount: moodLive,
|
||||
intakeLiveCount: intakeLive,
|
||||
lastSyncedAtBefore: previous?.toISOString() ?? null,
|
||||
lastSyncedAt: lastSyncedAt?.toISOString() ?? null,
|
||||
},
|
||||
});
|
||||
|
||||
return apiSuccess({
|
||||
userId: user.id,
|
||||
timezone: currentUser?.timezone ?? "Europe/Berlin",
|
||||
lastSyncedAt: previous?.toISOString() ?? null,
|
||||
serverNow: nextCheckpoint.toISOString(),
|
||||
lastSyncedAt: lastSyncedAt?.toISOString() ?? null,
|
||||
serverNow: serverNow.toISOString(),
|
||||
measurements: {
|
||||
lastUpdatedAt: measurementLatest?.updatedAt?.toISOString() ?? null,
|
||||
liveCount: measurementLive,
|
||||
|
||||
Reference in new issue
Block a user