1
0
Fork 0
polaris-task-force/tests/int/reinforcement-pools.int.spec.ts
Z8MB1E 38e6b3d89f feat(reinforcement-pools): store per-pool balances and sync to the game bridge
New Game collection reinforcement-pools (name, faction, armaFactions,
available, enabled) with manual-edit audit via reinforcement:adjust. The
events hook applies reinforcement.spawn/.refund deltas (soft limits, no
floor, idempotent by eventId) before the game's next pull, and a new GET
/api/arma/v1/reinforcements endpoint serves enabled pools to the server.
2026-10-07 00:28:42 -04:00

249 lines
8.9 KiB
TypeScript

import { getPayload, Payload } from "payload";
import config from "@/payload.config";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { NextRequest } from "next/server";
import { processReinforcementEvent } from "@/lib/arma-bridge/reinforcements";
import { GET } from "@/app/api/arma/v1/reinforcements/route";
import { POST as postEvents } from "@/app/api/arma/v1/events/route";
/**
* Reinforcement pools (web app -> Zeus soft limits).
*
* Processor delta math is tested directly; idempotency lives at the events
* route (unique eventId), so it is exercised through that endpoint, together
* with the reinforcements endpoint's shape and auth gating.
*/
let payload: Payload;
const RUN = `reinf-${Date.now().toString(36)}`;
const SERVER_ID = `${RUN}-srv`.replace(/[^a-zA-Z0-9_-]/g, "");
const BRIDGE_KEY = process.env.ARMA_BRIDGE_API_KEY || "test-bridge-key";
async function availableOf(id: number): Promise<number> {
const pool = await payload.findByID({
collection: "reinforcement-pools",
id,
depth: 0,
overrideAccess: true,
});
return pool.available ?? 0;
}
async function eventLogs(type: string, targetId: number) {
const res = await payload.find({
collection: "game-event-logs",
where: { type: { equals: type }, targetId: { equals: targetId } },
limit: 50,
sort: "-createdAt",
depth: 0,
overrideAccess: true,
});
return res.docs;
}
let eventSeq = 0;
function bridgeEvent(type: "reinforcement.spawn" | "reinforcement.refund", body: unknown) {
eventSeq += 1;
return { eventId: `${RUN}:${eventSeq}`, type, payload: body };
}
describe("Reinforcement pools", () => {
let poolAId: number;
let poolBId: number;
let serverDocId: number;
const createdPoolIds: number[] = [];
beforeAll(async () => {
process.env.ARMA_BRIDGE_API_KEY = BRIDGE_KEY;
const payloadConfig = await config;
payload = await getPayload({ config: payloadConfig });
const server = await payload.create({
collection: "game-servers",
data: { serverId: SERVER_ID, name: `${RUN} Server`, status: "online" },
overrideAccess: true,
depth: 0,
});
serverDocId = server.id;
const poolA = await payload.create({
collection: "reinforcement-pools",
data: { name: `${RUN}-A`, armaFactions: ["BLU_F", "PTF"], available: 16, enabled: true },
overrideAccess: true,
depth: 0,
});
poolAId = poolA.id;
createdPoolIds.push(poolAId);
const poolB = await payload.create({
collection: "reinforcement-pools",
data: { name: `${RUN}-B-disabled`, available: 5, enabled: false },
overrideAccess: true,
depth: 0,
});
poolBId = poolB.id;
createdPoolIds.push(poolBId);
});
afterAll(async () => {
for (const id of createdPoolIds) {
await payload.delete({ collection: "reinforcement-pools", id, overrideAccess: true }).catch(() => {});
}
if (serverDocId) {
await payload.delete({ collection: "game-servers", id: serverDocId, overrideAccess: true }).catch(() => {});
}
});
describe("processReinforcementEvent delta math", () => {
it("spawn decrements and refund increments the pool balance", async () => {
const before = await availableOf(poolAId);
await processReinforcementEvent(
payload,
bridgeEvent("reinforcement.spawn", [poolAId, 1, "B_Soldier_F"]),
);
expect(await availableOf(poolAId)).toBe(before - 1);
await processReinforcementEvent(
payload,
bridgeEvent("reinforcement.refund", [poolAId, 1, "B_Soldier_F"]),
);
expect(await availableOf(poolAId)).toBe(before);
const spawns = await eventLogs("reinforcement:spawn", poolAId);
expect(spawns.length).toBeGreaterThan(0);
const refunds = await eventLogs("reinforcement:refund", poolAId);
expect(refunds.length).toBeGreaterThan(0);
});
it("allows overdraft: balances may go negative (no floor)", async () => {
await payload.update({
collection: "reinforcement-pools",
id: poolAId,
data: { available: 2 },
overrideAccess: true,
depth: 0,
});
await processReinforcementEvent(
payload,
bridgeEvent("reinforcement.spawn", [poolAId, 5, "B_soldier_F"]),
);
expect(await availableOf(poolAId)).toBe(-3);
});
it("skips unknown pools and malformed payloads without throwing", async () => {
const before = await availableOf(poolAId);
await expect(
processReinforcementEvent(payload, bridgeEvent("reinforcement.spawn", [999999999, 1, "X"])),
).resolves.toBeUndefined();
await expect(
processReinforcementEvent(payload, bridgeEvent("reinforcement.spawn", "nope")),
).resolves.toBeUndefined();
await expect(
processReinforcementEvent(payload, bridgeEvent("reinforcement.spawn", [poolAId, 0, "X"])),
).resolves.toBeUndefined();
expect(await availableOf(poolAId)).toBe(before);
});
});
describe("manual-edit audit (reinforcement:adjust)", () => {
it("bridge writes emit no adjust event; admin writes do", async () => {
// Pool creation itself was a manual write, so count from the current baseline.
const baseline = (await eventLogs("reinforcement:adjust", poolAId)).length;
// A bridge processor write carries the system marker: no adjust audit.
await processReinforcementEvent(
payload,
bridgeEvent("reinforcement.spawn", [poolAId, 1, "B_Soldier_F"]),
);
const afterBridge = await availableOf(poolAId);
expect((await eventLogs("reinforcement:adjust", poolAId)).length).toBe(baseline);
// Admin-panel style write (no system marker header) is audited old -> new.
await payload.update({
collection: "reinforcement-pools",
id: poolAId,
data: { available: 42 },
overrideAccess: true,
depth: 0,
});
const adjusts = await eventLogs("reinforcement:adjust", poolAId);
expect(adjusts.length).toBe(baseline + 1);
expect(adjusts[0].data).toMatchObject({ operation: "update", availableBefore: afterBridge, availableAfter: 42 });
// A write that does not touch the balance emits nothing new.
await payload.update({
collection: "reinforcement-pools",
id: poolAId,
data: { name: `${RUN}-A-renamed` },
overrideAccess: true,
depth: 0,
});
expect((await eventLogs("reinforcement:adjust", poolAId)).length).toBe(baseline + 1);
});
});
describe("GET /api/arma/v1/reinforcements", () => {
function request(headers: Record<string, string>) {
return new NextRequest("http://localhost/api/arma/v1/reinforcements", { headers });
}
it("gates on the bridge key and a known server", async () => {
let res = await GET(request({}));
expect(res.status).toBe(401);
res = await GET(
request({ "x-arma-bridge-key": "wrong", "x-arma-server-id": SERVER_ID }),
);
expect(res.status).toBe(401);
res = await GET(
request({ "x-arma-bridge-key": BRIDGE_KEY, "x-arma-server-id": "never-beaten" }),
);
expect(res.status).toBe(409);
});
it("returns enabled pools with poolId, name, available and armaFactions", async () => {
const res = await GET(
request({ "x-arma-bridge-key": BRIDGE_KEY, "x-arma-server-id": SERVER_ID }),
);
expect(res.status).toBe(200);
const body = (await res.json()) as {
ok: boolean;
pools: { poolId: number; name: string; available: number; armaFactions: string[] }[];
};
expect(body.ok).toBe(true);
const a = body.pools.find((pool) => pool.poolId === poolAId);
expect(a).toMatchObject({ name: `${RUN}-A-renamed`, available: 42, armaFactions: ["BLU_F", "PTF"] });
expect(body.pools.some((pool) => pool.poolId === poolBId)).toBe(false);
});
});
describe("events route idempotency (duplicate eventId)", () => {
function eventsRequest(events: unknown[]) {
return new NextRequest("http://localhost/api/arma/v1/events", {
method: "POST",
headers: { "x-arma-bridge-key": BRIDGE_KEY, "x-arma-server-id": SERVER_ID },
body: JSON.stringify({ events }),
});
}
it("applies a reinforcement event once and ignores the redelivery", async () => {
const before = await availableOf(poolAId);
const event = {
id: `${RUN}-dup-1`,
type: "reinforcement.spawn",
payload: [poolAId, 1, "B_Soldier_F"],
occurredAt: new Date().toISOString(),
};
let res = await postEvents(eventsRequest([event]));
expect(res.status).toBe(200);
expect(await res.json()).toMatchObject({ ok: true, accepted: 1, duplicates: 0 });
expect(await availableOf(poolAId)).toBe(before - 1);
res = await postEvents(eventsRequest([event]));
expect(await res.json()).toMatchObject({ ok: true, accepted: 0, duplicates: 1 });
expect(await availableOf(poolAId)).toBe(before - 1);
});
});
});