1
0
Fork 0

feat(lockers): seed and unlimited-stock sync for limited arsenal

This commit is contained in:
Jason Fraley 2026-11-20 19:52:15 -05:00
parent 716c87bb87
commit 5418d6563e
10 changed files with 46583 additions and 22 deletions

View file

@ -46,13 +46,15 @@ serverTime]`, payload defaults to `[]`).
| Type | Payload | Meaning |
|---|---|---|
| `locker.sync` | `[instanceRef, [[itemClass, count], ...]]` | Full stock snapshot for one instance after a committed change. |
| `locker.seed` | `[instanceRef, [[itemClass, count], ...]]` | Create-only first-bind seed. Applied only when the web has no document (personal) or no `storedAssets` yet (structure); never overwrites existing web state. |
| `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).
- TOP-LEVEL stock only: `[itemClass, count]` pairs, one per class. Counts are
integers >= 0, or `-1` for an Antistasi-style **unlimited** entry. 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.
@ -70,9 +72,10 @@ serverTime]`, payload defaults to `[]`).
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.
the snapshot count (or `1` with `unlimited = true` for `-1`). **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
@ -88,6 +91,11 @@ serverTime]`, payload defaults to `[]`).
- 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.
- **No-wipe rule**: a linked Steam ID with no `locker-storages` document, and
an unknown structure slug, are both "unknown" → nothing is enqueued. An
empty snapshot is only sent for a document that actually exists and is empty.
The game therefore keeps its local `profileNamespace` stock until the web
has a real snapshot to apply.
## Command envelope and schemas
@ -96,7 +104,7 @@ 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. |
| `locker.apply` | `[instanceRef, [[itemClass, count], ...]]` | Server replaces the instance's stock wholesale with the given pairs, pushes availability to clients, and acks. `-1` means unlimited. |
- The web enqueues `locker.apply` when: (a) a member/admin edits locker items
or structure `storedAssets` in the UI (afterChange hook), or (b) a
@ -118,12 +126,19 @@ and `fn_executeCommand` destructures), stored in `arma-commands`.
- 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`.
- Bridge disabled/unreachable: the mod keeps its local stock AND persists it
to `profileNamespace` (per world, key `twwk_arsenal_store_<world>`, written by
a debounced saver and at mission end). The store survives mission restarts on
the same server with the bridge off. Queued `locker.sync` events flush when
the bridge returns (queue cap drops oldest, per existing bridge behavior).
- On mission start the mod loads the local store first, then emits
`locker.request` for every bound structure instance and per connecting
player; the web replies with `locker.apply` only when it has a document to
apply (no-wipe rule).
- New storage instances seed once: `cargo` turns the bound crate's Eden cargo
into stock and clears the crate; `custom` parses `class:count` pairs;
`none` starts empty. Personal lockers always start empty (per player) and
are created on first access.
## Security
@ -135,10 +150,19 @@ and `fn_executeCommand` destructures), stored in `arma-commands`.
## 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
- Server store: `instanceRef → (className → count)` in missionNamespace, backed
by the per-world `profileNamespace` store. `-1` is unlimited.
- Module binding: the Eden/Zeus "Limited Arsenal Storage" module binds the crate
it is placed on (or synced to) — `attachedTo` → `synchronizedObjects` → a
downward ray through the module → nearest object within 2.5 m. Eden applies
its Attributes at mission start; Zeus opens the bind window on placement and
on double-click.
- 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).
targeted per-player local set). Zero-stock classes are hidden.
- Count display: `[xN]` / `[∞]` in the left list's right column, a "Storage"
stat in the item panel, and a "Stock (high to low)" sort. Unlimited sorts
above finite stacks.
- 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`.

View file

@ -476,6 +476,15 @@ export const GameStructures: CollectionConfig = {
min: 0,
defaultValue: 1,
},
{
name: "unlimited",
type: "checkbox",
defaultValue: false,
admin: {
description:
"Antistasi-style unlimited stock: the game may take this entry without decrementing. The quantity field is kept at 1 for display.",
},
},
{
name: "gridX",
type: "number",

View file

@ -80,6 +80,15 @@ export const LockerStorages: CollectionConfig = {
min: 0,
defaultValue: 1,
},
{
name: "unlimited",
type: "checkbox",
defaultValue: false,
admin: {
description:
"Antistasi-style unlimited stock: the game may take this entry without decrementing. The quantity field is kept at 1 for display.",
},
},
{
name: "gridX",
type: "number",

View file

@ -66,7 +66,10 @@ export function parseStockSnapshot(value: unknown): LockerStockLine[] | null {
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)) });
// -1 is the Antistasi-style unlimited entry; any other negative is clamped
// to -1 so a malformed sender cannot create arbitrary negative stock.
const rounded = Math.round(count);
lines.push({ className, count: rounded < 0 ? -1 : rounded });
}
return lines;
}
@ -167,7 +170,12 @@ export async function stockPairsFromItems(
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;
if (!className) continue;
if (row.unlimited === true) {
pairs.push([className, -1]);
continue;
}
if (quantity < 1) continue;
pairs.push([className, quantity]);
}
return pairs;
@ -202,9 +210,11 @@ export function mergeStockIntoItems(
}, -1) + 1;
for (const line of snapshot) {
const unlimited = line.count < 0;
const quantity = unlimited ? 1 : line.count;
const hit = indexByClassName.get(line.className);
if (hit !== undefined) {
merged[hit] = { ...merged[hit], quantity: line.count };
merged[hit] = { ...merged[hit], quantity, unlimited };
continue;
}
const assetId = assetIdByClassName.get(line.className);
@ -214,7 +224,8 @@ export function mergeStockIntoItems(
}
const row: ExistingItemRow = {
asset: assetId,
quantity: line.count,
quantity,
unlimited,
gridX: 0,
gridY: nextY,
rotated: false,
@ -329,6 +340,16 @@ export async function processLockerEvent(
return;
}
if (raw.type === "locker.seed") {
const snapshot = parseStockSnapshot(raw.payload[1]);
if (!snapshot) {
payload.logger.warn(`[LockerSync] Event ${raw.eventId} has a malformed seed snapshot; skipping`);
return;
}
await applySeedToInstance(payload, ref, refString, snapshot, raw.eventId, req);
return;
}
if (raw.type === "locker.request") {
const stock = await currentStockForInstance(payload, ref);
if (stock === null) {
@ -436,6 +457,98 @@ async function applySnapshotToInstance(
});
}
/**
* Create-only seed: fills an EMPTY instance from the game's first-bind stock.
* An instance with existing items is left untouched so a seed event can never
* overwrite a web-managed document. Never echoes a locker.apply command.
*/
async function applySeedToInstance(
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] Seed for unlinked Steam ID ${ref.steamId}; 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 items = mergeStockIntoItems([], snapshot, assetIds, (m) => payload.logger.warn(m));
const existingLocker = lockers.docs[0];
if (existingLocker) {
const existingItems = (existingLocker as { items?: unknown }).items;
if (Array.isArray(existingItems) && existingItems.length > 0) {
payload.logger.info(`[LockerSync] Seed for non-empty ${refString}; ignored`);
return;
}
await payload.update({
collection: "locker-storages",
id: existingLocker.id,
data: { items: items as never },
overrideAccess: true,
depth: 0,
req,
});
return;
}
await payload.create({
collection: "locker-storages",
data: { name: "Personal Locker", ownerUser: userId, items: items 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] Seed for unknown structure "${ref.slug}"; event ${eventId} skipped`);
return;
}
const existing = (structure as { storedAssets?: unknown }).storedAssets;
if (Array.isArray(existing) && existing.length > 0) {
payload.logger.info(`[LockerSync] Seed for non-empty ${refString}; ignored`);
return;
}
const items = mergeStockIntoItems([], snapshot, assetIds, (m) => payload.logger.warn(m));
await payload.update({
collection: "game-structures",
id: structure.id,
data: { storedAssets: items 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);
@ -456,7 +569,10 @@ async function currentStockForInstance(
overrideAccess: true,
});
const locker = lockers.docs[0];
if (!locker) return [];
// No locker document = the web has never seen this locker. Enqueueing an
// empty snapshot would wipe the game's local stock, so return null: the
// game keeps its profileNamespace stock until it syncs a real snapshot.
if (!locker) return null;
return stockPairsFromItems(payload, (locker as { items?: unknown }).items);
}
const structures = await payload.find({

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,13 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "game_structures_stored_assets" ADD COLUMN "unlimited" boolean DEFAULT false;
ALTER TABLE "locker_storages_items" ADD COLUMN "unlimited" boolean DEFAULT false;`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "game_structures_stored_assets" DROP COLUMN "unlimited";
ALTER TABLE "locker_storages_items" DROP COLUMN "unlimited";`)
}

View file

@ -161,6 +161,7 @@ import * as migration_20261117_212337_add_faction_discovered_field from './20261
import * as migration_20261118_143000_add_wiki_pages_draft_and_created_by from './20261118_143000_add_wiki_pages_draft_and_created_by';
import * as migration_20261118_184813_add_faction_relation_entries from './20261118_184813_add_faction_relation_entries';
import * as migration_20261118_184851_drop_factions_relationships_array from './20261118_184851_drop_factions_relationships_array';
import * as migration_20261120_234950_add_locker_unlimited from './20261120_234950_add_locker_unlimited';
export const migrations = [
{
@ -976,6 +977,11 @@ export const migrations = [
{
up: migration_20261118_184851_drop_factions_relationships_array.up,
down: migration_20261118_184851_drop_factions_relationships_array.down,
name: '20261118_184851_drop_factions_relationships_array'
name: '20261118_184851_drop_factions_relationships_array',
},
{
up: migration_20261120_234950_add_locker_unlimited.up,
down: migration_20261120_234950_add_locker_unlimited.down,
name: '20261120_234950_add_locker_unlimited'
},
];

View file

@ -2151,6 +2151,7 @@ export const game_structures_stored_assets = pgTable(
onDelete: "set null",
}),
quantity: numeric("quantity", { mode: "number" }).notNull().default(1),
unlimited: boolean("unlimited").default(false),
gridX: numeric("grid_x", { mode: "number" }).notNull().default(0),
gridY: numeric("grid_y", { mode: "number" }).notNull().default(0),
rotated: boolean("rotated").default(false),
@ -6769,6 +6770,7 @@ export const locker_storages_items = pgTable(
onDelete: "set null",
}),
quantity: numeric("quantity", { mode: "number" }).notNull().default(1),
unlimited: boolean("unlimited").default(false),
gridX: numeric("grid_x", { mode: "number" }).notNull().default(0),
gridY: numeric("grid_y", { mode: "number" }).notNull().default(0),
rotated: boolean("rotated").default(false),

View file

@ -1302,6 +1302,10 @@ export interface GameStructure {
| {
asset: number | Asset;
quantity: number;
/**
* Antistasi-style unlimited stock: the game may take this entry without decrementing. The quantity field is kept at 1 for display.
*/
unlimited?: boolean | null;
/**
* Column position in the storage grid (0-indexed).
*/
@ -5461,6 +5465,10 @@ export interface LockerStorage {
| {
asset: number | Asset;
quantity: number;
/**
* Antistasi-style unlimited stock: the game may take this entry without decrementing. The quantity field is kept at 1 for display.
*/
unlimited?: boolean | null;
/**
* Column position in the locker grid (0-indexed).
*/
@ -9949,6 +9957,7 @@ export interface GameStructuresSelect<T extends boolean = true> {
| {
asset?: T;
quantity?: T;
unlimited?: T;
gridX?: T;
gridY?: T;
rotated?: T;
@ -11782,6 +11791,7 @@ export interface LockerStoragesSelect<T extends boolean = true> {
| {
asset?: T;
quantity?: T;
unlimited?: T;
gridX?: T;
gridY?: T;
rotated?: T;

View file

@ -34,6 +34,7 @@ let assetBId: number;
let resourceId: number;
let blueprintId: number;
let structureId: number;
let seedStructureId: number;
let lockerId: number;
let serverId: number;
// Highest arma-commands id when this file starts (set in beforeAll). Rows at or
@ -177,6 +178,19 @@ describe("Arma locker sync", () => {
});
structureId = structure.id;
const seedStructure = await payload.create({
collection: "game-structures",
data: {
name: `${RUN} Seed Storage`,
type: blueprintId,
constructionStatus: "complete",
storageSlug: `${RUN}-seed`,
} as never,
overrideAccess: true,
depth: 0,
});
seedStructureId = seedStructure.id;
// Isolate from arma-commands rows left by earlier spec files (foreign online
// servers change locker fan-out and pollute the total-count assertions).
const latest = await payload.find({
@ -200,6 +214,9 @@ describe("Arma locker sync", () => {
if (structureId) {
await payload.delete({ collection: "game-structures", id: structureId, overrideAccess: true }).catch(() => {});
}
if (seedStructureId) {
await payload.delete({ collection: "game-structures", id: seedStructureId, overrideAccess: true }).catch(() => {});
}
if (blueprintId) {
await payload.delete({ collection: "structures", id: blueprintId, overrideAccess: true }).catch(() => {});
}
@ -264,6 +281,18 @@ describe("Arma locker sync", () => {
{ className: CLASS_B, count: 2 },
]);
});
it("keeps -1 as unlimited and clamps other negatives to -1", () => {
expect(
parseStockSnapshot([
[CLASS_A, -1],
[CLASS_B, -17],
]),
).toEqual([
{ className: CLASS_A, count: -1 },
{ className: CLASS_B, count: -1 },
]);
});
});
describe("mergeStockIntoItems", () => {
@ -291,6 +320,18 @@ describe("Arma locker sync", () => {
expect(merged[1]).toMatchObject({ className: "other_class", quantity: 1 });
expect(merged[2]).toMatchObject({ asset: 2, quantity: 10, gridX: 0, gridY: 5, rotated: false });
});
it("stores unlimited entries as quantity 1 + unlimited flag, preserving grid metadata", () => {
const existing = [
{ asset: 1, quantity: 2, gridX: 3, gridY: 4, rotated: true, className: CLASS_A },
];
const merged = mergeStockIntoItems(
existing,
[{ className: CLASS_A, count: -1 }],
new Map([[CLASS_A, 1]]),
);
expect(merged[0]).toMatchObject({ quantity: 1, unlimited: true, gridX: 3, gridY: 4, rotated: true });
});
});
describe("locker.sync (personal)", () => {
@ -406,6 +447,28 @@ describe("Arma locker sync", () => {
processLockerEvent(payload, lockerEvent("locker.sync", [`structure:${RUN}-missing`, [[CLASS_A, 4]]], 1)),
).resolves.toBeUndefined();
});
it("seeds an empty structure once and never overwrites it", async () => {
const ref = `structure:${RUN}-seed`;
await processLockerEvent(payload, lockerEvent("locker.seed", [ref, [[CLASS_A, 3]]], 1));
let doc = (await payload.findByID({
collection: "game-structures",
id: seedStructureId,
depth: 0,
overrideAccess: true,
})) as unknown as { storedAssets: Record<string, unknown>[] };
expect(doc.storedAssets).toHaveLength(1);
expect(doc.storedAssets[0]).toMatchObject({ asset: assetAId, quantity: 3 });
await processLockerEvent(payload, lockerEvent("locker.seed", [ref, [[CLASS_A, 99]]], 1));
doc = (await payload.findByID({
collection: "game-structures",
id: seedStructureId,
depth: 0,
overrideAccess: true,
})) as unknown as { storedAssets: Record<string, unknown>[] };
expect(doc.storedAssets[0]).toMatchObject({ quantity: 3 });
});
});
describe("locker.request + locker.apply enqueue", () => {