fix(interior): bootstrap snapshots lazily, enforce per-room access, and cover gaps
This commit is contained in:
parent
d80a93c30c
commit
f2de7941ca
5 changed files with 214 additions and 25 deletions
|
|
@ -1,19 +1,11 @@
|
|||
import type { PayloadRequest } from "payload";
|
||||
import { hasPermission } from "@/utils/access-control/hasPermission";
|
||||
import { InteriorAccessMode } from "@/lib/interior/types";
|
||||
import { relId } from "./relations";
|
||||
|
||||
type PayloadLike = Parameters<typeof hasPermission>[0];
|
||||
type UserInput = { id: number | string; roleDocs?: unknown } | null | undefined;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interior access gate for the Superstructure. Mirrors
|
||||
* `canUserAccessStructureStorage` exactly, but reads the structure's
|
||||
|
|
|
|||
|
|
@ -333,7 +333,10 @@ export async function cancelInteriorJob(
|
|||
},
|
||||
});
|
||||
|
||||
await clearRoomSlot(payload, relId(job.room)!);
|
||||
// The room's output slot stays occupied by the cancelled job: the refund in
|
||||
// `output` is collected through the normal collect path, and only then does
|
||||
// the slot clear. This matches the plan ("a room with an awaiting_collect or
|
||||
// cancelled job blocks new jobs until its output is collected").
|
||||
|
||||
await emitGameEvent(payload, {
|
||||
type: EventTypes.InteriorJobCancelled,
|
||||
|
|
@ -347,7 +350,11 @@ export async function cancelInteriorJob(
|
|||
return { ok: true };
|
||||
}
|
||||
|
||||
/** Collect a finished job's output and free the room's output slot. */
|
||||
/**
|
||||
* Collect a finished job's output and free the room's output slot. Accepts both
|
||||
* sweep-completed jobs (`awaiting_collect`) and cancelled jobs, whose committed
|
||||
* inputs sit in `output.resources` as the refund.
|
||||
*/
|
||||
export async function collectInteriorJob(
|
||||
payload: PayloadType,
|
||||
user: { id: number | string } | null,
|
||||
|
|
@ -359,7 +366,9 @@ export async function collectInteriorJob(
|
|||
overrideAccess: true,
|
||||
depth: 1,
|
||||
});
|
||||
if (job.status !== "awaiting_collect") return { ok: false, error: "not_ready" };
|
||||
if (job.status !== "awaiting_collect" && job.status !== "cancelled") {
|
||||
return { ok: false, error: "not_ready" };
|
||||
}
|
||||
|
||||
// Credit resources to the structure store and asset outputs to structure
|
||||
// locker storage.
|
||||
|
|
|
|||
|
|
@ -15,9 +15,59 @@ import { relId } from "@/lib/interior/relations";
|
|||
*/
|
||||
export async function provisionInterior(
|
||||
payload: Payload,
|
||||
structure: Pick<GameStructure, "id" | "interior">,
|
||||
structure: Pick<GameStructure, "id" | "interior"> & {
|
||||
type?: number | { id: number } | null;
|
||||
},
|
||||
): Promise<{ provisioned: boolean; rooms: number }> {
|
||||
const snapshot = structure.interior;
|
||||
let snapshot = structure.interior;
|
||||
|
||||
// Bootstrap the runtime snapshot from the blueprint on first entry. The
|
||||
// blueprint lives at the root of the Structure document (`interiorEnabled`,
|
||||
// `rooms`, ...). Later blueprint edits never retarget live rooms because the
|
||||
// snapshot is copied exactly once; relationship values are normalized to ids
|
||||
// so a depth-populated blueprint cannot leak objects into the json columns.
|
||||
const hasRooms = Array.isArray(snapshot?.rooms) && (snapshot.rooms as unknown[]).length > 0;
|
||||
if (!hasRooms) {
|
||||
const blueprintId =
|
||||
typeof structure.type === "number" ? structure.type : structure.type?.id ?? null;
|
||||
const blueprint = blueprintId
|
||||
? await payload
|
||||
.findByID({
|
||||
collection: "structures",
|
||||
id: blueprintId,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
})
|
||||
.catch(() => null)
|
||||
: null;
|
||||
|
||||
if (!blueprint?.interiorEnabled || !Array.isArray(blueprint.rooms) || blueprint.rooms.length === 0) {
|
||||
return { provisioned: false, rooms: 0 };
|
||||
}
|
||||
|
||||
const access = blueprint.interiorAccess;
|
||||
snapshot = {
|
||||
...(snapshot ?? {}),
|
||||
rooms: blueprint.rooms,
|
||||
floorplan: relId(blueprint.floorplan) ?? null,
|
||||
floorplanAlt: blueprint.floorplanAlt ?? null,
|
||||
interiorAccess: access
|
||||
? {
|
||||
mode: access.mode ?? "anyone",
|
||||
roles: (access.roles ?? []).map(relId).filter((v): v is number => v != null),
|
||||
users: (access.users ?? []).map(relId).filter((v): v is number => v != null),
|
||||
}
|
||||
: snapshot?.interiorAccess,
|
||||
};
|
||||
|
||||
await payload.update({
|
||||
collection: "game-structures",
|
||||
id: relId(structure.id)!,
|
||||
overrideAccess: true,
|
||||
data: { interior: snapshot },
|
||||
});
|
||||
}
|
||||
|
||||
if (!snapshot || !Array.isArray(snapshot.rooms)) {
|
||||
return { provisioned: false, rooms: 0 };
|
||||
}
|
||||
|
|
@ -50,7 +100,7 @@ export async function provisionInterior(
|
|||
overrideAccess: true,
|
||||
data: {
|
||||
interior: {
|
||||
...(structure.interior as Record<string, unknown>),
|
||||
...(snapshot as Record<string, unknown>),
|
||||
provisionedAt: new Date().toISOString(),
|
||||
},
|
||||
},
|
||||
|
|
|
|||
|
|
@ -5,9 +5,12 @@
|
|||
*/
|
||||
export 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;
|
||||
if (value !== null && typeof value === "object") {
|
||||
const obj = value as { id?: unknown; relationTo?: unknown; value?: unknown };
|
||||
// Polymorphic relationships (recipe outputs, junk loot items) read back
|
||||
// verbatim as `{ relationTo, value }` at depth 0; unwrap those first.
|
||||
if ("relationTo" in obj && typeof obj.value === "number") return obj.value;
|
||||
if ("id" in obj && typeof obj.id === "number") return obj.id;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -693,6 +693,74 @@ describe("Interior job start gates", () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe("Interior snapshot bootstrap from blueprint", () => {
|
||||
it("copies an authored blueprint interior into the runtime snapshot on first entry and never retargets", async () => {
|
||||
const blueprint = await makeBlueprint("bootstrap-blueprint");
|
||||
const authoredRooms = [
|
||||
{
|
||||
key: "hall",
|
||||
name: "Hall",
|
||||
hotspot: { x: 5, y: 5, width: 40, height: 40 },
|
||||
initialLevel: 1,
|
||||
maxLevel: 2,
|
||||
levels: [{ level: 1, upgradeDurationMinutes: 5 }],
|
||||
},
|
||||
];
|
||||
await payload.update({
|
||||
collection: "structures",
|
||||
id: blueprint.id,
|
||||
overrideAccess: true,
|
||||
data: {
|
||||
interiorEnabled: true,
|
||||
rooms: authoredRooms,
|
||||
interiorAccess: { mode: "anyone" },
|
||||
} as Record<string, unknown>,
|
||||
});
|
||||
|
||||
// A game structure created WITHOUT any interior snapshot.
|
||||
const fresh = (await payload.create({
|
||||
collection: "game-structures",
|
||||
data: {
|
||||
name: `${RUN} bootstrap-structure`,
|
||||
type: blueprint.id,
|
||||
constructionStatus: "complete",
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
})) as unknown as GameStructure;
|
||||
created.structures.push(fresh.id);
|
||||
|
||||
const first = await provisionInterior(payload, await fetchStructure(fresh.id));
|
||||
expect(first).toEqual({ provisioned: true, rooms: 1 });
|
||||
|
||||
let stored = await fetchStructure(fresh.id);
|
||||
const snapshotRooms = stored.interior?.rooms as Array<Record<string, unknown>>;
|
||||
expect(Array.isArray(snapshotRooms) && snapshotRooms.length).toBe(1);
|
||||
expect(snapshotRooms[0]?.key).toBe("hall");
|
||||
expect((stored.interior as { provisionedAt?: string }).provisionedAt).toBeTruthy();
|
||||
const hall = await roomByKey(fresh.id, "hall");
|
||||
expect(hall.level).toBe(1);
|
||||
|
||||
// Editing the blueprint afterwards must not retarget the live snapshot.
|
||||
await payload.update({
|
||||
collection: "structures",
|
||||
id: blueprint.id,
|
||||
overrideAccess: true,
|
||||
data: {
|
||||
rooms: [
|
||||
{ key: "hall", name: "Hall", hotspot: { x: 5, y: 5, width: 40, height: 40 }, initialLevel: 1, maxLevel: 2, levels: [] },
|
||||
{ key: "wing", name: "Wing", hotspot: { x: 55, y: 5, width: 40, height: 40 }, initialLevel: 0, maxLevel: 1, levels: [] },
|
||||
],
|
||||
} as Record<string, unknown>,
|
||||
});
|
||||
const second = await provisionInterior(payload, await fetchStructure(fresh.id));
|
||||
expect(second.provisioned).toBe(false);
|
||||
stored = await fetchStructure(fresh.id);
|
||||
const after = stored.interior?.rooms as Array<Record<string, unknown>>;
|
||||
expect(after.length).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Interior cancel refund and collect credit", () => {
|
||||
it("withdraws committed materials at start, refunds them on cancel, and credits them on collect", async () => {
|
||||
const blueprint = await makeBlueprint("refund-blueprint", 1000);
|
||||
|
|
@ -742,15 +810,18 @@ describe("Interior cancel refund and collect credit", () => {
|
|||
expect(cancelledJob.output?.resources).toHaveLength(1);
|
||||
expect(Number(cancelledJob.output?.resources?.[0]?.resource)).toBe(scrap.id);
|
||||
expect(cancelledJob.output?.resources?.[0]?.amount).toBe(10);
|
||||
expect((await roomById(room.id)).pendingJob).toBeNull();
|
||||
|
||||
// The refund is credited on the normal collect path.
|
||||
await payload.update({
|
||||
collection: "interior-jobs",
|
||||
id: started.job.id,
|
||||
data: { status: "awaiting_collect" },
|
||||
overrideAccess: true,
|
||||
// The output slot stays occupied by the parked refund until it is collected.
|
||||
expect((await roomById(room.id)).pendingJob).toBe(started.job.id);
|
||||
const busyStart = await startInteriorJob(payload, { id: member.id }, {
|
||||
structureId: structure.id,
|
||||
roomKey: "workshop",
|
||||
type: "cleanup",
|
||||
});
|
||||
expect(!busyStart.ok && busyStart.error === "room_busy").toBe(true);
|
||||
|
||||
// The refund is credited on the normal collect path, straight from
|
||||
// `cancelled` - no status faking required.
|
||||
const collected = await collectInteriorJob(payload, { id: member.id }, started.job.id);
|
||||
expect(collected.ok).toBe(true);
|
||||
|
||||
|
|
@ -1391,6 +1462,10 @@ describe("Interior presence-based unlocks", () => {
|
|||
expect(plain.ok).toBe(true);
|
||||
if (!plain.ok) return;
|
||||
expect((await cancelInteriorJob(payload, { id: member.id }, plain.job.id)).ok).toBe(true);
|
||||
// Collecting the parked cancellation releases the room's output slot.
|
||||
expect(
|
||||
(await collectInteriorJob(payload, { id: member.id }, plain.job.id)).ok,
|
||||
).toBe(true);
|
||||
|
||||
// Raising the runtime room level applies the unlocking level's effects.
|
||||
await payload.update({
|
||||
|
|
@ -1586,6 +1661,62 @@ describe("Interior asset output credit", () => {
|
|||
expect(Number(afterSecond[0]?.asset)).toBe(asset.id);
|
||||
expect(afterSecond[0]?.quantity).toBe(5);
|
||||
});
|
||||
|
||||
it("credits resource outputs of a mixed job while its asset leg stays parked", async () => {
|
||||
await setAssetOutputsEnabled(false);
|
||||
const blueprint = await makeBlueprint("mixed-blueprint", 1000);
|
||||
const structure = await makeStructure({
|
||||
label: "mixed-structure",
|
||||
blueprintId: blueprint.id,
|
||||
rooms: [
|
||||
{
|
||||
key: "bay",
|
||||
name: "Bay",
|
||||
initialLevel: 1,
|
||||
maxLevel: 1,
|
||||
levels: [{ level: 1, upgradeDurationMinutes: 5 }],
|
||||
},
|
||||
],
|
||||
});
|
||||
await provisionInterior(payload, await fetchStructure(structure.id));
|
||||
const room = await roomByKey(structure.id, "bay");
|
||||
const now = new Date().toISOString();
|
||||
|
||||
const job = (await payload.create({
|
||||
collection: "interior-jobs",
|
||||
data: {
|
||||
structure: structure.id,
|
||||
room: room.id,
|
||||
type: "produce",
|
||||
status: "awaiting_collect",
|
||||
targetLevel: 1,
|
||||
startedBy: member.id,
|
||||
startedAt: now,
|
||||
endsAt: now,
|
||||
output: {
|
||||
resources: [{ resource: scrap.id, amount: 4 }],
|
||||
assets: [{ asset: asset.id, amount: 1 }],
|
||||
},
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
})) as unknown as InteriorJob;
|
||||
|
||||
const first = await collectInteriorJob(payload, { id: member.id }, job.id);
|
||||
expect(first).toEqual({ ok: false, error: "asset_outputs_disabled" });
|
||||
// The whole collect is atomic: nothing was credited and the job stays parked.
|
||||
expect(await storedAmount(payload, structure.id, scrap.id)).toBe(0);
|
||||
expect((await jobById(job.id)).status).toBe("awaiting_collect");
|
||||
|
||||
// Enabling the switch lets the same job collect in full, exactly once.
|
||||
await setAssetOutputsEnabled(true);
|
||||
expect(await collectInteriorJob(payload, { id: member.id }, job.id)).toEqual({ ok: true });
|
||||
expect(await storedAmount(payload, structure.id, scrap.id)).toBe(4);
|
||||
const assets = (await fetchStructure(structure.id)).storedAssets ?? [];
|
||||
expect(assets).toHaveLength(1);
|
||||
expect(assets[0]?.quantity).toBe(1);
|
||||
expect((await jobById(job.id)).status).toBe("collected");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Interior repair completion", () => {
|
||||
|
|
@ -2013,6 +2144,10 @@ describe("Interior room condition gate", () => {
|
|||
expect(
|
||||
(await cancelInteriorJob(payload, { id: member.id }, healthy.job.id)).ok,
|
||||
).toBe(true);
|
||||
// Release the slot before the final condition-0 probe in this same room.
|
||||
expect(
|
||||
(await collectInteriorJob(payload, { id: member.id }, healthy.job.id)).ok,
|
||||
).toBe(true);
|
||||
}
|
||||
|
||||
await payload.update({
|
||||
|
|
|
|||
Loading…
Reference in a new issue