import { sql } from "@payloadcms/db-postgres"; import type { Payload } from "payload"; import type { PositionConflict } from "@/lib/tech-tree/concurrency"; /** * Bulk Tech Tree position writes. * * The canvas used to persist positions with one REST PATCH per technology, all * fired at once. Auto-arrange or Save positions on a 60+ node tree therefore * hit the server with 60+ concurrent full document updates (auth, permission * lookups, populated responses each), which exhausted the database pool and * could take the server down. Every canvas position write now goes through * `writeTreePositions`: one request, one SQL statement. * * Only the `tree_position_x` / `tree_position_y` columns are touched; * `updated_at` is bumped to keep the documents honest (and to move optimistic * concurrency tokens forward). The technologies collection DOES have * `beforeChange` hooks (approval reset + concurrency guard), but this raw SQL * intentionally bypasses them: position writes are not content edits and must * not demote approval status. Concurrency for these writes is enforced here * instead, via the optional per-row `expectedUpdatedAt` precondition. * * All-or-nothing: when ANY preconditioned row mismatches, NOTHING is written * and the conflicting rows are reported. Each canvas bulk write is one logical * layout operation, so half-applied arrangements would leave the optimistic UI * diverging from the database in confusing ways; callers resolve conflicts by * refreshing their tokens or retrying the batch unconditionally. */ /** Hard cap per request so a malformed client cannot build a giant statement. */ export const MAX_POSITION_UPDATES = 2000; export type TreePositionUpdate = { id: number; /** Both numbers to pin a node, both null to return it to the automatic layout. */ x: number | null; y: number | null; /** * Optimistic concurrency token: the `updatedAt` the client loaded for this * technology, or null for an unconditional (force) write. */ expectedUpdatedAt: string | null; }; export type PositionWriteResult = { updated: number; conflicts: PositionConflict[]; /** * Fresh `updatedAt` tokens for every row this write touched (id -> ISO). * A successful write bumps `updated_at`, so callers MUST advance their * stored tokens with these or their next write falsely conflicts. */ tokens: Record; }; export type ParseResult = | { ok: true; updates: TreePositionUpdate[] } | { ok: false; error: string }; /** Validate a `{ positions: [...] }` request body. Pure. */ export function parsePositionUpdates(body: unknown): ParseResult { const positions = (body as { positions?: unknown } | null)?.positions; if (!Array.isArray(positions)) return { ok: false, error: "positions must be an array." }; if (positions.length > MAX_POSITION_UPDATES) { return { ok: false, error: `At most ${MAX_POSITION_UPDATES} positions per request.` }; } const byId = new Map(); for (const entry of positions) { const { id, x, y, ifUnmodifiedAt } = (entry ?? {}) as { id?: unknown; x?: unknown; y?: unknown; ifUnmodifiedAt?: unknown; }; if (typeof id !== "number" || !Number.isInteger(id) || id <= 0) { return { ok: false, error: "Each position needs a positive integer id." }; } const cleared = x === null && y === null; const pinned = typeof x === "number" && Number.isFinite(x) && typeof y === "number" && Number.isFinite(y); if (!cleared && !pinned) { return { ok: false, error: `Position for ${id} must have numeric x and y, or both null.` }; } let expectedUpdatedAt: string | null = null; if (ifUnmodifiedAt !== undefined && ifUnmodifiedAt !== null) { if (typeof ifUnmodifiedAt !== "string" || Number.isNaN(Date.parse(ifUnmodifiedAt))) { return { ok: false, error: `ifUnmodifiedAt for ${id} must be an ISO timestamp.` }; } expectedUpdatedAt = ifUnmodifiedAt; } // Last write wins for a repeated id. byId.set( id, cleared ? { id, x: null, y: null, expectedUpdatedAt } : { id, x: Math.round(x as number), y: Math.round(y as number), expectedUpdatedAt }, ); } return { ok: true, updates: [...byId.values()] }; } /** The pg driver hands timestamps back as Dates; the API speaks ISO strings. */ function toIsoString(value: unknown): string | null { if (value === null || value === undefined) return null; if (value instanceof Date) return value.toISOString(); return String(value); } /** * Write every position in a single conditional UPDATE. Rows whose * `expectedUpdatedAt` is set only match while the stored `updated_at` still * equals it; one mismatch aborts the whole statement (all-or-nothing). When * fewer rows were touched than requested, a follow-up read classifies which * ids conflicted (missing ids stay silently ignored, as before). */ export async function writeTreePositions( payload: Payload, updates: TreePositionUpdate[], ): Promise { if (updates.length === 0) return { updated: 0, conflicts: [], tokens: {} }; const values = sql.join( updates.map((u) => sql`(${u.id}::integer, ${u.x}::numeric, ${u.y}::numeric, ${ u.expectedUpdatedAt === null ? sql`NULL` : sql`${u.expectedUpdatedAt}` }::timestamptz)`), sql`, `, ); const result = await payload.db.drizzle.execute(sql` WITH input AS ( SELECT * FROM (VALUES ${values}) AS v(id, x, y, expected) ), conflicts AS ( SELECT i.id FROM input i JOIN technologies t ON t.id = i.id WHERE i.expected IS NOT NULL AND t.updated_at <> i.expected ) UPDATE technologies AS t SET tree_position_x = i.x, tree_position_y = i.y, updated_at = now() FROM input i WHERE t.id = i.id AND NOT EXISTS (SELECT 1 FROM conflicts) RETURNING t.id AS id, t.updated_at AS updated_at `); const writtenRows = ((result as unknown as { rows?: { id: number; updated_at: unknown }[] })?.rows ?? []).map( (row) => [row.id, toIsoString(row.updated_at)] as const, ); const tokens: Record = {}; for (const [id, iso] of writtenRows) { if (id !== null && iso !== null) tokens[String(id)] = iso; } const updated = (result as { rowCount?: number | null }).rowCount ?? writtenRows.length; if (updated === updates.length) return { updated, conflicts: [], tokens }; // Cold path: some ids are missing or a precondition failed. Classify with // one read so the caller gets actionable conflict data in the same round trip. const check = await payload.db.drizzle.execute(sql` SELECT id, updated_at FROM technologies WHERE id IN (${sql.join( updates.map((u) => sql`${u.id}::integer`), sql`, `, )}) `); const stored = new Map( ((check as unknown as { rows?: { id: number; updated_at: unknown }[] })?.rows ?? []).map( (row) => [row.id, toIsoString(row.updated_at)], ), ); const conflicts: PositionConflict[] = []; for (const u of updates) { if (u.expectedUpdatedAt === null) continue; const current = stored.get(u.id); if (current === undefined) continue; // Id does not exist: ignored, legacy behavior. const currentMs = current === null ? Number.NaN : Date.parse(current); if (currentMs !== Date.parse(u.expectedUpdatedAt)) { conflicts.push({ id: u.id, currentUpdatedAt: current }); } } return { updated, conflicts, tokens }; }