test(concurrency): cover the layout and about-me write guards

Add per-endpoint unit tests for the insights layout, medications layout, and
coach about-me write guards: an interleaved stale-base writer gets a 409 and
changes nothing, a tokenless request still writes (older-client compatibility),
the fresh token is echoed, and a malformed token 422s. Cover the client token
echo, the two 409 dispositions, and the insights read that must keep the token
through the resolver. Refresh the CHANGELOG and the generated OpenAPI spec.
This commit is contained in:
Marc-André Bombeck committed 2026-07-24 16:39:39 +02:00
1 parent ab03bc96f1
commit 572f5176bd
12 files changed
+634 -11

No files matched your search

@@ -0,0 +1,175 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
/**
* v1.32.21 (R5a) — optimistic concurrency on `PUT /api/coach/about-me`
* (issue #581 family). The write guards on `UserHealthProfile.updatedAt`:
*
* - a stale base token → 409 `about_me_conflict`, no write;
* - a matched base token → conditional update, fresh token echoed;
* - a zero-match against a MISSING row → create wins (nothing to clobber);
* - a tokenless request → the prior unconditional upsert (iOS-compat arm).
*
* Mirrors the mock scaffolding of `route-module-gate.test.ts`.
*/
vi.mock("@/lib/api-handler", () => ({
apiHandler: <T extends (...args: unknown[]) => unknown>(fn: T) => fn,
requireAuth: vi.fn(async () => ({ user: { id: "u1", locale: "en" } })),
}));
const { requireModuleEnabled } = vi.hoisted(() => ({
requireModuleEnabled: vi.fn(async () => ({ enabled: true })),
}));
vi.mock("@/lib/modules/gate", () => ({ requireModuleEnabled }));
vi.mock("@/lib/api-response", () => ({
apiError: (error: string, status: number, meta?: unknown) => ({
data: null,
error,
status,
meta,
}),
apiSuccess: (data: unknown) => ({ data, error: null, status: 200 }),
getClientIp: () => "127.0.0.1",
returnAllZodIssues: (_e: unknown, status: number) => ({
data: null,
error: "validation",
status,
}),
safeJson: async (req: Request) => ({ data: await req.json(), error: null }),
}));
vi.mock("@/lib/logging/context", () => ({ annotate: vi.fn() }));
vi.mock("@/lib/auth/audit", () => ({ auditLog: vi.fn() }));
const { profile } = vi.hoisted(() => ({
profile: {
upsert: vi.fn(),
updateMany: vi.fn(),
findUnique: vi.fn(),
create: vi.fn(),
},
}));
vi.mock("@/lib/db", () => ({ prisma: { userHealthProfile: profile } }));
vi.mock("@/lib/rate-limit", () => ({
checkRateLimit: vi.fn(async () => ({ allowed: true })),
rateLimitHeaders: vi.fn(() => ({})),
}));
vi.mock("@/lib/ai/coach/bytes-codec", () => ({
encryptToBytes: (s: string) => Buffer.from(s),
}));
vi.mock("@/lib/ai/coach/about-me", () => ({
getSelfContextForUser: vi.fn(async () => ({
aboutMe: null,
conditions: null,
allergies: null,
coachFocus: null,
})),
getPendingQuestionsForUser: vi.fn(async () => []),
setPendingQuestionsForUser: vi.fn(),
}));
vi.mock("@/lib/ai/coach/self-context-questions", () => ({
deriveClarifyingQuestions: vi.fn(async () => ({
questions: [],
source: "none",
})),
}));
import { PUT } from "../route";
type Envelope = {
data: { updatedAt?: string } | null;
error: string | null;
status: number;
meta?: { errorCode?: string };
};
const put = PUT as unknown as (req: Request) => Promise<Envelope>;
function putReq(baseUpdatedAt?: string): Request {
return new Request("http://localhost/api/coach/about-me", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
aboutMe: "I run daily",
...(baseUpdatedAt !== undefined ? { baseUpdatedAt } : {}),
}),
});
}
beforeEach(() => {
vi.clearAllMocks();
requireModuleEnabled.mockResolvedValue({ enabled: true });
});
describe("about-me — optimistic concurrency", () => {
it("guards on the base token and echoes the advanced token", async () => {
const base = new Date("2026-07-24T10:00:00.000Z");
const advanced = new Date("2026-07-24T10:05:00.000Z");
profile.updateMany.mockResolvedValue({ count: 1 });
profile.findUnique.mockResolvedValue({ updatedAt: advanced });
const res = await put(putReq(base.toISOString()));
expect(res.status).toBe(200);
// Conditional write on the exact base token — never the upsert.
expect(profile.updateMany).toHaveBeenCalledTimes(1);
const whereArg = profile.updateMany.mock.calls[0]?.[0]?.where as {
userId: string;
updatedAt: Date;
};
expect(whereArg.userId).toBe("u1");
expect((whereArg.updatedAt as Date).toISOString()).toBe(base.toISOString());
expect(profile.upsert).not.toHaveBeenCalled();
expect(res.data?.updatedAt).toBe(advanced.toISOString());
});
it("a stale base token 409s and clobbers nothing (existing row advanced)", async () => {
profile.updateMany.mockResolvedValue({ count: 0 });
// The row exists but its token advanced → real conflict, not a delete.
profile.findUnique.mockResolvedValue({
updatedAt: new Date("2026-07-24T10:05:00.000Z"),
});
const res = await put(putReq("2026-07-24T09:00:00.000Z"));
expect(res.status).toBe(409);
expect(res.data).toBeNull();
expect(res.meta?.errorCode).toBe("about_me_conflict");
// No write happened: neither the upsert nor a create ran.
expect(profile.upsert).not.toHaveBeenCalled();
expect(profile.create).not.toHaveBeenCalled();
});
it("a zero-match against a MISSING row creates instead of 409ing", async () => {
profile.updateMany.mockResolvedValue({ count: 0 });
profile.findUnique.mockResolvedValue(null);
profile.create.mockResolvedValue({
updatedAt: new Date("2026-07-24T12:00:00.000Z"),
});
const res = await put(putReq("2026-07-24T09:00:00.000Z"));
expect(res.status).toBe(200);
expect(profile.create).toHaveBeenCalledTimes(1);
expect(res.data?.updatedAt).toBe("2026-07-24T12:00:00.000Z");
});
it("keeps the unconditional upsert when the token is omitted (iOS compat)", async () => {
profile.upsert.mockResolvedValue({
updatedAt: new Date("2026-07-24T11:00:00.000Z"),
});
const res = await put(putReq());
expect(res.status).toBe(200);
expect(profile.upsert).toHaveBeenCalledTimes(1);
expect(profile.updateMany).not.toHaveBeenCalled();
expect(res.data?.updatedAt).toBe("2026-07-24T11:00:00.000Z");
});
it("422s a malformed base token without touching the row", async () => {
const res = await put(putReq("not-a-date"));
expect(res.status).toBe(422);
expect(res.meta?.errorCode).toBe("invalid_base_updated_at");
expect(profile.updateMany).not.toHaveBeenCalled();
expect(profile.upsert).not.toHaveBeenCalled();
});
});
@@ -15,6 +15,7 @@ vi.mock("@/lib/db", () => ({
user: {
findUnique: vi.fn(),
update: vi.fn(),
updateMany: vi.fn(),
},
auditLog: {
create: vi.fn(),
@@ -682,3 +683,91 @@ describe("DELETE /api/insights/layout", () => {
expect(call.data.insightsLayoutJson).toBeDefined();
});
});
/**
* v1.32.21 (R5a) — optimistic concurrency (issue #581 family). A PUT carrying
* the `baseUpdatedAt` it was based on writes CONDITIONALLY on the stored row
* still carrying that token, so an interleaved edit-mode Save and Settings
* pill-order Save can't clobber one another. A tokenless PUT keeps the prior
* unconditional write — the iOS-compat arm.
*/
describe("PUT /api/insights/layout — optimistic concurrency", () => {
function body(baseUpdatedAt?: string) {
return {
version: 2,
tiles: [{ id: "overview", visible: true, order: 0 }],
...(baseUpdatedAt !== undefined ? { baseUpdatedAt } : {}),
};
}
it("guards the write on the base token and returns the advanced token", async () => {
const base = new Date("2026-07-24T10:00:00.000Z");
const advanced = new Date("2026-07-24T10:05:00.000Z");
vi.mocked(prisma.user.updateMany).mockResolvedValue({ count: 1 } as never);
// The merge-read `previous` (no row) then the post-write token read.
vi.mocked(prisma.user.findUnique)
.mockResolvedValueOnce({ insightsLayoutJson: null } as never)
.mockResolvedValueOnce({ updatedAt: advanced } as never);
const res = await callPut(makeReq(body(base.toISOString())));
expect(res.status).toBe(200);
expect(prisma.user.updateMany).toHaveBeenCalledTimes(1);
const whereArg = vi.mocked(prisma.user.updateMany).mock.calls[0]?.[0]
?.where as { id: string; updatedAt: Date };
expect(whereArg.id).toBe("user-1");
expect((whereArg.updatedAt as Date).toISOString()).toBe(base.toISOString());
expect(prisma.user.update).not.toHaveBeenCalled();
const bodyJson = (await res.json()) as { data: { updatedAt: string } };
expect(bodyJson.data.updatedAt).toBe(advanced.toISOString());
});
it("interleaved writers: the stale-base second writer gets 409 and clobbers nothing", async () => {
vi.mocked(prisma.user.findUnique).mockResolvedValue({
insightsLayoutJson: null,
} as never);
// Writer B committed first; writer A's guarded write matches zero rows.
vi.mocked(prisma.user.updateMany).mockResolvedValue({ count: 0 } as never);
const res = await callPut(makeReq(body("2026-07-24T09:00:00.000Z")));
expect(res.status).toBe(409);
const bodyJson = (await res.json()) as {
data: null;
error: string;
meta?: { errorCode?: string };
};
expect(bodyJson.data).toBeNull();
expect(bodyJson.meta?.errorCode).toBe("insights_layout_conflict");
// Guarded write matched no row; no unconditional fallback → nothing written.
expect(prisma.user.updateMany).toHaveBeenCalledTimes(1);
expect(prisma.user.update).not.toHaveBeenCalled();
});
it("422s a malformed base token without touching the row", async () => {
const res = await callPut(makeReq(body("not-a-date")));
expect(res.status).toBe(422);
const bodyJson = (await res.json()) as { meta?: { errorCode?: string } };
expect(bodyJson.meta?.errorCode).toBe("invalid_base_updated_at");
expect(prisma.user.updateMany).not.toHaveBeenCalled();
expect(prisma.user.update).not.toHaveBeenCalled();
});
it("keeps the unconditional write when the client omits the token (iOS compat)", async () => {
vi.mocked(prisma.user.findUnique).mockResolvedValue({
insightsLayoutJson: null,
} as never);
vi.mocked(prisma.user.update).mockResolvedValue({
updatedAt: new Date("2026-07-24T11:00:00.000Z"),
} as never);
const res = await callPut(makeReq(body()));
expect(res.status).toBe(200);
expect(prisma.user.update).toHaveBeenCalledTimes(1);
expect(prisma.user.updateMany).not.toHaveBeenCalled();
const bodyJson = (await res.json()) as { data: { updatedAt: string } };
expect(bodyJson.data.updatedAt).toBe("2026-07-24T11:00:00.000Z");
});
});
@@ -15,6 +15,7 @@ vi.mock("@/lib/db", () => ({
user: {
findUnique: vi.fn(),
update: vi.fn(),
updateMany: vi.fn(),
},
auditLog: {
create: vi.fn(),
@@ -152,6 +153,8 @@ describe("PUT /api/medications/layout — preserve-when-absent", () => {
version: 1,
view: "table",
order: ["med-a", "med-b"],
// v1.32.21 — the write now echoes the fresh optimistic-concurrency token.
updatedAt: expect.any(String),
});
expect(prisma.user.update).toHaveBeenCalledTimes(1);
@@ -275,3 +278,90 @@ describe("DELETE /api/medications/layout", () => {
expect(call.data.medicationListLayoutJson).toBeDefined();
});
});
/**
* v1.32.21 (R5a) — optimistic concurrency (issue #581 family). A PUT carrying
* the `baseUpdatedAt` it was based on writes CONDITIONALLY on the stored row
* still carrying that token, so a view toggle can never resurrect an order the
* reorder Save just committed (and vice versa). A tokenless PUT keeps the prior
* unconditional write — the iOS-compat arm.
*/
describe("PUT /api/medications/layout — optimistic concurrency", () => {
// A full blob (view + order) so no preserve-read fires; the only findUnique
// is the post-write token read.
function fullBody(baseUpdatedAt?: string) {
return {
version: 1,
view: "table",
order: ["med-a", "med-b"],
...(baseUpdatedAt !== undefined ? { baseUpdatedAt } : {}),
};
}
it("guards the write on the base token and returns the advanced token", async () => {
const base = new Date("2026-07-24T10:00:00.000Z");
const advanced = new Date("2026-07-24T10:05:00.000Z");
vi.mocked(prisma.user.updateMany).mockResolvedValue({ count: 1 } as never);
vi.mocked(prisma.user.findUnique).mockResolvedValue({
updatedAt: advanced,
} as never);
const res = await callPut(makeReq(fullBody(base.toISOString())));
expect(res.status).toBe(200);
// Conditional write on the exact base token — never unconditional.
expect(prisma.user.updateMany).toHaveBeenCalledTimes(1);
const whereArg = vi.mocked(prisma.user.updateMany).mock.calls[0]?.[0]
?.where as { id: string; updatedAt: Date };
expect(whereArg.id).toBe("user-1");
expect((whereArg.updatedAt as Date).toISOString()).toBe(base.toISOString());
expect(prisma.user.update).not.toHaveBeenCalled();
const body = (await res.json()) as { data: { updatedAt: string } };
expect(body.data.updatedAt).toBe(advanced.toISOString());
});
it("interleaved writers: the stale-base second writer gets 409 and clobbers nothing", async () => {
// Writer B committed first (updatedAt advanced); writer A replays with the
// pre-B token → the conditional write matches zero rows.
vi.mocked(prisma.user.updateMany).mockResolvedValue({ count: 0 } as never);
const res = await callPut(makeReq(fullBody("2026-07-24T09:00:00.000Z")));
expect(res.status).toBe(409);
const body = (await res.json()) as {
data: null;
error: string;
meta?: { errorCode?: string };
};
expect(body.data).toBeNull();
expect(body.meta?.errorCode).toBe("medication_layout_conflict");
// The conditional write matched no row; there is NO unconditional
// fallback, so nothing was written — B's value survives.
expect(prisma.user.updateMany).toHaveBeenCalledTimes(1);
expect(prisma.user.update).not.toHaveBeenCalled();
});
it("422s a malformed base token without touching the row", async () => {
const res = await callPut(makeReq(fullBody("not-a-date")));
expect(res.status).toBe(422);
const body = (await res.json()) as { meta?: { errorCode?: string } };
expect(body.meta?.errorCode).toBe("invalid_base_updated_at");
expect(prisma.user.updateMany).not.toHaveBeenCalled();
expect(prisma.user.update).not.toHaveBeenCalled();
});
it("keeps the unconditional write when the client omits the token (iOS compat)", async () => {
vi.mocked(prisma.user.update).mockResolvedValue({
updatedAt: new Date("2026-07-24T11:00:00.000Z"),
} as never);
const res = await callPut(makeReq(fullBody()));
expect(res.status).toBe(200);
expect(prisma.user.update).toHaveBeenCalledTimes(1);
expect(prisma.user.updateMany).not.toHaveBeenCalled();
const body = (await res.json()) as { data: { updatedAt: string } };
expect(body.data.updatedAt).toBe("2026-07-24T11:00:00.000Z");
});
});