1
0
Fork 0

Compare commits

...

4 commits

Author SHA1 Message Date
000036beda v0.11.1 - approval reset on edit, tech tree conflict protection 2026-10-15 12:12:32 -04:00
02ad121220 docs: add v0.11.1 changelog entry 2026-10-15 12:12:25 -04:00
caf77e3a6b 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.
2026-10-15 11:48:30 -04:00
4f129fc59a feat(approval): reset reviewed documents to in progress on non-superuser edits
Add resetApprovalStatusOnEdit(), a collection beforeChange hook factory: when a
non-superuser updates a document whose stored approvalStatus is approved or
revision_requested, the status is rewritten to in_progress so the edit goes
through review again. Creates, superusers (system:admin-access), and system
writes with no user (catalog imports, seeds) are exempt, and an explicit
in_progress/ready_for_review in the edit is honored.

Wired into Technologies, Assets, Resources, Vehicles, and Structures.

Structures also moves from the legacy isDeveloper filterOptions gate to
approvalStatusFieldAccess("structures"), matching the other four collections
and removing the hard ValidationError when saving an already-approved structure.

Tests: 12 cases in tests/int/division-admin-access.int.spec.ts.
2026-10-15 10:01:02 -04:00
24 changed files with 1634 additions and 83 deletions

View file

@ -1,5 +1,16 @@
# Changelog
# v0.11.1
Two safeguards against silent data loss: reviewed documents re-enter review when edited, and the tech tree editor now refuses stale writes.
### Features
- **Approval reset.** When a member without superuser tier edits an approved or revision-requested asset, resource, vehicle, structure, or technology, its approval status returns to In Progress automatically, so an edited document never keeps a stale green light.
- **Tech tree conflict protection.** The tech tree editor detects when another user changed a technology (or moved a card) since you loaded it. Panel saves open a Version Conflict dialog with load latest or overwrite options; canvas position writes that collide raise a toolbar banner that highlights the affected nodes and offers refresh or force-overwrite. Nothing you save can silently overwrite someone else's work anymore.
---
# v0.11.0
Training games scheduled for retirement now warn you before you start them.

View file

@ -1,6 +1,6 @@
{
"name": "polaris-task-force",
"version": "0.11.0",
"version": "0.11.1",
"description": "Web app for the Arma 3 unit Polaris Task Force. Uses Next.js for client- and server-side rendering, with a Postgres database and some other neat libraries.",
"license": "MIT",
"type": "module",

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

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

View file

@ -3,6 +3,7 @@ import {
approvalStatusFieldAccess,
requireApprovalPermission,
requireLogisticsPermission,
resetApprovalStatusOnEdit,
} from "@/utils/access-control/divisionAccess";
const approvalFieldAccess = {
@ -23,6 +24,9 @@ export const Assets: CollectionConfig = {
update: requireLogisticsPermission("assets:update"),
delete: requireLogisticsPermission("assets:delete"),
},
hooks: {
beforeChange: [resetApprovalStatusOnEdit()],
},
fields: [
{
name: "name",

View file

@ -5,6 +5,7 @@ import {
approvalStatusFieldAccess,
requireApprovalPermission,
requireLogisticsPermission,
resetApprovalStatusOnEdit,
} from "@/utils/access-control/divisionAccess";
const onlyIfNotPrimaryCurrency = async ({ req }: { req: PayloadRequest }) => {
@ -61,6 +62,9 @@ export const Resources: CollectionConfig = {
update: logisticsWriteWithCurrencyGuard("resources:update"),
delete: logisticsWriteWithCurrencyGuard("resources:delete"),
},
hooks: {
beforeChange: [resetApprovalStatusOnEdit()],
},
fields: [
{
name: "NoEditWarning",

View file

@ -1,5 +1,5 @@
import { CollectionConfig } from "payload";
import { isDeveloper } from "@/utils/access-control/isRole";
import { approvalStatusFieldAccess, resetApprovalStatusOnEdit } from "@/utils/access-control/divisionAccess";
import type { Resource } from "@/payload-types";
import { emitGameEvent } from "@/utils/event-log/emit";
import { createStaffingFields } from "@/collections/game/staffingFields";
@ -7,6 +7,8 @@ import { createProductionFields } from "@/collections/game/productionFields";
import { createModuleFields } from "@/collections/game/moduleFields";
import { createAuraFields } from "@/collections/game/auraFields";
const approvalStatusFieldAccessConfig = approvalStatusFieldAccess("structures");
export const Structures: CollectionConfig = {
slug: "structures",
admin: {
@ -240,6 +242,9 @@ export const Structures: CollectionConfig = {
return data;
},
// Editing a structure that is already approved / revision-requested
// resets it to in_progress unless the writer is a superuser.
resetApprovalStatusOnEdit(),
],
},
fields: [
@ -275,15 +280,7 @@ export const Structures: CollectionConfig = {
{ label: "Revision Requested", value: "revision_requested" },
],
defaultValue: "in_progress",
filterOptions: ({ options, data: _data, req }) => {
return !isDeveloper({ req })
? options.filter((option) =>
typeof option === "string"
? options
: ["in_progress", "ready_for_review"].includes(option.value),
)
: options;
},
access: approvalStatusFieldAccessConfig,
required: true,
admin: {
description:

View file

@ -3,6 +3,7 @@ import {
approvalStatusFieldAccess,
requireApprovalPermission,
requireLogisticsPermission,
resetApprovalStatusOnEdit,
} from "@/utils/access-control/divisionAccess";
const approvalStatusFieldAccessConfig = approvalStatusFieldAccess("vehicles");
@ -18,6 +19,9 @@ export const Vehicles: CollectionConfig = {
update: requireLogisticsPermission("vehicles:update"),
delete: requireLogisticsPermission("vehicles:delete"),
},
hooks: {
beforeChange: [resetApprovalStatusOnEdit()],
},
fields: [
{
// D11b: searchable imported-library picker (name, classname, thumbnail)

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

@ -1,4 +1,11 @@
import type { Access, AccessArgs, AccessResult, Payload, PayloadRequest } from "payload";
import type {
Access,
AccessArgs,
AccessResult,
CollectionBeforeChangeHook,
Payload,
PayloadRequest,
} from "payload";
import type { Permission } from "@/permissions";
import {
canAccessAdminPanel as canAccessAdminPanelByPermissions,
@ -110,6 +117,54 @@ export function approvalStatusFieldAccess(collectionSlug: string) {
};
}
/**
* Approval statuses that a non-superuser edit invalidates:
* - `approved` the document is live/implemented, so an edit must be
* reviewed again before it stays live
* - `revision_requested` the author has changes to make, which is exactly the
* edit happening now
*/
const EDIT_INVALIDATED_APPROVAL_STATUSES = ["approved", "revision_requested"];
/** Statuses a non-superuser may legitimately land on while editing. */
const EDITABLE_APPROVAL_STATUSES = ["in_progress", "ready_for_review"];
/**
* Collection `beforeChange` hook factory: when a NON-superuser updates a
* document whose stored `approvalStatus` is Approved or Revision Requested,
* rewrite the status back to "In Progress" so the edit is reviewed again.
*
* A hook is required rather than field-level access for two reasons:
* - Payload field access can only *strip* a field, never rewrite its value.
* - It only sees the incoming payload, so it cannot react to a partial update
* that omits `approvalStatus` entirely (the normal case for the tech tree
* lite editor and PATCH-style edits).
*
* Rules:
* - Update only; creates keep the existing default/access behavior.
* - Superusers (holders of `system:admin-access`) are exempt.
* - System writes with no `req.user` (catalog imports, seeds, scripts using
* `overrideAccess: true`) are exempt, so automation never resets a reviewed
* document.
* - If the edit explicitly sets an editable status (In Progress, Ready for
* Review), that choice is honored instead of forcing In Progress.
*/
export function resetApprovalStatusOnEdit(): CollectionBeforeChangeHook {
return async ({ req, data, originalDoc, operation }) => {
if (operation !== "update" || !req.user || !data) return data;
const current = (originalDoc as { approvalStatus?: string } | null | undefined)?.approvalStatus;
if (!current || !EDIT_INVALIDATED_APPROVAL_STATUSES.includes(current)) return data;
if (await hasPermission(req.payload, req.user, "system:admin-access")) return data;
const incoming = data.approvalStatus as string | undefined;
if (incoming && EDITABLE_APPROVAL_STATUSES.includes(incoming)) return data;
return { ...data, approvalStatus: "in_progress" };
};
}
/**
* Same contract as `requireAdminPageAccess`, with one addition: for the four
* division-scoped collections an admin-panel request also passes when the user

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

@ -4,7 +4,7 @@ import config from "@/payload.config";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { Role, User } from "@/payload-types";
import type { Role, Structure, User } from "@/payload-types";
import {
approvalStatusFieldAccess,
canAccessAdminPanel,
@ -20,6 +20,17 @@ let payload: Payload;
const RUN = `div-${Date.now().toString(36)}`;
const TIMEOUT = 30_000;
const LEXICAL_EMPTY = {
root: {
children: [{ text: "" }],
direction: null,
format: "" as const,
indent: 0,
type: "text",
version: 1,
},
};
describe("Division-scoped admin access (intelligence / logistics)", () => {
const roleIds: number[] = [];
const userIds: number[] = [];
@ -27,6 +38,7 @@ describe("Division-scoped admin access (intelligence / logistics)", () => {
const resourceIds: number[] = [];
const vehicleIds: number[] = [];
const technologyIds: number[] = [];
const structureIds: number[] = [];
const createdQualificationIds: number[] = [];
let intelUser: User;
@ -165,8 +177,10 @@ describe("Division-scoped admin access (intelligence / logistics)", () => {
afterAll(async () => {
if (!payload) return;
type TestSlug = "assets" | "resources" | "vehicles" | "technologies";
type TestSlug = "assets" | "resources" | "vehicles" | "technologies" | "structures";
const docs: Array<[TestSlug, number]> = [
// Structures first: they may reference the resources deleted below.
...structureIds.map((id) => ["structures", id] as [TestSlug, number]),
...assetIds.map((id) => ["assets", id] as [TestSlug, number]),
...resourceIds.map((id) => ["resources", id] as [TestSlug, number]),
...vehicleIds.map((id) => ["vehicles", id] as [TestSlug, number]),
@ -502,4 +516,287 @@ describe("Division-scoped admin access (intelligence / logistics)", () => {
expect(await accessFnDecision(approvalStatusUpdate, plainUser, data("approved"))).toBe(false);
}, TIMEOUT);
});
describe("approval status reset on non-superuser edit", () => {
let seq = 0;
type ApprovalStatus = "in_progress" | "ready_for_review" | "approved" | "rejected" | "revision_requested";
// A final/held status can only be seeded by a superuser.
const createAsset = async (approvalStatus: ApprovalStatus): Promise<{ id: number }> => {
seq += 1;
const doc = (await payload.create({
collection: "assets",
data: {
name: `${RUN} Reset ${approvalStatus} ${seq}`,
className: `reset-${approvalStatus}-${seq}-${RUN}`,
assetType: "weapon",
approvalStatus,
crafting: { craftingData: { craftingTimePerUnit: 1, batchSize: 1 } },
storageDimensions: { gridWidth: 1, gridHeight: 1 },
},
user: superUser,
overrideAccess: false,
})) as unknown as { id: number };
assetIds.push(doc.id);
return doc;
};
it("resets an approved document to in_progress when a non-superuser edits it", async () => {
const asset = await createAsset("approved");
// editorUser holds assets:update but is not a member of the super-user tier.
// The payload mirrors the tech tree editor, which submits the document's
// current (final) status: field access strips "approved", then the hook
// rewrites the status to in_progress.
const updated = (await payload.update({
collection: "assets",
id: asset.id,
data: { name: `${RUN} Reset renamed`, approvalStatus: "approved" },
user: editorUser,
overrideAccess: false,
})) as unknown as { name: string; approvalStatus: string };
expect(updated.name).toBe(`${RUN} Reset renamed`);
expect(updated.approvalStatus).toBe("in_progress");
}, TIMEOUT);
it("resets a revision-requested technology when a non-superuser edits it", async () => {
const tech = (await payload.create({
collection: "technologies",
data: {
name: `${RUN} Revision Tech`,
summary: "needs rework",
type: "upgrade",
approvalStatus: "revision_requested",
researchCosts: { minimumResearchDuration: 1 },
},
user: superUser,
overrideAccess: false,
})) as unknown as { id: number };
technologyIds.push(tech.id);
const updated = (await payload.update({
collection: "technologies",
id: tech.id,
data: { name: `${RUN} Revision Tech v2` },
user: intelUser,
overrideAccess: false,
})) as unknown as { approvalStatus: string };
expect(updated.approvalStatus).toBe("in_progress");
}, TIMEOUT);
it("resets a revision-requested resource when a non-superuser edits it", async () => {
const resource = (await payload.create({
collection: "resources",
data: {
name: `${RUN} Revision Fuel`,
codeName: `res_revision_${RUN}`,
unitOfMeasure: "liter",
massPerUnit: 0,
gridWidth: 1,
gridHeight: 1,
type: "fluid",
baseValue: 1,
rarity: "common",
approvalStatus: "revision_requested",
},
user: superUser,
overrideAccess: false,
})) as unknown as { id: number };
resourceIds.push(resource.id);
const updated = (await payload.update({
collection: "resources",
id: resource.id,
data: { name: `${RUN} Revision Fuel v2` },
user: logiUser,
overrideAccess: false,
})) as unknown as { approvalStatus: string };
expect(updated.approvalStatus).toBe("in_progress");
}, TIMEOUT);
it("resets an approved vehicle when a non-superuser edits it", async () => {
const resource = (await payload.create({
collection: "resources",
data: {
name: `${RUN} Vehicle Fuel`,
codeName: `res_vehicle_fuel_${RUN}`,
unitOfMeasure: "liter",
massPerUnit: 0,
gridWidth: 1,
gridHeight: 1,
type: "fluid",
baseValue: 1,
rarity: "common",
approvalStatus: "approved",
},
user: superUser,
overrideAccess: false,
})) as unknown as { id: number };
resourceIds.push(resource.id);
const vehicle = (await payload.create({
collection: "vehicles",
data: {
name: `${RUN} Approved Truck`,
transportMode: "ground",
approvalStatus: "approved",
fuel: { fuelType: resource.id, fuelCapacity: 100, fuelConsumptionRate: 1 },
},
user: superUser,
overrideAccess: false,
})) as unknown as { id: number };
vehicleIds.push(vehicle.id);
const updated = (await payload.update({
collection: "vehicles",
id: vehicle.id,
data: { name: `${RUN} Approved Truck v2` },
user: logiUser,
overrideAccess: false,
})) as unknown as { approvalStatus: string };
expect(updated.approvalStatus).toBe("in_progress");
}, TIMEOUT);
it("does not reset when a superuser edits an approved document", async () => {
const asset = await createAsset("approved");
const updated = (await payload.update({
collection: "assets",
id: asset.id,
data: { name: `${RUN} Super edit` },
user: superUser,
overrideAccess: false,
})) as unknown as { approvalStatus: string };
expect(updated.approvalStatus).toBe("approved");
}, TIMEOUT);
it("does not reset on system writes with no user (catalog imports, seeds)", async () => {
const asset = await createAsset("approved");
const updated = (await payload.update({
collection: "assets",
id: asset.id,
data: { name: `${RUN} Import edit` },
overrideAccess: true,
})) as unknown as { approvalStatus: string };
expect(updated.approvalStatus).toBe("approved");
}, TIMEOUT);
it("honors an explicit editable status instead of forcing in_progress", async () => {
const asset = await createAsset("approved");
const updated = (await payload.update({
collection: "assets",
id: asset.id,
data: { approvalStatus: "ready_for_review" },
user: editorUser,
overrideAccess: false,
})) as unknown as { approvalStatus: string };
expect(updated.approvalStatus).toBe("ready_for_review");
}, TIMEOUT);
it("leaves statuses outside the invalidated set untouched", async () => {
const asset = await createAsset("rejected");
const updated = (await payload.update({
collection: "assets",
id: asset.id,
data: { name: `${RUN} Rejected edit` },
user: editorUser,
overrideAccess: false,
})) as unknown as { approvalStatus: string };
expect(updated.approvalStatus).toBe("rejected");
}, TIMEOUT);
});
describe("approval status reset on structures (parity with the four approval collections)", () => {
let seq = 0;
type ApprovalStatus = "in_progress" | "ready_for_review" | "approved" | "rejected" | "revision_requested";
const createStructure = async (approvalStatus: ApprovalStatus): Promise<{ id: number }> => {
seq += 1;
const resource = (await payload.create({
collection: "resources",
data: {
name: `${RUN} Structure Material ${seq}`,
codeName: `res_structure_${seq}_${RUN}`,
unitOfMeasure: "unit",
massPerUnit: 0,
gridWidth: 1,
gridHeight: 1,
type: "physical",
baseValue: 1,
rarity: "common",
approvalStatus: "approved",
},
user: superUser,
overrideAccess: false,
})) as unknown as { id: number };
resourceIds.push(resource.id);
const structure = (await payload.create({
collection: "structures",
data: {
name: `${RUN} Structure ${approvalStatus} ${seq}`,
codeName: `${RUN}-structure-${seq}-${approvalStatus}`,
approvalStatus,
category: "logistics",
materials: [{ resource: resource.id, amount: 1 }],
constructionDurationMinutes: 1,
terrainType: "land",
maxHealth: 100,
description: LEXICAL_EMPTY as unknown as Structure["description"],
},
user: superUser,
overrideAccess: false,
})) as unknown as { id: number };
structureIds.push(structure.id);
return structure;
};
it("resets an approved structure when a non-superuser edits it", async () => {
const structure = await createStructure("approved");
const updated = (await payload.update({
collection: "structures",
id: structure.id,
data: { name: `${RUN} Structure renamed` },
user: editorUser,
overrideAccess: false,
})) as unknown as { approvalStatus: string };
expect(updated.approvalStatus).toBe("in_progress");
}, TIMEOUT);
it("resets a revision-requested structure when a non-superuser edits it", async () => {
const structure = await createStructure("revision_requested");
const updated = (await payload.update({
collection: "structures",
id: structure.id,
data: { name: `${RUN} Structure rework` },
user: logiUser,
overrideAccess: false,
})) as unknown as { approvalStatus: string };
expect(updated.approvalStatus).toBe("in_progress");
}, TIMEOUT);
it("lets a superuser edit an approved structure (no filterOptions validation error)", async () => {
const structure = await createStructure("approved");
const updated = (await payload.update({
collection: "structures",
id: structure.id,
data: { name: `${RUN} Structure super edit` },
user: superUser,
overrideAccess: false,
})) as unknown as { approvalStatus: string };
expect(updated.approvalStatus).toBe("approved");
}, TIMEOUT);
it("strips a final status submitted by a non-superuser", async () => {
const structure = await createStructure("in_progress");
const updated = (await payload.update({
collection: "structures",
id: structure.id,
data: { name: `${RUN} Structure self-approve attempt`, approvalStatus: "approved" },
user: editorUser,
overrideAccess: false,
})) as unknown as { approvalStatus: string };
expect(updated.approvalStatus).toBe("in_progress");
}, TIMEOUT);
});
});

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,
});