1
0
Fork 0

feat(arma-bridge): sync limited-arsenal locker stock with the game

New locker-sync bridge: web-originated storedAssets edits enqueue a
locker.apply command sent to the game, and game-side locker.sync merges
feed back into the member UI. Position/equipment layout is preserved across
merges. Adds the lockers service, LockerStorages + ArmaSyncEvents wiring and
integration tests. Docs in docs/arma-bridge/locker-sync.md.
This commit is contained in:
Jason Fraley 2026-10-05 03:17:59 -04:00
parent 12cb62b487
commit 5963082f9d
5 changed files with 1139 additions and 0 deletions

View file

@ -0,0 +1,145 @@
# Locker Sync Contract
Binding contract for limited-arsenal storage sync between the Arma 3 mods and
the web app. It covers **personal lockers** (web `locker-storages`, one per
member) and **structure item storage** (web `game-structures.storedAssets`,
e.g. the Superstructure). Implement exactly what is written here; do not
redesign while implementing.
## Overview
In-game, each storage is a limited ACE Arsenal: every item class has a finite
quantity. The game server is authoritative for what a player physically takes
or deposits in a session; the web app is authoritative for everything outside
the session (member UI edits, admin edits, future crafting/market flows). Two
existing bridge channels carry the data; **no new extension channels** (same
precedent as crate sync — the Python module is closed):
- **Events (mod to web)**: the `locker.*` event family, delivered through the
existing `flush_events` ingestion (`POST /api/arma/v1/events`).
- **Commands (web to mod)**: the `locker.*` command types, delivered through
the existing `pull_commands` / `ack_command` loop.
## Instance identity
An `instanceRef` string identifies one storage:
| Form | Meaning |
|---|---|
| `personal:<steamId>` | The personal locker of the member whose `users.steamId` matches. |
| `structure:<storageSlug>` | The `storedAssets` of the `game-structures` row with this `storageSlug` (e.g. `structure:superstructure`). |
- The mod NEVER embeds a server identifier in an instanceRef. The web resolves
the owning server authoritatively from the authenticated connection
(`eventId = ${serverId}:${event.id}`), exactly as in crate sync.
- `personal:` refs are derived from the opening player's UID at open time; the
same physical locker box serves every player with their own stock.
- `structure:` refs are bound to boxes by the TWWK Eden/Zeus module
(`StructureStorageSlug` argument). Only structures with a `storageSlug`
expose item storage to the game.
## Event family
Payloads are flat arrays (`fn_queueEvent` stores `[_id, _type, _payload,
serverTime]`, payload defaults to `[]`).
| Type | Payload | Meaning |
|---|---|---|
| `locker.sync` | `[instanceRef, [[itemClass, count], ...]]` | Full stock snapshot for one instance after a committed change. |
| `locker.request` | `[instanceRef]` | The game asks the web to push current state for this instance (mission start, player connect, availability refresh). |
`locker.sync` snapshot rules:
- TOP-LEVEL stock only: `[itemClass, count]` pairs, one per class, counts are
integers >= 0. Classes with count 0 MAY be included (explicit depletion) or
omitted (treated as unknown/absent, not as zero — see merge rules).
- Emitted after every committed stock mutation (take settlement, deposit,
Zeus/Eden edit, `locker.apply` application) while the bridge is enabled.
- Dedup is web-side by `eventId`; retried flushes never double-apply.
Snapshots are idempotent wholesale state, so re-application is safe.
## Web-side consumption rules
`locker.sync` merges into the instance's item array keyed by Arma class name:
- `personal:<steamId>`: resolve `users.steamId` → that user's `locker-storages`
row (created lazily if a linked user has none). Unlinked Steam IDs are
logged and skipped (same rule as money sync); the game keeps a session-only
stock for them.
- `structure:<storageSlug>`: resolve the `game-structures` row by `storageSlug`.
Unknown slug is logged and skipped.
- Merge per entry by `asset.className`:
- Existing web entry whose class appears in the snapshot → `quantity` set to
the snapshot count. **All web-managed metadata is preserved**: `gridX`,
`gridY`, `rotated`, and the `equipment` group (attachments, skin,
customName) are never touched by the merge.
- Snapshot class with no web entry → create the entry (asset resolved by
`className`; unknown classes are skipped with a warning) and **auto-place**
it in the next free grid cell (row-major scan, unrotated). Equipment left
empty.
- Web entry whose class is absent from the snapshot → left untouched
(absence is not deletion; the game only reports classes it tracks).
- `itemCount` keeps deriving from the array length via its existing hook.
- Every merged write links the raw `arma-sync-events` row as provenance where
the storage model supports it.
`locker.request` handling:
- Enqueue exactly one `locker.apply` command for the requesting server with
the web's current full snapshot for that instanceRef. Unknown/unlinked
instanceRefs enqueue nothing.
## Command envelope and schemas
Envelope: `[commandId, commandType, payload]` (what `fn_pollCommands` passes
and `fn_executeCommand` destructures), stored in `arma-commands`.
| Type | Payload | Effect |
|---|---|---|
| `locker.apply` | `[instanceRef, [[itemClass, count], ...]]` | Server replaces the instance's stock wholesale with the given pairs, pushes availability to clients, and acks. |
- The web enqueues `locker.apply` when: (a) a member/admin edits locker items
or structure `storedAssets` in the UI (afterChange hook), or (b) a
`locker.request` event arrives. Target server: the most recently heartbeated
game server (single-server assumption, same as crate UI flows).
- The mod-side handler is registered through the bridge's command-handler
registry (`ptf_bridge_fnc_registerCommandHandler`); the bridge mod itself
stays storage-agnostic.
- Unknown instanceRef → the mod acks FAILED with an error string; the command
is marked `failed` web-side and is not retried by the mod.
- Ack shape is the existing `[commandId, success, result, error]`; successful
acks carry the applied instanceRef in `result` for traceability.
- Echo guard: web writes that originate from a `locker.sync` merge mark
`req.context.lockerSyncOrigin = true`; the afterChange enqueue hook skips
such writes so a game-originated change never bounces back as a command.
## Failure rules
- Web event processors never throw: malformed payloads are logged and skipped;
one bad event never aborts the batch or rolls back raw-event ingestion.
- Duplicate eventIds are deduped (counted as duplicates, no double-apply).
- Bridge disabled/unreachable: the mod keeps full session-local stock; queued
`locker.sync` events flush when the bridge returns (queue cap drops oldest,
per existing bridge behavior).
- Game store is volatile per mission (like crate registry): on mission start
the mod emits `locker.request` for every bound structure instance and per
connecting player, and the web replies with `locker.apply`.
## Security
- All channels sit behind `requireArmaServer` (`ARMA_BRIDGE_API_KEY` +
`x-arma-server-id`); server identity is always derived from the connection.
- The `storageAccess` group on `game-structures` (anyone / faction / roles /
users) governs **web UI** visibility/editing of `storedAssets` only; it does
not constrain the bridge (server-to-server) or in-game physical access.
## Mod-side behavior (TWWK `twwk_arsenal`)
- Server store: `instanceRef → (className → count)` in missionNamespace.
- Availability: a class is in the ACE Arsenal virtual-item set iff count > 0
(shared instances: global `addVirtualItems`/`removeVirtualItems`; personal:
targeted per-player local set).
- Settlement: client snapshots gear on `ace_arsenal_displayOpened`, diffs on
`ace_arsenal_displayClosed`, server validates/clamps and commits; live
over-take into containers is clamped per `ace_arsenal_cargoChanged`.
- Deposits run through the same commit path with the sign flipped.

View file

@ -1,5 +1,6 @@
import { CollectionConfig } from "payload";
import { requirePermission, hasPermission } from "@/utils/access-control/hasPermission";
import { enqueueLockerApplyForLockerDoc, isLockerSyncOrigin } from "@/lib/arma-bridge/lockers";
export const LockerStorages: CollectionConfig = {
slug: "locker-storages",
@ -8,6 +9,18 @@ export const LockerStorages: CollectionConfig = {
useAsTitle: "name",
defaultColumns: ["name", "ownerUser", "itemCount"],
},
hooks: {
afterChange: [
// Locker sync (docs/arma-bridge/locker-sync.md): web-originated item
// edits push a locker.apply command to the game. Writes that came from
// a locker.sync merge are marked in req.context and skipped.
async ({ doc, req, operation }) => {
if (operation !== "create" && operation !== "update") return;
if (isLockerSyncOrigin(req)) return;
await enqueueLockerApplyForLockerDoc(req.payload, doc);
},
],
},
access: {
read: async ({ req }) => {
if (!req.user) return false;

View file

@ -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 { processLockerEvent } from "@/lib/arma-bridge/lockers";
import { isOperationLedgerEnabled } from "@/lib/operations/rollout";
import { processOperationEvent } from "@/lib/operations/process";
@ -40,6 +41,15 @@ export const ArmaSyncEvents: CollectionConfig = {
// flushing). processMoneyEvent never throws.
await processMoneyEvent(req.payload, doc);
}
if (doc.type.startsWith("locker.")) {
// Awaited (same posture as box.*): locker writes join the raw-event
// transaction; processLockerEvent never throws.
try {
await processLockerEvent(req.payload, doc, req);
} catch (err) {
req.payload.logger.error(`[LockerSync] Failed to process locker event ${doc.eventId}: ${err}`);
}
}
},
],
},

View file

@ -0,0 +1,518 @@
import { randomBytes } from "crypto";
import type { Payload, PayloadRequest } from "payload";
import type { RawSyncEvent } from "@/lib/operations/types";
/**
* Limited-arsenal storage sync (Arma bridge) — contract: docs/arma-bridge/locker-sync.md.
*
* An `instanceRef` identifies one storage: `personal:<steamId>` (the member's
* locker-storages row) or `structure:<storageSlug>` (a game-structures row's
* storedAssets). The game sends `locker.sync` full snapshots after every
* committed stock change and `locker.request` when it needs web state; the web
* pushes `locker.apply` commands (full snapshots) on UI edits and on request.
*
* Merge rule: snapshots update asset+quantity only. Grid metadata (gridX,
* gridY, rotated, equipment) is web-managed and always preserved; entries the
* game does not know are left untouched; absence in a snapshot is NOT
* deletion. New game-side classes are auto-placed below the used grid rows.
*/
export interface LockerStockLine {
className: string;
count: number;
}
export type LockerInstanceRef =
| { kind: "personal"; steamId: string }
| { kind: "structure"; slug: string };
/** Hard cap on snapshot lines so a malformed event cannot build huge arrays. */
const MAX_STOCK_LINES = 1000;
const SLUG_PATTERN = /^[a-z0-9][a-z0-9-_]{1,63}$/;
export function formatInstanceRef(ref: LockerInstanceRef): string {
return ref.kind === "personal" ? `personal:${ref.steamId}` : `structure:${ref.slug}`;
}
export function parseInstanceRef(value: unknown): LockerInstanceRef | null {
if (typeof value !== "string") return null;
const sep = value.indexOf(":");
if (sep <= 0) return null;
const kind = value.slice(0, sep);
const key = value.slice(sep + 1).trim();
if (kind === "personal") {
if (key.length === 0 || key.length > 64) return null;
return { kind: "personal", steamId: key };
}
if (kind === "structure") {
if (!SLUG_PATTERN.test(key)) return null;
return { kind: "structure", slug: key };
}
return null;
}
/**
* Parses the snapshot half of a locker payload: [[itemClass, count], ...].
* Returns null only when the outer shape is not an array; individual bad
* lines are dropped (defensive, never-throws — same posture as crate sync).
*/
export function parseStockSnapshot(value: unknown): LockerStockLine[] | null {
if (!Array.isArray(value)) return null;
const lines: LockerStockLine[] = [];
for (const entry of value.slice(0, MAX_STOCK_LINES)) {
if (!Array.isArray(entry) || entry.length < 2) continue;
const className = entry[0];
const count = entry[1];
if (typeof className !== "string" || className.length === 0 || className.length > 200) continue;
if (typeof count !== "number" || !Number.isFinite(count)) continue;
lines.push({ className, count: Math.max(0, Math.round(count)) });
}
return lines;
}
function relId(value: unknown): number | null {
if (typeof value === "number") return value;
if (value !== null && typeof value === "object" && "id" in (value as { id: unknown })) {
const id = (value as { id: unknown }).id;
return typeof id === "number" ? id : null;
}
return null;
}
async function findUserIdBySteamId(payload: Payload, steamId: string): Promise<number | null> {
const users = await payload.find({
collection: "users",
where: { steamId: { equals: steamId } },
limit: 1,
depth: 0,
overrideAccess: true,
});
return users.docs[0]?.id ?? null;
}
/** The most recently heartbeated online server, per the locker-sync contract. */
export async function findLatestOnlineServerId(payload: Payload): Promise<number | null> {
const servers = await payload.find({
collection: "game-servers",
where: { status: { equals: "online" } },
sort: "-lastSeenAt",
limit: 1,
depth: 0,
overrideAccess: true,
});
return servers.docs[0]?.id ?? null;
}
/**
* Enqueues one `locker.apply` command. Targets the latest online server when
* no explicit server id is given. No-op (false) when no server is online —
* the game pulls state via locker.request when it next starts anyway.
*/
export async function enqueueLockerApply(
payload: Payload,
instanceRef: string,
stock: Array<[string, number]>,
serverId?: number,
): Promise<boolean> {
const target = serverId ?? (await findLatestOnlineServerId(payload));
if (target == null) {
payload.logger.warn(`[LockerSync] No online server; locker.apply for ${instanceRef} not enqueued`);
return false;
}
await payload.create({
collection: "arma-commands",
data: {
commandId: `locker-${randomBytes(12).toString("hex")}`,
server: target,
type: "locker.apply",
payload: [instanceRef, stock],
status: "queued",
},
overrideAccess: true,
depth: 0,
});
return true;
}
/**
* Converts a stored item array (locker-storages items / game-structures
* storedAssets) into [className, count] command pairs. Asset references are
* batch-resolved by id; entries without a resolvable className are skipped.
*/
export async function stockPairsFromItems(
payload: Payload,
items: unknown,
): Promise<Array<[string, number]>> {
if (!Array.isArray(items) || items.length === 0) return [];
const rows = items as Array<Record<string, unknown>>;
const assetIds = [
...new Set(rows.map((row) => relId(row.asset)).filter((v): v is number => v != null)),
];
if (assetIds.length === 0) return [];
const assets = await payload.find({
collection: "assets",
where: { id: { in: assetIds } },
limit: assetIds.length * 2,
depth: 0,
overrideAccess: true,
});
const classById = new Map<number, string>();
for (const asset of assets.docs) {
const className = (asset as { className?: unknown }).className;
if (typeof className === "string" && className.length > 0) classById.set(asset.id, className);
}
const pairs: Array<[string, number]> = [];
for (const row of rows) {
const assetId = relId(row.asset);
const className = assetId != null ? classById.get(assetId) : undefined;
const quantity = typeof row.quantity === "number" ? Math.round(row.quantity) : 0;
if (!className || quantity < 1) continue;
pairs.push([className, quantity]);
}
return pairs;
}
interface ExistingItemRow {
[key: string]: unknown;
}
/**
* Merges a game snapshot into a stored item array (contract merge rules):
* quantity updates in place for known classes (grid metadata preserved), new
* classes appended below the used rows, unknown-to-the-game entries untouched.
* Returns the new array (suitable as update `data.items` / `data.storedAssets`).
*/
export function mergeStockIntoItems(
existing: ExistingItemRow[],
snapshot: LockerStockLine[],
assetIdByClassName: Map<string, number>,
warn?: (message: string) => void,
): ExistingItemRow[] {
const merged = existing.map((row) => ({ ...row }));
const indexByClassName = new Map<string, number>();
merged.forEach((row, index) => {
if (typeof row.className === "string") indexByClassName.set(row.className, index);
});
let nextY =
merged.reduce((max, row) => {
const y = typeof row.gridY === "number" ? row.gridY : 0;
return Math.max(max, y);
}, -1) + 1;
for (const line of snapshot) {
const hit = indexByClassName.get(line.className);
if (hit !== undefined) {
merged[hit] = { ...merged[hit], quantity: line.count };
continue;
}
const assetId = assetIdByClassName.get(line.className);
if (assetId == null) {
warn?.(`[LockerSync] Snapshot class "${line.className}" has no matching asset; skipped`);
continue;
}
const row: ExistingItemRow = {
asset: assetId,
quantity: line.count,
gridX: 0,
gridY: nextY,
rotated: false,
className: line.className,
};
nextY += 1;
indexByClassName.set(line.className, merged.length);
merged.push(row);
}
return merged;
}
/**
* Resolves snapshot class names to asset ids (assets are keyed by className).
*/
async function findAssetIdsByClassName(
payload: Payload,
classNames: string[],
): Promise<Map<string, number>> {
const wanted = [...new Set(classNames)];
const map = new Map<string, number>();
if (wanted.length === 0) return map;
const assets = await payload.find({
collection: "assets",
where: { className: { in: wanted } },
limit: wanted.length * 2,
depth: 0,
overrideAccess: true,
});
for (const asset of assets.docs) {
const className = (asset as { className?: unknown }).className;
if (typeof className === "string") map.set(className, asset.id);
}
return map;
}
/** Marks the request so afterChange enqueue hooks skip game-originated writes. */
function markSyncOrigin(req: PayloadRequest | undefined): void {
if (!req) return;
req.context = { ...req.context, lockerSyncOrigin: true };
}
export function isLockerSyncOrigin(req: PayloadRequest): boolean {
return Boolean((req.context as Record<string, unknown> | undefined)?.lockerSyncOrigin);
}
/**
* Annotates stored rows with their asset className so mergeStockIntoItems can
* key by class. Stored rows reference assets by id; class names come from a
* batch lookup.
*/
async function annotateItemsWithClassName(
payload: Payload,
items: unknown,
): Promise<ExistingItemRow[]> {
if (!Array.isArray(items)) return [];
const rows = items as ExistingItemRow[];
const assetIds = [...new Set(rows.map((row) => relId(row.asset)).filter((v): v is number => v != null))];
if (assetIds.length === 0) return rows;
const assets = await payload.find({
collection: "assets",
where: { id: { in: assetIds } },
limit: assetIds.length * 2,
depth: 0,
overrideAccess: true,
});
const classById = new Map<number, string>();
for (const asset of assets.docs) {
const className = (asset as { className?: unknown }).className;
if (typeof className === "string") classById.set(asset.id, className);
}
return rows.map((row) => {
const assetId = relId(row.asset);
const className = assetId != null ? classById.get(assetId) : undefined;
return className ? { ...row, className } : row;
});
}
/**
* Consumes one `locker.*` raw sync event (contract: docs/arma-bridge/locker-sync.md).
* Never throws: malformed events are logged and skipped so raw-event ingestion
* is never rolled back by locker sync.
*/
export async function processLockerEvent(
payload: Payload,
raw: RawSyncEvent,
req?: PayloadRequest,
): Promise<void> {
try {
if (typeof raw.server !== "number") {
payload.logger.warn(`[LockerSync] Event ${raw.eventId} has no server; skipping (malformed)`);
return;
}
if (!Array.isArray(raw.payload)) {
payload.logger.warn(`[LockerSync] Event ${raw.eventId} payload is not an array; skipping`);
return;
}
const ref = parseInstanceRef(raw.payload[0]);
if (!ref) {
payload.logger.warn(`[LockerSync] Event ${raw.eventId} has a malformed instanceRef; skipping`);
return;
}
const refString = formatInstanceRef(ref);
if (raw.type === "locker.sync") {
const snapshot = parseStockSnapshot(raw.payload[1]);
if (!snapshot) {
payload.logger.warn(`[LockerSync] Event ${raw.eventId} has a malformed snapshot; skipping`);
return;
}
await applySnapshotToInstance(payload, ref, refString, snapshot, raw.eventId, req);
return;
}
if (raw.type === "locker.request") {
const stock = await currentStockForInstance(payload, ref);
if (stock === null) {
payload.logger.info(`[LockerSync] locker.request for unknown ${refString}; nothing enqueued`);
return;
}
await enqueueLockerApply(payload, refString, stock, raw.server);
return;
}
payload.logger.warn(`[LockerSync] Unknown locker event type "${raw.type}" for ${raw.eventId}; skipping`);
} catch (error) {
payload.logger.error(
`[LockerSync] Failed to process locker event ${raw.eventId}: ${error instanceof Error ? error.message : "unknown error"}`,
);
}
}
/**
* Applies one locker.sync snapshot to its instance. Returns after merging;
* all writes carry the sync-origin sentinel so afterChange hooks do not echo
* the change back to the game as a locker.apply command.
*/
async function applySnapshotToInstance(
payload: Payload,
ref: LockerInstanceRef,
refString: string,
snapshot: LockerStockLine[],
eventId: string,
req?: PayloadRequest,
): Promise<void> {
const assetIds = await findAssetIdsByClassName(
payload,
snapshot.map((line) => line.className),
);
markSyncOrigin(req);
if (ref.kind === "personal") {
const userId = await findUserIdBySteamId(payload, ref.steamId);
if (!userId) {
payload.logger.info(
`[LockerSync] Steam ID ${ref.steamId} is not linked to a user; session-only stock, event ${eventId} skipped`,
);
return;
}
const lockers = await payload.find({
collection: "locker-storages",
where: { ownerUser: { equals: userId } },
limit: 1,
depth: 0,
overrideAccess: true,
req,
});
const locker = lockers.docs[0];
if (!locker) {
// Linked user without a locker yet: create it from the snapshot.
const items = mergeStockIntoItems([], snapshot, assetIds, (m) => payload.logger.warn(m));
await payload.create({
collection: "locker-storages",
data: { name: "Personal Locker", ownerUser: userId, items: items as never },
overrideAccess: true,
depth: 0,
req,
});
return;
}
const existing = await annotateItemsWithClassName(payload, (locker as { items?: unknown }).items);
const merged = mergeStockIntoItems(existing, snapshot, assetIds, (m) => payload.logger.warn(m));
await payload.update({
collection: "locker-storages",
id: locker.id,
data: { items: merged as never },
overrideAccess: true,
depth: 0,
req,
});
return;
}
const structures = await payload.find({
collection: "game-structures",
where: { storageSlug: { equals: ref.slug } },
limit: 1,
depth: 0,
overrideAccess: true,
req,
});
const structure = structures.docs[0];
if (!structure) {
payload.logger.warn(`[LockerSync] No game-structure with storageSlug "${ref.slug}"; event ${eventId} skipped`);
return;
}
const existing = await annotateItemsWithClassName(
payload,
(structure as { storedAssets?: unknown }).storedAssets,
);
const merged = mergeStockIntoItems(existing, snapshot, assetIds, (m) => payload.logger.warn(m));
await payload.update({
collection: "game-structures",
id: structure.id,
data: { storedAssets: merged as never },
overrideAccess: true,
depth: 0,
req,
});
}
/**
* The web's current stock for an instance as [className, count] pairs.
* Null when the instance cannot be resolved (unknown slug / unlinked user);
* an EMPTY array is a valid, meaningful "known but empty" snapshot.
*/
async function currentStockForInstance(
payload: Payload,
ref: LockerInstanceRef,
): Promise<Array<[string, number]> | null> {
if (ref.kind === "personal") {
const userId = await findUserIdBySteamId(payload, ref.steamId);
if (!userId) return null;
const lockers = await payload.find({
collection: "locker-storages",
where: { ownerUser: { equals: userId } },
limit: 1,
depth: 0,
overrideAccess: true,
});
const locker = lockers.docs[0];
if (!locker) return [];
return stockPairsFromItems(payload, (locker as { items?: unknown }).items);
}
const structures = await payload.find({
collection: "game-structures",
where: { storageSlug: { equals: ref.slug } },
limit: 1,
depth: 0,
overrideAccess: true,
});
const structure = structures.docs[0];
if (!structure) return null;
return stockPairsFromItems(payload, (structure as { storedAssets?: unknown }).storedAssets);
}
/**
* afterChange helper for locker-storages: pushes the member's new stock to
* the game as locker.apply. Skips when the owner has no Steam ID (nothing to
* address) or when no server is online. Never throws — hook safety.
*/
export async function enqueueLockerApplyForLockerDoc(payload: Payload, doc: unknown): Promise<void> {
try {
const row = doc as { ownerUser?: unknown; items?: unknown };
const ownerId = relId(row.ownerUser);
if (ownerId == null) return;
const owner = await payload.findByID({
collection: "users",
id: ownerId,
depth: 0,
overrideAccess: true,
});
const steamId = (owner as { steamId?: unknown } | null)?.steamId;
if (typeof steamId !== "string" || steamId.length === 0) return;
const stock = await stockPairsFromItems(payload, row.items);
await enqueueLockerApply(payload, `personal:${steamId}`, stock);
} catch (error) {
payload.logger.error(
`[LockerSync] Failed to enqueue locker.apply for locker: ${error instanceof Error ? error.message : "unknown error"}`,
);
}
}
/**
* afterChange helper for game-structures: pushes storedAssets to the game as
* locker.apply when the structure exposes item storage (storageSlug set).
* Never throws — hook safety.
*/
export async function enqueueLockerApplyForStructureDoc(payload: Payload, doc: unknown): Promise<void> {
try {
const row = doc as { storageSlug?: unknown; storedAssets?: unknown };
const slug = typeof row.storageSlug === "string" ? row.storageSlug.trim() : "";
if (!slug) return;
const stock = await stockPairsFromItems(payload, row.storedAssets);
await enqueueLockerApply(payload, `structure:${slug}`, stock);
} catch (error) {
payload.logger.error(
`[LockerSync] Failed to enqueue locker.apply for structure: ${error instanceof Error ? error.message : "unknown error"}`,
);
}
}

View file

@ -0,0 +1,453 @@
import { getPayload, Payload } from "payload";
import config from "@/payload.config";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import {
formatInstanceRef,
mergeStockIntoItems,
parseInstanceRef,
parseStockSnapshot,
processLockerEvent,
} from "@/lib/arma-bridge/lockers";
let payload: Payload;
const RUN = `locker-${Date.now().toString(36)}`;
const STEAM_ID = `${RUN}-steam-001`;
const UNLINKED = `${RUN}-steam-unlinked`;
const SLUG = `${RUN}-superstructure`;
const CLASS_A = "arifle_MX_F";
const CLASS_B = "ACE_bandage";
const LEXICAL_EMPTY = {
root: {
children: [{ text: "" }],
direction: null,
format: "" as const,
indent: 0,
type: "text",
version: 1,
},
};
let userId: number;
let assetAId: number;
let assetBId: number;
let resourceId: number;
let blueprintId: number;
let structureId: number;
let lockerId: number;
let serverId: number;
const commandIds: number[] = [];
let eventSeq = 0;
function lockerEvent(type: string, eventPayload: unknown[], server: number) {
eventSeq += 1;
return {
id: eventSeq,
eventId: `${RUN}:${eventSeq}`,
server,
type,
occurredAt: new Date().toISOString(),
payload: eventPayload,
};
}
async function findLockerApplyCommands(): Promise<{ id: number; payload: unknown }[]> {
const found = await payload.find({
collection: "arma-commands",
where: { type: { equals: "locker.apply" } },
limit: 100,
depth: 0,
overrideAccess: true,
});
return found.docs.map((doc) => ({ id: doc.id, payload: (doc as { payload?: unknown }).payload }));
}
async function lockerDoc() {
return (await payload.findByID({
collection: "locker-storages",
id: lockerId,
depth: 0,
overrideAccess: true,
})) as unknown as { items: Record<string, unknown>[]; itemCount: number };
}
describe("Arma locker sync", () => {
beforeAll(async () => {
const payloadConfig = await config;
payload = await getPayload({ config: payloadConfig });
const user = await payload.create({
collection: "users",
data: {
username: `${RUN}-player`,
discordUsername: `${RUN}-player-discord`,
displayName: `${RUN} Player`,
steamId: STEAM_ID,
password: "Test1234",
},
overrideAccess: true,
depth: 0,
});
userId = user.id;
for (const [className, name] of [
[CLASS_A, `${RUN} MX Rifle`],
[CLASS_B, `${RUN} Bandage`],
] as const) {
const asset = await payload.create({
collection: "assets",
data: {
name,
className,
assetType: className === CLASS_A ? "weapon" : "medical",
approvalStatus: "approved",
} as never,
draft: false,
overrideAccess: true,
depth: 0,
});
if (className === CLASS_A) assetAId = asset.id;
else assetBId = asset.id;
}
const resource = await payload.create({
collection: "resources",
data: {
name: `${RUN} Steel`,
codeName: `${RUN}-steel`,
approvalStatus: "in_progress",
type: "physical",
baseValue: 1,
rarity: "common",
unitOfMeasure: "kg",
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} Superstructure`,
codeName: `${RUN}-superstructure`,
approvalStatus: "in_progress",
description: LEXICAL_EMPTY,
category: "logistics",
materials: [{ resource: resourceId, amount: 1 }],
constructionDurationMinutes: 1,
terrainType: "land",
maxHealth: 100,
} as never,
overrideAccess: true,
depth: 0,
});
blueprintId = blueprint.id;
const structure = await payload.create({
collection: "game-structures",
data: {
name: `${RUN} Superstructure`,
type: blueprintId,
constructionStatus: "complete",
storageSlug: SLUG,
} as never,
overrideAccess: true,
depth: 0,
});
structureId = structure.id;
});
afterAll(async () => {
for (const id of commandIds) {
await payload.delete({ collection: "arma-commands", id, overrideAccess: true }).catch(() => {});
}
if (lockerId) {
await payload.delete({ collection: "locker-storages", id: lockerId, 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(() => {});
}
for (const id of [assetAId, assetBId]) {
if (id) await payload.delete({ collection: "assets", id, overrideAccess: true }).catch(() => {});
}
if (serverId) {
await payload.delete({ collection: "game-servers", id: serverId, overrideAccess: true }).catch(() => {});
}
if (userId) {
const profiles = await payload.find({
collection: "profiles",
where: { user: { equals: userId } },
depth: 0,
overrideAccess: true,
});
for (const profile of profiles.docs) {
await payload.delete({ collection: "profiles", id: profile.id, overrideAccess: true }).catch(() => {});
}
await payload.delete({ collection: "users", id: userId, overrideAccess: true }).catch(() => {});
}
});
describe("parseInstanceRef", () => {
it("parses personal and structure refs", () => {
expect(parseInstanceRef(`personal:${STEAM_ID}`)).toEqual({ kind: "personal", steamId: STEAM_ID });
expect(parseInstanceRef("structure:superstructure")).toEqual({
kind: "structure",
slug: "superstructure",
});
expect(formatInstanceRef({ kind: "personal", steamId: "abc" })).toBe("personal:abc");
});
it("rejects malformed refs", () => {
expect(parseInstanceRef(null)).toBeNull();
expect(parseInstanceRef("nope")).toBeNull();
expect(parseInstanceRef("personal:")).toBeNull();
expect(parseInstanceRef("structure:Bad Slug!")).toBeNull();
expect(parseInstanceRef("other:x")).toBeNull();
});
});
describe("parseStockSnapshot", () => {
it("parses [[class, count], ...] and clamps counts", () => {
expect(
parseStockSnapshot([
[CLASS_A, 3],
[CLASS_B, 2.6],
]),
).toEqual([
{ className: CLASS_A, count: 3 },
{ className: CLASS_B, count: 3 },
]);
});
it("returns null for non-arrays and drops bad lines", () => {
expect(parseStockSnapshot("nope")).toBeNull();
expect(parseStockSnapshot([[CLASS_A, "x"], ["", 1], [CLASS_B, 2]])).toEqual([
{ className: CLASS_B, count: 2 },
]);
});
});
describe("mergeStockIntoItems", () => {
it("preserves grid metadata, appends new classes, leaves unknown entries", () => {
const existing = [
{ asset: 1, quantity: 2, gridX: 3, gridY: 4, rotated: true, className: CLASS_A, equipment: { customName: "Frank's Karma" } },
{ asset: 9, quantity: 1, gridX: 0, gridY: 0, rotated: false, className: "other_class" },
];
const assetIds = new Map<string, number>([
[CLASS_A, 1],
[CLASS_B, 2],
]);
const merged = mergeStockIntoItems(
existing,
[
{ className: CLASS_A, count: 7 },
{ className: CLASS_B, count: 10 },
{ className: "no_such_asset", count: 1 },
],
assetIds,
);
expect(merged).toHaveLength(3);
expect(merged[0]).toMatchObject({ quantity: 7, gridX: 3, gridY: 4, rotated: true });
expect((merged[0].equipment as { customName: string }).customName).toBe("Frank's Karma");
expect(merged[1]).toMatchObject({ className: "other_class", quantity: 1 });
expect(merged[2]).toMatchObject({ asset: 2, quantity: 10, gridX: 0, gridY: 5, rotated: false });
});
});
describe("locker.sync (personal)", () => {
it("creates the linked user's locker from the first snapshot", async () => {
await expect(
processLockerEvent(payload, lockerEvent("locker.sync", [`personal:${STEAM_ID}`, [[CLASS_A, 2]]], 1)),
).resolves.toBeUndefined();
const lockers = await payload.find({
collection: "locker-storages",
where: { ownerUser: { equals: userId } },
limit: 1,
depth: 0,
overrideAccess: true,
});
expect(lockers.docs).toHaveLength(1);
lockerId = lockers.docs[0].id;
const doc = await lockerDoc();
expect(doc.itemCount).toBe(1);
expect(doc.items[0]).toMatchObject({ asset: assetAId, quantity: 2, gridX: 0, gridY: 0, rotated: false });
});
it("preserves web-managed grid metadata on later syncs", async () => {
await payload.update({
collection: "locker-storages",
id: lockerId,
data: {
items: [
{
asset: assetAId,
quantity: 2,
gridX: 3,
gridY: 4,
rotated: true,
equipment: { customName: "Frank's Karma" },
},
],
} as never,
overrideAccess: true,
depth: 0,
});
await processLockerEvent(
payload,
lockerEvent("locker.sync", [`personal:${STEAM_ID}`, [[CLASS_A, 7], [CLASS_B, 10]]], 1),
);
const doc = await lockerDoc();
expect(doc.itemCount).toBe(2);
const byAsset = new Map(doc.items.map((item) => [item.asset, item]));
expect(byAsset.get(assetAId)).toMatchObject({
quantity: 7,
gridX: 3,
gridY: 4,
rotated: true,
equipment: { customName: "Frank's Karma" },
});
expect(byAsset.get(assetBId)).toMatchObject({ quantity: 10, gridX: 0, gridY: 5, rotated: false });
});
it("treats absence as not-deletion and skips unknown classes", async () => {
await processLockerEvent(
payload,
lockerEvent("locker.sync", [`personal:${STEAM_ID}`, [[CLASS_A, 1], ["no_such_class", 3]]], 1),
);
const doc = await lockerDoc();
expect(doc.itemCount).toBe(2);
const byAsset = new Map(doc.items.map((item) => [item.asset, item]));
expect(byAsset.get(assetAId)).toMatchObject({ quantity: 1 });
expect(byAsset.get(assetBId)).toMatchObject({ quantity: 10 });
});
it("skips unlinked Steam IDs without creating anything", async () => {
const before = await payload.find({ collection: "locker-storages", limit: 100, depth: 0, overrideAccess: true });
await expect(
processLockerEvent(payload, lockerEvent("locker.sync", [`personal:${UNLINKED}`, [[CLASS_A, 5]]], 1)),
).resolves.toBeUndefined();
const after = await payload.find({ collection: "locker-storages", limit: 100, depth: 0, overrideAccess: true });
expect(after.totalDocs).toBe(before.totalDocs);
});
it("is idempotent for repeated snapshots", async () => {
const event = lockerEvent("locker.sync", [`personal:${STEAM_ID}`, [[CLASS_A, 1]]], 1);
await processLockerEvent(payload, event);
await processLockerEvent(payload, { ...event });
const doc = await lockerDoc();
expect(doc.itemCount).toBe(2);
});
});
describe("locker.sync (structure)", () => {
it("merges into game-structures storedAssets by storageSlug", async () => {
await processLockerEvent(
payload,
lockerEvent("locker.sync", [`structure:${SLUG}`, [[CLASS_A, 4]]], 1),
);
const structure = (await payload.findByID({
collection: "game-structures",
id: structureId,
depth: 0,
overrideAccess: true,
})) as unknown as { storedAssets: Record<string, unknown>[]; storedAssetCount: number };
expect(structure.storedAssetCount).toBe(1);
expect(structure.storedAssets[0]).toMatchObject({ asset: assetAId, quantity: 4 });
});
it("skips unknown slugs without throwing", async () => {
await expect(
processLockerEvent(payload, lockerEvent("locker.sync", [`structure:${RUN}-missing`, [[CLASS_A, 4]]], 1)),
).resolves.toBeUndefined();
});
});
describe("locker.request + locker.apply enqueue", () => {
it("enqueues exactly one locker.apply for the requesting server with current stock", async () => {
const server = await payload.create({
collection: "game-servers",
data: {
serverId: `${RUN}-srv`,
name: `${RUN} Test Server`,
status: "online",
lastSeenAt: new Date().toISOString(),
} as never,
overrideAccess: true,
depth: 0,
});
serverId = server.id;
await processLockerEvent(payload, lockerEvent("locker.request", [`personal:${STEAM_ID}`], serverId));
const commands = await findLockerApplyCommands();
commandIds.push(...commands.map((command) => command.id));
expect(commands).toHaveLength(1);
const [instanceRef, stock] = commands[0].payload as [string, [string, number][]];
expect(instanceRef).toBe(`personal:${STEAM_ID}`);
expect(stock).toContainEqual([CLASS_A, 1]);
expect(stock).toContainEqual([CLASS_B, 10]);
});
it("enqueues nothing for unknown instances", async () => {
await processLockerEvent(payload, lockerEvent("locker.request", [`structure:${RUN}-missing`], serverId));
const commands = await findLockerApplyCommands();
expect(commands).toHaveLength(1);
});
});
describe("echo guard", () => {
it("web-originated locker edits enqueue locker.apply; sync-origin writes do not", async () => {
const beforeCommands = await findLockerApplyCommands();
const beforeIds = new Set(beforeCommands.map((command) => command.id));
const doc = await lockerDoc();
await payload.update({
collection: "locker-storages",
id: lockerId,
data: {
items: doc.items.map((item) =>
item.asset === assetAId ? { ...item, quantity: 42 } : item,
),
} as never,
overrideAccess: true,
depth: 0,
});
const afterEdit = await findLockerApplyCommands();
const newCommands = afterEdit.filter((command) => !beforeIds.has(command.id));
commandIds.push(...newCommands.map((command) => command.id));
expect(newCommands).toHaveLength(1);
const [instanceRef, stock] = newCommands[0].payload as [string, [string, number][]];
expect(instanceRef).toBe(`personal:${STEAM_ID}`);
expect(stock).toContainEqual([CLASS_A, 42]);
const docAgain = await lockerDoc();
await payload.update({
collection: "locker-storages",
id: lockerId,
data: {
items: docAgain.items.map((item) =>
item.asset === assetAId ? { ...item, quantity: 43 } : item,
),
} as never,
context: { lockerSyncOrigin: true },
overrideAccess: true,
depth: 0,
});
const afterSyncWrite = await findLockerApplyCommands();
expect(afterSyncWrite.filter((command) => !beforeIds.has(command.id))).toHaveLength(1);
});
});
});