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.
This commit is contained in:
parent
565e190c7e
commit
38e6b3d89f
14 changed files with 38903 additions and 2 deletions
35
src/app/api/arma/v1/reinforcements/route.ts
Normal file
35
src/app/api/arma/v1/reinforcements/route.ts
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { requireArmaServer } from "@/lib/arma-bridge/server";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* Called by the Arma 3 bridge (get_reinforcements) on the server's ~15 s
|
||||
* reinforcement cycle. Returns every enabled reinforcement pool with its
|
||||
* current balance and the Arma faction classes it counts, so the game can
|
||||
* attribute curator placements and render the Zeus HUD.
|
||||
*/
|
||||
export async function GET(req: NextRequest) {
|
||||
const auth = await requireArmaServer(req);
|
||||
if (auth instanceof NextResponse) return auth;
|
||||
const { payload } = auth;
|
||||
|
||||
const pools = await payload.find({
|
||||
collection: "reinforcement-pools",
|
||||
where: { enabled: { equals: true } },
|
||||
limit: 200,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
pools: pools.docs.map((pool) => ({
|
||||
poolId: pool.id,
|
||||
name: pool.name,
|
||||
available: pool.available ?? 0,
|
||||
armaFactions: pool.armaFactions ?? [],
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
|
@ -46,6 +46,7 @@ const TARGET_COLLECTIONS = [
|
|||
{ label: "Promotion Nominations", value: "promotion-nominations" },
|
||||
{ label: "Leadership Transfers", value: "leadership-transfers" },
|
||||
{ label: "Player Flags", value: "player-flags" },
|
||||
{ label: "Reinforcement Pools", value: "reinforcement-pools" },
|
||||
] as const;
|
||||
|
||||
export const GameEventLogs: CollectionConfig = {
|
||||
|
|
|
|||
105
src/collections/game/ReinforcementPools.ts
Normal file
105
src/collections/game/ReinforcementPools.ts
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
import { CollectionConfig } from "payload";
|
||||
import { requirePermission } from "@/utils/access-control/hasPermission";
|
||||
import { emitGameEvent } from "@/utils/event-log/emit";
|
||||
import { EventTypes } from "@/utils/event-log/eventTypes";
|
||||
import { REINFORCEMENT_SYSTEM_HEADER } from "@/lib/arma-bridge/reinforcements";
|
||||
|
||||
/**
|
||||
* Reinforcement pools: per-pool "units available" balances that the Arma
|
||||
* game server pulls every ~15 s and decrements as curators place units
|
||||
* (soft limits: spawns are never blocked, balances may go negative).
|
||||
* GMs manage the balance manually here in the admin panel; every manual
|
||||
* write is audited as a restricted-free `reinforcement:adjust` event. Bridge
|
||||
* writes carry the system marker header and are audited by the processor as
|
||||
* spawn/refund events instead, so this hook stays quiet for them.
|
||||
*/
|
||||
export const ReinforcementPools: CollectionConfig = {
|
||||
slug: "reinforcement-pools",
|
||||
admin: {
|
||||
group: "Game",
|
||||
useAsTitle: "name",
|
||||
listSearchableFields: ["name"],
|
||||
defaultColumns: ["name", "faction", "available", "enabled"],
|
||||
},
|
||||
access: {
|
||||
read: requirePermission("reinforcement-pools:read"),
|
||||
create: requirePermission("reinforcement-pools:create"),
|
||||
update: requirePermission("reinforcement-pools:update"),
|
||||
delete: requirePermission("reinforcement-pools:delete"),
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: "name",
|
||||
type: "text",
|
||||
required: true,
|
||||
unique: true,
|
||||
admin: {
|
||||
description: "Pool name shown on the in-game Zeus HUD (e.g. 'PTF').",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "faction",
|
||||
type: "relationship",
|
||||
relationTo: "factions",
|
||||
admin: {
|
||||
description:
|
||||
"Optional web-app faction this pool belongs to. Grouping only; in-game attribution uses the Arma faction classes below.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "armaFactions",
|
||||
type: "text",
|
||||
hasMany: true,
|
||||
admin: {
|
||||
description:
|
||||
"Arma CfgVehicles faction classes counted by this pool (e.g. 'BLU_F', 'PTF'). Matched case-insensitively against the placed unit's faction; units of unmatched factions are free.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "available",
|
||||
type: "number",
|
||||
defaultValue: 0,
|
||||
admin: {
|
||||
description:
|
||||
"Units available. Decremented by counted Zeus placements, refunded on curator deletions. May go negative (overdraft is allowed; spawning is never blocked).",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "enabled",
|
||||
type: "checkbox",
|
||||
defaultValue: true,
|
||||
admin: {
|
||||
description: "Disabled pools are hidden from the game server and the Zeus HUD.",
|
||||
},
|
||||
},
|
||||
],
|
||||
hooks: {
|
||||
afterChange: [
|
||||
async ({ doc, req, operation, previousDoc }) => {
|
||||
// Bridge processor writes carry the system marker header and are
|
||||
// audited as reinforcement:spawn / reinforcement:refund events by the
|
||||
// processor itself; only manual GM/admin edits need an adjust audit.
|
||||
if (req.headers.get(REINFORCEMENT_SYSTEM_HEADER) === "1") return doc;
|
||||
if (operation === "update" && previousDoc?.available === doc.available) return doc;
|
||||
await emitGameEvent(req.payload, {
|
||||
type: EventTypes.ReinforcementAdjust,
|
||||
message:
|
||||
operation === "create"
|
||||
? `Reinforcement pool "${doc.name}" created with balance ${doc.available ?? 0}`
|
||||
: `Reinforcement pool "${doc.name}" adjusted: ${previousDoc?.available ?? 0} -> ${doc.available}`,
|
||||
actor: req.user ? Number(req.user.id) : undefined,
|
||||
targetCollection: "reinforcement-pools",
|
||||
targetId: doc.id,
|
||||
data: {
|
||||
operation,
|
||||
name: doc.name,
|
||||
availableBefore: operation === "create" ? null : (previousDoc?.available ?? null),
|
||||
availableAfter: doc.available,
|
||||
},
|
||||
});
|
||||
return doc;
|
||||
},
|
||||
],
|
||||
},
|
||||
timestamps: true,
|
||||
};
|
||||
|
|
@ -2,6 +2,7 @@ import { CollectionConfig } from "payload";
|
|||
import { processPlayerKill } from "@/lib/arma-bridge/processSyncEvents";
|
||||
import { processBoxEvent } from "@/lib/arma-bridge/crates";
|
||||
import { processMoneyEvent } from "@/lib/arma-bridge/money";
|
||||
import { processReinforcementEvent } from "@/lib/arma-bridge/reinforcements";
|
||||
import { processLockerEvent } from "@/lib/arma-bridge/lockers";
|
||||
import { isOperationLedgerEnabled } from "@/lib/operations/rollout";
|
||||
import { processOperationEvent } from "@/lib/operations/process";
|
||||
|
|
@ -41,6 +42,12 @@ export const ArmaSyncEvents: CollectionConfig = {
|
|||
// flushing). processMoneyEvent never throws.
|
||||
await processMoneyEvent(req.payload, doc);
|
||||
}
|
||||
if (doc.type.startsWith("reinforcement.")) {
|
||||
// Awaited (same posture as money.delta): the pool balance must be
|
||||
// current before the game's next reinforcement pull, and
|
||||
// processReinforcementEvent never throws.
|
||||
await processReinforcementEvent(req.payload, doc, req);
|
||||
}
|
||||
if (doc.type.startsWith("locker.")) {
|
||||
// Awaited (same posture as box.*): locker writes join the raw-event
|
||||
// transaction; processLockerEvent never throws.
|
||||
|
|
|
|||
129
src/lib/arma-bridge/reinforcements.ts
Normal file
129
src/lib/arma-bridge/reinforcements.ts
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
import type { Payload, PayloadRequest } from "payload";
|
||||
import type { ReinforcementPool } from "@/payload-types";
|
||||
import { emitGameEvent } from "@/utils/event-log/emit";
|
||||
import { EventTypes } from "@/utils/event-log/eventTypes";
|
||||
|
||||
/**
|
||||
* Reinforcement pools <-> Arma game server sync (bridge).
|
||||
*
|
||||
* The game queues a `reinforcement.spawn` event for every curator placement
|
||||
* that matches a pool's Arma factions and a `reinforcement.refund` event when
|
||||
* a curator deletes such a unit (killed units stay spent). The events route
|
||||
* dedupes by `serverId:eventId`, so a retried delivery never double-spends.
|
||||
* Balances are soft limits: they may go negative and nothing ever blocks.
|
||||
*
|
||||
* Pool balances live on `reinforcement-pools.available`. The game pulls them
|
||||
* through GET /api/arma/v1/reinforcements, so this processor must have applied
|
||||
* an event before the next pull returns (the ArmaSyncEvents hook awaits it).
|
||||
*/
|
||||
|
||||
/**
|
||||
* Marker header the processor passes through the local API `req` option so the
|
||||
* ReinforcementPools afterChange audit hook can tell bridge writes apart from
|
||||
* manual GM edits (manual edits emit `reinforcement:adjust`, bridge writes are
|
||||
* audited here as spawn/refund events instead).
|
||||
*/
|
||||
export const REINFORCEMENT_SYSTEM_HEADER = "x-reinforcement-system";
|
||||
|
||||
interface ReinforcementDelta {
|
||||
poolId: number;
|
||||
count: number;
|
||||
unitClass: string;
|
||||
}
|
||||
|
||||
/** Payload shape from ptf_reinforcements: [poolId, count, unitClass]. */
|
||||
export function parseReinforcementPayload(raw: unknown): ReinforcementDelta | null {
|
||||
if (!Array.isArray(raw) || raw.length < 2) return null;
|
||||
const poolId =
|
||||
typeof raw[0] === "number" ? Math.trunc(raw[0]) : Number.parseInt(String(raw[0]), 10);
|
||||
if (!Number.isInteger(poolId) || poolId <= 0) return null;
|
||||
const count = typeof raw[1] === "number" ? Math.trunc(raw[1]) : 0;
|
||||
if (!Number.isInteger(count) || count <= 0) return null;
|
||||
const unitClass = typeof raw[2] === "string" ? raw[2].slice(0, 128) : "";
|
||||
return { poolId, count, unitClass };
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies one `reinforcement.spawn` / `reinforcement.refund` event to the
|
||||
* pool balance (spawn subtracts, refund adds, no floor at zero). Never
|
||||
* throws: a malformed payload or unknown pool is logged and skipped, and the
|
||||
* game's next pull corrects its displayed value.
|
||||
*/
|
||||
export async function processReinforcementEvent(
|
||||
payload: Payload,
|
||||
raw: { eventId: string; type: string; payload: unknown },
|
||||
req?: PayloadRequest,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const isSpawn = raw.type === "reinforcement.spawn";
|
||||
const isRefund = raw.type === "reinforcement.refund";
|
||||
if (!isSpawn && !isRefund) return;
|
||||
|
||||
const delta = parseReinforcementPayload(raw.payload);
|
||||
if (!delta) {
|
||||
payload.logger.warn(
|
||||
`[Reinforcements] ${raw.type} event ${raw.eventId} has a malformed payload; skipping`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let pool: ReinforcementPool | null = null;
|
||||
try {
|
||||
pool = await payload.findByID({
|
||||
collection: "reinforcement-pools",
|
||||
id: delta.poolId,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
} catch {
|
||||
pool = null;
|
||||
}
|
||||
if (!pool) {
|
||||
payload.logger.warn(
|
||||
`[Reinforcements] ${raw.type} event ${raw.eventId} references unknown pool ${delta.poolId}; skipping`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const before = pool.available ?? 0;
|
||||
// Soft limits: overdraft is allowed, so no floor at zero.
|
||||
const after = isSpawn ? before - delta.count : before + delta.count;
|
||||
|
||||
const headers = new Headers(req?.headers);
|
||||
headers.set(REINFORCEMENT_SYSTEM_HEADER, "1");
|
||||
await payload.update({
|
||||
collection: "reinforcement-pools",
|
||||
id: pool.id,
|
||||
data: { available: after },
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
// Pass the marker through the local API req so the collection's
|
||||
// afterChange hook skips its manual-edit audit for this write.
|
||||
req: { headers } as Partial<PayloadRequest>,
|
||||
});
|
||||
|
||||
await emitGameEvent(payload, {
|
||||
type: isSpawn ? EventTypes.ReinforcementSpawn : EventTypes.ReinforcementRefund,
|
||||
message: isSpawn
|
||||
? `Zeus spawn spent ${delta.count} from reinforcement pool "${pool.name}"${
|
||||
delta.unitClass ? ` (${delta.unitClass})` : ""
|
||||
}: ${before} -> ${after}`
|
||||
: `Curator deletion refunded ${delta.count} to reinforcement pool "${pool.name}"${
|
||||
delta.unitClass ? ` (${delta.unitClass})` : ""
|
||||
}: ${before} -> ${after}`,
|
||||
targetCollection: "reinforcement-pools",
|
||||
targetId: pool.id,
|
||||
data: {
|
||||
eventId: raw.eventId,
|
||||
poolId: pool.id,
|
||||
name: pool.name,
|
||||
count: delta.count,
|
||||
unitClass: delta.unitClass,
|
||||
availableBefore: before,
|
||||
availableAfter: after,
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
payload.logger.error(`[Reinforcements] Failed to apply event ${raw.eventId}: ${err}`);
|
||||
}
|
||||
}
|
||||
38185
src/migrations/20261007_040914_add_reinforcement_pools.json
Normal file
38185
src/migrations/20261007_040914_add_reinforcement_pools.json
Normal file
File diff suppressed because it is too large
Load diff
76
src/migrations/20261007_040914_add_reinforcement_pools.ts
Normal file
76
src/migrations/20261007_040914_add_reinforcement_pools.ts
Normal file
File diff suppressed because one or more lines are too long
|
|
@ -113,6 +113,7 @@ import * as migration_20261006_195605_add_text_flag_type from './20261006_195605
|
|||
import * as migration_20261006_203217_add_dialogue_entry_gate from './20261006_203217_add_dialogue_entry_gate';
|
||||
import * as migration_20261006_205845_add_flag_time_windows from './20261006_205845_add_flag_time_windows';
|
||||
import * as migration_20261007_025942_add_event_log_visibility from './20261007_025942_add_event_log_visibility';
|
||||
import * as migration_20261007_040914_add_reinforcement_pools from './20261007_040914_add_reinforcement_pools';
|
||||
|
||||
export const migrations = [
|
||||
{
|
||||
|
|
@ -688,6 +689,11 @@ export const migrations = [
|
|||
{
|
||||
up: migration_20261007_025942_add_event_log_visibility.up,
|
||||
down: migration_20261007_025942_add_event_log_visibility.down,
|
||||
name: '20261007_025942_add_event_log_visibility'
|
||||
name: '20261007_025942_add_event_log_visibility',
|
||||
},
|
||||
{
|
||||
up: migration_20261007_040914_add_reinforcement_pools.up,
|
||||
down: migration_20261007_040914_add_reinforcement_pools.down,
|
||||
name: '20261007_040914_add_reinforcement_pools'
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -77,6 +77,7 @@ export interface Config {
|
|||
'npc-staffing': NpcStaffing;
|
||||
'npc-dialogues': NpcDialogue;
|
||||
'player-flags': PlayerFlag;
|
||||
'reinforcement-pools': ReinforcementPool;
|
||||
'labor-classifications': LaborClassification;
|
||||
'game-event-logs': GameEventLog;
|
||||
users: User;
|
||||
|
|
@ -176,6 +177,7 @@ export interface Config {
|
|||
'npc-staffing': NpcStaffingSelect<false> | NpcStaffingSelect<true>;
|
||||
'npc-dialogues': NpcDialoguesSelect<false> | NpcDialoguesSelect<true>;
|
||||
'player-flags': PlayerFlagsSelect<false> | PlayerFlagsSelect<true>;
|
||||
'reinforcement-pools': ReinforcementPoolsSelect<false> | ReinforcementPoolsSelect<true>;
|
||||
'labor-classifications': LaborClassificationsSelect<false> | LaborClassificationsSelect<true>;
|
||||
'game-event-logs': GameEventLogsSelect<false> | GameEventLogsSelect<true>;
|
||||
users: UsersSelect<false> | UsersSelect<true>;
|
||||
|
|
@ -798,6 +800,11 @@ export interface Role {
|
|||
| 'game-event-logs:update'
|
||||
| 'game-event-logs:delete'
|
||||
| 'admin:game-event-logs:manage'
|
||||
| 'reinforcement-pools:create'
|
||||
| 'reinforcement-pools:read'
|
||||
| 'reinforcement-pools:update'
|
||||
| 'reinforcement-pools:delete'
|
||||
| 'admin:reinforcement-pools:manage'
|
||||
| 'maps:create'
|
||||
| 'maps:read'
|
||||
| 'maps:update'
|
||||
|
|
@ -2600,6 +2607,35 @@ export interface PlayerFlag {
|
|||
updatedAt: string;
|
||||
createdAt: string;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "reinforcement-pools".
|
||||
*/
|
||||
export interface ReinforcementPool {
|
||||
id: number;
|
||||
/**
|
||||
* Pool name shown on the in-game Zeus HUD (e.g. 'PTF').
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* Optional web-app faction this pool belongs to. Grouping only; in-game attribution uses the Arma faction classes below.
|
||||
*/
|
||||
faction?: (number | null) | Faction;
|
||||
/**
|
||||
* Arma CfgVehicles faction classes counted by this pool (e.g. 'BLU_F', 'PTF'). Matched case-insensitively against the placed unit's faction; units of unmatched factions are free.
|
||||
*/
|
||||
armaFactions?: string[] | null;
|
||||
/**
|
||||
* Units available. Decremented by counted Zeus placements, refunded on curator deletions. May go negative (overdraft is allowed; spawning is never blocked).
|
||||
*/
|
||||
available?: number | null;
|
||||
/**
|
||||
* Disabled pools are hidden from the game server and the Zeus HUD.
|
||||
*/
|
||||
enabled?: boolean | null;
|
||||
updatedAt: string;
|
||||
createdAt: string;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "game-event-logs".
|
||||
|
|
@ -2844,6 +2880,11 @@ export interface GameEventLog {
|
|||
| 'game-event-logs:update'
|
||||
| 'game-event-logs:delete'
|
||||
| 'admin:game-event-logs:manage'
|
||||
| 'reinforcement-pools:create'
|
||||
| 'reinforcement-pools:read'
|
||||
| 'reinforcement-pools:update'
|
||||
| 'reinforcement-pools:delete'
|
||||
| 'admin:reinforcement-pools:manage'
|
||||
| 'maps:create'
|
||||
| 'maps:read'
|
||||
| 'maps:update'
|
||||
|
|
@ -3013,6 +3054,7 @@ export interface GameEventLog {
|
|||
| 'promotion-nominations'
|
||||
| 'leadership-transfers'
|
||||
| 'player-flags'
|
||||
| 'reinforcement-pools'
|
||||
)
|
||||
| null;
|
||||
targetId?: number | null;
|
||||
|
|
@ -6219,6 +6261,24 @@ export interface PayloadMcpApiKey {
|
|||
*/
|
||||
delete?: boolean | null;
|
||||
};
|
||||
reinforcementPools?: {
|
||||
/**
|
||||
* Allow clients to find reinforcement-pools.
|
||||
*/
|
||||
find?: boolean | null;
|
||||
/**
|
||||
* Allow clients to create reinforcement-pools.
|
||||
*/
|
||||
create?: boolean | null;
|
||||
/**
|
||||
* Allow clients to update reinforcement-pools.
|
||||
*/
|
||||
update?: boolean | null;
|
||||
/**
|
||||
* Allow clients to delete reinforcement-pools.
|
||||
*/
|
||||
delete?: boolean | null;
|
||||
};
|
||||
laborClassifications?: {
|
||||
/**
|
||||
* Allow clients to find labor-classifications.
|
||||
|
|
@ -7582,6 +7642,10 @@ export interface PayloadLockedDocument {
|
|||
relationTo: 'player-flags';
|
||||
value: number | PlayerFlag;
|
||||
} | null)
|
||||
| ({
|
||||
relationTo: 'reinforcement-pools';
|
||||
value: number | ReinforcementPool;
|
||||
} | null)
|
||||
| ({
|
||||
relationTo: 'labor-classifications';
|
||||
value: number | LaborClassification;
|
||||
|
|
@ -8245,6 +8309,19 @@ export interface PlayerFlagsSelect<T extends boolean = true> {
|
|||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "reinforcement-pools_select".
|
||||
*/
|
||||
export interface ReinforcementPoolsSelect<T extends boolean = true> {
|
||||
name?: T;
|
||||
faction?: T;
|
||||
armaFactions?: T;
|
||||
available?: T;
|
||||
enabled?: T;
|
||||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "labor-classifications_select".
|
||||
|
|
@ -10481,6 +10558,14 @@ export interface PayloadMcpApiKeysSelect<T extends boolean = true> {
|
|||
update?: T;
|
||||
delete?: T;
|
||||
};
|
||||
reinforcementPools?:
|
||||
| T
|
||||
| {
|
||||
find?: T;
|
||||
create?: T;
|
||||
update?: T;
|
||||
delete?: T;
|
||||
};
|
||||
laborClassifications?:
|
||||
| T
|
||||
| {
|
||||
|
|
|
|||
|
|
@ -56,6 +56,7 @@ import { GameNpcs } from "@/collections/game/GameNpcs";
|
|||
import { NpcStaffing } from "@/collections/game/NpcStaffing";
|
||||
import { NpcDialogues } from "@/collections/game/NpcDialogues";
|
||||
import { PlayerFlags } from "@/collections/game/PlayerFlags";
|
||||
import { ReinforcementPools } from "@/collections/game/ReinforcementPools";
|
||||
import { LaborClassifications } from "@/collections/game/LaborClassifications";
|
||||
import { Experience } from "@/collections/users/Experience";
|
||||
import { BankAccounts } from "@/collections/banking/BankAccounts";
|
||||
|
|
@ -272,6 +273,7 @@ const collections = [
|
|||
NpcStaffing,
|
||||
NpcDialogues,
|
||||
PlayerFlags,
|
||||
ReinforcementPools,
|
||||
LaborClassifications,
|
||||
GameEventLogs,
|
||||
|
||||
|
|
|
|||
|
|
@ -501,6 +501,16 @@ export const PERMISSION_GROUPS: PermissionGroup[] = [
|
|||
{ value: "admin:game-event-logs:manage", label: "Manage Admin Page" },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: "Reinforcement Pools",
|
||||
permissions: [
|
||||
{ value: "reinforcement-pools:create", label: "Create" },
|
||||
{ value: "reinforcement-pools:read", label: "Read" },
|
||||
{ value: "reinforcement-pools:update", label: "Update" },
|
||||
{ value: "reinforcement-pools:delete", label: "Delete" },
|
||||
{ value: "admin:reinforcement-pools:manage", label: "Manage Admin Page" },
|
||||
],
|
||||
},
|
||||
|
||||
// ---- World ---------------------------------------------------------------
|
||||
{
|
||||
|
|
@ -984,6 +994,11 @@ export const ALL_PERMISSION_VALUES = PERMISSION_GROUPS.flatMap((g) =>
|
|||
"game-event-logs:update",
|
||||
"game-event-logs:delete",
|
||||
"admin:game-event-logs:manage",
|
||||
"reinforcement-pools:create",
|
||||
"reinforcement-pools:read",
|
||||
"reinforcement-pools:update",
|
||||
"reinforcement-pools:delete",
|
||||
"admin:reinforcement-pools:manage",
|
||||
"maps:create",
|
||||
"maps:read",
|
||||
"maps:update",
|
||||
|
|
|
|||
|
|
@ -51,7 +51,8 @@ interface GameEventInput {
|
|||
| "ribbon-submissions"
|
||||
| "promotion-nominations"
|
||||
| "leadership-transfers"
|
||||
| "player-flags";
|
||||
| "player-flags"
|
||||
| "reinforcement-pools";
|
||||
targetId?: number;
|
||||
data?: Record<string, unknown>;
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -172,6 +172,11 @@ export const EventTypes = {
|
|||
PlayerKill: "combat:kill",
|
||||
PlayerDeath: "combat:death",
|
||||
|
||||
// Reinforcement pools (Arma Zeus soft limits)
|
||||
ReinforcementSpawn: "reinforcement:spawn",
|
||||
ReinforcementRefund: "reinforcement:refund",
|
||||
ReinforcementAdjust: "reinforcement:adjust",
|
||||
|
||||
// Helpdesk
|
||||
TicketCreate: "ticket:create",
|
||||
TicketReply: "ticket:reply",
|
||||
|
|
|
|||
249
tests/int/reinforcement-pools.int.spec.ts
Normal file
249
tests/int/reinforcement-pools.int.spec.ts
Normal file
|
|
@ -0,0 +1,249 @@
|
|||
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);
|
||||
});
|
||||
});
|
||||
});
|
||||
Loading…
Reference in a new issue