import { getPayload, Payload } from "payload"; import config from "@/payload.config"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import type { Role, User } from "@/payload-types"; import { IF_UNMODIFIED_AT_HEADER } from "@/lib/tech-tree/concurrency"; import { writeTreePositions } from "@/lib/tech-tree/positions"; import { invalidatePermissionCache } from "@/utils/access-control/loadUserPermissions"; import { ifUnmodifiedAtGuard, StaleWriteError, } from "@/utils/access-control/optimisticConcurrency"; let payload: Payload; const RUN = `tcon-${Date.now().toString(36)}`; const TIMEOUT = 30_000; /** updatedAt has millisecond precision; space writes out so tokens advance. */ const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); describe("Tech Tree optimistic concurrency guard (database)", () => { const roleIds: number[] = []; const userIds: number[] = []; const techIds: number[] = []; let editorUser: User; const makeTech = async (label: string): Promise => { const doc = await payload.create({ collection: "technologies", data: { name: `${RUN}-${label}`, summary: "Optimistic concurrency fixture.", type: "upgrade", approvalStatus: "in_progress", researchCosts: { minimumResearchDuration: 1 }, }, overrideAccess: true, depth: 0, }); techIds.push(doc.id); return doc.id; }; const tokenOf = async (id: number): Promise => { const doc = await payload.findByID({ collection: "technologies", id, overrideAccess: true, depth: 0, }); return String(doc.updatedAt); }; /** * Update through the Local API with an optional precondition header. The * createLocalReq utility keeps passed req.headers verbatim, so hooks see * exactly what a REST client would send. */ const updateTech = ( id: number, data: { name?: string; summary?: string }, opts: { token?: string; user?: User } = {}, ) => payload.update({ collection: "technologies", id, data, overrideAccess: true, depth: 0, ...(opts.user ? { user: opts.user } : {}), ...(opts.token !== undefined ? { req: { headers: new Headers({ [IF_UNMODIFIED_AT_HEADER]: opts.token }) } } : {}), }); beforeAll(async () => { payload = await getPayload({ config }); const role = (await payload.create({ collection: "roles", data: { name: `${RUN}-editor`, slug: `${RUN}-editor`, permissions: ["technologies:update"], }, overrideAccess: true, depth: 0, })) as unknown as Role; roleIds.push(role.id); editorUser = (await payload.create({ collection: "users", data: { username: `${RUN}-editor`, discordUsername: `${RUN}-editor`, displayName: "EDITOR", steamId: `7656119${Math.floor(Math.random() * 1e9)}`, password: "Test123", roleDocs: [role.id], }, overrideAccess: true, depth: 0, })) as unknown as User; userIds.push(editorUser.id); invalidatePermissionCache(); for (const label of ["a", "b", "c"]) { await makeTech(label); } }, TIMEOUT); afterAll(async () => { for (const id of techIds) { await payload.delete({ collection: "technologies", id, overrideAccess: true }); } for (const id of userIds) { // Profiles hold a NOT NULL user_id FK: remove them before the user. const profiles = await payload .find({ collection: "profiles", where: { user: { equals: id } }, limit: 5, depth: 0, overrideAccess: true }) .catch(() => null); for (const p of profiles?.docs ?? []) { await payload.delete({ collection: "profiles", id: p.id, overrideAccess: true }).catch(() => {}); } await payload.delete({ collection: "users", id, overrideAccess: true }); } for (const id of roleIds) { await payload.delete({ collection: "roles", id, overrideAccess: true }); } invalidatePermissionCache(); }, TIMEOUT); it( "update without a precondition header keeps working (admin view, actions, seeds)", async () => { const res = await updateTech(techIds[0], { summary: "no token path" }); expect(res.summary).toBe("no token path"); }, TIMEOUT, ); it( "update with a matching token succeeds and advances the token", async () => { const t0 = await tokenOf(techIds[0]); await sleep(5); const res = await updateTech(techIds[0], { summary: "fresh token" }, { token: t0 }); expect(res.summary).toBe("fresh token"); expect(Date.parse(String(res.updatedAt))).toBeGreaterThan(Date.parse(t0)); }, TIMEOUT, ); it( "update with a stale token is rejected with 409 and changes nothing", async () => { const stale = await tokenOf(techIds[1]); await sleep(5); // Another user wins the race. await updateTech(techIds[1], { summary: "winner edit" }); let caught: unknown; try { await updateTech(techIds[1], { summary: "loser edit" }, { token: stale }); } catch (e) { caught = e; } expect(caught).toBeInstanceOf(StaleWriteError); const err = caught as StaleWriteError & { data?: Record }; expect(err.status).toBe(409); expect(err.name).toBe("StaleWriteError"); expect(err.data?.code).toBe("stale_write"); expect(err.data?.expectedUpdatedAt).toBe(stale); expect(Date.parse(String(err.data?.currentUpdatedAt))).toBe(Date.parse(await tokenOf(techIds[1]))); const after = await payload.findByID({ collection: "technologies", id: techIds[1], overrideAccess: true, depth: 0, }); expect(after.summary).toBe("winner edit"); }, TIMEOUT, ); it( "update with a malformed precondition header is rejected with 400", async () => { await expect(updateTech(techIds[0], { summary: "x" }, { token: "not-a-date" })).rejects.toMatchObject( { status: 400 }, ); }, TIMEOUT, ); it( "create ignores the precondition header entirely", async () => { const created = await payload.create({ collection: "technologies", data: { name: `${RUN}-created-with-header`, summary: "Creates never conflict.", type: "upgrade", approvalStatus: "in_progress", researchCosts: { minimumResearchDuration: 1 }, }, overrideAccess: true, depth: 0, req: { headers: new Headers({ [IF_UNMODIFIED_AT_HEADER]: "2000-01-01T00:00:00.000Z" }) }, }); techIds.push(created.id); expect(created.id).toBeGreaterThan(0); }, TIMEOUT, ); it( "coexists with the approval-reset hook: fresh token passes, non-superuser edit demotes approved docs", async () => { // Superuser approves the doc (system writes carry no token). await payload.update({ collection: "technologies", id: techIds[2], data: { approvalStatus: "approved" }, overrideAccess: true, depth: 0, }); const t0 = await tokenOf(techIds[2]); await sleep(5); const res = await updateTech(techIds[2], { name: `${RUN}-c-demoted` }, { token: t0, user: editorUser }); expect(res.approvalStatus).toBe("in_progress"); expect(Date.parse(String(res.updatedAt))).toBeGreaterThan(Date.parse(t0)); }, TIMEOUT, ); }); describe("Tech Tree bulk position preconditions (database)", () => { const techIds: number[] = []; const makeTech = async (label: string): Promise => { const doc = await payload.create({ collection: "technologies", data: { name: `${RUN}-pos-${label}`, summary: "Position precondition fixture.", type: "upgrade", approvalStatus: "in_progress", researchCosts: { minimumResearchDuration: 1 }, }, overrideAccess: true, depth: 0, }); techIds.push(doc.id); return doc.id; }; const tokenOf = async (id: number): Promise => { const doc = await payload.findByID({ collection: "technologies", id, overrideAccess: true, depth: 0, }); return String(doc.updatedAt); }; const positionOf = async (id: number) => { const doc = await payload.findByID({ collection: "technologies", id, overrideAccess: true, depth: 0, }); return doc.treePosition ?? null; }; beforeAll(async () => { payload = await getPayload({ config }); for (const label of ["a", "b", "c"]) { await makeTech(label); } }, TIMEOUT); afterAll(async () => { for (const id of techIds) { await payload.delete({ collection: "technologies", id, overrideAccess: true }); } }, TIMEOUT); it( "applies the batch when every preconditioned row still matches", async () => { const [a, b, c] = techIds; const tokens = new Map(); for (const id of techIds) tokens.set(id, await tokenOf(id)); const result = await writeTreePositions(payload, [ { id: a, x: 100, y: 200, expectedUpdatedAt: tokens.get(a)! }, { id: b, x: 101, y: 201, expectedUpdatedAt: tokens.get(b)! }, { id: c, x: 102, y: 202, expectedUpdatedAt: tokens.get(c)! }, ]); expect(result.updated).toBe(3); expect(result.conflicts).toEqual([]); expect(await positionOf(a)).toMatchObject({ x: 100, y: 200 }); // The write returns the fresh server tokens so callers stay current. for (const id of techIds) { expect(Date.parse(result.tokens[String(id)])).toBeGreaterThan( Date.parse(tokens.get(id)!), ); expect(Date.parse(result.tokens[String(id)])).toBe(Date.parse(await tokenOf(id))); } // Position writes bump updated_at so every token moves forward. expect(Date.parse(await tokenOf(a))).toBeGreaterThan(Date.parse(tokens.get(a)!)); }, TIMEOUT, ); it( "rejects the whole batch when one row is stale and reports the conflict", async () => { const [a, b] = techIds; const ta = await tokenOf(a); const tb = await tokenOf(b); await sleep(5); // Another user bumps b out of band. await payload.update({ collection: "technologies", id: b, data: { summary: "bumped elsewhere" }, overrideAccess: true, depth: 0, }); const result = await writeTreePositions(payload, [ { id: a, x: 999, y: 999, expectedUpdatedAt: ta }, { id: b, x: 888, y: 888, expectedUpdatedAt: tb }, ]); expect(result.updated).toBe(0); expect(result.conflicts).toHaveLength(1); expect(result.conflicts[0].id).toBe(b); expect(Date.parse(String(result.conflicts[0].currentUpdatedAt))).toBe(Date.parse(await tokenOf(b))); // All-or-nothing: the fresh row was NOT written either. expect(await positionOf(a)).toMatchObject({ x: 100, y: 200 }); }, TIMEOUT, ); it( "force retry without preconditions applies the same batch", async () => { const [a, b] = techIds; const forced = await writeTreePositions(payload, [ { id: a, x: 999, y: 999, expectedUpdatedAt: null }, { id: b, x: 888, y: 888, expectedUpdatedAt: null }, ]); expect(forced.updated).toBe(2); expect(forced.conflicts).toEqual([]); expect(await positionOf(b)).toMatchObject({ x: 888, y: 888 }); }, TIMEOUT, ); it( "an unconditional row in a batch with a stale row is not applied (all-or-nothing)", async () => { const [a, , c] = techIds; const ta = await tokenOf(a); await sleep(5); await payload.update({ collection: "technologies", id: a, data: { summary: "bumped again" }, overrideAccess: true, depth: 0, }); const result = await writeTreePositions(payload, [ { id: c, x: 777, y: 777, expectedUpdatedAt: null }, { id: a, x: 666, y: 666, expectedUpdatedAt: ta }, ]); expect(result.updated).toBe(0); expect(result.conflicts.map((conflict) => conflict.id)).toEqual([a]); // c kept the position from the earlier successful batch. expect(await positionOf(c)).toMatchObject({ x: 102, y: 202 }); }, TIMEOUT, ); it( "unknown ids stay silently ignored, with or without a precondition", async () => { const missing = await writeTreePositions(payload, [ { id: 999_999_998, x: 1, y: 1, expectedUpdatedAt: new Date().toISOString() }, { id: 999_999_997, x: 1, y: 1, expectedUpdatedAt: null }, ]); expect(missing.updated).toBe(0); expect(missing.conflicts).toEqual([]); }, TIMEOUT, ); }); describe("ifUnmodifiedAtGuard (direct hook invocation)", () => { const hook = ifUnmodifiedAtGuard(); const call = ( headers: Record, originalDoc: { updatedAt?: string } | null, operation: "create" | "update" = "update", ) => hook({ req: { headers: new Headers(headers) }, data: { name: "draft" }, originalDoc, operation, } as unknown as Parameters[0]); it("passes through when no header is present", async () => { await expect(call({}, { updatedAt: "2026-01-01T00:00:00.000Z" })).resolves.toEqual({ name: "draft", }); }); it("passes through on create even with a header", async () => { await expect( call({ [IF_UNMODIFIED_AT_HEADER]: "2020-01-01T00:00:00.000Z" }, { updatedAt: "2026-01-01T00:00:00.000Z" }, "create"), ).resolves.toEqual({ name: "draft" }); }); it("passes through when the token matches", async () => { await expect( call({ [IF_UNMODIFIED_AT_HEADER]: "2026-01-01T00:00:00.000Z" }, { updatedAt: "2026-01-01T00:00:00.000Z" }), ).resolves.toEqual({ name: "draft" }); }); it("rejects a mismatch with StaleWriteError (409, stale_write)", async () => { await expect( call({ [IF_UNMODIFIED_AT_HEADER]: "2026-01-01T00:00:00.000Z" }, { updatedAt: "2026-01-02T00:00:00.000Z" }), ).rejects.toBeInstanceOf(StaleWriteError); }); it("rejects an unparseable header with status 400", async () => { await expect( call({ [IF_UNMODIFIED_AT_HEADER]: "yesterday" }, { updatedAt: "2026-01-01T00:00:00.000Z" }), ).rejects.toMatchObject({ status: 400 }); }); });