1
0
Fork 0

feat(tech-tree): optimistic concurrency for the tree editor

Guard the Technologies collection with an X-PTF-If-Unmodified-At
precondition hook (update-only, header-only) that rejects stale writes
with HTTP 409 and a stale_write payload, placed before the approval
reset hook. Bulk position writes gain per-row ifUnmodifiedAt tokens in
one all-or-nothing statement; conflicts return the offending ids and
successful writes return fresh tokens so clients advance their own
versions. The lite editor shows a Version Conflict dialog (load latest
or overwrite anyway); canvas position conflicts surface as a toolbar
banner with refresh / force-overwrite plus red node rings.

Tests: new tech-tree-concurrency int spec (guard, coexistence with the
approval reset, positions preconditions), two e2e scenarios for the
dialog and the banner; existing positions spec adapted to the new
return shape.
This commit is contained in:
Jason Fraley 2026-10-15 11:48:30 -04:00
parent 4f129fc59a
commit caf77e3a6b
16 changed files with 1245 additions and 70 deletions

View file

@ -10,10 +10,13 @@ export const dynamic = "force-dynamic";
export const runtime = "nodejs";
/**
* Bulk Tech Tree position write: `{ positions: [{ id, x, y }] }`, where a
* null x/y returns a technology to the automatic layout. Used by every canvas
* position write (drags, Save positions, Auto-arrange, freeze pins) so they
* cost one request and one SQL statement instead of a PATCH per node.
* Bulk Tech Tree position write: `{ positions: [{ id, x, y, ifUnmodifiedAt? }] }`,
* where a null x/y returns a technology to the automatic layout and
* `ifUnmodifiedAt` (the loaded `updatedAt`) makes that row conditional: one
* mismatched precondition rejects the whole batch with HTTP 409 and the
* conflicting ids. Used by every canvas position write (drags, Save positions,
* Auto-arrange, freeze pins) so they cost one request and one SQL statement
* instead of a PATCH per node.
*
* Access mirrors the technologies collection's update rule: the
* `technologies:update` permission OR Intelligence division membership.
@ -43,8 +46,18 @@ export async function POST(req: NextRequest) {
}
try {
const updated = await writeTreePositions(payload, parsed.updates);
return NextResponse.json({ ok: true, updated });
const result = await writeTreePositions(payload, parsed.updates);
if (result.conflicts.length > 0) {
return NextResponse.json(
{
error:
"Some positions could not be saved: those technologies changed since you loaded them.",
conflicts: result.conflicts,
},
{ status: 409 },
);
}
return NextResponse.json({ ok: true, updated: result.updated, tokens: result.tokens });
} catch (err) {
payload.logger.error(`[TechTree] Bulk position write failed: ${err}`);
return NextResponse.json({ error: "Could not save positions." }, { status: 500 });

View file

@ -6,6 +6,7 @@ import {
requireIntelligencePermission,
resetApprovalStatusOnEdit,
} from "@/utils/access-control/divisionAccess";
import { ifUnmodifiedAtGuard } from "@/utils/access-control/optimisticConcurrency";
const approvalStatusFieldAccessConfig = approvalStatusFieldAccess("technologies");
@ -22,7 +23,9 @@ export const Technologies: CollectionConfig = {
read: requirePermission("technologies:read"),
},
hooks: {
beforeChange: [resetApprovalStatusOnEdit()],
// Guard first: a stale write must abort before the approval-reset hook
// rewrites data (see optimisticConcurrency.ts for the contract).
beforeChange: [ifUnmodifiedAtGuard(), resetApprovalStatusOnEdit()],
},
fields: [
{

View file

@ -11,6 +11,8 @@ export type TechNodeData = {
categoryName: string | null;
refLabel: string;
hasWarning: boolean;
/** Another user changed this document: red ring until the tree is refreshed. */
conflict: boolean;
connectable: boolean;
};
@ -41,7 +43,7 @@ function CornerBrackets() {
* classification strip, corner brackets, mono readouts).
*/
export function TechNodeCard({ data, selected }: NodeProps<TechNodeModel>) {
const { tech, categoryName, refLabel, hasWarning, connectable } = data;
const { tech, categoryName, refLabel, hasWarning, conflict, connectable } = data;
const status = STATUS_LABELS[tech.approvalStatus] ?? {
label: tech.approvalStatus,
className: "text-white/60",
@ -50,6 +52,7 @@ export function TechNodeCard({ data, selected }: NodeProps<TechNodeModel>) {
return (
<div
data-testid={`tech-node-${tech.id}`}
data-conflict={conflict ? "true" : undefined}
className="relative h-full w-full"
>
{/* Clipped card surface (the handles live outside this box) */}
@ -57,7 +60,9 @@ export function TechNodeCard({ data, selected }: NodeProps<TechNodeModel>) {
className={`flex h-full w-full flex-col overflow-hidden rounded-none border bg-black/60 backdrop-blur-sm transition-colors ${
selected
? "border-[#22d3ee]/70 shadow-[0_0_18px_rgba(34,211,238,0.15)]"
: "border-white/15 hover:border-white/40"
: conflict
? "border-red-400/80 shadow-[0_0_18px_rgba(248,113,113,0.22)] hover:border-red-300"
: "border-white/15 hover:border-white/40"
}`}
>
<CornerBrackets />

View file

@ -1,12 +1,21 @@
"use client";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { PencilIcon, PlusIcon, RotateCcwIcon, SaveIcon, XIcon } from "lucide-react";
import React from "react";
import { IF_UNMODIFIED_AT_HEADER } from "@/lib/tech-tree/concurrency";
import { CategoryPicker } from "./CategoryPicker";
import { PanelSelect } from "./PanelSelect";
import { buildPrereqRows } from "./prereqEdits";
@ -71,9 +80,17 @@ interface TechPreviewPanelProps {
canCreateCategories: boolean;
canSetFinalApproval: boolean;
warnings: string[];
/**
* Increment to force a draft reseed (used after conflict "load latest").
* Deliberately NOT keyed on tech.updatedAt: background refreshes would then
* clobber a dirty draft mid-typing.
*/
reseedNonce?: number;
onClose: () => void;
onEdit: () => void;
onSaved: (updated: TechTechLike) => void;
/** Ask the canvas to refetch the tree (conflict "load latest"). */
onConflictReload?: () => void;
}
/** Shape returned by the REST update (only the fields the tree reads). */
@ -101,9 +118,11 @@ export function TechPreviewPanel({
canCreateCategories,
canSetFinalApproval,
warnings,
reseedNonce,
onClose,
onEdit,
onSaved,
onConflictReload,
}: TechPreviewPanelProps) {
const categoryName =
tech.categoryId ? categories.find((c) => c.id === tech.categoryId)?.name ?? null : null;
@ -112,14 +131,22 @@ export function TechPreviewPanel({
const [busy, setBusy] = React.useState(false);
const [error, setError] = React.useState<string | null>(null);
const [savedAt, setSavedAt] = React.useState<number | null>(null);
// Optimistic concurrency: a PATCH rejected with HTTP 409 opens the conflict
// dialog and keeps the exact body here so "Overwrite anyway" can resend it
// without the precondition (and without recreating a new category).
const [conflictOpen, setConflictOpen] = React.useState(false);
const [pendingPatch, setPendingPatch] = React.useState<Record<string, unknown> | null>(null);
// Re-seed the draft when a different technology is selected.
// Re-seed the draft when a different technology is selected or the canvas
// bumps reseedNonce after a conflict reload.
React.useEffect(() => {
setDraft(draftFromTech(tech, categoryName));
setError(null);
setSavedAt(null);
setConflictOpen(false);
setPendingPatch(null);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tech.id]);
}, [tech.id, reseedNonce]);
const baseline = React.useMemo(() => draftFromTech(tech, categoryName), [tech, categoryName]);
const dirty = JSON.stringify(draft) !== JSON.stringify(baseline);
@ -169,6 +196,20 @@ export function TechPreviewPanel({
prereqOr: prev.prereqOr.filter((x) => x !== id),
}));
/** PATCH the technology; optionally carry the optimistic concurrency token. */
const sendPatch = async (data: Record<string, unknown>, usePrecondition: boolean) => {
const headers: Record<string, string> = { "Content-Type": "application/json" };
if (usePrecondition && tech.updatedAt) {
headers[IF_UNMODIFIED_AT_HEADER] = tech.updatedAt;
}
return fetch(`/api/technologies/${tech.id}`, {
method: "PATCH",
credentials: "same-origin",
headers,
body: JSON.stringify(data),
});
};
const save = async () => {
setError(null);
if (!draft.name.trim()) {
@ -227,11 +268,13 @@ export function TechPreviewPanel({
};
if (!statusLocked) data.approvalStatus = draft.approvalStatus;
const res = await fetch(`/api/technologies/${tech.id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});
const res = await sendPatch(data, true);
if (res.status === 409) {
// Version conflict: keep the draft, offer reload / overwrite choices.
setPendingPatch(data);
setConflictOpen(true);
return;
}
if (!res.ok) {
const body = await res.json().catch(() => null);
throw new Error(body?.errors?.[0]?.message || `Save failed (HTTP ${res.status}).`);
@ -245,6 +288,39 @@ export function TechPreviewPanel({
}
};
/** Conflict choice: resend the captured body without any precondition. */
const overwriteAnyway = async () => {
if (!pendingPatch) return;
const data = pendingPatch;
setConflictOpen(false);
setBusy(true);
try {
const res = await sendPatch(data, false);
if (!res.ok) {
const body = await res.json().catch(() => null);
throw new Error(body?.errors?.[0]?.message || `Save failed (HTTP ${res.status}).`);
}
setSavedAt(Date.now());
setPendingPatch(null);
onSaved({ ...tech, id: tech.id });
} catch (e) {
setError(e instanceof Error ? e.message : "Unknown error.");
} finally {
setBusy(false);
}
};
/**
* Conflict choice: accept the server version. "Reload" and "discard mine"
* are one action here because the lite editor has no field-level merge:
* the canvas refetches and bumps reseedNonce, which reseeds this draft.
*/
const loadLatest = () => {
setConflictOpen(false);
setPendingPatch(null);
onConflictReload?.();
};
return (
<aside
data-testid="tech-preview-panel"
@ -672,6 +748,48 @@ export function TechPreviewPanel({
Edit in full view
</Button>
</div>
{/* Version conflict dialog (optimistic concurrency rejection). */}
<Dialog open={conflictOpen} onOpenChange={setConflictOpen}>
<DialogContent
className="rounded-none sm:max-w-[420px]"
data-testid="tech-conflict-dialog"
>
<DialogHeader>
<DialogTitle className="font-mono text-xs tracking-widest text-red-300 uppercase">
Version Conflict
</DialogTitle>
</DialogHeader>
<p className="text-sm leading-relaxed text-white/80">
Another user saved changes to this technology since you opened it. Your draft has not
been written.
</p>
<p className="text-xs leading-relaxed text-white/50">
Load latest replaces your draft with the current server version. Overwrite anyway
writes your draft over their changes.
</p>
<DialogFooter>
<Button variant="outline" onClick={() => setConflictOpen(false)} disabled={busy}>
Keep editing
</Button>
<Button
variant="outline"
onClick={overwriteAnyway}
disabled={busy}
data-testid="tech-conflict-overwrite"
>
Overwrite anyway
</Button>
<Button
onClick={loadLatest}
disabled={busy}
data-testid="tech-conflict-reload"
>
Load latest
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</aside>
);
}

View file

@ -29,6 +29,10 @@ import { useRouter } from "next/navigation";
import React from "react";
import { Button } from "@/components/ui/button";
import {
IF_UNMODIFIED_AT_HEADER,
type PositionConflict,
} from "@/lib/tech-tree/concurrency";
import { CategoryBand, type CategoryBandData, type CategoryBandNode } from "./CategoryBand";
import {
@ -97,6 +101,7 @@ function buildFlowNodes(
categories: TreeCategory[],
layout: ReturnType<typeof computeLayout>,
connectable: boolean,
conflictIds: Set<number>,
): Node[] {
const warningsByTech = new Map<number, number>();
for (const warning of layout.warnings) {
@ -145,6 +150,7 @@ function buildFlowNodes(
categoryName: tech.categoryId ? categoryById.get(tech.categoryId)?.name ?? null : null,
refLabel: refLabel(tech.id),
hasWarning: warningsByTech.has(tech.id),
conflict: conflictIds.has(tech.id),
connectable,
},
};
@ -246,25 +252,64 @@ function buildFlowEdges(
});
}
/** One canvas position write; null x/y clears a pin. */
type PositionWrite = { id: number; x: number | null; y: number | null };
/** Bulk position write rejected because some documents changed since load. */
class PositionConflictError extends Error {
conflicts: PositionConflict[];
constructor(conflicts: PositionConflict[]) {
super("Some positions could not be saved: those technologies changed since you loaded them.");
this.name = "PositionConflictError";
this.conflicts = conflicts;
}
}
/** A single-document PATCH rejected with HTTP 409 (prerequisite writes). */
class StaleWriteClientError extends Error {
constructor() {
super("This technology changed since you loaded it.");
this.name = "StaleWriteClientError";
}
}
/**
* Persist canvas positions in ONE request (one SQL statement server-side).
* Never PATCH per node: dozens of concurrent document updates exhausted the
* database pool and could take the server down. Null x/y clears a pin.
* Each entry carries the `updatedAt` the client loaded as an optimistic
* concurrency precondition; the whole batch is rejected (HTTP 409) when any
* guarded row has since changed. Never PATCH per node: dozens of concurrent
* document updates exhausted the database pool and could take the server down.
* Null x/y clears a pin.
*/
async function saveTreePositions(
updates: { id: number; x: number | null; y: number | null }[],
): Promise<void> {
if (updates.length === 0) return;
updates: PositionWrite[],
tokens: Map<number, string>,
): Promise<Record<string, string>> {
if (updates.length === 0) return {};
const res = await fetch("/api/tech-tree/positions", {
method: "POST",
credentials: "same-origin",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ positions: updates }),
body: JSON.stringify({
positions: updates.map((u) => ({ ...u, ifUnmodifiedAt: tokens.get(u.id) ?? null })),
}),
});
if (res.status === 409) {
const body = await res.json().catch(() => null);
const conflicts = Array.isArray(body?.conflicts) ? (body.conflicts as PositionConflict[]) : [];
if (conflicts.length > 0) throw new PositionConflictError(conflicts);
throw new Error(body?.error || "Could not save positions: they changed since you loaded them.");
}
if (!res.ok) {
const body = await res.json().catch(() => null);
throw new Error(body?.error || `Could not save positions (HTTP ${res.status}).`);
}
// The write bumped updated_at server-side; hand the fresh tokens back so the
// caller can advance its stored versions (otherwise the next write on these
// docs would falsely conflict with our own edit).
const okBody = await res.json().catch(() => null);
const fresh = okBody?.tokens;
return typeof fresh === "object" && fresh !== null ? (fresh as Record<string, string>) : {};
}
async function fetchCollection<T>(slug: string): Promise<T[]> {
@ -287,6 +332,20 @@ function CanvasInner({ data }: { data: TechTreeData }) {
// null when idle. Drives the toolbar status chip and locks layout controls.
const [layoutBusy, setLayoutBusy] = React.useState<string | null>(null);
// Optimistic concurrency: nodes whose last bulk position write was rejected
// because another user changed those documents, plus the exact failed batch
// so the banner's "Overwrite anyway" can retry it without preconditions.
const [positionConflicts, setPositionConflicts] = React.useState<{ id: number; name: string }[]>(
[],
);
const lastFailedWrite = React.useRef<PositionWrite[] | null>(null);
// Bumped to reseed the preview panel's draft after a conflict "load latest".
const [panelReseedNonce, setPanelReseedNonce] = React.useState(0);
// Latest technologies list, read by stable callbacks to build concurrency tokens.
const techsRef = React.useRef(techs);
techsRef.current = techs;
// Manual edge routing, loaded from this browser's storage on mount. Empty =
// the edge draws its automatic path.
const [edgeRoutes, setEdgeRoutes] = React.useState<EdgeRouteMap>({});
@ -307,9 +366,13 @@ function CanvasInner({ data }: { data: TechTreeData }) {
);
const layout = React.useMemo(() => computeLayout(techs, categories), [techs, categories]);
const conflictIds = React.useMemo(
() => new Set(positionConflicts.map((c) => c.id)),
[positionConflicts],
);
const flowNodes = React.useMemo(
() => buildFlowNodes(techs, categories, layout, data.canUpdate),
[techs, categories, layout, data.canUpdate],
() => buildFlowNodes(techs, categories, layout, data.canUpdate, conflictIds),
[techs, categories, layout, data.canUpdate, conflictIds],
);
const flowEdges = React.useMemo(
() =>
@ -341,14 +404,65 @@ function CanvasInner({ data }: { data: TechTreeData }) {
return map;
}, []);
/**
* A successful write bumps updated_at server-side; advance the stored
* versions so the next write on the same docs does not conflict with ours.
*/
const applyServerTokens = React.useCallback((fresh: Record<string, string>) => {
setTechs((prev) => {
let touched = false;
const next = prev.map((t) => {
const iso = fresh[String(t.id)];
if (!iso || iso === t.updatedAt) return t;
touched = true;
return { ...t, updatedAt: iso };
});
return touched ? next : prev;
});
}, []);
/**
* Bulk position write guarded by optimistic concurrency tokens taken from
* the current tree (or an explicit fresher source during a freeze refresh).
* On a version conflict the failed batch is recorded and the toolbar banner
* offers refresh / force-overwrite; the error is rethrown so callers keep
* their existing failure handling (pin restoration, chips).
*/
const writePositions = React.useCallback(
async (updates: PositionWrite[], tokenSource?: TreeTech[]) => {
if (updates.length === 0) return;
const source = tokenSource ?? techsRef.current;
const tokens = new Map(source.map((t) => [t.id, t.updatedAt]));
try {
const fresh = await saveTreePositions(updates, tokens);
applyServerTokens(fresh);
} catch (e) {
if (e instanceof PositionConflictError) {
lastFailedWrite.current = updates;
const nameById = new Map(techsRef.current.map((t) => [t.id, t.name]));
setPositionConflicts(
e.conflicts.map((c) => ({ id: c.id, name: nameById.get(c.id) ?? `#${c.id}` })),
);
}
throw e;
}
},
[applyServerTokens],
);
/** Persist freeze pins (skipping ids whose own PATCH already carries one). */
const persistPins = React.useCallback(
async (pins: Map<number, CanvasPosition>, skip: Set<number> = new Set()) => {
await saveTreePositions(
async (
pins: Map<number, CanvasPosition>,
skip: Set<number> = new Set(),
tokenSource?: TreeTech[],
) => {
await writePositions(
[...pins].filter(([id]) => !skip.has(id)).map(([id, pin]) => ({ id, x: pin.x, y: pin.y })),
tokenSource,
);
},
[],
[writePositions],
);
// Nodes are data-driven: block React Flow's own remove changes so Backspace
@ -419,19 +533,29 @@ function CanvasInner({ data }: { data: TechTreeData }) {
targetId: number,
lists: { and: number[]; or: number[] },
pin?: { x: number; y: number },
) => {
token?: string,
): Promise<string | null> => {
const headers: Record<string, string> = { "Content-Type": "application/json" };
if (token) headers[IF_UNMODIFIED_AT_HEADER] = token;
const res = await fetch(`/api/technologies/${targetId}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
credentials: "same-origin",
headers,
body: JSON.stringify({
requirements: { prerequisiteTechnologies: buildPrereqRows(lists) },
...(pin ? { treePosition: pin } : {}),
}),
});
if (res.status === 409) throw new StaleWriteClientError();
if (!res.ok) {
const body = await res.json().catch(() => null);
throw new Error(body?.errors?.[0]?.message || `Save failed (HTTP ${res.status}).`);
}
// The PATCH bumped the document version; return the fresh token so the
// caller can keep its stored version honest for the next write.
const body = await res.json().catch(() => null);
const iso = body?.doc?.updatedAt ?? body?.updatedAt;
return typeof iso === "string" ? iso : null;
},
[],
);
@ -457,10 +581,24 @@ function CanvasInner({ data }: { data: TechTreeData }) {
const pins = pinsToFreeze(currentPositions(), updated, categories);
setTechs(applyPins(updated, pins));
try {
await patchPrereqs(targetId, result.lists, pins.get(targetId));
const targetToken = techs.find((t) => t.id === targetId)?.updatedAt;
const freshTarget = await patchPrereqs(targetId, result.lists, pins.get(targetId), targetToken);
if (freshTarget) {
setTechs((prev) =>
prev.map((t) => (t.id === targetId ? { ...t, updatedAt: freshTarget } : t)),
);
}
await persistPins(pins, new Set([targetId]));
} catch (e) {
setConnectError(e instanceof Error ? e.message : "Could not save the connection.");
if (e instanceof StaleWriteClientError) {
const name = techs.find((t) => t.id === targetId)?.name ?? `#${targetId}`;
setConnectError(
`Someone else changed "${name}". The tree was refreshed; try the connection again.`,
);
} else if (!(e instanceof PositionConflictError)) {
// Position conflicts report themselves through the toolbar banner.
setConnectError(e instanceof Error ? e.message : "Could not save the connection.");
}
await refresh();
}
},
@ -484,11 +622,23 @@ function CanvasInner({ data }: { data: TechTreeData }) {
setTechs(applyPins(next, pins));
try {
for (const [targetId, lists] of listsByTarget) {
await patchPrereqs(targetId, lists, pins.get(targetId));
const token = next.find((t) => t.id === targetId)?.updatedAt;
const freshTarget = await patchPrereqs(targetId, lists, pins.get(targetId), token);
if (freshTarget) {
setTechs((prev) =>
prev.map((t) => (t.id === targetId ? { ...t, updatedAt: freshTarget } : t)),
);
}
}
await persistPins(pins, new Set(listsByTarget.keys()));
} catch (e) {
setConnectError(e instanceof Error ? e.message : "Could not remove the prerequisite.");
if (e instanceof StaleWriteClientError) {
setConnectError(
"Someone else changed a technology here. The tree was refreshed; some removals were not applied.",
);
} else if (!(e instanceof PositionConflictError)) {
setConnectError(e instanceof Error ? e.message : "Could not remove the prerequisite.");
}
await refresh();
}
},
@ -512,13 +662,16 @@ function CanvasInner({ data }: { data: TechTreeData }) {
}),
);
try {
await saveTreePositions(positions);
await writePositions(positions);
} catch (e) {
// The optimistic position stays on screen; a reload shows what is stored.
setConnectError(e instanceof Error ? e.message : "Could not save positions.");
// Version conflicts report themselves through the toolbar banner.
if (!(e instanceof PositionConflictError)) {
setConnectError(e instanceof Error ? e.message : "Could not save positions.");
}
}
},
[],
[writePositions],
);
// Live session for a category-band drag: the header moves the band and every
@ -629,7 +782,9 @@ function CanvasInner({ data }: { data: TechTreeData }) {
await persistPins(pins);
setSaveStatus(`Positions saved. ${pins.size} node(s).`);
} catch (e) {
setConnectError(e instanceof Error ? e.message : "Could not save positions.");
if (!(e instanceof PositionConflictError)) {
setConnectError(e instanceof Error ? e.message : "Could not save positions.");
}
} finally {
setLayoutBusy(null);
}
@ -646,18 +801,20 @@ function CanvasInner({ data }: { data: TechTreeData }) {
setConnectError(null);
setTechs((prev) => prev.map((t) => (t.treePosition ? { ...t, treePosition: null } : t)));
try {
await saveTreePositions(pinned.map((t) => ({ id: t.id, x: null, y: null })));
await writePositions(pinned.map((t) => ({ id: t.id, x: null, y: null })));
setSaveStatus(`Layout reset. ${pinned.length} node(s) re-arranged.`);
} catch (e) {
// Put the pins back so the canvas matches what is actually stored.
setTechs((prev) =>
prev.map((t) => (previous.has(t.id) ? { ...t, treePosition: previous.get(t.id) ?? null } : t)),
);
setConnectError(e instanceof Error ? e.message : "Could not reset the layout.");
if (!(e instanceof PositionConflictError)) {
setConnectError(e instanceof Error ? e.message : "Could not reset the layout.");
}
} finally {
setLayoutBusy(null);
}
}, [techs, layoutBusy]);
}, [techs, layoutBusy, writePositions]);
const techById = React.useMemo(
() => new Map(techs.map((t) => [String(t.id), t])),
@ -679,20 +836,48 @@ function CanvasInner({ data }: { data: TechTreeData }) {
]);
let nextTechs = techDocs.map(mapTechDoc);
const nextCategories = categoryDocs.map(mapCategoryDoc);
let freezePins: Map<number, CanvasPosition> | null = null;
if (options.freeze) {
const pins = pinsToFreeze(currentPositions(), nextTechs, nextCategories);
nextTechs = applyPins(nextTechs, pins);
persistPins(pins).catch((e: unknown) =>
setConnectError(e instanceof Error ? e.message : "Could not save positions."),
);
freezePins = pinsToFreeze(currentPositions(), nextTechs, nextCategories);
nextTechs = applyPins(nextTechs, freezePins);
}
setTechs(nextTechs);
setCategories(nextCategories);
setResources(resourceDocs.map((d) => ({ id: d.id as number, name: String(d.name ?? "") })));
if (freezePins) {
// Persist AFTER setTechs and with the freshly fetched docs as the token
// source: the pin writes bump updated_at, and stale pre-refresh tokens
// would falsely conflict.
persistPins(freezePins, new Set(), nextTechs).catch((e: unknown) =>
setConnectError(e instanceof Error ? e.message : "Could not save positions."),
);
}
},
[currentPositions, persistPins],
);
/** Conflict banner action: refetch the truth and drop the pending batch. */
const resolvePositionConflicts = React.useCallback(async () => {
setPositionConflicts([]);
lastFailedWrite.current = null;
await refresh();
}, [refresh]);
/** Conflict banner action: retry the failed batch without preconditions. */
const forceOverwritePositions = React.useCallback(async () => {
const batch = lastFailedWrite.current;
if (!batch) return;
try {
const fresh = await saveTreePositions(batch, new Map());
applyServerTokens(fresh);
setPositionConflicts([]);
lastFailedWrite.current = null;
setSaveStatus(`Positions overwritten. ${batch.length} node(s).`);
} catch (e) {
setConnectError(e instanceof Error ? e.message : "Could not overwrite positions.");
}
}, [applyServerTokens]);
const handleCreated = React.useCallback(
async (result: QuickCreateResult) => {
await refresh({ freeze: true });
@ -802,6 +987,31 @@ function CanvasInner({ data }: { data: TechTreeData }) {
{connectError}
</span>
) : null}
{positionConflicts.length > 0 ? (
<span
className="flex items-center gap-2 font-mono text-[10px] tracking-widest text-red-400 uppercase"
data-testid="tech-tree-conflict-banner"
>
<TriangleAlertIcon className="size-3" />
{positionConflicts.length} NODE(S) CHANGED ELSEWHERE
<button
type="button"
onClick={() => void resolvePositionConflicts()}
className={`${TACTICAL_BUTTON} px-2 py-1`}
data-testid="tech-tree-conflict-refresh"
>
Refresh
</button>
<button
type="button"
onClick={() => void forceOverwritePositions()}
className={`${TACTICAL_BUTTON} border-red-400/50 px-2 py-1 text-red-300 hover:border-red-300/70 hover:text-red-200`}
data-testid="tech-tree-conflict-force"
>
Overwrite anyway
</button>
</span>
) : null}
{layoutBusy ? (
<span
role="status"
@ -921,11 +1131,20 @@ function CanvasInner({ data }: { data: TechTreeData }) {
canCreateCategories={data.canCreateCategories}
canSetFinalApproval={data.canSetFinalApproval}
warnings={selectedWarnings}
reseedNonce={panelReseedNonce}
onClose={() => setSelectedId(null)}
onEdit={() => router.push(`/admin/collections/technologies/${selectedTech.id}`)}
onSaved={() => {
void refresh({ freeze: true });
}}
onConflictReload={() => {
// Accept the server version: refetch truth, clear any pending
// conflict batch, and reseed the panel draft via the nonce.
setPositionConflicts([]);
lastFailedWrite.current = null;
void refresh();
setPanelReseedNonce((n) => n + 1);
}}
/>
) : null}

View file

@ -53,6 +53,7 @@ export function mapTechDoc(doc: Record<string, unknown>): TreeTech {
prereqOr: [...new Set(prereqOr)].filter((id) => !prereqAnd.includes(id)),
resourceCosts,
treePosition,
updatedAt: String(doc.updatedAt ?? ""),
};
}

View file

@ -19,6 +19,12 @@ export type TreeTech = {
resourceCosts: { resource: number; amount: number }[];
/** Manual canvas position (dragged node); null = automatic layout. */
treePosition: { x: number; y: number } | null;
/**
* Document version (`updatedAt`) used as the optimistic concurrency token.
* Sent back in `X-PTF-If-Unmodified-At` on panel saves and as
* `ifUnmodifiedAt` per row on bulk position writes.
*/
updatedAt: string;
};
export type TreeCategory = {

View file

@ -0,0 +1,24 @@
/**
* Optimistic concurrency protocol shared by the Tech Tree editor's client and
* server sides (Option A: whole-document version tokens based on updatedAt).
*
* This module must stay importable from client components: no Payload or
* server imports here. The server-side enforcement lives in
* `src/utils/access-control/optimisticConcurrency.ts` (collection hook) and
* `src/lib/tech-tree/positions.ts` (bulk position writes).
*/
/**
* Request header carrying the `updatedAt` value the client loaded. When
* present on an update, the write is rejected with HTTP 409 if the stored
* document has changed since. Requests without the header keep the existing
* unconditional behavior (admin edit view, server actions, scripts, seeds).
*/
export const IF_UNMODIFIED_AT_HEADER = "x-ptf-if-unmodified-at";
/** One bulk-position entry that failed its precondition. */
export type PositionConflict = {
id: number;
/** The stored `updatedAt` right now, so the client can refresh its token. */
currentUpdatedAt: string | null;
};

View file

@ -1,5 +1,6 @@
import { sql } from "@payloadcms/db-postgres";
import type { Payload } from "payload";
import type { PositionConflict } from "@/lib/tech-tree/concurrency";
/**
* Bulk Tech Tree position writes.
@ -11,9 +12,19 @@ import type { Payload } from "payload";
* 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. The
* technologies collection has no hooks, so bypassing the Local API loses
* nothing; `updated_at` is bumped to keep the documents honest.
* 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. */
@ -24,6 +35,22 @@ export type TreePositionUpdate = {
/** 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<string, string>;
};
export type ParseResult =
@ -40,7 +67,12 @@ export function parsePositionUpdates(body: unknown): ParseResult {
const byId = new Map<number, TreePositionUpdate>();
for (const entry of positions) {
const { id, x, y } = (entry ?? {}) as { id?: unknown; x?: unknown; y?: unknown };
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." };
}
@ -50,32 +82,101 @@ export function parsePositionUpdates(body: unknown): ParseResult {
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 }
: { id, x: Math.round(x as number), y: Math.round(y as number) },
? { 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()] };
}
/** Write every position in a single UPDATE. Returns the number of rows touched. */
/** 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<number> {
if (updates.length === 0) return 0;
): Promise<PositionWriteResult> {
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)`),
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 = v.x, tree_position_y = v.y, updated_at = now()
FROM (VALUES ${values}) AS v(id, x, y)
WHERE t.id = v.id
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
`);
return (result as { rowCount?: number | null }).rowCount ?? 0;
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<string, string> = {};
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<number, string | null>(
((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 };
}

View file

@ -0,0 +1,60 @@
import { APIError, type CollectionBeforeChangeHook } from "payload";
import { IF_UNMODIFIED_AT_HEADER } from "@/lib/tech-tree/concurrency";
/**
* Optimistic concurrency guard for collections edited by the Tech Tree lite
* editor (Option A: whole-document version tokens).
*
* The token is the document's `updatedAt` (a millisecond-precision timestamp,
* see the `precision: 3` columns in payload-generated-schema.ts), sent back
* verbatim in the `X-PTF-If-Unmodified-At` request header. Enforcement fires
* ONLY when a preconditioned update carries that header, so every other write
* flow (standard admin edit view, server actions, scripts, seeds) keeps its
* existing unconditional behavior untouched.
*
* Conflicts surface as HTTP 409 with a machine-readable `data.code` because
* Payload's routeError responds with `err.status || 500` and formatErrors
* serializes an APIError's `name` and `data` into `{ errors: [...] }`.
*/
/** Thrown when a preconditioned update targets a document that changed since load. */
export class StaleWriteError extends APIError {
constructor(expectedUpdatedAt: string, currentUpdatedAt: string) {
super(
"This document changed since you loaded it. Load the latest version before saving.",
409,
{ code: "stale_write", expectedUpdatedAt, currentUpdatedAt },
);
}
}
/**
* Collection `beforeChange` hook factory: reject updates whose
* `X-PTF-If-Unmodified-At` header no longer matches the stored `updatedAt`.
*
* Order note: place this FIRST in `hooks.beforeChange` so a stale write aborts
* before content-rewriting hooks (e.g. resetApprovalStatusOnEdit) do any work.
* The guard reads only the request header and `originalDoc`, so it never
* fights with hooks that rewrite `data`.
*/
export function ifUnmodifiedAtGuard(): CollectionBeforeChangeHook {
return async ({ req, data, originalDoc, operation }) => {
if (operation !== "update") return data;
const header = req?.headers?.get?.(IF_UNMODIFIED_AT_HEADER);
if (!header) return data; // No precondition supplied: behavior unchanged.
const expected = Date.parse(header);
if (Number.isNaN(expected)) {
throw new APIError("Invalid If-Unmodified-At precondition.", 400);
}
const stored = (originalDoc as { updatedAt?: string } | null | undefined)?.updatedAt;
const current = Date.parse(String(stored ?? ""));
if (Number.isNaN(current)) return data; // Defensive: cannot compare, do not block.
if (expected !== current) {
throw new StaleWriteError(header, String(stored));
}
return data;
};
}

View file

@ -764,4 +764,141 @@ test.describe("Tech Tree admin view", () => {
}
expect(xs.size).toBeGreaterThanOrEqual(2);
});
test("stale panel save surfaces the conflict dialog; overwrite and reload resolve it", async ({
page,
}) => {
await login(page);
await clearTree(page);
const costs = { minimumResearchDuration: 1, maximumResearchDuration: 10 };
const doc = await createDoc(page, "technologies", {
name: "Tech Tree Conflict Alpha",
type: "upgrade",
summary: "Optimistic concurrency seed.",
category: null,
researchCosts: costs,
});
await gotoTree(page);
await page.getByTestId(`tech-node-${doc.id}`).click();
const panel = page.getByTestId("tech-preview-panel");
await expect(panel).toBeVisible();
// Another user saves first, making this browser's loaded version stale.
const bump = await page.request.patch(`/api/technologies/${doc.id}`, {
data: { summary: "External edit wins the race." },
});
expect(bump.ok()).toBe(true);
// The panel still holds the pre-bump token: saving must not silently win.
await panel.getByTestId("tech-panel-name").fill("Tech Tree Conflict Alpha (mine)");
await panel.getByTestId("tech-panel-save").click();
const dialog = page.getByTestId("tech-conflict-dialog");
await expect(dialog).toBeVisible();
await expect(dialog).toContainText("Version Conflict");
// Choice 1: Overwrite anyway writes the draft over the external edit.
await page.getByTestId("tech-conflict-overwrite").click();
await expect(dialog).toBeHidden();
await expect
.poll(
async () => {
const res = await page.request.get(`/api/technologies/${doc.id}`);
return ((await res.json())?.name ?? "") as string;
},
{ timeout: 15_000 },
)
.toBe("Tech Tree Conflict Alpha (mine)");
// Choice 2: Load latest discards the draft and reseeds from the server.
const bump2 = await page.request.patch(`/api/technologies/${doc.id}`, {
data: { summary: "Second external edit." },
});
expect(bump2.ok()).toBe(true);
await panel.getByTestId("tech-panel-name").fill("Discarded draft name");
await panel.getByTestId("tech-panel-save").click();
await expect(dialog).toBeVisible();
await page.getByTestId("tech-conflict-reload").click();
await expect(dialog).toBeHidden();
await expect(panel.getByTestId("tech-panel-name")).toHaveValue(
"Tech Tree Conflict Alpha (mine)",
);
await page.request.delete(`/api/technologies/${doc.id}`);
});
test("stale position writes return 409 with conflicts and surface the toolbar banner", async ({
page,
}) => {
await login(page);
await clearTree(page);
const costs = { minimumResearchDuration: 1, maximumResearchDuration: 10 };
const alpha = await createDoc(page, "technologies", {
name: "Tech Tree PosConf Alpha",
type: "upgrade",
summary: "Position conflict seed A.",
category: null,
researchCosts: costs,
});
const beta = await createDoc(page, "technologies", {
name: "Tech Tree PosConf Beta",
type: "upgrade",
summary: "Position conflict seed B.",
category: null,
researchCosts: costs,
});
// API-level contract: one stale precondition rejects the whole batch and
// reports exactly the conflicting ids (the fresh row is not applied).
const docsRes = await page.request.get("/api/technologies?limit=0&depth=0");
const docs = ((await docsRes.json()).docs ?? []) as { id: number; updatedAt: string }[];
const tokenOf = (id: number) => docs.find((d) => d.id === id)?.updatedAt ?? "";
const staleWrite = await page.request.post("/api/tech-tree/positions", {
data: {
positions: [
{ id: alpha.id, x: 500, y: 500, ifUnmodifiedAt: "2000-01-01T00:00:00.000Z" },
{ id: beta.id, x: 600, y: 600, ifUnmodifiedAt: tokenOf(beta.id) },
],
},
});
expect(staleWrite.status()).toBe(409);
const conflictBody = await staleWrite.json();
expect((conflictBody.conflicts as { id: number }[]).map((c) => c.id)).toEqual([alpha.id]);
const betaAfter = await (await page.request.get(`/api/technologies/${beta.id}?depth=0`)).json();
expect(betaAfter?.treePosition?.x ?? null).toBeNull();
// UI-level: bump beta out of band AFTER the canvas loaded its tokens, then
// drag its card. The optimistic position stays on screen but the rejected
// write surfaces as the toolbar banner plus a red ring on the node.
await gotoTree(page);
const bump = await page.request.patch(`/api/technologies/${beta.id}`, {
data: { summary: "Bumped while the canvas was open." },
});
expect(bump.ok()).toBe(true);
const node = page.getByTestId(`tech-node-${beta.id}`);
await expect(node).toBeVisible();
const box = (await node.boundingBox())!;
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
await page.mouse.down();
await page.mouse.move(box.x + box.width / 2 + 240, box.y + box.height / 2 + 160, {
steps: 12,
});
await page.mouse.up();
const banner = page.getByTestId("tech-tree-conflict-banner");
await expect(banner).toBeVisible({ timeout: 15_000 });
await expect(banner).toContainText("1 NODE(S) CHANGED ELSEWHERE");
await expect(node).toHaveAttribute("data-conflict", "true");
// Refresh refetches truth and clears both the banner and the highlight.
await page.getByTestId("tech-tree-conflict-refresh").click();
await expect(banner).toHaveCount(0, { timeout: 15_000 });
await expect(node).not.toHaveAttribute("data-conflict", "true");
for (const id of [alpha.id, beta.id]) await page.request.delete(`/api/technologies/${id}`);
});
});

View file

@ -0,0 +1,455 @@
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<number> => {
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<string> => {
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<string, unknown> };
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<number> => {
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<string> => {
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<number, string>();
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<string, string>,
originalDoc: { updatedAt?: string } | null,
operation: "create" | "update" = "update",
) =>
hook({
req: { headers: new Headers(headers) },
data: { name: "draft" },
originalDoc,
operation,
} as unknown as Parameters<typeof hook>[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 });
});
});

View file

@ -22,6 +22,8 @@ const tech = (over: Partial<TreeTech> & { id: number }): TreeTech => ({
prereqOr: [],
resourceCosts: [],
treePosition: null,
// Concurrency token; irrelevant to the pure layout helper.
updatedAt: "",
...over,
});

View file

@ -23,8 +23,8 @@ describe("tech tree position bulk-write validation", () => {
expect(result).toEqual({
ok: true,
updates: [
{ id: 1, x: 10, y: 21 },
{ id: 2, x: null, y: null },
{ id: 1, x: 10, y: 21, expectedUpdatedAt: null },
{ id: 2, x: null, y: null, expectedUpdatedAt: null },
],
});
});
@ -36,7 +36,30 @@ describe("tech tree position bulk-write validation", () => {
{ id: 3, x: null, y: null },
],
});
expect(result).toEqual({ ok: true, updates: [{ id: 3, x: null, y: null }] });
expect(result).toEqual({
ok: true,
updates: [{ id: 3, x: null, y: null, expectedUpdatedAt: null }],
});
});
it("carries and validates the optimistic concurrency token", () => {
const accepted = parsePositionUpdates({
positions: [{ id: 1, x: 5, y: 5, ifUnmodifiedAt: "2026-10-15T12:00:00.000Z" }],
});
expect(accepted).toEqual({
ok: true,
updates: [{ id: 1, x: 5, y: 5, expectedUpdatedAt: "2026-10-15T12:00:00.000Z" }],
});
// Null means unconditional; malformed values are rejected.
expect(
parsePositionUpdates({ positions: [{ id: 1, x: 5, y: 5, ifUnmodifiedAt: null }] }),
).toEqual({ ok: true, updates: [{ id: 1, x: 5, y: 5, expectedUpdatedAt: null }] });
expect(
parsePositionUpdates({ positions: [{ id: 1, x: 5, y: 5, ifUnmodifiedAt: "soon" }] }).ok,
).toBe(false);
expect(
parsePositionUpdates({ positions: [{ id: 1, x: 5, y: 5, ifUnmodifiedAt: 123 }] }).ok,
).toBe(false);
});
it("rejects malformed bodies", () => {
@ -102,11 +125,12 @@ describe("tech tree position bulk write (database)", () => {
"pins many technologies in one write and clears them again",
async () => {
const pinned = await writeTreePositions(payload, [
{ id: ids[0], x: 46, y: 92 },
{ id: ids[1], x: 368, y: 184 },
{ id: ids[2], x: 0, y: 0 },
{ id: ids[0], x: 46, y: 92, expectedUpdatedAt: null },
{ id: ids[1], x: 368, y: 184, expectedUpdatedAt: null },
{ id: ids[2], x: 0, y: 0, expectedUpdatedAt: null },
]);
expect(pinned).toBe(3);
expect(pinned.updated).toBe(3);
expect(pinned.conflicts).toEqual([]);
expect(await positionOf(ids[0])).toMatchObject({ x: 46, y: 92 });
expect(await positionOf(ids[1])).toMatchObject({ x: 368, y: 184 });
expect(await positionOf(ids[2])).toMatchObject({ x: 0, y: 0 });
@ -114,9 +138,9 @@ describe("tech tree position bulk write (database)", () => {
// Auto-arrange path: clear every pin in a single statement.
const cleared = await writeTreePositions(
payload,
ids.map((id) => ({ id, x: null, y: null })),
ids.map((id) => ({ id, x: null, y: null, expectedUpdatedAt: null })),
);
expect(cleared).toBe(3);
expect(cleared.updated).toBe(3);
for (const id of ids) {
const position = await positionOf(id);
expect(position?.x ?? null).toBeNull();
@ -129,8 +153,11 @@ describe("tech tree position bulk write (database)", () => {
it(
"ignores ids that do not exist",
async () => {
const touched = await writeTreePositions(payload, [{ id: 999_999_999, x: 1, y: 1 }]);
expect(touched).toBe(0);
const touched = await writeTreePositions(payload, [
{ id: 999_999_999, x: 1, y: 1, expectedUpdatedAt: null },
]);
expect(touched.updated).toBe(0);
expect(touched.conflicts).toEqual([]);
},
TIMEOUT,
);

View file

@ -20,6 +20,8 @@ const tech = (over: Partial<TreeTech> & { id: number }): TreeTech => ({
prereqOr: [],
resourceCosts: [],
treePosition: null,
// Concurrency token; irrelevant to the pure prereq-edit helper.
updatedAt: "",
...over,
});

View file

@ -15,6 +15,8 @@ const tech = (over: Partial<TreeTech> & { id: number }): TreeTech => ({
prereqOr: [],
resourceCosts: [],
treePosition: null,
// Concurrency token; irrelevant to the pure freeze helper.
updatedAt: "",
...over,
});