Stage 3 of the int-suite speedup (gate G2 showed Vitest 4's pool scheduler only reuses worker processes between isolate:false tasks, so per-file fork spawning made clone+boot costs unavoidable at stage 2): - config: workers branch runs pool=forks with isolate:false, cap 8 via VITEST_MAX_FORKS, node default env (jsdom docblocks on DOM specs), failure-marker reporter, and idempotent setupFiles chain - vitest-worker-setup: one template clone PER FORK PROCESS named by pid (VITEST_WORKER_ID churns per task, which silently re-cloned per file); DATABASE_URI repoint + TEST_PG_POOL_MAX=8 (measured hook deadlocks at 3) - vitest.setup: once-per-process serial test URI markers; afterEach useRealTimers guard (restoreAllMocks omitted: it resurrects vi.mock module factories mid-file); logging absorber for fire-and-forget event writes that reject after their spec's cleanup deleted fixture users - helpers/get-test-payload.ts: memoized Payload boot shared across files in a fork; codemod converted all 91 self-booting specs mechanically - pinned opt-outs (own boot + comments): game-structures-labor-route, mission-reminder, notification-inbox-scope (jwtSign writes leak into the shared instance's auth state across files) - promotion-nominations: create the superuser before its rank ladder so the Users-hook Recruit rank gets leading orderable tokens (its top-of-ladder guard needs Col to remain ladder-max on fresh clones); operation-economy: itemType-scope the market-state assertion (asset and resource ids collide as bare integers under per-fork databases) Gate G3: 5 consecutive full green runs (149/149 files), warm wall 53-65s vs 598s baseline (~10x), zero clone residue after green runs. Vitest 4 note: globalTeardown config no longer exists; teardown returns from globalSetup.
523 lines
18 KiB
TypeScript
523 lines
18 KiB
TypeScript
import { getTestPayload } from "../helpers/get-test-payload";
|
|
import { Payload } from "payload";
|
|
import { afterAll, beforeAll, describe, expect, it, vi, type MockInstance } from "vitest";
|
|
import type { GameVehicle, User } from "@/payload-types";
|
|
import {
|
|
autoArrangeGarageItems,
|
|
findGarageEmptySpot,
|
|
formatGarageInstanceRef,
|
|
getVehicleFootprint,
|
|
isGaragePlacementValid,
|
|
parseGarageInstanceRef,
|
|
type GarageGridItem,
|
|
} from "@/lib/garage";
|
|
import { canUserAccessStructureStorage } from "@/collections/game/GameStructures";
|
|
import {
|
|
dispatchVehicle,
|
|
moveGarageItem,
|
|
rotateGarageItem,
|
|
storeVehicle,
|
|
} from "@/app/(frontend)/logistics/garage/actions";
|
|
|
|
// Mock next/headers so the actions' authenticate() can run outside a request.
|
|
vi.mock("next/headers", () => ({
|
|
headers: async () => new Headers(),
|
|
}));
|
|
|
|
let payload: Payload;
|
|
let authSpy: MockInstance;
|
|
|
|
const RUN = `garage-${Date.now().toString(36)}`;
|
|
const SLUG_A = `${RUN}-bay-a`;
|
|
const CLASSNAME = `${RUN}-truck`;
|
|
|
|
const LEXICAL_EMPTY = {
|
|
root: {
|
|
children: [{ text: "" }],
|
|
direction: null,
|
|
format: "" as const,
|
|
indent: 0,
|
|
type: "text",
|
|
version: 1,
|
|
},
|
|
};
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Fixture tracking for cleanup
|
|
// ---------------------------------------------------------------------------
|
|
const userIds: number[] = [];
|
|
const roleIds: number[] = [];
|
|
const vehicleIds: number[] = [];
|
|
const commandIds: number[] = [];
|
|
const reservationIds: number[] = [];
|
|
let resourceId: number;
|
|
let blueprintAId: number;
|
|
let blueprintBId: number;
|
|
let structureAId: number;
|
|
let structureBId: number;
|
|
let templateId: number;
|
|
let serverId: number;
|
|
|
|
let officerUser: User;
|
|
let plainUser: User;
|
|
|
|
function item(id: string, gridX: number, gridY: number, w: number, h: number, rotated = false): GarageGridItem {
|
|
return {
|
|
id,
|
|
vehicleId: Number(id),
|
|
gridX,
|
|
gridY,
|
|
rotated,
|
|
template: { garageWidth: w, garageHeight: h } as GarageGridItem["template"],
|
|
};
|
|
}
|
|
|
|
async function makeUser(label: string, roleDocIds?: number[]): Promise<User> {
|
|
const user = (await payload.create({
|
|
collection: "users",
|
|
data: {
|
|
username: `${RUN}-${label}`,
|
|
discordUsername: `${RUN}-${label}-discord`,
|
|
displayName: `${RUN} ${label}`,
|
|
steamId: `${RUN}-steam-${label}`,
|
|
password: "Test1234",
|
|
roles: ["user"],
|
|
...(roleDocIds && roleDocIds.length > 0 ? { roleDocs: roleDocIds } : {}),
|
|
},
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as unknown as User;
|
|
userIds.push(user.id);
|
|
return user;
|
|
}
|
|
|
|
async function makeVehicle(data: Record<string, unknown>): Promise<GameVehicle> {
|
|
const vehicle = (await payload.create({
|
|
collection: "game-vehicles",
|
|
data: {
|
|
name: `${RUN} Truck`,
|
|
type: templateId,
|
|
status: "idle",
|
|
currentFuel: 100,
|
|
currentHealth: 100,
|
|
...data,
|
|
} as never,
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as unknown as GameVehicle;
|
|
vehicleIds.push(vehicle.id);
|
|
return vehicle;
|
|
}
|
|
|
|
async function vehicleDoc(id: number) {
|
|
return payload.findByID({ collection: "game-vehicles", id, depth: 0, overrideAccess: true });
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Setup / teardown
|
|
// ---------------------------------------------------------------------------
|
|
beforeAll(async () => {
|
|
payload = await getTestPayload();
|
|
authSpy = vi.spyOn(payload, "auth");
|
|
|
|
const garageRole = await payload.create({
|
|
collection: "roles",
|
|
data: {
|
|
name: `${RUN} Garage Officer`,
|
|
slug: `${RUN}-garage-officer`,
|
|
permissions: ["game-vehicles:update"],
|
|
} as never,
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
});
|
|
roleIds.push(garageRole.id);
|
|
|
|
officerUser = await makeUser("officer", [garageRole.id]);
|
|
plainUser = await makeUser("plain");
|
|
|
|
const resource = await payload.create({
|
|
collection: "resources",
|
|
data: {
|
|
name: `${RUN} Fuel`,
|
|
codeName: `${RUN}-fuel`,
|
|
approvalStatus: "in_progress",
|
|
type: "physical",
|
|
baseValue: 1,
|
|
rarity: "common",
|
|
unitOfMeasure: "L",
|
|
massPerUnit: 1,
|
|
gridWidth: 1,
|
|
gridHeight: 1,
|
|
} as never,
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
});
|
|
resourceId = resource.id;
|
|
|
|
const blueprints = await Promise.all(
|
|
[4, 2].map((baySize, i) =>
|
|
payload.create({
|
|
collection: "structures",
|
|
data: {
|
|
name: `${RUN} Depot ${i}`,
|
|
codeName: `${RUN}-depot-${i}`,
|
|
approvalStatus: "in_progress",
|
|
description: LEXICAL_EMPTY,
|
|
category: "logistics",
|
|
materials: [{ resource: resourceId, amount: 1 }],
|
|
constructionDurationMinutes: 1,
|
|
terrainType: "land",
|
|
maxHealth: 100,
|
|
vehicleBay: i === 0 ? { xSize: 4, ySize: 4 } : { xSize: baySize, ySize: 2 },
|
|
} as never,
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
}),
|
|
),
|
|
);
|
|
blueprintAId = blueprints[0].id;
|
|
blueprintBId = blueprints[1].id;
|
|
|
|
const structureA = await payload.create({
|
|
collection: "game-structures",
|
|
data: {
|
|
name: `${RUN} Motor Pool`,
|
|
type: blueprintAId,
|
|
constructionStatus: "complete",
|
|
storageSlug: SLUG_A,
|
|
} as never,
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
});
|
|
structureAId = structureA.id;
|
|
const structureB = await payload.create({
|
|
collection: "game-structures",
|
|
data: {
|
|
name: `${RUN} Restricted Depot`,
|
|
type: blueprintBId,
|
|
constructionStatus: "complete",
|
|
storageSlug: `${RUN}-bay-b`,
|
|
storageAccess: { mode: "users", users: [plainUser.id] },
|
|
} as never,
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
});
|
|
structureBId = structureB.id;
|
|
|
|
const template = await payload.create({
|
|
collection: "vehicles",
|
|
data: {
|
|
name: `${RUN} Truck Template`,
|
|
classname: CLASSNAME,
|
|
approvalStatus: "approved",
|
|
garageWidth: 2,
|
|
garageHeight: 1,
|
|
maxHealth: 100,
|
|
fuel: { fuelType: resourceId, fuelCapacity: 100, fuelConsumptionRate: 1 },
|
|
} as never,
|
|
draft: false,
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
});
|
|
templateId = template.id;
|
|
|
|
const server = await payload.create({
|
|
collection: "game-servers",
|
|
data: { serverId: `${RUN}-srv`, name: `${RUN} Server`, status: "online" },
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
});
|
|
serverId = server.id;
|
|
});
|
|
|
|
afterAll(async () => {
|
|
if (!payload) return;
|
|
for (const id of commandIds) {
|
|
await payload.delete({ collection: "arma-commands", id, overrideAccess: true }).catch(() => {});
|
|
}
|
|
for (const id of reservationIds) {
|
|
await payload
|
|
.delete({ collection: "operation-reservations", id, overrideAccess: true })
|
|
.catch(() => {});
|
|
}
|
|
for (const id of vehicleIds) {
|
|
await payload.delete({ collection: "game-vehicles", id, overrideAccess: true }).catch(() => {});
|
|
}
|
|
if (templateId) {
|
|
await payload.delete({ collection: "vehicles", id: templateId, overrideAccess: true }).catch(() => {});
|
|
}
|
|
for (const id of [structureAId, structureBId]) {
|
|
if (id) await payload.delete({ collection: "game-structures", id, overrideAccess: true }).catch(() => {});
|
|
}
|
|
for (const id of [blueprintAId, blueprintBId]) {
|
|
if (id) await payload.delete({ collection: "structures", id, overrideAccess: true }).catch(() => {});
|
|
}
|
|
if (resourceId) {
|
|
await payload.delete({ collection: "resources", id: resourceId, overrideAccess: true }).catch(() => {});
|
|
}
|
|
for (const id of userIds) {
|
|
const profiles = await payload
|
|
.find({ collection: "profiles", where: { user: { equals: id } }, depth: 0, overrideAccess: true })
|
|
.catch(() => ({ docs: [] as { id: number }[] }));
|
|
for (const profile of profiles.docs) {
|
|
await payload.delete({ collection: "profiles", id: profile.id, overrideAccess: true }).catch(() => {});
|
|
}
|
|
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => {});
|
|
}
|
|
for (const id of roleIds) {
|
|
await payload.delete({ collection: "roles", id, overrideAccess: true }).catch(() => {});
|
|
}
|
|
if (serverId) {
|
|
await payload.delete({ collection: "game-servers", id: serverId, overrideAccess: true }).catch(() => {});
|
|
}
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Pure geometry
|
|
// ---------------------------------------------------------------------------
|
|
describe("garage geometry", () => {
|
|
it("footprint swaps width/height when rotated and defaults to 1x1", () => {
|
|
const fp = getVehicleFootprint({ garageWidth: 3, garageHeight: 2 } as never, true);
|
|
expect(fp).toEqual({ width: 2, height: 3 });
|
|
expect(getVehicleFootprint(null, false)).toEqual({ width: 1, height: 1 });
|
|
});
|
|
|
|
it("rejects overlapping and out-of-bounds placements", () => {
|
|
const items = [item("1", 0, 0, 2, 1)];
|
|
expect(isGaragePlacementValid(items, "1", 2, 0, 2, 1, 4, 3)).toBe(true);
|
|
expect(isGaragePlacementValid(items, null, 1, 0, 2, 1, 4, 3)).toBe(false);
|
|
expect(isGaragePlacementValid(items, null, 3, 0, 2, 1, 4, 3)).toBe(false);
|
|
expect(isGaragePlacementValid(items, null, 0, 3, 1, 1, 4, 3)).toBe(false);
|
|
});
|
|
|
|
it("finds empty spots row-major and reports overflow on auto-arrange", () => {
|
|
const items = [item("1", 0, 0, 2, 1)];
|
|
expect(findGarageEmptySpot(items, 1, 1, 4, 2)).toEqual({ x: 2, y: 0 });
|
|
const packed = [item("1", 0, 0, 2, 1), item("2", 2, 0, 2, 1)];
|
|
expect(findGarageEmptySpot(packed, 2, 1, 4, 1)).toBeNull();
|
|
const arranged = autoArrangeGarageItems(
|
|
[item("1", 3, 2, 2, 1), item("2", 0, 0, 2, 1), item("3", 1, 1, 2, 1)],
|
|
3,
|
|
1,
|
|
);
|
|
expect(arranged.placed).toHaveLength(1);
|
|
expect(arranged.overflow).toEqual(["2", "3"]);
|
|
});
|
|
|
|
it("parses and formats garage instance refs (A1)", () => {
|
|
expect(formatGarageInstanceRef("motor-pool")).toBe("garage:motor-pool");
|
|
expect(parseGarageInstanceRef("garage:motor_pool")).toEqual({ slug: "motor_pool" });
|
|
expect(parseGarageInstanceRef("locker:x")).toBeNull();
|
|
expect(parseGarageInstanceRef("garage:")).toBeNull();
|
|
expect(parseGarageInstanceRef(null)).toBeNull();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// storageAccess gating modes (D5)
|
|
// ---------------------------------------------------------------------------
|
|
describe("canUserAccessStructureStorage", () => {
|
|
it("honors anyone, users and roles modes", async () => {
|
|
const structureA = await payload.findByID({
|
|
collection: "game-structures",
|
|
id: structureAId,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
await expect(
|
|
canUserAccessStructureStorage(payload, officerUser, structureA as unknown as Record<string, unknown>),
|
|
).resolves.toBe(true);
|
|
|
|
const structureB = await payload.findByID({
|
|
collection: "game-structures",
|
|
id: structureBId,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
await expect(
|
|
canUserAccessStructureStorage(payload, plainUser, structureB as unknown as Record<string, unknown>),
|
|
).resolves.toBe(true);
|
|
await expect(
|
|
canUserAccessStructureStorage(payload, officerUser, structureB as unknown as Record<string, unknown>),
|
|
).resolves.toBe(false);
|
|
|
|
const restrictedRole = await payload.create({
|
|
collection: "roles",
|
|
data: { name: `${RUN} Depot Crew`, slug: `${RUN}-depot-crew` },
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
});
|
|
roleIds.push(restrictedRole.id);
|
|
await payload.update({
|
|
collection: "game-structures",
|
|
id: structureBId,
|
|
data: { storageAccess: { mode: "roles", roles: [restrictedRole.id] } } as never,
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
});
|
|
const crewUser = await makeUser("crew", [restrictedRole.id]);
|
|
const structureBRoles = await payload.findByID({
|
|
collection: "game-structures",
|
|
id: structureBId,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
await expect(
|
|
canUserAccessStructureStorage(payload, crewUser, structureBRoles as unknown as Record<string, unknown>),
|
|
).resolves.toBe(true);
|
|
await expect(
|
|
canUserAccessStructureStorage(payload, plainUser, structureBRoles as unknown as Record<string, unknown>),
|
|
).resolves.toBe(false);
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Server actions (D6/D7)
|
|
// ---------------------------------------------------------------------------
|
|
describe("garage server actions", () => {
|
|
let vehicle1: GameVehicle; // parked at (0,0)
|
|
let vehicle2: GameVehicle; // parked at (2,0)
|
|
let vehicle3: GameVehicle; // off-map, for store
|
|
let wreck: GameVehicle; // destroyed at (2,2)
|
|
let tagged: GameVehicle; // bridgeUid-tagged at (2,1)? placed after moves
|
|
|
|
beforeAll(async () => {
|
|
vehicle1 = await makeVehicle({ deployedAt: structureAId, garageGridX: 0, garageGridY: 0 });
|
|
vehicle2 = await makeVehicle({ deployedAt: structureAId, garageGridX: 2, garageGridY: 0 });
|
|
vehicle3 = await makeVehicle({ status: "in_transit" });
|
|
wreck = await makeVehicle({
|
|
status: "destroyed",
|
|
deployedAt: structureAId,
|
|
garageGridX: 2,
|
|
garageGridY: 2,
|
|
});
|
|
tagged = await makeVehicle({
|
|
deployedAt: structureAId,
|
|
garageGridX: 0,
|
|
garageGridY: 1,
|
|
bridgeUid: `${RUN}-uid-5`,
|
|
currentFuel: 50,
|
|
currentHealth: 100,
|
|
});
|
|
});
|
|
|
|
it("rejects users without game-vehicles:update (D6)", async () => {
|
|
authSpy.mockResolvedValue({ user: plainUser } as never);
|
|
const result = await moveGarageItem(vehicle1.id, 1, 1);
|
|
expect(result.success).toBe(false);
|
|
expect(result.error).toMatch(/Insufficient permissions/);
|
|
});
|
|
|
|
it("moves a vehicle to a free cell and persists it", async () => {
|
|
authSpy.mockResolvedValue({ user: officerUser } as never);
|
|
const result = await moveGarageItem(vehicle1.id, 0, 2);
|
|
expect(result.success).toBe(true);
|
|
const doc = await vehicleDoc(vehicle1.id);
|
|
expect(doc.garageGridX).toBe(0);
|
|
expect(doc.garageGridY).toBe(2);
|
|
});
|
|
|
|
it("rejects overlapping and out-of-bounds moves", async () => {
|
|
authSpy.mockResolvedValue({ user: officerUser } as never);
|
|
const overlap = await moveGarageItem(vehicle1.id, 1, 0); // hits vehicle2 at (2,0)
|
|
expect(overlap.success).toBe(false);
|
|
expect(overlap.error).toMatch(/occupied or out of bounds/i);
|
|
const oob = await moveGarageItem(vehicle1.id, 3, 0); // 2-wide truck past x=3
|
|
expect(oob.success).toBe(false);
|
|
});
|
|
|
|
it("rotates a parked vehicle in place", async () => {
|
|
authSpy.mockResolvedValue({ user: officerUser } as never);
|
|
const before = await vehicleDoc(vehicle1.id);
|
|
const result = await rotateGarageItem(vehicle1.id);
|
|
expect(result.success).toBe(true);
|
|
const after = await vehicleDoc(vehicle1.id);
|
|
expect(Boolean(after.garageRotated)).toBe(!Boolean(before.garageRotated));
|
|
});
|
|
|
|
it("dispatches an idle tagged vehicle: clears cells + deployedAt, queues garage.dispatch", async () => {
|
|
authSpy.mockResolvedValue({ user: officerUser } as never);
|
|
const result = await dispatchVehicle(tagged.id);
|
|
expect(result.success).toBe(true);
|
|
const doc = await vehicleDoc(tagged.id);
|
|
expect(doc.status).toBe("in_transit");
|
|
expect(doc.garageGridX).toBeNull();
|
|
expect(doc.deployedAt).toBeNull();
|
|
|
|
const commands = await payload.find({
|
|
collection: "arma-commands",
|
|
where: { type: { equals: "garage.dispatch" } },
|
|
limit: 10,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
const command = commands.docs.find(
|
|
(c) => Array.isArray(c.payload) && String(c.payload[0]).includes(SLUG_A),
|
|
);
|
|
expect(command).toBeDefined();
|
|
commandIds.push(Number(command!.id));
|
|
expect(command!.payload).toEqual([`garage:${SLUG_A}`, `${RUN}-uid-5`, CLASSNAME, 0.5, 0]);
|
|
});
|
|
|
|
it("refuses to dispatch destroyed or reserved vehicles (A4/D10)", async () => {
|
|
authSpy.mockResolvedValue({ user: officerUser } as never);
|
|
const destroyed = await dispatchVehicle(wreck.id);
|
|
expect(destroyed.success).toBe(false);
|
|
expect(destroyed.error).toMatch(/Destroyed/);
|
|
|
|
const reservation = await payload.create({
|
|
collection: "operation-reservations",
|
|
data: {
|
|
reservationKey: `${RUN}-op`,
|
|
operationId: `${RUN}-operation`,
|
|
status: "reserved",
|
|
vehicles: [{ vehicle: vehicle1.id }],
|
|
} as never,
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
});
|
|
reservationIds.push(reservation.id);
|
|
|
|
const reserved = await dispatchVehicle(vehicle1.id);
|
|
expect(reserved.success).toBe(false);
|
|
expect(reserved.error).toMatch(/reserved/i);
|
|
});
|
|
|
|
it("stores a vehicle into the first free row-major cell and queues garage.store", async () => {
|
|
authSpy.mockResolvedValue({ user: officerUser } as never);
|
|
// Occupied now: vehicle2 (2,0 2x1), wreck (2,2 2x1), vehicle1 rotated at (0,2).
|
|
const result = await storeVehicle(vehicle3.id, structureAId);
|
|
expect(result.success).toBe(true);
|
|
const doc = await vehicleDoc(vehicle3.id);
|
|
expect(doc.status).toBe("idle");
|
|
expect(doc.garageGridX).toBe(0);
|
|
expect(doc.garageGridY).toBe(0);
|
|
expect(Number(typeof doc.deployedAt === "object" ? doc.deployedAt?.id : doc.deployedAt)).toBe(
|
|
structureAId,
|
|
);
|
|
// vehicle3 has no bridgeUid, so no garage.store command is queued.
|
|
const commands = await payload.find({
|
|
collection: "arma-commands",
|
|
where: { type: { equals: "garage.store" } },
|
|
limit: 10,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
expect(
|
|
commands.docs.filter((c) => Array.isArray(c.payload) && String(c.payload[0]).includes(SLUG_A)),
|
|
).toHaveLength(0);
|
|
});
|
|
|
|
it("refuses to store destroyed vehicles and respects the target storageAccess gate", async () => {
|
|
authSpy.mockResolvedValue({ user: officerUser } as never);
|
|
const destroyed = await storeVehicle(wreck.id, structureAId);
|
|
expect(destroyed.success).toBe(false);
|
|
expect(destroyed.error).toMatch(/Destroyed/);
|
|
|
|
// structureB is users-restricted to plainUser; the officer passes the
|
|
// permission check but fails the storage gate (D5).
|
|
const gated = await storeVehicle(vehicle3.id, structureBId);
|
|
expect(gated.success).toBe(false);
|
|
expect(gated.error).toMatch(/access/i);
|
|
});
|
|
});
|