1
0
Fork 0
polaris-task-force/tests/int/garage-bridge.int.spec.ts

406 lines
13 KiB
TypeScript

import { getPayload, Payload } from "payload";
import config from "@/payload.config";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { GameVehicle } from "@/payload-types";
import { processGarageEvent } from "@/lib/arma-bridge/garages";
let payload: Payload;
const RUN = `garagebr-${Date.now().toString(36)}`;
const SLUG = `${RUN}-motorpool`;
const CLASSNAME = `${RUN}-truck`;
const UID_PARKED = `${RUN}-uid-parked`;
const UID_UNTAGGED = `${RUN}-uid-claim`;
const LEXICAL_EMPTY = {
root: {
children: [{ text: "" }],
direction: null,
format: "" as const,
indent: 0,
type: "text",
version: 1,
},
};
let resourceId: number;
let blueprintId: number;
let structureId: number;
let templateId: number;
let serverId: number;
let parkedId: number;
let untaggedId: number;
const vehicleIds: number[] = [];
const commandIds: number[] = [];
const eventIds: number[] = [];
let eventSeq = 0;
function garageEvent(type: string, eventPayload: unknown[], server: number) {
eventSeq += 1;
return {
id: eventSeq,
eventId: `${RUN}:${eventSeq}`,
server,
type,
occurredAt: new Date().toISOString(),
payload: eventPayload,
};
}
async function vehicleDoc(id: number) {
return (await payload.findByID({
collection: "game-vehicles",
id,
depth: 0,
overrideAccess: true,
})) as GameVehicle;
}
async function findVehicleByUid(uid: string): Promise<GameVehicle | null> {
const found = await payload.find({
collection: "game-vehicles",
where: { bridgeUid: { equals: uid } },
limit: 1,
depth: 0,
overrideAccess: true,
});
return (found.docs[0] as GameVehicle | undefined) ?? null;
}
async function findGarageCommands(type: string) {
const found = await payload.find({
collection: "arma-commands",
where: { type: { equals: type } },
limit: 100,
depth: 0,
overrideAccess: true,
});
return found.docs.filter(
(doc) =>
Array.isArray((doc as { payload?: unknown }).payload) &&
String((doc as { payload: unknown[] }).payload[0]).includes(SLUG),
);
}
describe("Arma garage sync", () => {
beforeAll(async () => {
const payloadConfig = await config;
payload = await getPayload({ config: payloadConfig });
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 blueprint = await payload.create({
collection: "structures",
data: {
name: `${RUN} Motor Pool Blueprint`,
codeName: `${RUN}-mp`,
approvalStatus: "in_progress",
description: LEXICAL_EMPTY,
category: "logistics",
materials: [{ resource: resourceId, amount: 1 }],
constructionDurationMinutes: 1,
terrainType: "land",
maxHealth: 100,
vehicleBay: { xSize: 4, ySize: 3 },
} as never,
overrideAccess: true,
depth: 0,
});
blueprintId = blueprint.id;
const structure = await payload.create({
collection: "game-structures",
data: {
name: `${RUN} Motor Pool`,
type: blueprintId,
constructionStatus: "complete",
storageSlug: SLUG,
} as never,
overrideAccess: true,
depth: 0,
});
structureId = structure.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 parked = await payload.create({
collection: "game-vehicles",
data: {
name: `${RUN} Parked Truck`,
type: templateId,
deployedAt: structureId,
status: "idle",
bridgeUid: UID_PARKED,
garageGridX: 0,
garageGridY: 0,
currentFuel: 80,
currentHealth: 100,
} as never,
overrideAccess: true,
depth: 0,
});
parkedId = parked.id;
vehicleIds.push(parkedId);
// Untagged instance at the same structure: claim-by-classname target.
const untagged = await payload.create({
collection: "game-vehicles",
data: {
name: `${RUN} Untagged Truck`,
type: templateId,
deployedAt: structureId,
status: "idle",
currentFuel: 100,
currentHealth: 100,
} as never,
overrideAccess: true,
depth: 0,
});
untaggedId = untagged.id;
vehicleIds.push(untaggedId);
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 eventIds) {
await payload.delete({ collection: "arma-sync-events", 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(() => {});
}
if (structureId) {
await payload.delete({ collection: "game-structures", id: structureId, overrideAccess: true }).catch(() => {});
}
if (blueprintId) {
await payload.delete({ collection: "structures", id: blueprintId, overrideAccess: true }).catch(() => {});
}
if (resourceId) {
await payload.delete({ collection: "resources", id: resourceId, overrideAccess: true }).catch(() => {});
}
if (serverId) {
await payload.delete({ collection: "game-servers", id: serverId, overrideAccess: true }).catch(() => {});
}
});
describe("garage.deposit", () => {
it("applies fuel/damage to a known instance and preserves its cell", async () => {
await expect(
processGarageEvent(payload, garageEvent("garage.deposit", [`garage:${SLUG}`, UID_PARKED, CLASSNAME, 0.5, 0.25], 1)),
).resolves.toBeUndefined();
const doc = await vehicleDoc(parkedId);
expect(doc.currentFuel).toBe(50);
expect(doc.currentHealth).toBe(75);
expect(doc.garageGridX).toBe(0);
expect(doc.garageGridY).toBe(0);
expect(doc.status).toBe("idle");
});
it("claims an untagged classname match at the structure (first-tag-wins)", async () => {
await processGarageEvent(
payload,
garageEvent("garage.deposit", [`garage:${SLUG}`, UID_UNTAGGED, CLASSNAME, 1, 0], 1),
);
const doc = await vehicleDoc(untaggedId);
expect(doc.bridgeUid).toBe(UID_UNTAGGED);
// Row-major auto-place: (0,0) is taken by the parked truck, so a 2x1
// lands at (2,0).
expect(doc.garageGridX).toBe(2);
expect(doc.garageGridY).toBe(0);
expect(doc.status).toBe("idle");
});
it("creates a new instance for an unknown uid with a known template", async () => {
const uid = `${RUN}-uid-created`;
await processGarageEvent(
payload,
garageEvent("garage.deposit", [`garage:${SLUG}`, uid, CLASSNAME, 0.4, 0], 1),
);
const created = await findVehicleByUid(uid);
expect(created).not.toBeNull();
vehicleIds.push(created!.id);
expect(created!.status).toBe("idle");
expect(created!.currentFuel).toBe(40);
expect(Number(typeof created!.deployedAt === "object" ? created!.deployedAt?.id : created!.deployedAt)).toBe(
structureId,
);
});
it("skips unknown classnames without creating anything", async () => {
const before = await payload.count({
collection: "game-vehicles",
where: { bridgeUid: { exists: true } },
overrideAccess: true,
});
await expect(
processGarageEvent(
payload,
garageEvent("garage.deposit", [`garage:${SLUG}`, `${RUN}-uid-ghost`, "no_such_class", 1, 0], 1),
),
).resolves.toBeUndefined();
const after = await payload.count({
collection: "game-vehicles",
where: { bridgeUid: { exists: true } },
overrideAccess: true,
});
expect(after.totalDocs).toBe(before.totalDocs);
});
it("marks full damage as destroyed", async () => {
await processGarageEvent(
payload,
garageEvent("garage.deposit", [`garage:${SLUG}`, UID_UNTAGGED, CLASSNAME, 0.1, 1], 1),
);
const doc = await vehicleDoc(untaggedId);
expect(doc.status).toBe("destroyed");
expect(doc.currentHealth).toBe(0);
});
});
describe("garage.withdraw", () => {
it("clears cells and deployedAt and sets in_transit", async () => {
await processGarageEvent(
payload,
garageEvent("garage.withdraw", [`garage:${SLUG}`, UID_PARKED, CLASSNAME, 0.4, 0], 1),
);
const doc = await vehicleDoc(parkedId);
expect(doc.garageGridX).toBeNull();
expect(doc.garageGridY).toBeNull();
expect(doc.deployedAt).toBeNull();
expect(doc.status).toBe("in_transit");
expect(doc.bridgeUid).toBe(UID_PARKED);
});
it("skips unknown bridgeUids without throwing", async () => {
await expect(
processGarageEvent(
payload,
garageEvent("garage.withdraw", [`garage:${SLUG}`, `${RUN}-uid-nope`, CLASSNAME, 1, 0], 1),
),
).resolves.toBeUndefined();
});
});
describe("garage.sync snapshot", () => {
it("applies every line and is idempotent (absence is not deletion)", async () => {
const uid = `${RUN}-uid-sync`;
const snapshot = [
[`garage:${SLUG}`, [
[uid, CLASSNAME, 0.9, 0],
[UID_UNTAGGED, CLASSNAME, 0.1, 1],
]],
];
await processGarageEvent(payload, garageEvent("garage.sync", snapshot[0], 1));
const created = await findVehicleByUid(uid);
expect(created).not.toBeNull();
vehicleIds.push(created!.id);
// Re-apply the same snapshot: no duplicates, state unchanged.
await processGarageEvent(payload, garageEvent("garage.sync", snapshot[0], 1));
const found = await payload.find({
collection: "game-vehicles",
where: { bridgeUid: { equals: uid } },
limit: 5,
depth: 0,
overrideAccess: true,
});
expect(found.totalDocs).toBe(1);
// UID_PARKED was absent from the snapshot but keeps its row.
expect((await vehicleDoc(parkedId)).bridgeUid).toBe(UID_PARKED);
});
});
describe("garage.request -> garage.apply", () => {
it("enqueues one apply command with the parked tagged instances", async () => {
await processGarageEvent(payload, garageEvent("garage.request", [`garage:${SLUG}`], serverId));
const commands = await findGarageCommands("garage.apply");
expect(commands).toHaveLength(1);
commandIds.push(Number(commands[0].id));
const [ref, lines] = commands[0].payload as [string, Array<[string, string, number, number]>];
expect(ref).toBe(`garage:${SLUG}`);
const uids = lines.map((line) => line[0]);
expect(uids).toContain(UID_UNTAGGED);
expect(uids).not.toContain(UID_PARKED); // withdrawn, no longer parked
expect(commands[0].server).toBe(serverId);
});
});
describe("router wiring + malformed input", () => {
it("processes a real arma-sync-events row of type garage.deposit", async () => {
const uid = `${RUN}-uid-router`;
const raw = await payload.create({
collection: "arma-sync-events",
data: {
eventId: `${RUN}-router`,
server: serverId,
type: "garage.deposit",
occurredAt: new Date().toISOString(),
payload: [`garage:${SLUG}`, uid, CLASSNAME, 1, 0],
} as never,
overrideAccess: true,
depth: 0,
});
eventIds.push(raw.id);
const created = await findVehicleByUid(uid);
expect(created).not.toBeNull();
vehicleIds.push(created!.id);
});
it("never throws on malformed payloads or unknown refs", async () => {
await expect(processGarageEvent(payload, garageEvent("garage.deposit", [], 1))).resolves.toBeUndefined();
await expect(
processGarageEvent(payload, garageEvent("garage.sync", ["bogus-ref", []], 1)),
).resolves.toBeUndefined();
await expect(
processGarageEvent(payload, garageEvent("garage.sync", [`garage:${RUN}-missing`, []], 1)),
).resolves.toBeUndefined();
await expect(
processGarageEvent(payload, { ...garageEvent("garage.sync", [], 1), payload: "nope" as never }),
).resolves.toBeUndefined();
});
});
});