feat(arma-bridge): handle garage deposit, withdraw, and sync events
This commit is contained in:
parent
6c1bbda944
commit
3f15fbfb11
5 changed files with 758 additions and 17 deletions
138
docs/arma-bridge/garage-sync.md
Normal file
138
docs/arma-bridge/garage-sync.md
Normal file
|
|
@ -0,0 +1,138 @@
|
||||||
|
# Garage Sync Contract
|
||||||
|
|
||||||
|
Binding contract for vehicle-garage sync between the Arma 3 addon and the web
|
||||||
|
app. It covers **structure vehicle bays** (the Garage view at
|
||||||
|
`/logistics/garage`): parking, dispatching, and state (fuel/damage) of specific
|
||||||
|
vehicle **instances**. Implement exactly what is written here; do not redesign
|
||||||
|
while implementing.
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
The Garage is a grid inventory of vehicle instances parked in structure vehicle
|
||||||
|
bays. The web app owns placement (grid cells are pure web bookkeeping, never
|
||||||
|
sent to the game); the game owns physical existence. Every physical vehicle
|
||||||
|
instance carries a `bridgeUid` assigned by the addon so two identical trucks are
|
||||||
|
distinguishable and fuel/damage stay honest per instance.
|
||||||
|
|
||||||
|
**Authority and physical despawn policy.** Until the addon ships, the garage is
|
||||||
|
**web-authoritative**: dispatch/store only change web state and enqueue commands
|
||||||
|
that no client consumes yet. Once the addon implements this contract:
|
||||||
|
|
||||||
|
- `garage.dispatch` means the physical object must **despawn from the bay**. The
|
||||||
|
unit relocates through game logic (cargo plane, sea port, scenario start),
|
||||||
|
never by driving out of the garage cell.
|
||||||
|
- `garage.store` means the addon must **spawn (or relocate) the instance at this
|
||||||
|
garage** with the given fuel and damage.
|
||||||
|
- `garage.apply` is a full reconciliation of the bay: spawn missing entries,
|
||||||
|
update existing ones, and despawn bay objects whose `bridgeUid` is absent
|
||||||
|
from the list.
|
||||||
|
- Cell coordinates are never transmitted. A web-side drag that only rearranges
|
||||||
|
cells must not produce any game-side movement.
|
||||||
|
|
||||||
|
## Instance identity
|
||||||
|
|
||||||
|
| Ref | Meaning |
|
||||||
|
|---|---|
|
||||||
|
| `garage:<storageSlug>` | One structure's vehicle bay. `<storageSlug>` is the structure's existing `storageSlug` field (the same slug the arsenal module binds to via `structure:<slug>`). No separate garage slug exists (assumption A1). |
|
||||||
|
|
||||||
|
A vehicle instance is identified on the wire by its `bridgeUid`: an opaque
|
||||||
|
addon-assigned string (1-64 chars, `[A-Za-z0-9_-]+`), stable for the lifetime of
|
||||||
|
the physical object and persisted across missions if the object persists. The
|
||||||
|
web claims unknown instances by classname match against unassigned vehicles at
|
||||||
|
that structure (first-tag-wins, provenance logged); otherwise it creates a new
|
||||||
|
`game-vehicles` row.
|
||||||
|
|
||||||
|
`fuel` is a fraction of tank capacity (0..1). `damage` is a fraction of total
|
||||||
|
damage (0 = intact, 1 = destroyed). Both are clamped by the web; out-of-range or
|
||||||
|
non-finite values fall back to 0.
|
||||||
|
|
||||||
|
## Event family
|
||||||
|
|
||||||
|
Payloads are flat arrays (`fn_queueEvent` stores `[_id, _type, _payload,
|
||||||
|
serverTime]`, payload defaults to `[]`). Events ride the existing
|
||||||
|
`POST /api/arma/v1/events` flush; dedup is by the unique `eventId`
|
||||||
|
(`<serverId>:<localId>`), so retries are no-ops.
|
||||||
|
|
||||||
|
| Type | Payload | Meaning |
|
||||||
|
|---|---|---|
|
||||||
|
| `garage.deposit` | `[garageRef, bridgeUid, classname, fuel, damage]` | An instance entered the bay and is parked. |
|
||||||
|
| `garage.withdraw` | `[garageRef, bridgeUid, classname, fuel, damage]` | A known instance physically left the bay (driven out, destroyed in place, deleted). |
|
||||||
|
| `garage.sync` | `[garageRef, [[bridgeUid, classname, fuel, damage], ...]]` | Full snapshot of instances currently parked in the bay. |
|
||||||
|
| `garage.request` | `[garageRef]` | The game asks the web to push current state for this garage (mission start, garage module load). |
|
||||||
|
|
||||||
|
## Web-side consumption rules
|
||||||
|
|
||||||
|
Processed from the `arma-sync-events` afterChange router (`src/lib/arma-bridge/garages.ts`):
|
||||||
|
|
||||||
|
1. **Claim or create.** Resolve `bridgeUid` to a `game-vehicles` row. Unknown
|
||||||
|
uid: claim the oldest untagged (null `bridgeUid`) instance whose populated
|
||||||
|
template `classname` matches, at the structure named by `garageRef`
|
||||||
|
(first-tag-wins; the claim is logged with the event id as provenance). No
|
||||||
|
candidate: create a new `game-vehicles` instance from the template matching
|
||||||
|
`classname`; unknown classnames are skipped with a warning.
|
||||||
|
2. **State merge.** Apply `fuel` (scaled to the template's `fuelCapacity`) and
|
||||||
|
`damage` (scaled to the template's `maxHealth`). `damage >= 1` sets status
|
||||||
|
`destroyed`; recovery below 1 clears `destroyed`/`damaged` back to `idle`.
|
||||||
|
Statuses `assigned` and `in_transit` are never overwritten by sync.
|
||||||
|
3. **Placement.** Deposit/sync entries without a cell are auto-placed row-major
|
||||||
|
into free bay cells. Cells already set on web rows are **preserved**; sync
|
||||||
|
never moves parked vehicles. A snapshot line for an unknown-to-the-game row
|
||||||
|
updates state only; absence from a snapshot is **not** deletion or
|
||||||
|
withdrawal.
|
||||||
|
4. **Withdraw.** Clears the instance's bay cells and `deployedAt`, sets status
|
||||||
|
`in_transit` (unless destroyed), keeps `bridgeUid`.
|
||||||
|
5. **Echo guard.** All writes made while processing garage events run with
|
||||||
|
`req.context.garageSyncOrigin = true`. Garage commands (`garage.apply`,
|
||||||
|
`garage.dispatch`, `garage.store`) are enqueued only by explicit user
|
||||||
|
actions, so sync-originated writes never bounce back as commands.
|
||||||
|
6. Processors **never throw**: malformed payloads log a warning and return;
|
||||||
|
unexpected errors are caught and logged so event ingestion cannot roll back.
|
||||||
|
|
||||||
|
## Command envelope and schemas
|
||||||
|
|
||||||
|
Envelope: `[commandId, commandType, payload]` (what `fn_pollCommands` passes
|
||||||
|
and `fn_executeCommand` destructures), stored in `arma-commands` and pulled via
|
||||||
|
`GET /api/arma/v1/commands/pull`. Commands target the most recently heartbeated
|
||||||
|
online game server (single-server assumption, same as locker sync).
|
||||||
|
|
||||||
|
| Type | Payload | Effect |
|
||||||
|
|---|---|---|
|
||||||
|
| `garage.apply` | `[garageRef, [[bridgeUid, classname, fuel, damage], ...]]` | Full state push for the bay; the addon reconciles as described above. Sent in response to `garage.request`. |
|
||||||
|
| `garage.dispatch` | `[garageRef, bridgeUid, classname, fuel, damage]` | Despawn this instance from the bay; it is now in transit (web cleared its cell and location). |
|
||||||
|
| `garage.store` | `[garageRef, bridgeUid, classname, fuel, damage]` | Spawn/relocate this instance into this garage bay. |
|
||||||
|
|
||||||
|
Instances without a `bridgeUid` (never seen by the game) produce no commands;
|
||||||
|
their dispatch/store stays web-only.
|
||||||
|
|
||||||
|
## Failure rules
|
||||||
|
|
||||||
|
- Unknown `garageRef` slug: warn and skip the event.
|
||||||
|
- Malformed payload shape (not an array, bad ref, non-string uid, non-finite
|
||||||
|
numbers): warn and skip the whole event, never partially apply.
|
||||||
|
- Snapshot arrays are capped at 200 lines; longer snapshots are truncated with
|
||||||
|
a warning.
|
||||||
|
- Commands are fire-and-forget: no online server means the enqueue is skipped
|
||||||
|
with a warning (the web state is already committed).
|
||||||
|
- Duplicate `eventId` deliveries are dropped by the unique index before the
|
||||||
|
processor runs.
|
||||||
|
|
||||||
|
## Security
|
||||||
|
|
||||||
|
- Server identity always comes from the authenticated bridge connection
|
||||||
|
(`x-arma-bridge-key` + `x-arma-server-id`), never from event payloads.
|
||||||
|
- Events are read-only inserts for the bridge; the addon cannot call
|
||||||
|
`arma-commands` directly, only pull/ack them.
|
||||||
|
- Classnames and uids are treated as opaque strings; they are length-capped and
|
||||||
|
never interpolated into queries beyond Payload's parameterized `where`.
|
||||||
|
|
||||||
|
## Mod-side behavior (garage module)
|
||||||
|
|
||||||
|
- Assign each tracked physical vehicle a `bridgeUid` on spawn; persist it on the
|
||||||
|
object (e.g. `setVariable`) and reuse it in every event.
|
||||||
|
- Emit `garage.deposit` when an instance parks in a bay zone, `garage.withdraw`
|
||||||
|
when it leaves or dies, and batch `garage.sync` after any committed change to
|
||||||
|
bay contents (same flush cadence as locker sync).
|
||||||
|
- On module load / mission start, emit `garage.request` per configured bay and
|
||||||
|
apply the returned `garage.apply` snapshot.
|
||||||
|
- Ack every executed command through the existing commands ack route; failed
|
||||||
|
executions ack with `success: false` and an error string.
|
||||||
|
|
@ -18,23 +18,17 @@ function relId(value: unknown): number | null {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Field-level gate for storedAssets (web UI only — bridge sync writes use
|
* Request-independent core of the structure storage gate. Field-level access
|
||||||
* overrideAccess and are unaffected). Admins with game-structures:update
|
* (below) and server actions / pages that must evaluate the same rule without
|
||||||
* always pass; otherwise the structure's storageAccess mode decides:
|
* a PayloadRequest (e.g. the Garage view) both call this.
|
||||||
* anyone / specific roles (matched against the user's roleDocs) / specific
|
|
||||||
* users. A "faction" mode is deliberately not offered yet: members have no
|
|
||||||
* faction linkage in the users/profiles model, so it could not be evaluated.
|
|
||||||
*/
|
*/
|
||||||
async function canAccessStructureStorage({
|
export async function canUserAccessStructureStorage(
|
||||||
req,
|
payload: Parameters<typeof hasPermission>[0],
|
||||||
doc,
|
user: { id: number | string; roleDocs?: unknown } | null | undefined,
|
||||||
}: {
|
doc?: Record<string, unknown> | null,
|
||||||
req: PayloadRequest;
|
): Promise<boolean> {
|
||||||
doc?: Record<string, unknown> | null;
|
|
||||||
}): Promise<boolean> {
|
|
||||||
const user = req.user;
|
|
||||||
if (!user) return false;
|
if (!user) return false;
|
||||||
if (await hasPermission(req.payload, user, "game-structures:update")) return true;
|
if (await hasPermission(payload, user, "game-structures:update")) return true;
|
||||||
const access = (doc?.storageAccess ?? undefined) as
|
const access = (doc?.storageAccess ?? undefined) as
|
||||||
| { mode?: string; roles?: unknown; users?: unknown }
|
| { mode?: string; roles?: unknown; users?: unknown }
|
||||||
| undefined;
|
| undefined;
|
||||||
|
|
@ -54,11 +48,29 @@ async function canAccessStructureStorage({
|
||||||
}
|
}
|
||||||
if (mode === "users") {
|
if (mode === "users") {
|
||||||
const allowed = (Array.isArray(access?.users) ? (access.users as unknown[]) : []).map(relId);
|
const allowed = (Array.isArray(access?.users) ? (access.users as unknown[]) : []).map(relId);
|
||||||
return allowed.includes(user.id);
|
return allowed.some((id) => id != null && String(id) === String(user.id));
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Field-level gate for storedAssets (web UI only; bridge sync writes use
|
||||||
|
* overrideAccess and are unaffected). Admins with game-structures:update
|
||||||
|
* always pass; otherwise the structure's storageAccess mode decides:
|
||||||
|
* anyone / specific roles (matched against the user's roleDocs) / specific
|
||||||
|
* users. A "faction" mode is deliberately not offered yet: members have no
|
||||||
|
* faction linkage in the users/profiles model, so it could not be evaluated.
|
||||||
|
*/
|
||||||
|
async function canAccessStructureStorage({
|
||||||
|
req,
|
||||||
|
doc,
|
||||||
|
}: {
|
||||||
|
req: PayloadRequest;
|
||||||
|
doc?: Record<string, unknown> | null;
|
||||||
|
}): Promise<boolean> {
|
||||||
|
return canUserAccessStructureStorage(req.payload, req.user, doc);
|
||||||
|
}
|
||||||
|
|
||||||
export const GameStructures: CollectionConfig = {
|
export const GameStructures: CollectionConfig = {
|
||||||
slug: "game-structures",
|
slug: "game-structures",
|
||||||
admin: {
|
admin: {
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@ import { processBoxEvent } from "@/lib/arma-bridge/crates";
|
||||||
import { processMoneyEvent } from "@/lib/arma-bridge/money";
|
import { processMoneyEvent } from "@/lib/arma-bridge/money";
|
||||||
import { processReinforcementEvent } from "@/lib/arma-bridge/reinforcements";
|
import { processReinforcementEvent } from "@/lib/arma-bridge/reinforcements";
|
||||||
import { processLockerEvent } from "@/lib/arma-bridge/lockers";
|
import { processLockerEvent } from "@/lib/arma-bridge/lockers";
|
||||||
|
import { processGarageEvent } from "@/lib/arma-bridge/garages";
|
||||||
import { isOperationLedgerEnabled } from "@/lib/operations/rollout";
|
import { isOperationLedgerEnabled } from "@/lib/operations/rollout";
|
||||||
import { processOperationEvent } from "@/lib/operations/process";
|
import { processOperationEvent } from "@/lib/operations/process";
|
||||||
|
|
||||||
|
|
@ -57,6 +58,15 @@ export const ArmaSyncEvents: CollectionConfig = {
|
||||||
req.payload.logger.error(`[LockerSync] Failed to process locker event ${doc.eventId}: ${err}`);
|
req.payload.logger.error(`[LockerSync] Failed to process locker event ${doc.eventId}: ${err}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (doc.type.startsWith("garage.")) {
|
||||||
|
// Awaited (same posture as locker.*): garage writes join the
|
||||||
|
// raw-event transaction; processGarageEvent never throws.
|
||||||
|
try {
|
||||||
|
await processGarageEvent(req.payload, doc, req);
|
||||||
|
} catch (err) {
|
||||||
|
req.payload.logger.error(`[GarageSync] Failed to process garage event ${doc.eventId}: ${err}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
|
|
||||||
543
src/lib/arma-bridge/garages.ts
Normal file
543
src/lib/arma-bridge/garages.ts
Normal file
|
|
@ -0,0 +1,543 @@
|
||||||
|
import { randomBytes } from "crypto";
|
||||||
|
import type { Payload, PayloadRequest } from "payload";
|
||||||
|
import type { GameStructure, GameVehicle, Structure, Vehicle } from "@/payload-types";
|
||||||
|
import type { RawSyncEvent } from "@/lib/operations/types";
|
||||||
|
import { findLatestOnlineServerId } from "./lockers";
|
||||||
|
import {
|
||||||
|
findGarageEmptySpot,
|
||||||
|
getGarageBayDimensions,
|
||||||
|
garageRelId,
|
||||||
|
parkedVehiclesToGridItems,
|
||||||
|
parseGarageInstanceRef,
|
||||||
|
type GarageGridItem,
|
||||||
|
} from "@/lib/garage";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Garage sync bridge processor (docs/arma-bridge/garage-sync.md).
|
||||||
|
*
|
||||||
|
* Instance refs are `garage:<storageSlug>` (the structure's existing item
|
||||||
|
* storage slug, assumption A1). Events carry per-instance identity via the
|
||||||
|
* addon-assigned `bridgeUid` plus fuel/damage fractions; the web claims
|
||||||
|
* unknown instances by classname match against untagged vehicles at that
|
||||||
|
* structure (first-tag-wins, provenance logged) or creates new game-vehicles
|
||||||
|
* rows. Grid cells are web bookkeeping: deposits auto-place row-major into
|
||||||
|
* free bay cells, and sync never moves already-parked vehicles.
|
||||||
|
*
|
||||||
|
* Merge rules mirror locker sync: snapshots update state only, absence is NOT
|
||||||
|
* deletion, grid metadata is preserved, and processors never throw so event
|
||||||
|
* ingestion cannot roll back.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export interface GarageInstanceLine {
|
||||||
|
bridgeUid: string;
|
||||||
|
classname: string;
|
||||||
|
/** Fraction of tank capacity, 0..1. */
|
||||||
|
fuel: number;
|
||||||
|
/** Fraction of total damage, 0..1 (1 = destroyed). */
|
||||||
|
damage: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
const MAX_SNAPSHOT_LINES = 200;
|
||||||
|
const UID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
|
||||||
|
const CLASSNAME_MAX = 200;
|
||||||
|
|
||||||
|
function clamp01(value: unknown): number {
|
||||||
|
const n = typeof value === "number" ? value : Number(value);
|
||||||
|
if (!Number.isFinite(n)) return 0;
|
||||||
|
return Math.min(1, Math.max(0, n));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Parse `[bridgeUid, classname, fuel, damage]`; null when malformed. */
|
||||||
|
export function parseInstanceLine(value: unknown): GarageInstanceLine | null {
|
||||||
|
if (!Array.isArray(value) || value.length < 2) return null;
|
||||||
|
const [uid, classname, fuel, damage] = value as unknown[];
|
||||||
|
if (typeof uid !== "string" || !UID_PATTERN.test(uid)) return null;
|
||||||
|
if (typeof classname !== "string" || classname.length === 0 || classname.length > CLASSNAME_MAX) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (value.length > 2 && !Number.isFinite(Number(fuel))) return null;
|
||||||
|
if (value.length > 3 && !Number.isFinite(Number(damage))) return null;
|
||||||
|
return {
|
||||||
|
bridgeUid: uid,
|
||||||
|
classname,
|
||||||
|
fuel: clamp01(fuel),
|
||||||
|
damage: clamp01(damage),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Parse a snapshot array of instance lines; null when the shape is invalid. */
|
||||||
|
export function parseGarageSnapshot(value: unknown): GarageInstanceLine[] | null {
|
||||||
|
if (!Array.isArray(value)) return null;
|
||||||
|
const lines: GarageInstanceLine[] = [];
|
||||||
|
for (const entry of value.slice(0, MAX_SNAPSHOT_LINES)) {
|
||||||
|
const line = parseInstanceLine(entry);
|
||||||
|
if (!line) return null;
|
||||||
|
lines.push(line);
|
||||||
|
}
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Marks the request so garage writes never echo back as commands. */
|
||||||
|
function markGarageSyncOrigin(req: PayloadRequest | undefined): void {
|
||||||
|
if (!req) return;
|
||||||
|
req.context = { ...req.context, garageSyncOrigin: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isGarageSyncOrigin(req: PayloadRequest): boolean {
|
||||||
|
return Boolean((req.context as Record<string, unknown> | undefined)?.garageSyncOrigin);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Command enqueue (web -> mod) ──────────────────────────────────────────
|
||||||
|
|
||||||
|
async function enqueueGarageCommand(
|
||||||
|
payload: Payload,
|
||||||
|
type: string,
|
||||||
|
commandPayload: unknown[],
|
||||||
|
serverId?: number,
|
||||||
|
): Promise<boolean> {
|
||||||
|
const target = serverId ?? (await findLatestOnlineServerId(payload));
|
||||||
|
if (target == null) {
|
||||||
|
payload.logger.warn(
|
||||||
|
`[GarageSync] No online server; ${type} command not enqueued`,
|
||||||
|
);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
await payload.create({
|
||||||
|
collection: "arma-commands",
|
||||||
|
data: {
|
||||||
|
commandId: `garage-${randomBytes(12).toString("hex")}`,
|
||||||
|
server: target,
|
||||||
|
type,
|
||||||
|
payload: commandPayload,
|
||||||
|
status: "queued",
|
||||||
|
},
|
||||||
|
overrideAccess: true,
|
||||||
|
depth: 0,
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Build the wire line for a web-side instance; null when it has no game identity. */
|
||||||
|
export function garageInstanceLine(
|
||||||
|
vehicle: GameVehicle,
|
||||||
|
template: Vehicle | null | undefined,
|
||||||
|
): GarageInstanceLine | null {
|
||||||
|
if (!vehicle.bridgeUid) return null;
|
||||||
|
const classname = template?.classname?.trim();
|
||||||
|
if (!classname) return null;
|
||||||
|
const capacity = template?.fuel?.fuelCapacity ?? 0;
|
||||||
|
const fuel = capacity > 0 ? clamp01((vehicle.currentFuel ?? 0) / capacity) : 0;
|
||||||
|
const maxHealth = template?.maxHealth ?? 0;
|
||||||
|
const damage =
|
||||||
|
vehicle.status === "destroyed"
|
||||||
|
? 1
|
||||||
|
: maxHealth > 0
|
||||||
|
? clamp01(1 - (vehicle.currentHealth ?? 0) / maxHealth)
|
||||||
|
: 0;
|
||||||
|
return { bridgeUid: vehicle.bridgeUid, classname, fuel, damage };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Enqueue `garage.dispatch` (despawn from bay; instance now in transit). */
|
||||||
|
export async function enqueueGarageDispatch(
|
||||||
|
payload: Payload,
|
||||||
|
slug: string,
|
||||||
|
line: GarageInstanceLine,
|
||||||
|
): Promise<boolean> {
|
||||||
|
return enqueueGarageCommand(payload, "garage.dispatch", [
|
||||||
|
`garage:${slug}`,
|
||||||
|
line.bridgeUid,
|
||||||
|
line.classname,
|
||||||
|
line.fuel,
|
||||||
|
line.damage,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Enqueue `garage.store` (spawn/relocate the instance into this bay). */
|
||||||
|
export async function enqueueGarageStore(
|
||||||
|
payload: Payload,
|
||||||
|
slug: string,
|
||||||
|
line: GarageInstanceLine,
|
||||||
|
): Promise<boolean> {
|
||||||
|
return enqueueGarageCommand(payload, "garage.store", [
|
||||||
|
`garage:${slug}`,
|
||||||
|
line.bridgeUid,
|
||||||
|
line.classname,
|
||||||
|
line.fuel,
|
||||||
|
line.damage,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Enqueue a full `garage.apply` state push for one bay. */
|
||||||
|
export async function enqueueGarageApply(
|
||||||
|
payload: Payload,
|
||||||
|
slug: string,
|
||||||
|
lines: Array<[string, string, number, number]>,
|
||||||
|
serverId?: number,
|
||||||
|
): Promise<boolean> {
|
||||||
|
return enqueueGarageCommand(payload, "garage.apply", [`garage:${slug}`, lines], serverId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Event processing (mod -> web) ─────────────────────────────────────────
|
||||||
|
|
||||||
|
function statusFromDamage(
|
||||||
|
damage: number,
|
||||||
|
currentStatus: GameVehicle["status"],
|
||||||
|
): GameVehicle["status"] {
|
||||||
|
if (damage >= 1) return "destroyed";
|
||||||
|
if (currentStatus === "destroyed" || currentStatus === "damaged") return "idle";
|
||||||
|
return currentStatus;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function findStructureBySlug(
|
||||||
|
payload: Payload,
|
||||||
|
slug: string,
|
||||||
|
req?: PayloadRequest,
|
||||||
|
): Promise<(GameStructure & { type?: Structure | null }) | null> {
|
||||||
|
const found = await payload.find({
|
||||||
|
collection: "game-structures",
|
||||||
|
where: { storageSlug: { equals: slug } },
|
||||||
|
depth: 1,
|
||||||
|
limit: 1,
|
||||||
|
overrideAccess: true,
|
||||||
|
req,
|
||||||
|
});
|
||||||
|
return (found.docs[0] as (GameStructure & { type?: Structure | null }) | undefined) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve a wire instance to a game-vehicles row: existing bridgeUid match,
|
||||||
|
* else claim an untagged classname match at this structure (first-tag-wins),
|
||||||
|
* else create a new instance from the template. Null when the classname is
|
||||||
|
* unknown to the vehicles templates.
|
||||||
|
*/
|
||||||
|
async function resolveInstance(
|
||||||
|
payload: Payload,
|
||||||
|
structureId: number,
|
||||||
|
line: GarageInstanceLine,
|
||||||
|
eventId: string,
|
||||||
|
req?: PayloadRequest,
|
||||||
|
): Promise<GameVehicle | null> {
|
||||||
|
const tagged = await payload.find({
|
||||||
|
collection: "game-vehicles",
|
||||||
|
where: { bridgeUid: { equals: line.bridgeUid } },
|
||||||
|
depth: 1,
|
||||||
|
limit: 1,
|
||||||
|
overrideAccess: true,
|
||||||
|
req,
|
||||||
|
});
|
||||||
|
if (tagged.docs[0]) return tagged.docs[0];
|
||||||
|
|
||||||
|
const untagged = await payload.find({
|
||||||
|
collection: "game-vehicles",
|
||||||
|
where: {
|
||||||
|
and: [
|
||||||
|
{ bridgeUid: { exists: false } },
|
||||||
|
{ deployedAt: { equals: structureId } },
|
||||||
|
{ "type.classname": { equals: line.classname } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
depth: 1,
|
||||||
|
limit: 1,
|
||||||
|
sort: "createdAt",
|
||||||
|
overrideAccess: true,
|
||||||
|
req,
|
||||||
|
});
|
||||||
|
const claim = untagged.docs[0];
|
||||||
|
if (claim) {
|
||||||
|
payload.logger.info(
|
||||||
|
`[GarageSync] Claimed vehicle ${claim.id} as bridgeUid ${line.bridgeUid} ` +
|
||||||
|
`(classname ${line.classname}, structure ${structureId}, provenance event ${eventId})`,
|
||||||
|
);
|
||||||
|
return payload.update({
|
||||||
|
collection: "game-vehicles",
|
||||||
|
id: claim.id,
|
||||||
|
data: { bridgeUid: line.bridgeUid },
|
||||||
|
depth: 1,
|
||||||
|
overrideAccess: true,
|
||||||
|
req,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const templates = await payload.find({
|
||||||
|
collection: "vehicles",
|
||||||
|
where: { classname: { equals: line.classname } },
|
||||||
|
depth: 0,
|
||||||
|
limit: 1,
|
||||||
|
overrideAccess: true,
|
||||||
|
req,
|
||||||
|
});
|
||||||
|
const template = templates.docs[0];
|
||||||
|
if (!template) {
|
||||||
|
payload.logger.warn(
|
||||||
|
`[GarageSync] Classname "${line.classname}" has no vehicle template; instance ${line.bridgeUid} skipped (event ${eventId})`,
|
||||||
|
);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const capacity = template.fuel?.fuelCapacity ?? 100;
|
||||||
|
const maxHealth = template.maxHealth ?? 100;
|
||||||
|
return payload.create({
|
||||||
|
collection: "game-vehicles",
|
||||||
|
data: {
|
||||||
|
name: template.name,
|
||||||
|
type: template.id,
|
||||||
|
deployedAt: structureId,
|
||||||
|
status: line.damage >= 1 ? "destroyed" : "idle",
|
||||||
|
currentFuel: Math.round(line.fuel * capacity),
|
||||||
|
currentHealth: Math.round((1 - line.damage) * maxHealth),
|
||||||
|
bridgeUid: line.bridgeUid,
|
||||||
|
},
|
||||||
|
depth: 1,
|
||||||
|
overrideAccess: true,
|
||||||
|
req,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Row-major auto-place an unplaced instance into the bay; null when full. */
|
||||||
|
async function autoPlaceIntoBay(
|
||||||
|
payload: Payload,
|
||||||
|
structure: GameStructure & { type?: Structure | null },
|
||||||
|
vehicle: GameVehicle & { type?: Vehicle | null },
|
||||||
|
req?: PayloadRequest,
|
||||||
|
): Promise<{ x: number; y: number } | null> {
|
||||||
|
const bay = getGarageBayDimensions(structure.type ?? null);
|
||||||
|
if (!bay) return null;
|
||||||
|
const { docs } = await payload.find({
|
||||||
|
collection: "game-vehicles",
|
||||||
|
where: { deployedAt: { equals: structure.id } },
|
||||||
|
depth: 1,
|
||||||
|
limit: 1000,
|
||||||
|
overrideAccess: true,
|
||||||
|
req,
|
||||||
|
});
|
||||||
|
const others = parkedVehiclesToGridItems(
|
||||||
|
(docs as Array<GameVehicle & { type?: unknown }>).filter((v) => v.id !== vehicle.id),
|
||||||
|
);
|
||||||
|
const template = typeof vehicle.type === "object" ? vehicle.type : null;
|
||||||
|
const fp = {
|
||||||
|
width: Math.max(1, Math.floor(template?.garageWidth ?? 1)),
|
||||||
|
height: Math.max(1, Math.floor(template?.garageHeight ?? 1)),
|
||||||
|
};
|
||||||
|
return findGarageEmptySpot(others, fp.width, fp.height, bay.width, bay.height);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function applyDeposit(
|
||||||
|
payload: Payload,
|
||||||
|
structure: GameStructure & { type?: Structure | null },
|
||||||
|
line: GarageInstanceLine,
|
||||||
|
eventId: string,
|
||||||
|
req?: PayloadRequest,
|
||||||
|
): Promise<void> {
|
||||||
|
const instance = await resolveInstance(payload, structure.id, line, eventId, req);
|
||||||
|
if (!instance) return;
|
||||||
|
const template = typeof instance.type === "object" ? instance.type : null;
|
||||||
|
const capacity = template?.fuel?.fuelCapacity ?? 100;
|
||||||
|
const maxHealth = template?.maxHealth ?? 100;
|
||||||
|
|
||||||
|
const data: Record<string, unknown> = {
|
||||||
|
deployedAt: structure.id,
|
||||||
|
currentFuel: Math.round(line.fuel * capacity),
|
||||||
|
currentHealth: Math.round((1 - line.damage) * maxHealth),
|
||||||
|
};
|
||||||
|
const nextStatus = statusFromDamage(line.damage, instance.status);
|
||||||
|
if (nextStatus !== instance.status) data.status = nextStatus;
|
||||||
|
else if (instance.status === "in_transit") data.status = "idle";
|
||||||
|
|
||||||
|
if (instance.garageGridX == null || instance.garageGridY == null) {
|
||||||
|
const spot = await autoPlaceIntoBay(
|
||||||
|
payload,
|
||||||
|
structure,
|
||||||
|
instance as GameVehicle & { type?: Vehicle | null },
|
||||||
|
req,
|
||||||
|
);
|
||||||
|
if (spot) {
|
||||||
|
data.garageGridX = spot.x;
|
||||||
|
data.garageGridY = spot.y;
|
||||||
|
} else {
|
||||||
|
payload.logger.warn(
|
||||||
|
`[GarageSync] Bay full at structure ${structure.id}; vehicle ${instance.id} parked off-grid (event ${eventId})`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await payload.update({
|
||||||
|
collection: "game-vehicles",
|
||||||
|
id: instance.id,
|
||||||
|
data: data as never,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
req,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function applyWithdraw(
|
||||||
|
payload: Payload,
|
||||||
|
line: GarageInstanceLine,
|
||||||
|
eventId: string,
|
||||||
|
req?: PayloadRequest,
|
||||||
|
): Promise<void> {
|
||||||
|
const found = await payload.find({
|
||||||
|
collection: "game-vehicles",
|
||||||
|
where: { bridgeUid: { equals: line.bridgeUid } },
|
||||||
|
depth: 1,
|
||||||
|
limit: 1,
|
||||||
|
overrideAccess: true,
|
||||||
|
req,
|
||||||
|
});
|
||||||
|
const instance = found.docs[0];
|
||||||
|
if (!instance) {
|
||||||
|
payload.logger.warn(
|
||||||
|
`[GarageSync] garage.withdraw for unknown bridgeUid ${line.bridgeUid} (event ${eventId}); skipped`,
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const template = typeof instance.type === "object" ? instance.type : null;
|
||||||
|
const capacity = template?.fuel?.fuelCapacity ?? 100;
|
||||||
|
const maxHealth = template?.maxHealth ?? 100;
|
||||||
|
const destroyed = line.damage >= 1;
|
||||||
|
|
||||||
|
await payload.update({
|
||||||
|
collection: "game-vehicles",
|
||||||
|
id: instance.id,
|
||||||
|
data: {
|
||||||
|
garageGridX: null,
|
||||||
|
garageGridY: null,
|
||||||
|
garageRotated: false,
|
||||||
|
deployedAt: null,
|
||||||
|
currentFuel: Math.round(line.fuel * capacity),
|
||||||
|
currentHealth: Math.round((1 - line.damage) * maxHealth),
|
||||||
|
status: destroyed ? "destroyed" : instance.status === "assigned" ? "assigned" : "in_transit",
|
||||||
|
} as never,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
req,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleRequest(
|
||||||
|
payload: Payload,
|
||||||
|
structure: GameStructure & { type?: Structure | null },
|
||||||
|
raw: RawSyncEvent,
|
||||||
|
req?: PayloadRequest,
|
||||||
|
): Promise<void> {
|
||||||
|
const { docs } = await payload.find({
|
||||||
|
collection: "game-vehicles",
|
||||||
|
where: {
|
||||||
|
and: [{ deployedAt: { equals: structure.id } }, { bridgeUid: { exists: true } }],
|
||||||
|
},
|
||||||
|
depth: 1,
|
||||||
|
limit: 1000,
|
||||||
|
overrideAccess: true,
|
||||||
|
req,
|
||||||
|
});
|
||||||
|
const lines: Array<[string, string, number, number]> = [];
|
||||||
|
for (const vehicle of docs as Array<GameVehicle & { type?: Vehicle }>) {
|
||||||
|
if (vehicle.garageGridX == null || vehicle.garageGridY == null) continue;
|
||||||
|
const line = garageInstanceLine(vehicle, vehicle.type);
|
||||||
|
if (!line) continue;
|
||||||
|
lines.push([line.bridgeUid, line.classname, line.fuel, line.damage]);
|
||||||
|
}
|
||||||
|
const slug = structure.storageSlug?.trim();
|
||||||
|
if (!slug) return;
|
||||||
|
await enqueueGarageApply(payload, slug, lines, typeof raw.server === "number" ? raw.server : undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Router entry for `garage.*` events (wired from the arma-sync-events
|
||||||
|
* afterChange hook). Never throws.
|
||||||
|
*/
|
||||||
|
export async function processGarageEvent(
|
||||||
|
payload: Payload,
|
||||||
|
raw: RawSyncEvent,
|
||||||
|
req?: PayloadRequest,
|
||||||
|
): Promise<void> {
|
||||||
|
try {
|
||||||
|
if (typeof raw.server !== "number") {
|
||||||
|
payload.logger.warn(`[GarageSync] Garage event ${raw.eventId} has no server; skipped`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!Array.isArray(raw.payload)) {
|
||||||
|
payload.logger.warn(`[GarageSync] Malformed garage event payload ${raw.eventId}; skipped`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const ref = parseGarageInstanceRef(raw.payload[0]);
|
||||||
|
if (!ref) {
|
||||||
|
payload.logger.warn(`[GarageSync] Invalid garage instance ref on event ${raw.eventId}; skipped`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const structure = await findStructureBySlug(payload, ref.slug, req);
|
||||||
|
if (!structure) {
|
||||||
|
payload.logger.warn(
|
||||||
|
`[GarageSync] Unknown garage ref "garage:${ref.slug}" on event ${raw.eventId}; skipped`,
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!getGarageBayDimensions(structure.type ?? null)) {
|
||||||
|
payload.logger.warn(
|
||||||
|
`[GarageSync] Structure ${structure.id} ("${ref.slug}") has no vehicle bay; skipping event ${raw.eventId}`,
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
markGarageSyncOrigin(req);
|
||||||
|
|
||||||
|
if (raw.type === "garage.deposit" || raw.type === "garage.withdraw") {
|
||||||
|
const line = parseInstanceLine(raw.payload.slice(1));
|
||||||
|
if (!line) {
|
||||||
|
payload.logger.warn(`[GarageSync] Malformed ${raw.type} payload ${raw.eventId}; skipped`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (raw.type === "garage.deposit") {
|
||||||
|
await applyDeposit(payload, structure, line, raw.eventId, req);
|
||||||
|
} else {
|
||||||
|
await applyWithdraw(payload, line, raw.eventId, req);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (raw.type === "garage.sync") {
|
||||||
|
if (Array.isArray(raw.payload[1]) && raw.payload[1].length > MAX_SNAPSHOT_LINES) {
|
||||||
|
payload.logger.warn(
|
||||||
|
`[GarageSync] Snapshot for garage:${ref.slug} truncated to ${MAX_SNAPSHOT_LINES} lines (event ${raw.eventId})`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const lines = parseGarageSnapshot(raw.payload[1]);
|
||||||
|
if (!lines) {
|
||||||
|
payload.logger.warn(`[GarageSync] Malformed garage.sync snapshot ${raw.eventId}; skipped`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (const line of lines) {
|
||||||
|
await applyDeposit(payload, structure, line, raw.eventId, req);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (raw.type === "garage.request") {
|
||||||
|
await handleRequest(payload, structure, raw, req);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
payload.logger.warn(`[GarageSync] Unknown garage event type "${raw.type}" (${raw.eventId})`);
|
||||||
|
} catch (error) {
|
||||||
|
payload.logger.error(`[GarageSync] Failed to process garage event ${raw.eventId}: ${error}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Parked instances at a structure that the game can reconcile (used by tests/actions). */
|
||||||
|
export async function parkedTaggedVehicles(
|
||||||
|
payload: Payload,
|
||||||
|
structureId: number,
|
||||||
|
): Promise<Array<GameVehicle & { type?: Vehicle }>> {
|
||||||
|
const { docs } = await payload.find({
|
||||||
|
collection: "game-vehicles",
|
||||||
|
where: { deployedAt: { equals: structureId } },
|
||||||
|
depth: 1,
|
||||||
|
limit: 1000,
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
return (docs as Array<GameVehicle & { type?: Vehicle }>).filter(
|
||||||
|
(v) => v.bridgeUid && v.garageGridX != null && v.garageGridY != null,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export type { GarageGridItem };
|
||||||
|
export { garageRelId };
|
||||||
|
|
@ -129,7 +129,7 @@ function fuelPercent(vehicle: Depth0Vehicle): number {
|
||||||
return Math.round((current / capacity) * 100);
|
return Math.round((current / capacity) * 100);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function activeReservedVehicleIds(
|
export async function activeReservedVehicleIds(
|
||||||
payload: PayloadType,
|
payload: PayloadType,
|
||||||
): Promise<Set<number>> {
|
): Promise<Set<number>> {
|
||||||
const res = await payload
|
const res = await payload
|
||||||
|
|
@ -155,6 +155,44 @@ async function activeReservedVehicleIds(
|
||||||
return ids;
|
return ids;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Map of game-vehicle id -> human label of the operation it is actively
|
||||||
|
* reserved for ("Reserved for op X" badges on garage vehicle faces).
|
||||||
|
* First reservation wins; mission name preferred over the free-text
|
||||||
|
* operationId. Shares semantics with activeReservedVehicleIds: only
|
||||||
|
* status === "reserved" counts as active.
|
||||||
|
*/
|
||||||
|
export async function reservedVehiclesByOperation(
|
||||||
|
payload: PayloadType,
|
||||||
|
): Promise<Map<number, string>> {
|
||||||
|
const res = await payload
|
||||||
|
.find({
|
||||||
|
collection: "operation-reservations",
|
||||||
|
where: { status: { equals: "reserved" } },
|
||||||
|
limit: 1000,
|
||||||
|
depth: 1,
|
||||||
|
overrideAccess: true,
|
||||||
|
})
|
||||||
|
.catch(() => ({ docs: [] as unknown[] }));
|
||||||
|
const map = new Map<number, string>();
|
||||||
|
for (const doc of res.docs) {
|
||||||
|
const row = doc as {
|
||||||
|
operationId?: string;
|
||||||
|
mission?: { name?: string } | number | null;
|
||||||
|
vehicles?: { vehicle: number | { id: number } }[] | null;
|
||||||
|
};
|
||||||
|
const missionName =
|
||||||
|
row.mission && typeof row.mission === "object" ? row.mission.name : undefined;
|
||||||
|
const label = missionName?.trim() || row.operationId || "an operation";
|
||||||
|
for (const entry of row.vehicles ?? []) {
|
||||||
|
const ref = entry.vehicle;
|
||||||
|
const id = typeof ref === "object" && ref ? ref.id : ref;
|
||||||
|
if (typeof id === "number" && !map.has(id)) map.set(id, label);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
async function fetchBudgetAccounts(
|
async function fetchBudgetAccounts(
|
||||||
payload: PayloadType,
|
payload: PayloadType,
|
||||||
userId: number | null,
|
userId: number | null,
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue