Compare commits
No commits in common. "000036beda8ea619e7ea3a850ba4c43c7c797278" and "b5bef669ec6dd0de2d4b57d8b667fc5cd177fb70" have entirely different histories.
000036beda
...
b5bef669ec
24 changed files with 83 additions and 1634 deletions
11
CHANGELOG.md
11
CHANGELOG.md
|
|
@ -1,16 +1,5 @@
|
||||||
# Changelog
|
# 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
|
# v0.11.0
|
||||||
|
|
||||||
Training games scheduled for retirement now warn you before you start them.
|
Training games scheduled for retirement now warn you before you start them.
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "polaris-task-force",
|
"name": "polaris-task-force",
|
||||||
"version": "0.11.1",
|
"version": "0.11.0",
|
||||||
"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.",
|
"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",
|
"license": "MIT",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
|
|
|
||||||
|
|
@ -10,13 +10,10 @@ export const dynamic = "force-dynamic";
|
||||||
export const runtime = "nodejs";
|
export const runtime = "nodejs";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Bulk Tech Tree position write: `{ positions: [{ id, x, y, ifUnmodifiedAt? }] }`,
|
* Bulk Tech Tree position write: `{ positions: [{ id, x, y }] }`, where a
|
||||||
* where a null x/y returns a technology to the automatic layout and
|
* null x/y returns a technology to the automatic layout. Used by every canvas
|
||||||
* `ifUnmodifiedAt` (the loaded `updatedAt`) makes that row conditional: one
|
* position write (drags, Save positions, Auto-arrange, freeze pins) so they
|
||||||
* mismatched precondition rejects the whole batch with HTTP 409 and the
|
* cost one request and one SQL statement instead of a PATCH per node.
|
||||||
* 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
|
* Access mirrors the technologies collection's update rule: the
|
||||||
* `technologies:update` permission OR Intelligence division membership.
|
* `technologies:update` permission OR Intelligence division membership.
|
||||||
|
|
@ -46,18 +43,8 @@ export async function POST(req: NextRequest) {
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const result = await writeTreePositions(payload, parsed.updates);
|
const updated = await writeTreePositions(payload, parsed.updates);
|
||||||
if (result.conflicts.length > 0) {
|
return NextResponse.json({ ok: true, updated });
|
||||||
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) {
|
} catch (err) {
|
||||||
payload.logger.error(`[TechTree] Bulk position write failed: ${err}`);
|
payload.logger.error(`[TechTree] Bulk position write failed: ${err}`);
|
||||||
return NextResponse.json({ error: "Could not save positions." }, { status: 500 });
|
return NextResponse.json({ error: "Could not save positions." }, { status: 500 });
|
||||||
|
|
|
||||||
|
|
@ -4,9 +4,7 @@ import {
|
||||||
approvalStatusFieldAccess,
|
approvalStatusFieldAccess,
|
||||||
requireApprovalPermission,
|
requireApprovalPermission,
|
||||||
requireIntelligencePermission,
|
requireIntelligencePermission,
|
||||||
resetApprovalStatusOnEdit,
|
|
||||||
} from "@/utils/access-control/divisionAccess";
|
} from "@/utils/access-control/divisionAccess";
|
||||||
import { ifUnmodifiedAtGuard } from "@/utils/access-control/optimisticConcurrency";
|
|
||||||
|
|
||||||
const approvalStatusFieldAccessConfig = approvalStatusFieldAccess("technologies");
|
const approvalStatusFieldAccessConfig = approvalStatusFieldAccess("technologies");
|
||||||
|
|
||||||
|
|
@ -22,11 +20,6 @@ export const Technologies: CollectionConfig = {
|
||||||
delete: requireIntelligencePermission("technologies:delete"),
|
delete: requireIntelligencePermission("technologies:delete"),
|
||||||
read: requirePermission("technologies:read"),
|
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: [
|
fields: [
|
||||||
{
|
{
|
||||||
name: "name",
|
name: "name",
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,6 @@ import {
|
||||||
approvalStatusFieldAccess,
|
approvalStatusFieldAccess,
|
||||||
requireApprovalPermission,
|
requireApprovalPermission,
|
||||||
requireLogisticsPermission,
|
requireLogisticsPermission,
|
||||||
resetApprovalStatusOnEdit,
|
|
||||||
} from "@/utils/access-control/divisionAccess";
|
} from "@/utils/access-control/divisionAccess";
|
||||||
|
|
||||||
const approvalFieldAccess = {
|
const approvalFieldAccess = {
|
||||||
|
|
@ -24,9 +23,6 @@ export const Assets: CollectionConfig = {
|
||||||
update: requireLogisticsPermission("assets:update"),
|
update: requireLogisticsPermission("assets:update"),
|
||||||
delete: requireLogisticsPermission("assets:delete"),
|
delete: requireLogisticsPermission("assets:delete"),
|
||||||
},
|
},
|
||||||
hooks: {
|
|
||||||
beforeChange: [resetApprovalStatusOnEdit()],
|
|
||||||
},
|
|
||||||
fields: [
|
fields: [
|
||||||
{
|
{
|
||||||
name: "name",
|
name: "name",
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,6 @@ import {
|
||||||
approvalStatusFieldAccess,
|
approvalStatusFieldAccess,
|
||||||
requireApprovalPermission,
|
requireApprovalPermission,
|
||||||
requireLogisticsPermission,
|
requireLogisticsPermission,
|
||||||
resetApprovalStatusOnEdit,
|
|
||||||
} from "@/utils/access-control/divisionAccess";
|
} from "@/utils/access-control/divisionAccess";
|
||||||
|
|
||||||
const onlyIfNotPrimaryCurrency = async ({ req }: { req: PayloadRequest }) => {
|
const onlyIfNotPrimaryCurrency = async ({ req }: { req: PayloadRequest }) => {
|
||||||
|
|
@ -62,9 +61,6 @@ export const Resources: CollectionConfig = {
|
||||||
update: logisticsWriteWithCurrencyGuard("resources:update"),
|
update: logisticsWriteWithCurrencyGuard("resources:update"),
|
||||||
delete: logisticsWriteWithCurrencyGuard("resources:delete"),
|
delete: logisticsWriteWithCurrencyGuard("resources:delete"),
|
||||||
},
|
},
|
||||||
hooks: {
|
|
||||||
beforeChange: [resetApprovalStatusOnEdit()],
|
|
||||||
},
|
|
||||||
fields: [
|
fields: [
|
||||||
{
|
{
|
||||||
name: "NoEditWarning",
|
name: "NoEditWarning",
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import { CollectionConfig } from "payload";
|
import { CollectionConfig } from "payload";
|
||||||
import { approvalStatusFieldAccess, resetApprovalStatusOnEdit } from "@/utils/access-control/divisionAccess";
|
import { isDeveloper } from "@/utils/access-control/isRole";
|
||||||
import type { Resource } from "@/payload-types";
|
import type { Resource } from "@/payload-types";
|
||||||
import { emitGameEvent } from "@/utils/event-log/emit";
|
import { emitGameEvent } from "@/utils/event-log/emit";
|
||||||
import { createStaffingFields } from "@/collections/game/staffingFields";
|
import { createStaffingFields } from "@/collections/game/staffingFields";
|
||||||
|
|
@ -7,8 +7,6 @@ import { createProductionFields } from "@/collections/game/productionFields";
|
||||||
import { createModuleFields } from "@/collections/game/moduleFields";
|
import { createModuleFields } from "@/collections/game/moduleFields";
|
||||||
import { createAuraFields } from "@/collections/game/auraFields";
|
import { createAuraFields } from "@/collections/game/auraFields";
|
||||||
|
|
||||||
const approvalStatusFieldAccessConfig = approvalStatusFieldAccess("structures");
|
|
||||||
|
|
||||||
export const Structures: CollectionConfig = {
|
export const Structures: CollectionConfig = {
|
||||||
slug: "structures",
|
slug: "structures",
|
||||||
admin: {
|
admin: {
|
||||||
|
|
@ -242,9 +240,6 @@ export const Structures: CollectionConfig = {
|
||||||
|
|
||||||
return data;
|
return data;
|
||||||
},
|
},
|
||||||
// Editing a structure that is already approved / revision-requested
|
|
||||||
// resets it to in_progress unless the writer is a superuser.
|
|
||||||
resetApprovalStatusOnEdit(),
|
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
fields: [
|
fields: [
|
||||||
|
|
@ -280,7 +275,15 @@ export const Structures: CollectionConfig = {
|
||||||
{ label: "Revision Requested", value: "revision_requested" },
|
{ label: "Revision Requested", value: "revision_requested" },
|
||||||
],
|
],
|
||||||
defaultValue: "in_progress",
|
defaultValue: "in_progress",
|
||||||
access: approvalStatusFieldAccessConfig,
|
filterOptions: ({ options, data: _data, req }) => {
|
||||||
|
return !isDeveloper({ req })
|
||||||
|
? options.filter((option) =>
|
||||||
|
typeof option === "string"
|
||||||
|
? options
|
||||||
|
: ["in_progress", "ready_for_review"].includes(option.value),
|
||||||
|
)
|
||||||
|
: options;
|
||||||
|
},
|
||||||
required: true,
|
required: true,
|
||||||
admin: {
|
admin: {
|
||||||
description:
|
description:
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,6 @@ import {
|
||||||
approvalStatusFieldAccess,
|
approvalStatusFieldAccess,
|
||||||
requireApprovalPermission,
|
requireApprovalPermission,
|
||||||
requireLogisticsPermission,
|
requireLogisticsPermission,
|
||||||
resetApprovalStatusOnEdit,
|
|
||||||
} from "@/utils/access-control/divisionAccess";
|
} from "@/utils/access-control/divisionAccess";
|
||||||
|
|
||||||
const approvalStatusFieldAccessConfig = approvalStatusFieldAccess("vehicles");
|
const approvalStatusFieldAccessConfig = approvalStatusFieldAccess("vehicles");
|
||||||
|
|
@ -19,9 +18,6 @@ export const Vehicles: CollectionConfig = {
|
||||||
update: requireLogisticsPermission("vehicles:update"),
|
update: requireLogisticsPermission("vehicles:update"),
|
||||||
delete: requireLogisticsPermission("vehicles:delete"),
|
delete: requireLogisticsPermission("vehicles:delete"),
|
||||||
},
|
},
|
||||||
hooks: {
|
|
||||||
beforeChange: [resetApprovalStatusOnEdit()],
|
|
||||||
},
|
|
||||||
fields: [
|
fields: [
|
||||||
{
|
{
|
||||||
// D11b: searchable imported-library picker (name, classname, thumbnail)
|
// D11b: searchable imported-library picker (name, classname, thumbnail)
|
||||||
|
|
|
||||||
|
|
@ -11,8 +11,6 @@ export type TechNodeData = {
|
||||||
categoryName: string | null;
|
categoryName: string | null;
|
||||||
refLabel: string;
|
refLabel: string;
|
||||||
hasWarning: boolean;
|
hasWarning: boolean;
|
||||||
/** Another user changed this document: red ring until the tree is refreshed. */
|
|
||||||
conflict: boolean;
|
|
||||||
connectable: boolean;
|
connectable: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -43,7 +41,7 @@ function CornerBrackets() {
|
||||||
* classification strip, corner brackets, mono readouts).
|
* classification strip, corner brackets, mono readouts).
|
||||||
*/
|
*/
|
||||||
export function TechNodeCard({ data, selected }: NodeProps<TechNodeModel>) {
|
export function TechNodeCard({ data, selected }: NodeProps<TechNodeModel>) {
|
||||||
const { tech, categoryName, refLabel, hasWarning, conflict, connectable } = data;
|
const { tech, categoryName, refLabel, hasWarning, connectable } = data;
|
||||||
const status = STATUS_LABELS[tech.approvalStatus] ?? {
|
const status = STATUS_LABELS[tech.approvalStatus] ?? {
|
||||||
label: tech.approvalStatus,
|
label: tech.approvalStatus,
|
||||||
className: "text-white/60",
|
className: "text-white/60",
|
||||||
|
|
@ -52,7 +50,6 @@ export function TechNodeCard({ data, selected }: NodeProps<TechNodeModel>) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
data-testid={`tech-node-${tech.id}`}
|
data-testid={`tech-node-${tech.id}`}
|
||||||
data-conflict={conflict ? "true" : undefined}
|
|
||||||
className="relative h-full w-full"
|
className="relative h-full w-full"
|
||||||
>
|
>
|
||||||
{/* Clipped card surface (the handles live outside this box) */}
|
{/* Clipped card surface (the handles live outside this box) */}
|
||||||
|
|
@ -60,8 +57,6 @@ 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 ${
|
className={`flex h-full w-full flex-col overflow-hidden rounded-none border bg-black/60 backdrop-blur-sm transition-colors ${
|
||||||
selected
|
selected
|
||||||
? "border-[#22d3ee]/70 shadow-[0_0_18px_rgba(34,211,238,0.15)]"
|
? "border-[#22d3ee]/70 shadow-[0_0_18px_rgba(34,211,238,0.15)]"
|
||||||
: 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"
|
: "border-white/15 hover:border-white/40"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
|
|
|
||||||
|
|
@ -1,21 +1,12 @@
|
||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogFooter,
|
|
||||||
DialogHeader,
|
|
||||||
DialogTitle,
|
|
||||||
} from "@/components/ui/dialog";
|
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Label } from "@/components/ui/label";
|
import { Label } from "@/components/ui/label";
|
||||||
import { Textarea } from "@/components/ui/textarea";
|
import { Textarea } from "@/components/ui/textarea";
|
||||||
import { PencilIcon, PlusIcon, RotateCcwIcon, SaveIcon, XIcon } from "lucide-react";
|
import { PencilIcon, PlusIcon, RotateCcwIcon, SaveIcon, XIcon } from "lucide-react";
|
||||||
import React from "react";
|
import React from "react";
|
||||||
|
|
||||||
import { IF_UNMODIFIED_AT_HEADER } from "@/lib/tech-tree/concurrency";
|
|
||||||
|
|
||||||
import { CategoryPicker } from "./CategoryPicker";
|
import { CategoryPicker } from "./CategoryPicker";
|
||||||
import { PanelSelect } from "./PanelSelect";
|
import { PanelSelect } from "./PanelSelect";
|
||||||
import { buildPrereqRows } from "./prereqEdits";
|
import { buildPrereqRows } from "./prereqEdits";
|
||||||
|
|
@ -80,17 +71,9 @@ interface TechPreviewPanelProps {
|
||||||
canCreateCategories: boolean;
|
canCreateCategories: boolean;
|
||||||
canSetFinalApproval: boolean;
|
canSetFinalApproval: boolean;
|
||||||
warnings: string[];
|
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;
|
onClose: () => void;
|
||||||
onEdit: () => void;
|
onEdit: () => void;
|
||||||
onSaved: (updated: TechTechLike) => 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). */
|
/** Shape returned by the REST update (only the fields the tree reads). */
|
||||||
|
|
@ -118,11 +101,9 @@ export function TechPreviewPanel({
|
||||||
canCreateCategories,
|
canCreateCategories,
|
||||||
canSetFinalApproval,
|
canSetFinalApproval,
|
||||||
warnings,
|
warnings,
|
||||||
reseedNonce,
|
|
||||||
onClose,
|
onClose,
|
||||||
onEdit,
|
onEdit,
|
||||||
onSaved,
|
onSaved,
|
||||||
onConflictReload,
|
|
||||||
}: TechPreviewPanelProps) {
|
}: TechPreviewPanelProps) {
|
||||||
const categoryName =
|
const categoryName =
|
||||||
tech.categoryId ? categories.find((c) => c.id === tech.categoryId)?.name ?? null : null;
|
tech.categoryId ? categories.find((c) => c.id === tech.categoryId)?.name ?? null : null;
|
||||||
|
|
@ -131,22 +112,14 @@ export function TechPreviewPanel({
|
||||||
const [busy, setBusy] = React.useState(false);
|
const [busy, setBusy] = React.useState(false);
|
||||||
const [error, setError] = React.useState<string | null>(null);
|
const [error, setError] = React.useState<string | null>(null);
|
||||||
const [savedAt, setSavedAt] = React.useState<number | 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 or the canvas
|
// Re-seed the draft when a different technology is selected.
|
||||||
// bumps reseedNonce after a conflict reload.
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
setDraft(draftFromTech(tech, categoryName));
|
setDraft(draftFromTech(tech, categoryName));
|
||||||
setError(null);
|
setError(null);
|
||||||
setSavedAt(null);
|
setSavedAt(null);
|
||||||
setConflictOpen(false);
|
|
||||||
setPendingPatch(null);
|
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [tech.id, reseedNonce]);
|
}, [tech.id]);
|
||||||
|
|
||||||
const baseline = React.useMemo(() => draftFromTech(tech, categoryName), [tech, categoryName]);
|
const baseline = React.useMemo(() => draftFromTech(tech, categoryName), [tech, categoryName]);
|
||||||
const dirty = JSON.stringify(draft) !== JSON.stringify(baseline);
|
const dirty = JSON.stringify(draft) !== JSON.stringify(baseline);
|
||||||
|
|
@ -196,20 +169,6 @@ export function TechPreviewPanel({
|
||||||
prereqOr: prev.prereqOr.filter((x) => x !== id),
|
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 () => {
|
const save = async () => {
|
||||||
setError(null);
|
setError(null);
|
||||||
if (!draft.name.trim()) {
|
if (!draft.name.trim()) {
|
||||||
|
|
@ -268,13 +227,11 @@ export function TechPreviewPanel({
|
||||||
};
|
};
|
||||||
if (!statusLocked) data.approvalStatus = draft.approvalStatus;
|
if (!statusLocked) data.approvalStatus = draft.approvalStatus;
|
||||||
|
|
||||||
const res = await sendPatch(data, true);
|
const res = await fetch(`/api/technologies/${tech.id}`, {
|
||||||
if (res.status === 409) {
|
method: "PATCH",
|
||||||
// Version conflict: keep the draft, offer reload / overwrite choices.
|
headers: { "Content-Type": "application/json" },
|
||||||
setPendingPatch(data);
|
body: JSON.stringify(data),
|
||||||
setConflictOpen(true);
|
});
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const body = await res.json().catch(() => null);
|
const body = await res.json().catch(() => null);
|
||||||
throw new Error(body?.errors?.[0]?.message || `Save failed (HTTP ${res.status}).`);
|
throw new Error(body?.errors?.[0]?.message || `Save failed (HTTP ${res.status}).`);
|
||||||
|
|
@ -288,39 +245,6 @@ 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 (
|
return (
|
||||||
<aside
|
<aside
|
||||||
data-testid="tech-preview-panel"
|
data-testid="tech-preview-panel"
|
||||||
|
|
@ -748,48 +672,6 @@ export function TechPreviewPanel({
|
||||||
Edit in full view
|
Edit in full view
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</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>
|
</aside>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -29,10 +29,6 @@ import { useRouter } from "next/navigation";
|
||||||
import React from "react";
|
import React from "react";
|
||||||
|
|
||||||
import { Button } from "@/components/ui/button";
|
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 { CategoryBand, type CategoryBandData, type CategoryBandNode } from "./CategoryBand";
|
||||||
import {
|
import {
|
||||||
|
|
@ -101,7 +97,6 @@ function buildFlowNodes(
|
||||||
categories: TreeCategory[],
|
categories: TreeCategory[],
|
||||||
layout: ReturnType<typeof computeLayout>,
|
layout: ReturnType<typeof computeLayout>,
|
||||||
connectable: boolean,
|
connectable: boolean,
|
||||||
conflictIds: Set<number>,
|
|
||||||
): Node[] {
|
): Node[] {
|
||||||
const warningsByTech = new Map<number, number>();
|
const warningsByTech = new Map<number, number>();
|
||||||
for (const warning of layout.warnings) {
|
for (const warning of layout.warnings) {
|
||||||
|
|
@ -150,7 +145,6 @@ function buildFlowNodes(
|
||||||
categoryName: tech.categoryId ? categoryById.get(tech.categoryId)?.name ?? null : null,
|
categoryName: tech.categoryId ? categoryById.get(tech.categoryId)?.name ?? null : null,
|
||||||
refLabel: refLabel(tech.id),
|
refLabel: refLabel(tech.id),
|
||||||
hasWarning: warningsByTech.has(tech.id),
|
hasWarning: warningsByTech.has(tech.id),
|
||||||
conflict: conflictIds.has(tech.id),
|
|
||||||
connectable,
|
connectable,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
@ -252,64 +246,25 @@ 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).
|
* Persist canvas positions in ONE request (one SQL statement server-side).
|
||||||
* Each entry carries the `updatedAt` the client loaded as an optimistic
|
* Never PATCH per node: dozens of concurrent document updates exhausted the
|
||||||
* concurrency precondition; the whole batch is rejected (HTTP 409) when any
|
* database pool and could take the server down. Null x/y clears a pin.
|
||||||
* 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(
|
async function saveTreePositions(
|
||||||
updates: PositionWrite[],
|
updates: { id: number; x: number | null; y: number | null }[],
|
||||||
tokens: Map<number, string>,
|
): Promise<void> {
|
||||||
): Promise<Record<string, string>> {
|
if (updates.length === 0) return;
|
||||||
if (updates.length === 0) return {};
|
|
||||||
const res = await fetch("/api/tech-tree/positions", {
|
const res = await fetch("/api/tech-tree/positions", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
credentials: "same-origin",
|
credentials: "same-origin",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({ positions: updates }),
|
||||||
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) {
|
if (!res.ok) {
|
||||||
const body = await res.json().catch(() => null);
|
const body = await res.json().catch(() => null);
|
||||||
throw new Error(body?.error || `Could not save positions (HTTP ${res.status}).`);
|
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[]> {
|
async function fetchCollection<T>(slug: string): Promise<T[]> {
|
||||||
|
|
@ -332,20 +287,6 @@ function CanvasInner({ data }: { data: TechTreeData }) {
|
||||||
// null when idle. Drives the toolbar status chip and locks layout controls.
|
// null when idle. Drives the toolbar status chip and locks layout controls.
|
||||||
const [layoutBusy, setLayoutBusy] = React.useState<string | null>(null);
|
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 =
|
// Manual edge routing, loaded from this browser's storage on mount. Empty =
|
||||||
// the edge draws its automatic path.
|
// the edge draws its automatic path.
|
||||||
const [edgeRoutes, setEdgeRoutes] = React.useState<EdgeRouteMap>({});
|
const [edgeRoutes, setEdgeRoutes] = React.useState<EdgeRouteMap>({});
|
||||||
|
|
@ -366,13 +307,9 @@ function CanvasInner({ data }: { data: TechTreeData }) {
|
||||||
);
|
);
|
||||||
|
|
||||||
const layout = React.useMemo(() => computeLayout(techs, categories), [techs, categories]);
|
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(
|
const flowNodes = React.useMemo(
|
||||||
() => buildFlowNodes(techs, categories, layout, data.canUpdate, conflictIds),
|
() => buildFlowNodes(techs, categories, layout, data.canUpdate),
|
||||||
[techs, categories, layout, data.canUpdate, conflictIds],
|
[techs, categories, layout, data.canUpdate],
|
||||||
);
|
);
|
||||||
const flowEdges = React.useMemo(
|
const flowEdges = React.useMemo(
|
||||||
() =>
|
() =>
|
||||||
|
|
@ -404,65 +341,14 @@ function CanvasInner({ data }: { data: TechTreeData }) {
|
||||||
return map;
|
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). */
|
/** Persist freeze pins (skipping ids whose own PATCH already carries one). */
|
||||||
const persistPins = React.useCallback(
|
const persistPins = React.useCallback(
|
||||||
async (
|
async (pins: Map<number, CanvasPosition>, skip: Set<number> = new Set()) => {
|
||||||
pins: Map<number, CanvasPosition>,
|
await saveTreePositions(
|
||||||
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 })),
|
[...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
|
// Nodes are data-driven: block React Flow's own remove changes so Backspace
|
||||||
|
|
@ -533,29 +419,19 @@ function CanvasInner({ data }: { data: TechTreeData }) {
|
||||||
targetId: number,
|
targetId: number,
|
||||||
lists: { and: number[]; or: number[] },
|
lists: { and: number[]; or: number[] },
|
||||||
pin?: { x: number; y: 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}`, {
|
const res = await fetch(`/api/technologies/${targetId}`, {
|
||||||
method: "PATCH",
|
method: "PATCH",
|
||||||
credentials: "same-origin",
|
headers: { "Content-Type": "application/json" },
|
||||||
headers,
|
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
requirements: { prerequisiteTechnologies: buildPrereqRows(lists) },
|
requirements: { prerequisiteTechnologies: buildPrereqRows(lists) },
|
||||||
...(pin ? { treePosition: pin } : {}),
|
...(pin ? { treePosition: pin } : {}),
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
if (res.status === 409) throw new StaleWriteClientError();
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const body = await res.json().catch(() => null);
|
const body = await res.json().catch(() => null);
|
||||||
throw new Error(body?.errors?.[0]?.message || `Save failed (HTTP ${res.status}).`);
|
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;
|
|
||||||
},
|
},
|
||||||
[],
|
[],
|
||||||
);
|
);
|
||||||
|
|
@ -581,24 +457,10 @@ function CanvasInner({ data }: { data: TechTreeData }) {
|
||||||
const pins = pinsToFreeze(currentPositions(), updated, categories);
|
const pins = pinsToFreeze(currentPositions(), updated, categories);
|
||||||
setTechs(applyPins(updated, pins));
|
setTechs(applyPins(updated, pins));
|
||||||
try {
|
try {
|
||||||
const targetToken = techs.find((t) => t.id === targetId)?.updatedAt;
|
await patchPrereqs(targetId, result.lists, pins.get(targetId));
|
||||||
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]));
|
await persistPins(pins, new Set([targetId]));
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
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.");
|
setConnectError(e instanceof Error ? e.message : "Could not save the connection.");
|
||||||
}
|
|
||||||
await refresh();
|
await refresh();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
@ -622,23 +484,11 @@ function CanvasInner({ data }: { data: TechTreeData }) {
|
||||||
setTechs(applyPins(next, pins));
|
setTechs(applyPins(next, pins));
|
||||||
try {
|
try {
|
||||||
for (const [targetId, lists] of listsByTarget) {
|
for (const [targetId, lists] of listsByTarget) {
|
||||||
const token = next.find((t) => t.id === targetId)?.updatedAt;
|
await patchPrereqs(targetId, lists, pins.get(targetId));
|
||||||
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()));
|
await persistPins(pins, new Set(listsByTarget.keys()));
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
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.");
|
setConnectError(e instanceof Error ? e.message : "Could not remove the prerequisite.");
|
||||||
}
|
|
||||||
await refresh();
|
await refresh();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
@ -662,16 +512,13 @@ function CanvasInner({ data }: { data: TechTreeData }) {
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
try {
|
try {
|
||||||
await writePositions(positions);
|
await saveTreePositions(positions);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// The optimistic position stays on screen; a reload shows what is stored.
|
// The optimistic position stays on screen; a reload shows what is stored.
|
||||||
// Version conflicts report themselves through the toolbar banner.
|
|
||||||
if (!(e instanceof PositionConflictError)) {
|
|
||||||
setConnectError(e instanceof Error ? e.message : "Could not save positions.");
|
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
|
// Live session for a category-band drag: the header moves the band and every
|
||||||
|
|
@ -782,9 +629,7 @@ function CanvasInner({ data }: { data: TechTreeData }) {
|
||||||
await persistPins(pins);
|
await persistPins(pins);
|
||||||
setSaveStatus(`Positions saved. ${pins.size} node(s).`);
|
setSaveStatus(`Positions saved. ${pins.size} node(s).`);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (!(e instanceof PositionConflictError)) {
|
|
||||||
setConnectError(e instanceof Error ? e.message : "Could not save positions.");
|
setConnectError(e instanceof Error ? e.message : "Could not save positions.");
|
||||||
}
|
|
||||||
} finally {
|
} finally {
|
||||||
setLayoutBusy(null);
|
setLayoutBusy(null);
|
||||||
}
|
}
|
||||||
|
|
@ -801,20 +646,18 @@ function CanvasInner({ data }: { data: TechTreeData }) {
|
||||||
setConnectError(null);
|
setConnectError(null);
|
||||||
setTechs((prev) => prev.map((t) => (t.treePosition ? { ...t, treePosition: null } : t)));
|
setTechs((prev) => prev.map((t) => (t.treePosition ? { ...t, treePosition: null } : t)));
|
||||||
try {
|
try {
|
||||||
await writePositions(pinned.map((t) => ({ id: t.id, x: null, y: null })));
|
await saveTreePositions(pinned.map((t) => ({ id: t.id, x: null, y: null })));
|
||||||
setSaveStatus(`Layout reset. ${pinned.length} node(s) re-arranged.`);
|
setSaveStatus(`Layout reset. ${pinned.length} node(s) re-arranged.`);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// Put the pins back so the canvas matches what is actually stored.
|
// Put the pins back so the canvas matches what is actually stored.
|
||||||
setTechs((prev) =>
|
setTechs((prev) =>
|
||||||
prev.map((t) => (previous.has(t.id) ? { ...t, treePosition: previous.get(t.id) ?? null } : t)),
|
prev.map((t) => (previous.has(t.id) ? { ...t, treePosition: previous.get(t.id) ?? null } : t)),
|
||||||
);
|
);
|
||||||
if (!(e instanceof PositionConflictError)) {
|
|
||||||
setConnectError(e instanceof Error ? e.message : "Could not reset the layout.");
|
setConnectError(e instanceof Error ? e.message : "Could not reset the layout.");
|
||||||
}
|
|
||||||
} finally {
|
} finally {
|
||||||
setLayoutBusy(null);
|
setLayoutBusy(null);
|
||||||
}
|
}
|
||||||
}, [techs, layoutBusy, writePositions]);
|
}, [techs, layoutBusy]);
|
||||||
|
|
||||||
const techById = React.useMemo(
|
const techById = React.useMemo(
|
||||||
() => new Map(techs.map((t) => [String(t.id), t])),
|
() => new Map(techs.map((t) => [String(t.id), t])),
|
||||||
|
|
@ -836,48 +679,20 @@ function CanvasInner({ data }: { data: TechTreeData }) {
|
||||||
]);
|
]);
|
||||||
let nextTechs = techDocs.map(mapTechDoc);
|
let nextTechs = techDocs.map(mapTechDoc);
|
||||||
const nextCategories = categoryDocs.map(mapCategoryDoc);
|
const nextCategories = categoryDocs.map(mapCategoryDoc);
|
||||||
let freezePins: Map<number, CanvasPosition> | null = null;
|
|
||||||
if (options.freeze) {
|
if (options.freeze) {
|
||||||
freezePins = pinsToFreeze(currentPositions(), nextTechs, nextCategories);
|
const pins = pinsToFreeze(currentPositions(), nextTechs, nextCategories);
|
||||||
nextTechs = applyPins(nextTechs, freezePins);
|
nextTechs = applyPins(nextTechs, pins);
|
||||||
|
persistPins(pins).catch((e: unknown) =>
|
||||||
|
setConnectError(e instanceof Error ? e.message : "Could not save positions."),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
setTechs(nextTechs);
|
setTechs(nextTechs);
|
||||||
setCategories(nextCategories);
|
setCategories(nextCategories);
|
||||||
setResources(resourceDocs.map((d) => ({ id: d.id as number, name: String(d.name ?? "") })));
|
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],
|
[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(
|
const handleCreated = React.useCallback(
|
||||||
async (result: QuickCreateResult) => {
|
async (result: QuickCreateResult) => {
|
||||||
await refresh({ freeze: true });
|
await refresh({ freeze: true });
|
||||||
|
|
@ -987,31 +802,6 @@ function CanvasInner({ data }: { data: TechTreeData }) {
|
||||||
{connectError}
|
{connectError}
|
||||||
</span>
|
</span>
|
||||||
) : null}
|
) : 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 ? (
|
{layoutBusy ? (
|
||||||
<span
|
<span
|
||||||
role="status"
|
role="status"
|
||||||
|
|
@ -1131,20 +921,11 @@ function CanvasInner({ data }: { data: TechTreeData }) {
|
||||||
canCreateCategories={data.canCreateCategories}
|
canCreateCategories={data.canCreateCategories}
|
||||||
canSetFinalApproval={data.canSetFinalApproval}
|
canSetFinalApproval={data.canSetFinalApproval}
|
||||||
warnings={selectedWarnings}
|
warnings={selectedWarnings}
|
||||||
reseedNonce={panelReseedNonce}
|
|
||||||
onClose={() => setSelectedId(null)}
|
onClose={() => setSelectedId(null)}
|
||||||
onEdit={() => router.push(`/admin/collections/technologies/${selectedTech.id}`)}
|
onEdit={() => router.push(`/admin/collections/technologies/${selectedTech.id}`)}
|
||||||
onSaved={() => {
|
onSaved={() => {
|
||||||
void refresh({ freeze: true });
|
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}
|
) : null}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -53,7 +53,6 @@ export function mapTechDoc(doc: Record<string, unknown>): TreeTech {
|
||||||
prereqOr: [...new Set(prereqOr)].filter((id) => !prereqAnd.includes(id)),
|
prereqOr: [...new Set(prereqOr)].filter((id) => !prereqAnd.includes(id)),
|
||||||
resourceCosts,
|
resourceCosts,
|
||||||
treePosition,
|
treePosition,
|
||||||
updatedAt: String(doc.updatedAt ?? ""),
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -19,12 +19,6 @@ export type TreeTech = {
|
||||||
resourceCosts: { resource: number; amount: number }[];
|
resourceCosts: { resource: number; amount: number }[];
|
||||||
/** Manual canvas position (dragged node); null = automatic layout. */
|
/** Manual canvas position (dragged node); null = automatic layout. */
|
||||||
treePosition: { x: number; y: number } | null;
|
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 = {
|
export type TreeCategory = {
|
||||||
|
|
|
||||||
|
|
@ -1,24 +0,0 @@
|
||||||
/**
|
|
||||||
* 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;
|
|
||||||
};
|
|
||||||
|
|
@ -1,6 +1,5 @@
|
||||||
import { sql } from "@payloadcms/db-postgres";
|
import { sql } from "@payloadcms/db-postgres";
|
||||||
import type { Payload } from "payload";
|
import type { Payload } from "payload";
|
||||||
import type { PositionConflict } from "@/lib/tech-tree/concurrency";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Bulk Tech Tree position writes.
|
* Bulk Tech Tree position writes.
|
||||||
|
|
@ -12,19 +11,9 @@ import type { PositionConflict } from "@/lib/tech-tree/concurrency";
|
||||||
* could take the server down. Every canvas position write now goes through
|
* could take the server down. Every canvas position write now goes through
|
||||||
* `writeTreePositions`: one request, one SQL statement.
|
* `writeTreePositions`: one request, one SQL statement.
|
||||||
*
|
*
|
||||||
* Only the `tree_position_x` / `tree_position_y` columns are touched;
|
* Only the `tree_position_x` / `tree_position_y` columns are touched. The
|
||||||
* `updated_at` is bumped to keep the documents honest (and to move optimistic
|
* technologies collection has no hooks, so bypassing the Local API loses
|
||||||
* concurrency tokens forward). The technologies collection DOES have
|
* nothing; `updated_at` is bumped to keep the documents honest.
|
||||||
* `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. */
|
/** Hard cap per request so a malformed client cannot build a giant statement. */
|
||||||
|
|
@ -35,22 +24,6 @@ export type TreePositionUpdate = {
|
||||||
/** Both numbers to pin a node, both null to return it to the automatic layout. */
|
/** Both numbers to pin a node, both null to return it to the automatic layout. */
|
||||||
x: number | null;
|
x: number | null;
|
||||||
y: 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 =
|
export type ParseResult =
|
||||||
|
|
@ -67,12 +40,7 @@ export function parsePositionUpdates(body: unknown): ParseResult {
|
||||||
|
|
||||||
const byId = new Map<number, TreePositionUpdate>();
|
const byId = new Map<number, TreePositionUpdate>();
|
||||||
for (const entry of positions) {
|
for (const entry of positions) {
|
||||||
const { id, x, y, ifUnmodifiedAt } = (entry ?? {}) as {
|
const { id, x, y } = (entry ?? {}) as { id?: unknown; x?: unknown; y?: unknown };
|
||||||
id?: unknown;
|
|
||||||
x?: unknown;
|
|
||||||
y?: unknown;
|
|
||||||
ifUnmodifiedAt?: unknown;
|
|
||||||
};
|
|
||||||
if (typeof id !== "number" || !Number.isInteger(id) || id <= 0) {
|
if (typeof id !== "number" || !Number.isInteger(id) || id <= 0) {
|
||||||
return { ok: false, error: "Each position needs a positive integer id." };
|
return { ok: false, error: "Each position needs a positive integer id." };
|
||||||
}
|
}
|
||||||
|
|
@ -82,101 +50,32 @@ export function parsePositionUpdates(body: unknown): ParseResult {
|
||||||
if (!cleared && !pinned) {
|
if (!cleared && !pinned) {
|
||||||
return { ok: false, error: `Position for ${id} must have numeric x and y, or both null.` };
|
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.
|
// Last write wins for a repeated id.
|
||||||
byId.set(
|
byId.set(
|
||||||
id,
|
id,
|
||||||
cleared
|
cleared
|
||||||
? { id, x: null, y: null, expectedUpdatedAt }
|
? { id, x: null, y: null }
|
||||||
: { id, x: Math.round(x as number), y: Math.round(y as number), expectedUpdatedAt },
|
: { id, x: Math.round(x as number), y: Math.round(y as number) },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return { ok: true, updates: [...byId.values()] };
|
return { ok: true, updates: [...byId.values()] };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The pg driver hands timestamps back as Dates; the API speaks ISO strings. */
|
/** Write every position in a single UPDATE. Returns the number of rows touched. */
|
||||||
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(
|
export async function writeTreePositions(
|
||||||
payload: Payload,
|
payload: Payload,
|
||||||
updates: TreePositionUpdate[],
|
updates: TreePositionUpdate[],
|
||||||
): Promise<PositionWriteResult> {
|
): Promise<number> {
|
||||||
if (updates.length === 0) return { updated: 0, conflicts: [], tokens: {} };
|
if (updates.length === 0) return 0;
|
||||||
|
|
||||||
const values = sql.join(
|
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`, `,
|
sql`, `,
|
||||||
);
|
);
|
||||||
const result = await payload.db.drizzle.execute(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
|
UPDATE technologies AS t
|
||||||
SET tree_position_x = i.x, tree_position_y = i.y, updated_at = now()
|
SET tree_position_x = v.x, tree_position_y = v.y, updated_at = now()
|
||||||
FROM input i
|
FROM (VALUES ${values}) AS v(id, x, y)
|
||||||
WHERE t.id = i.id
|
WHERE t.id = v.id
|
||||||
AND NOT EXISTS (SELECT 1 FROM conflicts)
|
|
||||||
RETURNING t.id AS id, t.updated_at AS updated_at
|
|
||||||
`);
|
`);
|
||||||
const writtenRows =
|
return (result as { rowCount?: number | null }).rowCount ?? 0;
|
||||||
((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 };
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,4 @@
|
||||||
import type {
|
import type { Access, AccessArgs, AccessResult, Payload, PayloadRequest } from "payload";
|
||||||
Access,
|
|
||||||
AccessArgs,
|
|
||||||
AccessResult,
|
|
||||||
CollectionBeforeChangeHook,
|
|
||||||
Payload,
|
|
||||||
PayloadRequest,
|
|
||||||
} from "payload";
|
|
||||||
import type { Permission } from "@/permissions";
|
import type { Permission } from "@/permissions";
|
||||||
import {
|
import {
|
||||||
canAccessAdminPanel as canAccessAdminPanelByPermissions,
|
canAccessAdminPanel as canAccessAdminPanelByPermissions,
|
||||||
|
|
@ -117,54 +110,6 @@ 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
|
* Same contract as `requireAdminPageAccess`, with one addition: for the four
|
||||||
* division-scoped collections an admin-panel request also passes when the user
|
* division-scoped collections an admin-panel request also passes when the user
|
||||||
|
|
|
||||||
|
|
@ -1,60 +0,0 @@
|
||||||
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;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
@ -764,141 +764,4 @@ test.describe("Tech Tree admin view", () => {
|
||||||
}
|
}
|
||||||
expect(xs.size).toBeGreaterThanOrEqual(2);
|
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}`);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@ import config from "@/payload.config";
|
||||||
|
|
||||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||||
|
|
||||||
import type { Role, Structure, User } from "@/payload-types";
|
import type { Role, User } from "@/payload-types";
|
||||||
import {
|
import {
|
||||||
approvalStatusFieldAccess,
|
approvalStatusFieldAccess,
|
||||||
canAccessAdminPanel,
|
canAccessAdminPanel,
|
||||||
|
|
@ -20,17 +20,6 @@ let payload: Payload;
|
||||||
const RUN = `div-${Date.now().toString(36)}`;
|
const RUN = `div-${Date.now().toString(36)}`;
|
||||||
const TIMEOUT = 30_000;
|
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)", () => {
|
describe("Division-scoped admin access (intelligence / logistics)", () => {
|
||||||
const roleIds: number[] = [];
|
const roleIds: number[] = [];
|
||||||
const userIds: number[] = [];
|
const userIds: number[] = [];
|
||||||
|
|
@ -38,7 +27,6 @@ describe("Division-scoped admin access (intelligence / logistics)", () => {
|
||||||
const resourceIds: number[] = [];
|
const resourceIds: number[] = [];
|
||||||
const vehicleIds: number[] = [];
|
const vehicleIds: number[] = [];
|
||||||
const technologyIds: number[] = [];
|
const technologyIds: number[] = [];
|
||||||
const structureIds: number[] = [];
|
|
||||||
const createdQualificationIds: number[] = [];
|
const createdQualificationIds: number[] = [];
|
||||||
|
|
||||||
let intelUser: User;
|
let intelUser: User;
|
||||||
|
|
@ -177,10 +165,8 @@ describe("Division-scoped admin access (intelligence / logistics)", () => {
|
||||||
|
|
||||||
afterAll(async () => {
|
afterAll(async () => {
|
||||||
if (!payload) return;
|
if (!payload) return;
|
||||||
type TestSlug = "assets" | "resources" | "vehicles" | "technologies" | "structures";
|
type TestSlug = "assets" | "resources" | "vehicles" | "technologies";
|
||||||
const docs: Array<[TestSlug, number]> = [
|
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]),
|
...assetIds.map((id) => ["assets", id] as [TestSlug, number]),
|
||||||
...resourceIds.map((id) => ["resources", id] as [TestSlug, number]),
|
...resourceIds.map((id) => ["resources", id] as [TestSlug, number]),
|
||||||
...vehicleIds.map((id) => ["vehicles", id] as [TestSlug, number]),
|
...vehicleIds.map((id) => ["vehicles", id] as [TestSlug, number]),
|
||||||
|
|
@ -516,287 +502,4 @@ describe("Division-scoped admin access (intelligence / logistics)", () => {
|
||||||
expect(await accessFnDecision(approvalStatusUpdate, plainUser, data("approved"))).toBe(false);
|
expect(await accessFnDecision(approvalStatusUpdate, plainUser, data("approved"))).toBe(false);
|
||||||
}, TIMEOUT);
|
}, 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);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -1,455 +0,0 @@
|
||||||
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 });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -22,8 +22,6 @@ const tech = (over: Partial<TreeTech> & { id: number }): TreeTech => ({
|
||||||
prereqOr: [],
|
prereqOr: [],
|
||||||
resourceCosts: [],
|
resourceCosts: [],
|
||||||
treePosition: null,
|
treePosition: null,
|
||||||
// Concurrency token; irrelevant to the pure layout helper.
|
|
||||||
updatedAt: "",
|
|
||||||
...over,
|
...over,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -23,8 +23,8 @@ describe("tech tree position bulk-write validation", () => {
|
||||||
expect(result).toEqual({
|
expect(result).toEqual({
|
||||||
ok: true,
|
ok: true,
|
||||||
updates: [
|
updates: [
|
||||||
{ id: 1, x: 10, y: 21, expectedUpdatedAt: null },
|
{ id: 1, x: 10, y: 21 },
|
||||||
{ id: 2, x: null, y: null, expectedUpdatedAt: null },
|
{ id: 2, x: null, y: null },
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
@ -36,30 +36,7 @@ describe("tech tree position bulk-write validation", () => {
|
||||||
{ id: 3, x: null, y: null },
|
{ id: 3, x: null, y: null },
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
expect(result).toEqual({
|
expect(result).toEqual({ ok: true, updates: [{ id: 3, x: null, y: null }] });
|
||||||
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", () => {
|
it("rejects malformed bodies", () => {
|
||||||
|
|
@ -125,12 +102,11 @@ describe("tech tree position bulk write (database)", () => {
|
||||||
"pins many technologies in one write and clears them again",
|
"pins many technologies in one write and clears them again",
|
||||||
async () => {
|
async () => {
|
||||||
const pinned = await writeTreePositions(payload, [
|
const pinned = await writeTreePositions(payload, [
|
||||||
{ id: ids[0], x: 46, y: 92, expectedUpdatedAt: null },
|
{ id: ids[0], x: 46, y: 92 },
|
||||||
{ id: ids[1], x: 368, y: 184, expectedUpdatedAt: null },
|
{ id: ids[1], x: 368, y: 184 },
|
||||||
{ id: ids[2], x: 0, y: 0, expectedUpdatedAt: null },
|
{ id: ids[2], x: 0, y: 0 },
|
||||||
]);
|
]);
|
||||||
expect(pinned.updated).toBe(3);
|
expect(pinned).toBe(3);
|
||||||
expect(pinned.conflicts).toEqual([]);
|
|
||||||
expect(await positionOf(ids[0])).toMatchObject({ x: 46, y: 92 });
|
expect(await positionOf(ids[0])).toMatchObject({ x: 46, y: 92 });
|
||||||
expect(await positionOf(ids[1])).toMatchObject({ x: 368, y: 184 });
|
expect(await positionOf(ids[1])).toMatchObject({ x: 368, y: 184 });
|
||||||
expect(await positionOf(ids[2])).toMatchObject({ x: 0, y: 0 });
|
expect(await positionOf(ids[2])).toMatchObject({ x: 0, y: 0 });
|
||||||
|
|
@ -138,9 +114,9 @@ describe("tech tree position bulk write (database)", () => {
|
||||||
// Auto-arrange path: clear every pin in a single statement.
|
// Auto-arrange path: clear every pin in a single statement.
|
||||||
const cleared = await writeTreePositions(
|
const cleared = await writeTreePositions(
|
||||||
payload,
|
payload,
|
||||||
ids.map((id) => ({ id, x: null, y: null, expectedUpdatedAt: null })),
|
ids.map((id) => ({ id, x: null, y: null })),
|
||||||
);
|
);
|
||||||
expect(cleared.updated).toBe(3);
|
expect(cleared).toBe(3);
|
||||||
for (const id of ids) {
|
for (const id of ids) {
|
||||||
const position = await positionOf(id);
|
const position = await positionOf(id);
|
||||||
expect(position?.x ?? null).toBeNull();
|
expect(position?.x ?? null).toBeNull();
|
||||||
|
|
@ -153,11 +129,8 @@ describe("tech tree position bulk write (database)", () => {
|
||||||
it(
|
it(
|
||||||
"ignores ids that do not exist",
|
"ignores ids that do not exist",
|
||||||
async () => {
|
async () => {
|
||||||
const touched = await writeTreePositions(payload, [
|
const touched = await writeTreePositions(payload, [{ id: 999_999_999, x: 1, y: 1 }]);
|
||||||
{ id: 999_999_999, x: 1, y: 1, expectedUpdatedAt: null },
|
expect(touched).toBe(0);
|
||||||
]);
|
|
||||||
expect(touched.updated).toBe(0);
|
|
||||||
expect(touched.conflicts).toEqual([]);
|
|
||||||
},
|
},
|
||||||
TIMEOUT,
|
TIMEOUT,
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -20,8 +20,6 @@ const tech = (over: Partial<TreeTech> & { id: number }): TreeTech => ({
|
||||||
prereqOr: [],
|
prereqOr: [],
|
||||||
resourceCosts: [],
|
resourceCosts: [],
|
||||||
treePosition: null,
|
treePosition: null,
|
||||||
// Concurrency token; irrelevant to the pure prereq-edit helper.
|
|
||||||
updatedAt: "",
|
|
||||||
...over,
|
...over,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -15,8 +15,6 @@ const tech = (over: Partial<TreeTech> & { id: number }): TreeTech => ({
|
||||||
prereqOr: [],
|
prereqOr: [],
|
||||||
resourceCosts: [],
|
resourceCosts: [],
|
||||||
treePosition: null,
|
treePosition: null,
|
||||||
// Concurrency token; irrelevant to the pure freeze helper.
|
|
||||||
updatedAt: "",
|
|
||||||
...over,
|
...over,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue