Reserve personnel, vehicles, cargo, and budget with idempotent keys and exactly-once settlement; extraction effects preflight before any write so validated HQ deposits and locker credits are final and survive mission failure. Failure sweeps touch only unextracted reservations. Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent) Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
211 lines
6.7 KiB
TypeScript
211 lines
6.7 KiB
TypeScript
import type { Payload, PayloadRequest } from "payload";
|
|
import type { OperationReservation } from "@/payload-types";
|
|
import {
|
|
type ReservationRow,
|
|
type ReserveOperationAssetsInput,
|
|
type SettlementConsumed,
|
|
type SettlementOutcome,
|
|
type SettlementRecord,
|
|
} from "./allocationTypes";
|
|
import { validateReservation } from "./allocationValidate";
|
|
import {
|
|
computeReturned,
|
|
defaultReason,
|
|
normalizeConsumed,
|
|
reservedAmounts,
|
|
} from "./settlementMath";
|
|
|
|
/**
|
|
* Mission allocation reservations: reserve assets against an operation, then
|
|
* settle each reservation exactly once.
|
|
*
|
|
* Reservations are earmarks with capacity checks. No locker, shipment, bank,
|
|
* or storage rows are mutated here: reserving validates that the requested
|
|
* personnel, vehicles, cargo, and treasury budget are available (net of other
|
|
* active reservations), and settlement records the consumed versus returned
|
|
* amounts on the reservation row itself. Actual asset movement from these
|
|
* settlement records is extraction/economy scope (later roadmap tasks).
|
|
*
|
|
* Non-negotiable policy: a later mission failure must not reverse any
|
|
* separately validated extraction deposit. `failOperationReservations` only
|
|
* settles rows still in `reserved` state and never writes to the
|
|
* operation-effects ledger, so recorded extraction effects stay final.
|
|
*/
|
|
|
|
export type {
|
|
ReservationCargoLine,
|
|
ReservationRow,
|
|
ReserveOperationAssetsInput,
|
|
ReservePersonnelLine,
|
|
SettlementAmounts,
|
|
SettlementConsumed,
|
|
SettlementOutcome,
|
|
SettlementRecord,
|
|
} from "./allocationTypes";
|
|
|
|
export { expireOperationReservations, failOperationReservations } from "./allocationSweep";
|
|
|
|
function pgErrorCode(error: unknown): string | undefined {
|
|
const cause = (error as { cause?: { code?: string } })?.cause;
|
|
return cause?.code ?? (error as { code?: string })?.code;
|
|
}
|
|
|
|
async function findByKey(
|
|
payload: Payload,
|
|
key: string,
|
|
req?: PayloadRequest,
|
|
): Promise<OperationReservation | null> {
|
|
const res = await payload.find({
|
|
collection: "operation-reservations",
|
|
where: { reservationKey: { equals: key } },
|
|
limit: 1,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
req,
|
|
});
|
|
return (res.docs[0] as OperationReservation | undefined) ?? null;
|
|
}
|
|
|
|
async function activeReservationRows(
|
|
payload: Payload,
|
|
req?: PayloadRequest,
|
|
): Promise<ReservationRow[]> {
|
|
const res = await payload.find({
|
|
collection: "operation-reservations",
|
|
where: { status: { equals: "reserved" } },
|
|
limit: 1000,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
req,
|
|
});
|
|
return res.docs as unknown as ReservationRow[];
|
|
}
|
|
|
|
/**
|
|
* Reserve assets for an operation. Idempotent by `reservationKey`: a retry
|
|
* with an existing key returns the stored row. Every capacity check runs
|
|
* before the create, so an insufficient allocation fails without partial
|
|
* writes.
|
|
*/
|
|
export async function reserveOperationAssets(
|
|
payload: Payload,
|
|
input: ReserveOperationAssetsInput,
|
|
req?: PayloadRequest,
|
|
): Promise<OperationReservation> {
|
|
if (input.reservationKey) {
|
|
const existing = await findByKey(payload, input.reservationKey, req);
|
|
if (existing) return existing;
|
|
}
|
|
|
|
const active = await activeReservationRows(payload, req);
|
|
await validateReservation(payload, input, active, req);
|
|
|
|
try {
|
|
return (await payload.create({
|
|
collection: "operation-reservations",
|
|
data: {
|
|
reservationKey: input.reservationKey,
|
|
operationId: input.operationId,
|
|
mission: input.missionId ?? null,
|
|
status: "reserved",
|
|
personnel: (input.personnel ?? []).map((p) => ({ user: p.userId, slot: p.slot ?? null })),
|
|
vehicles: (input.vehicleIds ?? []).map((v) => ({ vehicle: v })),
|
|
cargo: (input.cargo ?? []).map((c) => ({ resource: c.resourceId, amount: c.amount })),
|
|
...(input.budget
|
|
? { budget: { account: input.budget.accountId, amount: input.budget.amount } }
|
|
: {}),
|
|
origin: input.originId ?? null,
|
|
destination: input.destinationId ?? null,
|
|
expiresAt: input.expiresAt ?? null,
|
|
createdBy: input.actorId,
|
|
},
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
req,
|
|
})) as unknown as OperationReservation;
|
|
} catch (error) {
|
|
if (pgErrorCode(error) === "23505") {
|
|
// Unique-constraint race on reservationKey: the other request won.
|
|
const existing = await findByKey(payload, input.reservationKey, req);
|
|
if (existing) return existing;
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Settle a reservation exactly once. A reservation already in a terminal
|
|
* state is returned unchanged (idempotent no-op); the stored status is
|
|
* re-read immediately before the outcome is computed, mirroring the
|
|
* completeShipment guard.
|
|
*/
|
|
export async function settleOperationReservation(
|
|
payload: Payload,
|
|
ref: { reservationId?: number; reservationKey?: string },
|
|
opts: {
|
|
outcome: SettlementOutcome;
|
|
consumed?: SettlementConsumed;
|
|
reason?: string;
|
|
effectId?: number;
|
|
actorId?: number;
|
|
},
|
|
req?: PayloadRequest,
|
|
): Promise<OperationReservation> {
|
|
let located: OperationReservation | null = null;
|
|
if (ref.reservationId != null) {
|
|
located = (await payload
|
|
.findByID({
|
|
collection: "operation-reservations",
|
|
id: ref.reservationId,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
req,
|
|
})
|
|
.catch(() => null)) as unknown as OperationReservation | null;
|
|
} else if (ref.reservationKey) {
|
|
located = await findByKey(payload, ref.reservationKey, req);
|
|
}
|
|
if (!located) throw new Error("Reservation not found.");
|
|
|
|
// Fresh re-read: another caller may have settled since `located` was read.
|
|
const fresh = (await payload
|
|
.findByID({
|
|
collection: "operation-reservations",
|
|
id: located.id,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
req,
|
|
})
|
|
.catch(() => null)) as unknown as OperationReservation | null;
|
|
if (!fresh) throw new Error("Reservation not found.");
|
|
if (fresh.status !== "reserved") return fresh;
|
|
|
|
const row = fresh as unknown as ReservationRow;
|
|
const reserved = reservedAmounts(row);
|
|
const consumed = normalizeConsumed(reserved, opts.outcome, opts.consumed);
|
|
const returned = computeReturned(reserved, consumed);
|
|
|
|
const settlement: SettlementRecord = {
|
|
outcome: opts.outcome,
|
|
reason: opts.reason ?? defaultReason(opts.outcome),
|
|
consumed,
|
|
returned,
|
|
actorId: opts.actorId ?? null,
|
|
effectId: opts.effectId ?? null,
|
|
settledAt: new Date().toISOString(),
|
|
};
|
|
|
|
return (await payload.update({
|
|
collection: "operation-reservations",
|
|
id: fresh.id,
|
|
data: {
|
|
status: opts.outcome,
|
|
settledAt: settlement.settledAt,
|
|
settledByEffect: opts.effectId ?? null,
|
|
settlement,
|
|
},
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
req,
|
|
})) as unknown as OperationReservation;
|
|
}
|