감사 수집과 저장 장애를 게임 진행에서 분리한다
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
import { asRecord } from '@sammo-ts/common';
|
||||
import type { InMemoryTurnWorld } from '../turn/inMemoryWorld.js';
|
||||
|
||||
/** A bounded, sticky notice: later successful writes cannot make history complete again. */
|
||||
export const markAuditGap = (world: InMemoryTurnWorld, stage: string): void => {
|
||||
const state = world.getState();
|
||||
const previous = asRecord(state.meta.playAuditGap);
|
||||
world.updateWorldMeta({
|
||||
playAuditGap: {
|
||||
serverId: state.meta.serverId ?? null,
|
||||
firstYear:
|
||||
previous.serverId === state.meta.serverId
|
||||
? (previous.firstYear ?? state.currentYear)
|
||||
: state.currentYear,
|
||||
firstMonth:
|
||||
previous.serverId === state.meta.serverId
|
||||
? (previous.firstMonth ?? state.currentMonth)
|
||||
: state.currentMonth,
|
||||
lastYear: state.currentYear,
|
||||
lastMonth: state.currentMonth,
|
||||
stage,
|
||||
},
|
||||
});
|
||||
console.warn(`[play-audit] ${stage}: history gap recorded; gameplay continues.`);
|
||||
};
|
||||
|
||||
export const collectPlayAudit = <T>(world: InMemoryTurnWorld, stage: string, collect: () => T, fallback: T): T => {
|
||||
try {
|
||||
return collect();
|
||||
} catch {
|
||||
markAuditGap(world, stage);
|
||||
return fallback;
|
||||
}
|
||||
};
|
||||
@@ -1,3 +1,4 @@
|
||||
import { collectPlayAudit } from './bestEffort.js';
|
||||
import { asRecord } from '@sammo-ts/common';
|
||||
import type { InMemoryTurnWorld, TurnCalendarHandler } from '../turn/inMemoryWorld.js';
|
||||
import { buildAuditSnapshot, type AuditSettlement } from './snapshot.js';
|
||||
@@ -32,86 +33,104 @@ const readFlows = (world: InMemoryTurnWorld): MonthlyFlows => {
|
||||
return { year: state.currentYear, month: state.currentMonth, complete: matches && raw.complete === true, entries };
|
||||
};
|
||||
|
||||
export const recordAuditSettlement = (world: InMemoryTurnWorld, settlement: AuditSettlement): void => {
|
||||
if (typeof world.getState().meta.serverId !== 'string') return;
|
||||
const flows = readFlows(world);
|
||||
const key = `${settlement.nationId}:${settlement.resource}`;
|
||||
const previous = flows.entries[key];
|
||||
flows.entries[key] = {
|
||||
...settlement,
|
||||
income: (previous?.income ?? 0) + settlement.income,
|
||||
paid: (previous?.paid ?? 0) + settlement.paid,
|
||||
};
|
||||
// 월내 flush/reload에도 누적값을 잃지 않도록 작은 국가별 합계만 world meta에 보존한다.
|
||||
world.updateWorldMeta({ playAuditFlows: flows });
|
||||
};
|
||||
export const recordAuditSettlement = (world: InMemoryTurnWorld, settlement: AuditSettlement): void =>
|
||||
collectPlayAudit(
|
||||
world,
|
||||
'recordAuditSettlement',
|
||||
() => {
|
||||
if (typeof world.getState().meta.serverId !== 'string') return;
|
||||
const flows = readFlows(world);
|
||||
const key = `${settlement.nationId}:${settlement.resource}`;
|
||||
const previous = flows.entries[key];
|
||||
flows.entries[key] = {
|
||||
...settlement,
|
||||
income: (previous?.income ?? 0) + settlement.income,
|
||||
paid: (previous?.paid ?? 0) + settlement.paid,
|
||||
};
|
||||
// 월내 flush/reload에도 누적값을 잃지 않도록 작은 국가별 합계만 world meta에 보존한다.
|
||||
world.updateWorldMeta({ playAuditFlows: flows });
|
||||
},
|
||||
undefined
|
||||
);
|
||||
|
||||
export const queueAuditMonth = (
|
||||
world: InMemoryTurnWorld,
|
||||
kind: 'MONTH_END' | 'FINAL' | 'INITIAL' = 'MONTH_END'
|
||||
): void => {
|
||||
const state = world.getState();
|
||||
const serverId = state.meta.serverId;
|
||||
// identity 없는 레거시 fixture/설치에서 profile명으로 가짜 기수를 만들지 않는다.
|
||||
if (typeof serverId !== 'string' || !serverId.trim()) return;
|
||||
const flows = readFlows(world);
|
||||
const snapshot = buildAuditSnapshot({
|
||||
nations: world.listNations(),
|
||||
cities: world.listCities(),
|
||||
generals: world.listGenerals(),
|
||||
settlements: Object.values(flows.entries),
|
||||
settlementsComplete: flows.complete,
|
||||
});
|
||||
world.queueAuditMonth({
|
||||
...snapshot,
|
||||
serverId,
|
||||
year: state.currentYear,
|
||||
month: state.currentMonth,
|
||||
tick: kind === 'INITIAL' ? world.getGameClockState().tick : (state.lastTurnTick ?? null),
|
||||
kind,
|
||||
settlementsComplete: flows.complete,
|
||||
});
|
||||
};
|
||||
): void =>
|
||||
collectPlayAudit(
|
||||
world,
|
||||
'queueAuditMonth',
|
||||
() => {
|
||||
const state = world.getState();
|
||||
const serverId = state.meta.serverId;
|
||||
// identity 없는 레거시 fixture/설치에서 profile명으로 가짜 기수를 만들지 않는다.
|
||||
if (typeof serverId !== 'string' || !serverId.trim()) return;
|
||||
const flows = readFlows(world);
|
||||
const snapshot = buildAuditSnapshot({
|
||||
nations: world.listNations(),
|
||||
cities: world.listCities(),
|
||||
generals: world.listGenerals(),
|
||||
settlements: Object.values(flows.entries),
|
||||
settlementsComplete: flows.complete,
|
||||
});
|
||||
world.queueAuditMonth({
|
||||
...snapshot,
|
||||
serverId,
|
||||
year: state.currentYear,
|
||||
month: state.currentMonth,
|
||||
tick: kind === 'INITIAL' ? world.getGameClockState().tick : (state.lastTurnTick ?? null),
|
||||
kind,
|
||||
settlementsComplete: flows.complete,
|
||||
});
|
||||
},
|
||||
undefined
|
||||
);
|
||||
|
||||
/** 도입 당시 상태는 월말로 가장하지 않고 기수별 최초 기준으로 한 번 고정한다. */
|
||||
export const initializeAuditCollection = (world: InMemoryTurnWorld, observedAt = new Date()): boolean => {
|
||||
const state = world.getState();
|
||||
const serverId = state.meta.serverId;
|
||||
if (typeof serverId !== 'string' || !serverId.trim()) return false;
|
||||
const previous = asRecord(state.meta.playAuditCollection);
|
||||
if (previous.serverId === serverId) {
|
||||
if (
|
||||
previous.schemaVersion !== 1 ||
|
||||
typeof previous.year !== 'number' ||
|
||||
!Number.isInteger(previous.year) ||
|
||||
previous.year < 0 ||
|
||||
typeof previous.month !== 'number' ||
|
||||
!Number.isInteger(previous.month) ||
|
||||
previous.month < 1 ||
|
||||
previous.month > 12 ||
|
||||
typeof previous.tick !== 'number' ||
|
||||
!Number.isSafeInteger(previous.tick) ||
|
||||
previous.tick < 0 ||
|
||||
typeof previous.observedAt !== 'string' ||
|
||||
!Number.isFinite(Date.parse(previous.observedAt)) ||
|
||||
previous.year * 12 + previous.month > state.currentYear * 12 + state.currentMonth
|
||||
)
|
||||
throw new Error('Invalid play audit collection boundary');
|
||||
return false;
|
||||
}
|
||||
queueAuditMonth(world, 'INITIAL');
|
||||
world.updateWorldMeta({
|
||||
playAuditCollection: {
|
||||
schemaVersion: 1,
|
||||
serverId,
|
||||
year: state.currentYear,
|
||||
month: state.currentMonth,
|
||||
tick: world.getGameClockState().tick,
|
||||
observedAt: observedAt.toISOString(),
|
||||
export const initializeAuditCollection = (world: InMemoryTurnWorld, observedAt = new Date()): boolean =>
|
||||
collectPlayAudit(
|
||||
world,
|
||||
'initializeAuditCollection',
|
||||
() => {
|
||||
const state = world.getState();
|
||||
const serverId = state.meta.serverId;
|
||||
if (typeof serverId !== 'string' || !serverId.trim()) return false;
|
||||
const previous = asRecord(state.meta.playAuditCollection);
|
||||
if (previous.serverId === serverId) {
|
||||
if (
|
||||
previous.schemaVersion !== 1 ||
|
||||
typeof previous.year !== 'number' ||
|
||||
!Number.isInteger(previous.year) ||
|
||||
previous.year < 0 ||
|
||||
typeof previous.month !== 'number' ||
|
||||
!Number.isInteger(previous.month) ||
|
||||
previous.month < 1 ||
|
||||
previous.month > 12 ||
|
||||
typeof previous.tick !== 'number' ||
|
||||
!Number.isSafeInteger(previous.tick) ||
|
||||
previous.tick < 0 ||
|
||||
typeof previous.observedAt !== 'string' ||
|
||||
!Number.isFinite(Date.parse(previous.observedAt)) ||
|
||||
previous.year * 12 + previous.month > state.currentYear * 12 + state.currentMonth
|
||||
)
|
||||
throw new Error('Invalid play audit collection boundary');
|
||||
return false;
|
||||
}
|
||||
queueAuditMonth(world, 'INITIAL');
|
||||
world.updateWorldMeta({
|
||||
playAuditCollection: {
|
||||
schemaVersion: 1,
|
||||
serverId,
|
||||
year: state.currentYear,
|
||||
month: state.currentMonth,
|
||||
tick: world.getGameClockState().tick,
|
||||
observedAt: observedAt.toISOString(),
|
||||
},
|
||||
});
|
||||
return true;
|
||||
},
|
||||
});
|
||||
return true;
|
||||
};
|
||||
false
|
||||
);
|
||||
|
||||
export const createPlayAuditHandler = (getWorld: () => InMemoryTurnWorld | null): TurnCalendarHandler => ({
|
||||
beforeMonthChanged: (context) => {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { collectPlayAudit } from './bestEffort.js';
|
||||
import { asRecord } from '@sammo-ts/common';
|
||||
import type { InMemoryTurnWorld } from '../turn/inMemoryWorld.js';
|
||||
import type { TurnDiplomacy } from '../turn/types.js';
|
||||
@@ -7,46 +8,52 @@ export const recordMonthlyAuditDiplomacy = (
|
||||
world: InMemoryTurnWorld,
|
||||
before: readonly TurnDiplomacy[],
|
||||
afterByKey: ReadonlyMap<string, TurnDiplomacy>
|
||||
): void => {
|
||||
const state = world.getState();
|
||||
const serverId = state.meta.serverId;
|
||||
if (typeof serverId !== 'string' || !serverId.trim()) return;
|
||||
const clock = world.getGameClockState();
|
||||
const project = (entry: TurnDiplomacy) => ({ state: entry.state, term: entry.term, dead: entry.dead });
|
||||
let ordinal = 0;
|
||||
for (const entry of [...before].sort(
|
||||
(left, right) => left.fromNationId - right.fromNationId || left.toNationId - right.toNationId
|
||||
)) {
|
||||
const next = afterByKey.get(`${entry.fromNationId}:${entry.toNationId}`);
|
||||
if (!next) continue;
|
||||
const previousState = project(entry);
|
||||
const nextState = project(next);
|
||||
if (JSON.stringify(previousState) === JSON.stringify(nextState)) continue;
|
||||
world.queueAuditDiplomacy({
|
||||
schemaVersion: 1,
|
||||
serverId,
|
||||
srcNationId: entry.fromNationId,
|
||||
destNationId: entry.toNationId,
|
||||
category: 'RELATION',
|
||||
source: 'ENGINE',
|
||||
eventType: 'MONTHLY_RELATION_CHANGED',
|
||||
documentId: null,
|
||||
documentHash: null,
|
||||
previousDocumentId: null,
|
||||
year: state.currentYear,
|
||||
month: state.currentMonth,
|
||||
tick: BigInt(clock.tick),
|
||||
clockRevision: BigInt(clock.revision),
|
||||
executionId: `monthly:${state.currentYear}:${state.currentMonth}:${clock.revision}`,
|
||||
ordinal: ++ordinal,
|
||||
requestId: null,
|
||||
inputSequence: null,
|
||||
actor: null,
|
||||
before: previousState,
|
||||
after: nextState,
|
||||
});
|
||||
}
|
||||
};
|
||||
): void =>
|
||||
collectPlayAudit(
|
||||
world,
|
||||
'recordMonthlyAuditDiplomacy',
|
||||
() => {
|
||||
const state = world.getState();
|
||||
const serverId = state.meta.serverId;
|
||||
if (typeof serverId !== 'string' || !serverId.trim()) return;
|
||||
const clock = world.getGameClockState();
|
||||
const project = (entry: TurnDiplomacy) => ({ state: entry.state, term: entry.term, dead: entry.dead });
|
||||
let ordinal = 0;
|
||||
for (const entry of [...before].sort(
|
||||
(left, right) => left.fromNationId - right.fromNationId || left.toNationId - right.toNationId
|
||||
)) {
|
||||
const next = afterByKey.get(`${entry.fromNationId}:${entry.toNationId}`);
|
||||
if (!next) continue;
|
||||
const previousState = project(entry);
|
||||
const nextState = project(next);
|
||||
if (JSON.stringify(previousState) === JSON.stringify(nextState)) continue;
|
||||
world.queueAuditDiplomacy({
|
||||
schemaVersion: 1,
|
||||
serverId,
|
||||
srcNationId: entry.fromNationId,
|
||||
destNationId: entry.toNationId,
|
||||
category: 'RELATION',
|
||||
source: 'ENGINE',
|
||||
eventType: 'MONTHLY_RELATION_CHANGED',
|
||||
documentId: null,
|
||||
documentHash: null,
|
||||
previousDocumentId: null,
|
||||
year: state.currentYear,
|
||||
month: state.currentMonth,
|
||||
tick: BigInt(clock.tick),
|
||||
clockRevision: BigInt(clock.revision),
|
||||
executionId: `monthly:${state.currentYear}:${state.currentMonth}:${clock.revision}`,
|
||||
ordinal: ++ordinal,
|
||||
requestId: null,
|
||||
inputSequence: null,
|
||||
actor: null,
|
||||
before: previousState,
|
||||
after: nextState,
|
||||
});
|
||||
}
|
||||
},
|
||||
undefined
|
||||
);
|
||||
|
||||
export interface AuditDiplomacyAction {
|
||||
actionKey: string;
|
||||
@@ -68,116 +75,133 @@ export const recordTurnAuditDiplomacy = (
|
||||
after: TurnDiplomacy,
|
||||
action: AuditDiplomacyAction,
|
||||
turn: { generalId: number; tick: number; ordinal: number }
|
||||
): void => {
|
||||
const state = world.getState();
|
||||
const serverId = state.meta.serverId;
|
||||
if (typeof serverId !== 'string' || !serverId.trim()) return;
|
||||
const previousState = { state: before.state, term: before.term, dead: before.dead };
|
||||
const nextState = { state: after.state, term: after.term, dead: after.dead };
|
||||
if (JSON.stringify(previousState) === JSON.stringify(nextState)) return;
|
||||
const clock = world.getGameClockState();
|
||||
world.queueAuditDiplomacy({
|
||||
schemaVersion: 1,
|
||||
serverId,
|
||||
srcNationId: before.fromNationId,
|
||||
destNationId: before.toNationId,
|
||||
category: 'RELATION',
|
||||
source: 'ENGINE',
|
||||
eventType: 'TURN_RELATION_CHANGED',
|
||||
documentId: null,
|
||||
documentHash: null,
|
||||
previousDocumentId: null,
|
||||
year: state.currentYear,
|
||||
month: state.currentMonth,
|
||||
tick: BigInt(turn.tick),
|
||||
clockRevision: BigInt(clock.revision),
|
||||
executionId: `turn:${turn.generalId}:${turn.tick}:${clock.revision}`,
|
||||
ordinal: turn.ordinal,
|
||||
requestId: null,
|
||||
inputSequence: null,
|
||||
actor: { ...action.actor, actionKey: action.actionKey, kind: action.kind, actionOrdinal: action.actionOrdinal },
|
||||
before: previousState,
|
||||
after: nextState,
|
||||
});
|
||||
};
|
||||
): void =>
|
||||
collectPlayAudit(
|
||||
world,
|
||||
'recordTurnAuditDiplomacy',
|
||||
() => {
|
||||
const state = world.getState();
|
||||
const serverId = state.meta.serverId;
|
||||
if (typeof serverId !== 'string' || !serverId.trim()) return;
|
||||
const previousState = { state: before.state, term: before.term, dead: before.dead };
|
||||
const nextState = { state: after.state, term: after.term, dead: after.dead };
|
||||
if (JSON.stringify(previousState) === JSON.stringify(nextState)) return;
|
||||
const clock = world.getGameClockState();
|
||||
world.queueAuditDiplomacy({
|
||||
schemaVersion: 1,
|
||||
serverId,
|
||||
srcNationId: before.fromNationId,
|
||||
destNationId: before.toNationId,
|
||||
category: 'RELATION',
|
||||
source: 'ENGINE',
|
||||
eventType: 'TURN_RELATION_CHANGED',
|
||||
documentId: null,
|
||||
documentHash: null,
|
||||
previousDocumentId: null,
|
||||
year: state.currentYear,
|
||||
month: state.currentMonth,
|
||||
tick: BigInt(turn.tick),
|
||||
clockRevision: BigInt(clock.revision),
|
||||
executionId: `turn:${turn.generalId}:${turn.tick}:${clock.revision}`,
|
||||
ordinal: turn.ordinal,
|
||||
requestId: null,
|
||||
inputSequence: null,
|
||||
actor: {
|
||||
...action.actor,
|
||||
actionKey: action.actionKey,
|
||||
kind: action.kind,
|
||||
actionOrdinal: action.actionOrdinal,
|
||||
},
|
||||
before: previousState,
|
||||
after: nextState,
|
||||
});
|
||||
},
|
||||
undefined
|
||||
);
|
||||
|
||||
/** 현재 로드된 관계를 도입 시 한 번만 고정한다. 과거 발생 원인/주체는 추정하지 않는다. */
|
||||
export const initializeAuditDiplomacy = (world: InMemoryTurnWorld, observedAt = new Date()): boolean => {
|
||||
const state = world.getState();
|
||||
const serverId = state.meta.serverId;
|
||||
if (typeof serverId !== 'string' || !serverId.trim()) return false;
|
||||
const previous = asRecord(state.meta.playAuditDiplomacy);
|
||||
if (previous.serverId === serverId) {
|
||||
if (
|
||||
previous.schemaVersion !== 1 ||
|
||||
typeof previous.year !== 'number' ||
|
||||
previous.year < 0 ||
|
||||
!Number.isInteger(previous.year) ||
|
||||
!Number.isInteger(previous.month) ||
|
||||
typeof previous.month !== 'number' ||
|
||||
previous.month < 1 ||
|
||||
previous.month > 12 ||
|
||||
typeof previous.tick !== 'number' ||
|
||||
!Number.isSafeInteger(previous.tick) ||
|
||||
previous.tick < 0 ||
|
||||
typeof previous.clockRevision !== 'number' ||
|
||||
!Number.isSafeInteger(previous.clockRevision) ||
|
||||
previous.clockRevision < 0 ||
|
||||
typeof previous.relationCount !== 'number' ||
|
||||
!Number.isInteger(previous.relationCount) ||
|
||||
previous.relationCount < 0 ||
|
||||
previous.year * 12 + previous.month > state.currentYear * 12 + state.currentMonth ||
|
||||
typeof previous.observedAt !== 'string' ||
|
||||
!Number.isFinite(Date.parse(previous.observedAt))
|
||||
)
|
||||
throw new Error('Invalid play audit diplomacy boundary');
|
||||
return false;
|
||||
}
|
||||
const clock = world.getGameClockState();
|
||||
const observedAtIso = observedAt.toISOString();
|
||||
const relations = world
|
||||
.listDiplomacy()
|
||||
.filter((entry) => entry.fromNationId > 0 && entry.toNationId > 0)
|
||||
.sort((left, right) => left.fromNationId - right.fromNationId || left.toNationId - right.toNationId);
|
||||
for (const [index, entry] of relations.entries()) {
|
||||
world.queueAuditDiplomacy({
|
||||
schemaVersion: 1,
|
||||
serverId,
|
||||
srcNationId: entry.fromNationId,
|
||||
destNationId: entry.toNationId,
|
||||
category: 'RELATION',
|
||||
source: 'BASELINE',
|
||||
eventType: 'RELATION_BASELINE',
|
||||
documentId: null,
|
||||
documentHash: null,
|
||||
previousDocumentId: null,
|
||||
year: state.currentYear,
|
||||
month: state.currentMonth,
|
||||
tick: BigInt(clock.tick),
|
||||
clockRevision: BigInt(clock.revision),
|
||||
executionId: 'relation-baseline',
|
||||
ordinal: index + 1,
|
||||
requestId: null,
|
||||
inputSequence: null,
|
||||
actor: null,
|
||||
before: null,
|
||||
after: { state: entry.state, term: entry.term, dead: entry.dead },
|
||||
});
|
||||
}
|
||||
world.updateWorldMeta({
|
||||
playAuditDiplomacy: {
|
||||
schemaVersion: 1,
|
||||
serverId,
|
||||
year: state.currentYear,
|
||||
month: state.currentMonth,
|
||||
tick: clock.tick,
|
||||
clockRevision: clock.revision,
|
||||
observedAt: observedAtIso,
|
||||
relationCount: relations.length,
|
||||
export const initializeAuditDiplomacy = (world: InMemoryTurnWorld, observedAt = new Date()): boolean =>
|
||||
collectPlayAudit(
|
||||
world,
|
||||
'initializeAuditDiplomacy',
|
||||
() => {
|
||||
const state = world.getState();
|
||||
const serverId = state.meta.serverId;
|
||||
if (typeof serverId !== 'string' || !serverId.trim()) return false;
|
||||
const previous = asRecord(state.meta.playAuditDiplomacy);
|
||||
if (previous.serverId === serverId) {
|
||||
if (
|
||||
previous.schemaVersion !== 1 ||
|
||||
typeof previous.year !== 'number' ||
|
||||
previous.year < 0 ||
|
||||
!Number.isInteger(previous.year) ||
|
||||
!Number.isInteger(previous.month) ||
|
||||
typeof previous.month !== 'number' ||
|
||||
previous.month < 1 ||
|
||||
previous.month > 12 ||
|
||||
typeof previous.tick !== 'number' ||
|
||||
!Number.isSafeInteger(previous.tick) ||
|
||||
previous.tick < 0 ||
|
||||
typeof previous.clockRevision !== 'number' ||
|
||||
!Number.isSafeInteger(previous.clockRevision) ||
|
||||
previous.clockRevision < 0 ||
|
||||
typeof previous.relationCount !== 'number' ||
|
||||
!Number.isInteger(previous.relationCount) ||
|
||||
previous.relationCount < 0 ||
|
||||
previous.year * 12 + previous.month > state.currentYear * 12 + state.currentMonth ||
|
||||
typeof previous.observedAt !== 'string' ||
|
||||
!Number.isFinite(Date.parse(previous.observedAt))
|
||||
)
|
||||
throw new Error('Invalid play audit diplomacy boundary');
|
||||
return false;
|
||||
}
|
||||
const clock = world.getGameClockState();
|
||||
const observedAtIso = observedAt.toISOString();
|
||||
const relations = world
|
||||
.listDiplomacy()
|
||||
.filter((entry) => entry.fromNationId > 0 && entry.toNationId > 0)
|
||||
.sort((left, right) => left.fromNationId - right.fromNationId || left.toNationId - right.toNationId);
|
||||
for (const [index, entry] of relations.entries()) {
|
||||
world.queueAuditDiplomacy({
|
||||
schemaVersion: 1,
|
||||
serverId,
|
||||
srcNationId: entry.fromNationId,
|
||||
destNationId: entry.toNationId,
|
||||
category: 'RELATION',
|
||||
source: 'BASELINE',
|
||||
eventType: 'RELATION_BASELINE',
|
||||
documentId: null,
|
||||
documentHash: null,
|
||||
previousDocumentId: null,
|
||||
year: state.currentYear,
|
||||
month: state.currentMonth,
|
||||
tick: BigInt(clock.tick),
|
||||
clockRevision: BigInt(clock.revision),
|
||||
executionId: 'relation-baseline',
|
||||
ordinal: index + 1,
|
||||
requestId: null,
|
||||
inputSequence: null,
|
||||
actor: null,
|
||||
before: null,
|
||||
after: { state: entry.state, term: entry.term, dead: entry.dead },
|
||||
});
|
||||
}
|
||||
world.updateWorldMeta({
|
||||
playAuditDiplomacy: {
|
||||
schemaVersion: 1,
|
||||
serverId,
|
||||
year: state.currentYear,
|
||||
month: state.currentMonth,
|
||||
tick: clock.tick,
|
||||
clockRevision: clock.revision,
|
||||
observedAt: observedAtIso,
|
||||
relationCount: relations.length,
|
||||
},
|
||||
});
|
||||
return true;
|
||||
},
|
||||
});
|
||||
return true;
|
||||
};
|
||||
false
|
||||
);
|
||||
|
||||
/** 국가 생멸로 생성/제거된 관계를 기록한다. 행위자나 명령은 관측하지 못했다면 추정하지 않는다. */
|
||||
export const recordNationAuditDiplomacy = (
|
||||
@@ -186,47 +210,53 @@ export const recordNationAuditDiplomacy = (
|
||||
relations: readonly TurnDiplomacy[],
|
||||
operation: 'CREATED' | 'REMOVED',
|
||||
observedTick?: number
|
||||
): void => {
|
||||
const state = world.getState();
|
||||
const serverId = state.meta.serverId;
|
||||
if (typeof serverId !== 'string' || !serverId.trim()) return;
|
||||
const targets = new Set(nationIds.filter((id) => id > 0));
|
||||
const observed = relations
|
||||
.filter(
|
||||
(entry) =>
|
||||
entry.fromNationId > 0 &&
|
||||
entry.toNationId > 0 &&
|
||||
(targets.has(entry.fromNationId) || targets.has(entry.toNationId))
|
||||
)
|
||||
.sort((left, right) => left.fromNationId - right.fromNationId || left.toNationId - right.toNationId);
|
||||
if (!observed.length) return;
|
||||
// 전역 순번은 실행 identity에만 사용한다. 한 사건 묶음 안의 순서는 방향별 local ordinal이다.
|
||||
const executionId = `nation-relations:${world.nextAuditOrdinal()}`;
|
||||
const clock = world.getGameClockState();
|
||||
for (const [index, entry] of observed.entries()) {
|
||||
const value = { state: entry.state, term: entry.term, dead: entry.dead };
|
||||
world.queueAuditDiplomacy({
|
||||
schemaVersion: 1,
|
||||
serverId,
|
||||
srcNationId: entry.fromNationId,
|
||||
destNationId: entry.toNationId,
|
||||
category: 'RELATION',
|
||||
source: 'ENGINE',
|
||||
eventType: `NATION_RELATION_${operation}`,
|
||||
documentId: null,
|
||||
documentHash: null,
|
||||
previousDocumentId: null,
|
||||
year: state.currentYear,
|
||||
month: state.currentMonth,
|
||||
tick: BigInt(observedTick ?? clock.tick),
|
||||
clockRevision: BigInt(clock.revision),
|
||||
executionId,
|
||||
ordinal: index + 1,
|
||||
requestId: null,
|
||||
inputSequence: null,
|
||||
actor: null,
|
||||
before: operation === 'REMOVED' ? value : null,
|
||||
after: operation === 'CREATED' ? value : null,
|
||||
});
|
||||
}
|
||||
};
|
||||
): void =>
|
||||
collectPlayAudit(
|
||||
world,
|
||||
'recordNationAuditDiplomacy',
|
||||
() => {
|
||||
const state = world.getState();
|
||||
const serverId = state.meta.serverId;
|
||||
if (typeof serverId !== 'string' || !serverId.trim()) return;
|
||||
const targets = new Set(nationIds.filter((id) => id > 0));
|
||||
const observed = relations
|
||||
.filter(
|
||||
(entry) =>
|
||||
entry.fromNationId > 0 &&
|
||||
entry.toNationId > 0 &&
|
||||
(targets.has(entry.fromNationId) || targets.has(entry.toNationId))
|
||||
)
|
||||
.sort((left, right) => left.fromNationId - right.fromNationId || left.toNationId - right.toNationId);
|
||||
if (!observed.length) return;
|
||||
// 전역 순번은 실행 identity에만 사용한다. 한 사건 묶음 안의 순서는 방향별 local ordinal이다.
|
||||
const executionId = `nation-relations:${world.nextAuditOrdinal()}`;
|
||||
const clock = world.getGameClockState();
|
||||
for (const [index, entry] of observed.entries()) {
|
||||
const value = { state: entry.state, term: entry.term, dead: entry.dead };
|
||||
world.queueAuditDiplomacy({
|
||||
schemaVersion: 1,
|
||||
serverId,
|
||||
srcNationId: entry.fromNationId,
|
||||
destNationId: entry.toNationId,
|
||||
category: 'RELATION',
|
||||
source: 'ENGINE',
|
||||
eventType: `NATION_RELATION_${operation}`,
|
||||
documentId: null,
|
||||
documentHash: null,
|
||||
previousDocumentId: null,
|
||||
year: state.currentYear,
|
||||
month: state.currentMonth,
|
||||
tick: BigInt(observedTick ?? clock.tick),
|
||||
clockRevision: BigInt(clock.revision),
|
||||
executionId,
|
||||
ordinal: index + 1,
|
||||
requestId: null,
|
||||
inputSequence: null,
|
||||
actor: null,
|
||||
before: operation === 'REMOVED' ? value : null,
|
||||
after: operation === 'CREATED' ? value : null,
|
||||
});
|
||||
}
|
||||
},
|
||||
undefined
|
||||
);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { collectPlayAudit } from './bestEffort.js';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { asRecord } from '@sammo-ts/common';
|
||||
import type { Nation } from '@sammo-ts/logic';
|
||||
@@ -70,85 +71,97 @@ export const recordAuditPolicyChange = (options: {
|
||||
actor?: TurnGeneral;
|
||||
permission?: number;
|
||||
requestId?: string;
|
||||
}): { _playAuditPolicy?: Record<string, PolicyHead> } => {
|
||||
const { world, nation, area } = options;
|
||||
const state = world.getState();
|
||||
const serverId = state.meta.serverId;
|
||||
if (typeof serverId !== 'string' || !serverId.trim()) return {};
|
||||
const rawHeads = asRecord(nation.meta._playAuditPolicy);
|
||||
const heads: Record<string, PolicyHead> = {};
|
||||
for (const key of AUDIT_POLICY_AREAS) {
|
||||
const value = asRecord(rawHeads[key]);
|
||||
if (
|
||||
value.serverId === serverId &&
|
||||
typeof value.id === 'string' &&
|
||||
typeof value.revision === 'number' &&
|
||||
Number.isSafeInteger(value.revision) &&
|
||||
value.revision > 0 &&
|
||||
typeof value.hash === 'string' &&
|
||||
value.id === auditPolicyHash([serverId, nation.id, key, value.revision])
|
||||
) {
|
||||
heads[key] = { id: value.id, revision: value.revision, hash: value.hash, serverId };
|
||||
}
|
||||
}
|
||||
let head: PolicyHead | null = heads[area] ?? null;
|
||||
const before = projectAuditPolicy(nation.meta, area);
|
||||
const after = projectAuditPolicy(options.nextMeta, area);
|
||||
const append = (source: PendingAuditPolicy['source'], old: PolicyData | null, value: PolicyData) => {
|
||||
const revision = (head?.revision ?? 0) + 1;
|
||||
const id = auditPolicyHash([serverId, nation.id, area, revision]);
|
||||
const actor = options.actor;
|
||||
world.queueAuditPolicy({
|
||||
schemaVersion: 1,
|
||||
id,
|
||||
serverId,
|
||||
nationId: nation.id,
|
||||
area,
|
||||
revision,
|
||||
previousId: head?.id ?? null,
|
||||
source,
|
||||
year: state.currentYear,
|
||||
month: state.currentMonth,
|
||||
tick: world.getGameClockState().tick,
|
||||
requestId: source === 'CHANGE' ? (options.requestId ?? null) : null,
|
||||
ordinal: world.nextAuditOrdinal(),
|
||||
actor:
|
||||
source === 'CHANGE' && actor
|
||||
? {
|
||||
userId: actor.userId ?? null,
|
||||
generalId: actor.id,
|
||||
name: actor.name,
|
||||
nationId: actor.nationId,
|
||||
officerLevel: actor.officerLevel,
|
||||
npcState: actor.npcState,
|
||||
permission: options.permission ?? 0,
|
||||
}
|
||||
: null,
|
||||
before: old,
|
||||
after: value,
|
||||
});
|
||||
head = { id, revision, hash: auditPolicyHash(value), serverId };
|
||||
};
|
||||
if (!head) append('BASELINE', null, before);
|
||||
else if (head.hash !== auditPolicyHash(before)) append('OBSERVED_GAP', null, before);
|
||||
if (auditPolicyHash(before) !== auditPolicyHash(after)) append('CHANGE', before, after);
|
||||
if (!head) throw new Error('Play audit policy baseline missing');
|
||||
return { _playAuditPolicy: { ...heads, [area]: head } };
|
||||
};
|
||||
}): { _playAuditPolicy?: Record<string, PolicyHead> } =>
|
||||
collectPlayAudit(
|
||||
options.world,
|
||||
'recordAuditPolicyChange',
|
||||
() => {
|
||||
const { world, nation, area } = options;
|
||||
const state = world.getState();
|
||||
const serverId = state.meta.serverId;
|
||||
if (typeof serverId !== 'string' || !serverId.trim()) return {};
|
||||
const rawHeads = asRecord(nation.meta._playAuditPolicy);
|
||||
const heads: Record<string, PolicyHead> = {};
|
||||
for (const key of AUDIT_POLICY_AREAS) {
|
||||
const value = asRecord(rawHeads[key]);
|
||||
if (
|
||||
value.serverId === serverId &&
|
||||
typeof value.id === 'string' &&
|
||||
typeof value.revision === 'number' &&
|
||||
Number.isSafeInteger(value.revision) &&
|
||||
value.revision > 0 &&
|
||||
typeof value.hash === 'string' &&
|
||||
value.id === auditPolicyHash([serverId, nation.id, key, value.revision])
|
||||
) {
|
||||
heads[key] = { id: value.id, revision: value.revision, hash: value.hash, serverId };
|
||||
}
|
||||
}
|
||||
let head: PolicyHead | null = heads[area] ?? null;
|
||||
const before = projectAuditPolicy(nation.meta, area);
|
||||
const after = projectAuditPolicy(options.nextMeta, area);
|
||||
const append = (source: PendingAuditPolicy['source'], old: PolicyData | null, value: PolicyData) => {
|
||||
const revision = (head?.revision ?? 0) + 1;
|
||||
const id = auditPolicyHash([serverId, nation.id, area, revision]);
|
||||
const actor = options.actor;
|
||||
world.queueAuditPolicy({
|
||||
schemaVersion: 1,
|
||||
id,
|
||||
serverId,
|
||||
nationId: nation.id,
|
||||
area,
|
||||
revision,
|
||||
previousId: head?.id ?? null,
|
||||
source,
|
||||
year: state.currentYear,
|
||||
month: state.currentMonth,
|
||||
tick: world.getGameClockState().tick,
|
||||
requestId: source === 'CHANGE' ? (options.requestId ?? null) : null,
|
||||
ordinal: world.nextAuditOrdinal(),
|
||||
actor:
|
||||
source === 'CHANGE' && actor
|
||||
? {
|
||||
userId: actor.userId ?? null,
|
||||
generalId: actor.id,
|
||||
name: actor.name,
|
||||
nationId: actor.nationId,
|
||||
officerLevel: actor.officerLevel,
|
||||
npcState: actor.npcState,
|
||||
permission: options.permission ?? 0,
|
||||
}
|
||||
: null,
|
||||
before: old,
|
||||
after: value,
|
||||
});
|
||||
head = { id, revision, hash: auditPolicyHash(value), serverId };
|
||||
};
|
||||
if (!head) append('BASELINE', null, before);
|
||||
else if (head.hash !== auditPolicyHash(before)) append('OBSERVED_GAP', null, before);
|
||||
if (auditPolicyHash(before) !== auditPolicyHash(after)) append('CHANGE', before, after);
|
||||
if (!head) throw new Error('Play audit policy baseline missing');
|
||||
return { _playAuditPolicy: { ...heads, [area]: head } };
|
||||
},
|
||||
{}
|
||||
);
|
||||
|
||||
export const initializeNationAuditPolicies = (world: InMemoryTurnWorld, nationId: number): void => {
|
||||
let nation = world.getNationById(nationId);
|
||||
if (!nation) return;
|
||||
for (const area of AUDIT_POLICY_AREAS) {
|
||||
const patch = recordAuditPolicyChange({ world, nation, area, nextMeta: nation.meta });
|
||||
if (
|
||||
Object.keys(patch).length &&
|
||||
auditPolicyHash(patch._playAuditPolicy) !== auditPolicyHash(nation.meta._playAuditPolicy ?? {})
|
||||
) {
|
||||
nation = world.updateNation(nation.id, { meta: { ...nation.meta, ...patch } })!;
|
||||
}
|
||||
}
|
||||
};
|
||||
export const initializeNationAuditPolicies = (world: InMemoryTurnWorld, nationId: number): void =>
|
||||
collectPlayAudit(
|
||||
world,
|
||||
'initializeNationAuditPolicies',
|
||||
() => {
|
||||
let nation = world.getNationById(nationId);
|
||||
if (!nation) return;
|
||||
for (const area of AUDIT_POLICY_AREAS) {
|
||||
const patch = recordAuditPolicyChange({ world, nation, area, nextMeta: nation.meta });
|
||||
if (
|
||||
Object.keys(patch).length &&
|
||||
auditPolicyHash(patch._playAuditPolicy) !== auditPolicyHash(nation.meta._playAuditPolicy ?? {})
|
||||
) {
|
||||
nation = world.updateNation(nation.id, { meta: { ...nation.meta, ...patch } })!;
|
||||
}
|
||||
}
|
||||
},
|
||||
undefined
|
||||
);
|
||||
|
||||
export const initializeAuditPolicies = (world: InMemoryTurnWorld): void => {
|
||||
for (const nation of world.listNations()) initializeNationAuditPolicies(world, nation.id);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { persistAuditDecisions } from '../playAudit/decisionPersistence.js';
|
||||
import { persistAuditDiplomacyEvents } from '@sammo-ts/infra';
|
||||
import { collectPlayAudit, markAuditGap } from '../playAudit/bestEffort.js';
|
||||
import { persistAuditDiplomacyEvents, withPlayAuditSavepoint } from '@sammo-ts/infra';
|
||||
import { hasAuditDocumentBaseline, persistAuditDocumentBaseline } from '../playAudit/documentBaseline.js';
|
||||
import { persistAuditPolicies, restoreMissingAuditPolicyHeads } from '../playAudit/policyPersistence.js';
|
||||
import { prunePreviousAuditBatch, type AuditRetentionResult } from '../playAudit/retention.js';
|
||||
@@ -1236,6 +1237,7 @@ export const createDatabaseTurnHooks = async (
|
||||
}
|
||||
const persistedClock = await prisma.$queryRaw<
|
||||
Array<{
|
||||
audit_gap: unknown;
|
||||
clock_phase: string;
|
||||
clock_revision: bigint;
|
||||
deadline_generation: bigint;
|
||||
@@ -1243,7 +1245,7 @@ export const createDatabaseTurnHooks = async (
|
||||
opening_reached: boolean;
|
||||
}>
|
||||
>(GamePrisma.sql`
|
||||
SELECT clock_phase,
|
||||
SELECT meta->'playAuditGap' AS audit_gap, clock_phase,
|
||||
clock_revision,
|
||||
deadline_generation,
|
||||
clock_base_time IS NOT NULL
|
||||
@@ -1259,6 +1261,21 @@ export const createDatabaseTurnHooks = async (
|
||||
if (!durableClock) {
|
||||
throw new Error(`world_state ${state.id} is missing during a fenced turn flush.`);
|
||||
}
|
||||
const durableGap = asRecord(durableClock.audit_gap);
|
||||
if (durableGap.serverId && durableGap.serverId === state.meta.serverId) {
|
||||
const localGap = asRecord(world.getState().meta.playAuditGap);
|
||||
const gap =
|
||||
localGap.serverId === durableGap.serverId
|
||||
? {
|
||||
...durableGap,
|
||||
...localGap,
|
||||
firstYear: durableGap.firstYear,
|
||||
firstMonth: durableGap.firstMonth,
|
||||
}
|
||||
: durableGap;
|
||||
world.updateWorldMeta({ playAuditGap: gap });
|
||||
worldStateUpdate.meta = asJson(world.getState().meta);
|
||||
}
|
||||
const expectedPhase = state.clockPhase ?? (state.clockMode === 'realtime' ? 'RUNNING' : 'MANUAL');
|
||||
const expectedRevision = BigInt(state.clockRevision ?? 1);
|
||||
const expectedGeneration = BigInt(state.deadlineGeneration ?? 1);
|
||||
@@ -1895,11 +1912,25 @@ export const createDatabaseTurnHooks = async (
|
||||
data: pendingLogRows,
|
||||
});
|
||||
}
|
||||
await persistAuditPolicies(prisma, pendingAuditPolicies, auditCommand);
|
||||
await persistAuditDiplomacyEvents(prisma, pendingAuditDiplomacy);
|
||||
await persistAuditDecisions(prisma, pendingAuditDecisions);
|
||||
for (const snapshot of pendingAuditMonths) {
|
||||
await persistAuditMonth(prisma, snapshot);
|
||||
if (
|
||||
pendingAuditPolicies.length ||
|
||||
pendingAuditDiplomacy.length ||
|
||||
pendingAuditDecisions.length ||
|
||||
pendingAuditMonths.length
|
||||
) {
|
||||
const audit = await withPlayAuditSavepoint(prisma, async (auditDb) => {
|
||||
await persistAuditPolicies(auditDb, pendingAuditPolicies, auditCommand);
|
||||
await persistAuditDiplomacyEvents(auditDb, pendingAuditDiplomacy);
|
||||
await persistAuditDecisions(auditDb, pendingAuditDecisions);
|
||||
for (const snapshot of pendingAuditMonths) await persistAuditMonth(auditDb, snapshot);
|
||||
});
|
||||
if (!audit.ok) {
|
||||
markAuditGap(world, 'persistence');
|
||||
await prisma.worldState.update({
|
||||
where: { id: state.id },
|
||||
data: { meta: world.getState().meta as GamePrisma.InputJsonValue },
|
||||
});
|
||||
}
|
||||
}
|
||||
for (const snapshot of pendingYearbookSnapshots) {
|
||||
await persistYearbookSnapshot(prisma, snapshot);
|
||||
@@ -2094,8 +2125,8 @@ export const createDatabaseTurnHooks = async (
|
||||
enqueueCommittedReceipt(committed.readModelChanges, committed.journalWrite);
|
||||
};
|
||||
const flushInitialAudit = async (observedAt: Date, force = false): Promise<void> => {
|
||||
if (hasAuditDocumentBaseline(world)) {
|
||||
if (force || world.hasPendingAuditRecords()) await flushChanges();
|
||||
if (collectPlayAudit(world, 'document-boundary', () => hasAuditDocumentBaseline(world), false)) {
|
||||
if (force || world.hasPendingAuditRecords() || world.getState().meta.playAuditGap) await flushChanges();
|
||||
return;
|
||||
}
|
||||
const checkpoint = world.captureState();
|
||||
@@ -2108,7 +2139,10 @@ export const createDatabaseTurnHooks = async (
|
||||
await acquireGameSchemaAdvisoryXactLock(transaction, CLOCK_OPERATION_PERSISTENCE_LOCK);
|
||||
await acquireGameSchemaAdvisoryXactLock(transaction, GENERAL_ACCESS_PERSISTENCE_LOCK);
|
||||
await synchronizeRuntimeClockAuthorityUnderHeldLock(transaction, world);
|
||||
await persistAuditDocumentBaseline(transaction, world, observedAt);
|
||||
const audit = await withPlayAuditSavepoint(transaction, (auditDb) =>
|
||||
persistAuditDocumentBaseline(auditDb, world, observedAt)
|
||||
);
|
||||
if (!audit.ok) markAuditGap(world, 'document-baseline');
|
||||
return persistChanges(transaction);
|
||||
}, transactionOptions);
|
||||
} catch (error) {
|
||||
@@ -2165,7 +2199,17 @@ export const createDatabaseTurnHooks = async (
|
||||
hooks,
|
||||
flushChanges,
|
||||
flushInitialAudit,
|
||||
restoreMissingAuditPolicyHeads: () => restoreMissingAuditPolicyHeads(prisma, world),
|
||||
restoreMissingAuditPolicyHeads: async () => {
|
||||
const result = await prisma.$transaction(
|
||||
(tx) => withPlayAuditSavepoint(tx, (auditDb) => restoreMissingAuditPolicyHeads(auditDb, world)),
|
||||
transactionOptions
|
||||
);
|
||||
if (!result.ok) {
|
||||
markAuditGap(world, 'policy-head-recovery');
|
||||
return false;
|
||||
}
|
||||
return result.value;
|
||||
},
|
||||
takeCommittedReadModelChanges: () => {
|
||||
return takeCommittedReceipt()?.changes ?? null;
|
||||
},
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { collectPlayAudit } from '../playAudit/bestEffort.js';
|
||||
import type { PendingAuditDecision } from '../playAudit/decision.js';
|
||||
import {
|
||||
recordTurnAuditDiplomacy,
|
||||
@@ -1393,15 +1394,36 @@ export class InMemoryTurnWorld {
|
||||
}
|
||||
|
||||
queueAuditDiplomacy(event: AuditDiplomacyEventDraft): void {
|
||||
this.pendingAuditDiplomacy.push(structuredClone(event));
|
||||
collectPlayAudit(
|
||||
this,
|
||||
'queueDiplomacy',
|
||||
() => {
|
||||
this.pendingAuditDiplomacy.push(structuredClone(event));
|
||||
},
|
||||
undefined
|
||||
);
|
||||
}
|
||||
|
||||
queueAuditDecision(decision: PendingAuditDecision): void {
|
||||
this.pendingAuditDecisions.push(structuredClone(decision));
|
||||
collectPlayAudit(
|
||||
this,
|
||||
'queueDecision',
|
||||
() => {
|
||||
this.pendingAuditDecisions.push(structuredClone(decision));
|
||||
},
|
||||
undefined
|
||||
);
|
||||
}
|
||||
|
||||
queueAuditPolicy(policy: PendingAuditPolicy): void {
|
||||
this.pendingAuditPolicies.push(structuredClone(policy));
|
||||
collectPlayAudit(
|
||||
this,
|
||||
'queuePolicy',
|
||||
() => {
|
||||
this.pendingAuditPolicies.push(structuredClone(policy));
|
||||
},
|
||||
undefined
|
||||
);
|
||||
}
|
||||
|
||||
hasPendingAuditRecords(): boolean {
|
||||
@@ -1414,7 +1436,14 @@ export class InMemoryTurnWorld {
|
||||
}
|
||||
|
||||
queueAuditMonth(snapshot: PendingAuditMonth): void {
|
||||
this.pendingAuditMonths.push(structuredClone(snapshot));
|
||||
collectPlayAudit(
|
||||
this,
|
||||
'queueMonth',
|
||||
() => {
|
||||
this.pendingAuditMonths.push(structuredClone(snapshot));
|
||||
},
|
||||
undefined
|
||||
);
|
||||
}
|
||||
|
||||
queueYearbookSnapshot(snapshot: PendingYearbookSnapshot): void {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { collectPlayAudit } from '../playAudit/bestEffort.js';
|
||||
import { auditDecisionIdentity, normalizeAuditCodeVersion, type PendingAuditDecision } from '../playAudit/decision.js';
|
||||
import { auditPolicyHash, AUDIT_POLICY_AREAS } from '../playAudit/policy.js';
|
||||
import type { AiDecisionTraceEvent, AiExecutionAttempt, AiExecutionCheck } from './ai/generalAi/trace.js';
|
||||
@@ -1085,46 +1086,61 @@ export const createReservedTurnHandler = async (options: {
|
||||
const onDecisionTrace: AiDecisionTraceObserver | undefined =
|
||||
collectDecisions || options.onDecisionTrace
|
||||
? (event) => {
|
||||
if (collectDecisions) {
|
||||
if (event.kind === 'DECISION_START') {
|
||||
decisionSteps.set(event.phase, []);
|
||||
const heads = asRecord(currentNation?.meta._playAuditPolicy);
|
||||
decisionPolicyRefs.set(
|
||||
event.phase,
|
||||
Object.fromEntries(
|
||||
AUDIT_POLICY_AREAS.flatMap((area) => {
|
||||
const head = asRecord(heads[area]);
|
||||
return head.serverId === auditServerId && typeof head.id === 'string'
|
||||
? [[area, head.id]]
|
||||
: [];
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
decisionSteps
|
||||
.get(event.phase)
|
||||
?.push({ ...structuredClone(event), sequence: storedDecisionSequence++ });
|
||||
}
|
||||
if (collectDecisions && worldRef)
|
||||
collectPlayAudit(
|
||||
worldRef,
|
||||
'decision-trace',
|
||||
() => {
|
||||
if (event.kind === 'DECISION_START') {
|
||||
decisionSteps.set(event.phase, []);
|
||||
const heads = asRecord(currentNation?.meta._playAuditPolicy);
|
||||
decisionPolicyRefs.set(
|
||||
event.phase,
|
||||
Object.fromEntries(
|
||||
AUDIT_POLICY_AREAS.flatMap((area) => {
|
||||
const head = asRecord(heads[area]);
|
||||
return head.serverId === auditServerId &&
|
||||
typeof head.id === 'string'
|
||||
? [[area, head.id]]
|
||||
: [];
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
decisionSteps
|
||||
.get(event.phase)
|
||||
?.push({ ...structuredClone(event), sequence: storedDecisionSequence++ });
|
||||
},
|
||||
undefined
|
||||
);
|
||||
options.onDecisionTrace?.(event);
|
||||
}
|
||||
: undefined;
|
||||
const recordExecution = (phase: 'general' | 'nation', attempt: AiExecutionAttempt): void => {
|
||||
const steps = decisionSteps.get(phase);
|
||||
const first = steps?.[0];
|
||||
if (!collectDecisions || !first || !steps) return;
|
||||
const { generalId, nationId, cityId, npcState, year, month, tick } = first;
|
||||
steps.push({
|
||||
...attempt,
|
||||
sequence: storedDecisionSequence++,
|
||||
phase,
|
||||
generalId,
|
||||
nationId,
|
||||
cityId,
|
||||
npcState,
|
||||
year,
|
||||
month,
|
||||
tick,
|
||||
});
|
||||
if (!worldRef) return;
|
||||
collectPlayAudit(
|
||||
worldRef,
|
||||
'decision-summary',
|
||||
() => {
|
||||
const steps = decisionSteps.get(phase);
|
||||
const first = steps?.[0];
|
||||
if (!collectDecisions || !first || !steps) return;
|
||||
const { generalId, nationId, cityId, npcState, year, month, tick } = first;
|
||||
steps.push({
|
||||
...attempt,
|
||||
sequence: storedDecisionSequence++,
|
||||
phase,
|
||||
generalId,
|
||||
nationId,
|
||||
cityId,
|
||||
npcState,
|
||||
year,
|
||||
month,
|
||||
tick,
|
||||
});
|
||||
},
|
||||
undefined
|
||||
);
|
||||
};
|
||||
const finishDecision = (
|
||||
phase: 'general' | 'nation',
|
||||
@@ -1135,64 +1151,72 @@ export const createReservedTurnHandler = async (options: {
|
||||
blockedReason?: string;
|
||||
}
|
||||
): void => {
|
||||
const steps = decisionSteps.get(phase);
|
||||
const first = steps?.[0];
|
||||
const last = steps?.find((step) => step.kind === 'DECISION_END');
|
||||
if (
|
||||
!collectDecisions ||
|
||||
!auditServerId ||
|
||||
!worldRef ||
|
||||
!steps ||
|
||||
first?.kind !== 'DECISION_START' ||
|
||||
last?.kind !== 'DECISION_END'
|
||||
)
|
||||
return;
|
||||
const tick = context.general.turnTick ?? worldRef.dateToGameTick(context.general.turnTime);
|
||||
const revision = worldRef.getGameClockState().revision;
|
||||
const executionId = auditDecisionIdentity(auditServerId, context.general.id, tick, revision);
|
||||
const execution = steps.at(-1);
|
||||
auditDecisions.push({
|
||||
id: auditPolicyHash([executionId, phase]),
|
||||
serverId: auditServerId,
|
||||
executionId,
|
||||
phase,
|
||||
generalId: first.generalId,
|
||||
nationId: first.nationId,
|
||||
cityId: first.cityId,
|
||||
npcState: first.npcState,
|
||||
year: first.year,
|
||||
month: first.month,
|
||||
tick,
|
||||
summary: {
|
||||
schemaVersion: 1,
|
||||
coverage: 'PROCEDURES',
|
||||
executionCoverage: 'ATTEMPTS',
|
||||
executionStatus:
|
||||
execution?.kind === 'EXECUTION_ATTEMPT' && execution.preparation
|
||||
? 'PREPARING'
|
||||
: execution?.kind === 'EXECUTION_ATTEMPT' &&
|
||||
execution.checks.some((check) => check.stage === 'BLOCK')
|
||||
? 'BLOCKED'
|
||||
: 'RESOLVED',
|
||||
clockRevision: revision,
|
||||
codeVersion: auditCodeVersion ?? null,
|
||||
policyRefs: decisionPolicyRefs.get(phase) ?? {},
|
||||
requestedAction: first.reservedAction,
|
||||
selectedAction: last.action,
|
||||
selectedReason: last.reason,
|
||||
executedAction: outcome.actionKey,
|
||||
completed: outcome.completed ?? null,
|
||||
usedFallback:
|
||||
outcome.usedFallback ||
|
||||
steps.some(
|
||||
(step) =>
|
||||
step.kind === 'EXECUTION_ATTEMPT' &&
|
||||
(step.usedFallback || step.alternativeAction !== null)
|
||||
),
|
||||
blockedReason: outcome.blockedReason ?? null,
|
||||
if (!worldRef) return;
|
||||
collectPlayAudit(
|
||||
worldRef,
|
||||
'decision-summary',
|
||||
() => {
|
||||
const steps = decisionSteps.get(phase);
|
||||
const first = steps?.[0];
|
||||
const last = steps?.find((step) => step.kind === 'DECISION_END');
|
||||
if (
|
||||
!collectDecisions ||
|
||||
!auditServerId ||
|
||||
!worldRef ||
|
||||
!steps ||
|
||||
first?.kind !== 'DECISION_START' ||
|
||||
last?.kind !== 'DECISION_END'
|
||||
)
|
||||
return;
|
||||
const tick = context.general.turnTick ?? worldRef.dateToGameTick(context.general.turnTime);
|
||||
const revision = worldRef.getGameClockState().revision;
|
||||
const executionId = auditDecisionIdentity(auditServerId, context.general.id, tick, revision);
|
||||
const execution = steps.at(-1);
|
||||
auditDecisions.push({
|
||||
id: auditPolicyHash([executionId, phase]),
|
||||
serverId: auditServerId,
|
||||
executionId,
|
||||
phase,
|
||||
generalId: first.generalId,
|
||||
nationId: first.nationId,
|
||||
cityId: first.cityId,
|
||||
npcState: first.npcState,
|
||||
year: first.year,
|
||||
month: first.month,
|
||||
tick,
|
||||
summary: {
|
||||
schemaVersion: 1,
|
||||
coverage: 'PROCEDURES',
|
||||
executionCoverage: 'ATTEMPTS',
|
||||
executionStatus:
|
||||
execution?.kind === 'EXECUTION_ATTEMPT' && execution.preparation
|
||||
? 'PREPARING'
|
||||
: execution?.kind === 'EXECUTION_ATTEMPT' &&
|
||||
execution.checks.some((check) => check.stage === 'BLOCK')
|
||||
? 'BLOCKED'
|
||||
: 'RESOLVED',
|
||||
clockRevision: revision,
|
||||
codeVersion: auditCodeVersion ?? null,
|
||||
policyRefs: decisionPolicyRefs.get(phase) ?? {},
|
||||
requestedAction: first.reservedAction,
|
||||
selectedAction: last.action,
|
||||
selectedReason: last.reason,
|
||||
executedAction: outcome.actionKey,
|
||||
completed: outcome.completed ?? null,
|
||||
usedFallback:
|
||||
outcome.usedFallback ||
|
||||
steps.some(
|
||||
(step) =>
|
||||
step.kind === 'EXECUTION_ATTEMPT' &&
|
||||
(step.usedFallback || step.alternativeAction !== null)
|
||||
),
|
||||
blockedReason: outcome.blockedReason ?? null,
|
||||
},
|
||||
steps,
|
||||
});
|
||||
},
|
||||
steps,
|
||||
});
|
||||
undefined
|
||||
);
|
||||
};
|
||||
|
||||
// Ref는 장수와 첫 커맨드를 만들 때 getNationStaticInfo 캐시를 채운다.
|
||||
|
||||
@@ -157,6 +157,23 @@ integration('monthly diplomacy persistence', () => {
|
||||
});
|
||||
const hooks = await createDatabaseTurnHooks(databaseUrl!, world);
|
||||
try {
|
||||
// An API writer may have recorded a gap since this daemon loaded its world.
|
||||
await db.worldState.update({
|
||||
where: { id: worldRow.id },
|
||||
data: {
|
||||
meta: {
|
||||
...world.getState().meta,
|
||||
playAuditGap: {
|
||||
serverId: scenarioCode,
|
||||
firstYear: 192,
|
||||
firstMonth: 12,
|
||||
lastYear: 192,
|
||||
lastMonth: 12,
|
||||
stage: 'persistence',
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const checkpoint = world.captureState();
|
||||
await world.advanceMonth(new Date('0193-02-01T00:00:00.000Z'));
|
||||
const queued = world.peekDirtyState().pendingAuditDiplomacy;
|
||||
@@ -170,11 +187,11 @@ integration('monthly diplomacy persistence', () => {
|
||||
await db.$executeRawUnsafe(`CREATE TRIGGER reject_monthly_audit_fixture BEFORE INSERT ON play_audit_diplomacy_event
|
||||
FOR EACH ROW EXECUTE FUNCTION reject_monthly_audit_fixture()`);
|
||||
try {
|
||||
await expect(hooks.flushChanges()).rejects.toThrow('monthly audit fixture failure');
|
||||
expect(world.peekDirtyState().pendingAuditDiplomacy).toEqual(queued);
|
||||
await expect(hooks.flushChanges()).resolves.toBeUndefined();
|
||||
expect(world.peekDirtyState().pendingAuditDiplomacy).toEqual([]);
|
||||
expect(await db.playAuditDiplomacyEvent.count({ where: { serverId: scenarioCode } })).toBe(0);
|
||||
expect(await db.worldState.findUniqueOrThrow({ where: { id: worldRow.id } })).toMatchObject({
|
||||
currentMonth: 1,
|
||||
currentMonth: 2,
|
||||
});
|
||||
expect(
|
||||
await db.diplomacy.findUniqueOrThrow({
|
||||
@@ -185,7 +202,7 @@ integration('monthly diplomacy persistence', () => {
|
||||
},
|
||||
},
|
||||
})
|
||||
).toMatchObject({ stateCode: 1, term: 1 });
|
||||
).toMatchObject({ stateCode: 0, term: 6 });
|
||||
} finally {
|
||||
await db.$executeRawUnsafe('DROP TRIGGER reject_monthly_audit_fixture ON play_audit_diplomacy_event');
|
||||
await db.$executeRawUnsafe('DROP FUNCTION reject_monthly_audit_fixture()');
|
||||
@@ -193,18 +210,25 @@ integration('monthly diplomacy persistence', () => {
|
||||
|
||||
const decision = buildAuditDecisionFixture('monthly-decision', scenarioCode);
|
||||
world.queueAuditDecision(decision);
|
||||
await db.$executeRawUnsafe(`CREATE FUNCTION reject_decision_flush_fixture() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'decision flush rollback'; END; $$`);
|
||||
await db.$executeRawUnsafe(`CREATE TRIGGER reject_decision_flush_fixture BEFORE INSERT ON play_audit_decision_chunk FOR EACH ROW EXECUTE FUNCTION reject_decision_flush_fixture()`);
|
||||
await db.$executeRawUnsafe(
|
||||
`CREATE FUNCTION reject_decision_flush_fixture() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'decision flush rollback'; END; $$`
|
||||
);
|
||||
await db.$executeRawUnsafe(
|
||||
`CREATE TRIGGER reject_decision_flush_fixture BEFORE INSERT ON play_audit_decision_chunk FOR EACH ROW EXECUTE FUNCTION reject_decision_flush_fixture()`
|
||||
);
|
||||
try {
|
||||
await expect(hooks.flushChanges()).rejects.toThrow('decision flush rollback');
|
||||
expect(world.peekDirtyState().pendingAuditDecisions).toEqual([decision]);
|
||||
await expect(hooks.flushChanges()).resolves.toBeUndefined();
|
||||
expect(world.peekDirtyState().pendingAuditDecisions).toEqual([]);
|
||||
expect(await db.playAuditDecision.count({ where: { serverId: scenarioCode } })).toBe(0);
|
||||
expect(await db.playAuditDiplomacyEvent.count({ where: { serverId: scenarioCode } })).toBe(0);
|
||||
expect((await db.worldState.findUniqueOrThrow({ where: { id: worldRow.id } })).currentMonth).toBe(1);
|
||||
expect((await db.worldState.findUniqueOrThrow({ where: { id: worldRow.id } })).currentMonth).toBe(2);
|
||||
} finally {
|
||||
await db.$executeRawUnsafe('DROP TRIGGER reject_decision_flush_fixture ON play_audit_decision_chunk');
|
||||
await db.$executeRawUnsafe('DROP FUNCTION reject_decision_flush_fixture()');
|
||||
}
|
||||
// New observations after recovery can be stored; discarded batches do not retry themselves.
|
||||
for (const event of queued) world.queueAuditDiplomacy(event);
|
||||
world.queueAuditDecision(decision);
|
||||
await hooks.hooks.flushChanges?.({
|
||||
lastTurnTime: '0193-02-01T00:00:00.000Z',
|
||||
processedGenerals: 0,
|
||||
@@ -313,9 +337,9 @@ integration('monthly diplomacy persistence', () => {
|
||||
await db.$executeRawUnsafe(`CREATE TRIGGER reject_lifecycle_audit_fixture BEFORE INSERT ON play_audit_diplomacy_event
|
||||
FOR EACH ROW EXECUTE FUNCTION reject_lifecycle_audit_fixture()`);
|
||||
try {
|
||||
await expect(hooks.flushChanges()).rejects.toThrow('lifecycle audit fixture failure');
|
||||
expect(await db.nation.count({ where: { id: endingNation } })).toBe(1);
|
||||
expect(world.peekDirtyState().pendingAuditDiplomacy).toEqual(removals);
|
||||
await expect(hooks.flushChanges()).resolves.toBeUndefined();
|
||||
expect(await db.nation.count({ where: { id: endingNation } })).toBe(0);
|
||||
expect(world.peekDirtyState().pendingAuditDiplomacy).toEqual([]);
|
||||
} finally {
|
||||
await db.$executeRawUnsafe('DROP TRIGGER reject_lifecycle_audit_fixture ON play_audit_diplomacy_event');
|
||||
await db.$executeRawUnsafe('DROP FUNCTION reject_lifecycle_audit_fixture()');
|
||||
@@ -331,7 +355,7 @@ integration('monthly diplomacy persistence', () => {
|
||||
await db.playAuditDiplomacyEvent.count({
|
||||
where: { serverId: scenarioCode, eventType: 'NATION_RELATION_REMOVED' },
|
||||
})
|
||||
).toBe(6);
|
||||
).toBe(0);
|
||||
expect(world.addNation(buildNation(endingNation, '재건국', 1))).toBe(true);
|
||||
await hooks.flushChanges();
|
||||
expect(await db.nation.count({ where: { id: endingNation } })).toBe(1);
|
||||
@@ -349,6 +373,18 @@ integration('monthly diplomacy persistence', () => {
|
||||
where: { serverId: scenarioCode, eventType: 'NATION_RELATION_CREATED' },
|
||||
})
|
||||
).toBe(6);
|
||||
const savedDecision = await db.playAuditDecision.findUniqueOrThrow({ where: { id: decision.id } });
|
||||
const nation = world.getNationById(nationIds[0]!)!;
|
||||
world.updateNation(nation.id, { gold: nation.gold + 1 });
|
||||
world.queueAuditDecision({
|
||||
...decision,
|
||||
summary: { ...decision.summary, selectedReason: 'changed after update' },
|
||||
});
|
||||
await hooks.flushChanges();
|
||||
expect(await db.playAuditDecision.findUniqueOrThrow({ where: { id: decision.id } })).toEqual(savedDecision);
|
||||
expect((await db.nation.findUniqueOrThrow({ where: { id: nation.id } })).gold).toBe(nation.gold + 1);
|
||||
expect(world.hasPendingAuditRecords()).toBe(false);
|
||||
expect(world.getState().meta.playAuditGap).toMatchObject({ firstYear: 192, firstMonth: 12 });
|
||||
} finally {
|
||||
await hooks.close();
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { buildAuditDecisionFixture } from './fixtures/playAuditDecision.js';
|
||||
import { initializeAuditDiplomacy } from '../src/playAudit/diplomacy.js';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import type { City, Nation } from '@sammo-ts/logic';
|
||||
import { InMemoryTurnWorld, type GeneralTurnHandler } from '../src/turn/inMemoryWorld.js';
|
||||
import type { TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js';
|
||||
@@ -130,6 +130,29 @@ const buildWorld = (generalTurnHandler?: GeneralTurnHandler) => {
|
||||
return world;
|
||||
};
|
||||
describe('play audit collection durability state', () => {
|
||||
it('discards collector failures without changing gameplay state and can collect again', () => {
|
||||
const world = buildWorld();
|
||||
const nations = structuredClone(world.listNations());
|
||||
const broken = vi.spyOn(world, 'listGenerals').mockImplementationOnce(() => {
|
||||
throw new Error('audit projection');
|
||||
});
|
||||
expect(() => queueAuditMonth(world)).not.toThrow();
|
||||
expect(world.peekDirtyState().pendingAuditMonths).toHaveLength(0);
|
||||
expect(world.listNations()).toEqual(nations);
|
||||
expect(world.getState().meta.playAuditGap).toMatchObject({
|
||||
stage: 'queueAuditMonth',
|
||||
firstYear: 200,
|
||||
firstMonth: 1,
|
||||
});
|
||||
broken.mockRestore();
|
||||
queueAuditMonth(world);
|
||||
expect(world.peekDirtyState().pendingAuditMonths).toHaveLength(1);
|
||||
expect(world.getState().meta.playAuditGap).toBeDefined();
|
||||
world.updateWorldMeta({ playAuditCollection: { serverId: 'yearbook-projection-test', schemaVersion: 999 } });
|
||||
expect(initializeAuditCollection(world)).toBe(false);
|
||||
expect(world.getState().meta.playAuditGap).toMatchObject({ stage: 'initializeAuditCollection' });
|
||||
});
|
||||
|
||||
it('restores decision buffers and acknowledges only the committed prefix', () => {
|
||||
const world = buildWorld();
|
||||
const first = buildAuditDecisionFixture('first');
|
||||
@@ -207,7 +230,8 @@ describe('play audit collection durability state', () => {
|
||||
world.removeNation(1);
|
||||
world.removeNation(2);
|
||||
world.updateWorldMeta({ serverId: 'yearbook-projection-test' });
|
||||
expect(() => initializeAuditDiplomacy(world, new Date('invalid'))).toThrow(RangeError);
|
||||
expect(initializeAuditDiplomacy(world, new Date('invalid'))).toBe(false);
|
||||
expect(world.getState().meta.playAuditGap).toMatchObject({ stage: 'initializeAuditDiplomacy' });
|
||||
expect(world.getState().meta.playAuditDiplomacy).toBeUndefined();
|
||||
expect(world.peekDirtyState().pendingAuditDiplomacy).toEqual([]);
|
||||
expect(initializeAuditDiplomacy(world)).toBe(true);
|
||||
|
||||
@@ -2,6 +2,7 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { asRecord, GAME_TICKS_PER_TURN } from '@sammo-ts/common';
|
||||
import {
|
||||
createGamePostgresConnector,
|
||||
withPlayAuditSavepoint,
|
||||
hashAuditDiplomacyDocument,
|
||||
type GamePrismaClient,
|
||||
type GamePrisma,
|
||||
@@ -92,7 +93,7 @@ integration('initial audit durability before runtime readiness', () => {
|
||||
await closeDb?.();
|
||||
});
|
||||
|
||||
it('rolls initial policies, sample and collection marker back before readiness on persistence failure', async () => {
|
||||
it('keeps readiness and gameplay when initial audit persistence fails', async () => {
|
||||
const before = await clock();
|
||||
await db.$executeRawUnsafe(
|
||||
"CREATE OR REPLACE FUNCTION audit_initial_fail() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'fixture initial audit failure'; END $$"
|
||||
@@ -101,27 +102,33 @@ integration('initial audit durability before runtime readiness', () => {
|
||||
"CREATE TRIGGER audit_initial_fail BEFORE INSERT ON play_audit_month FOR EACH ROW WHEN (NEW.kind = 'INITIAL') EXECUTE FUNCTION audit_initial_fail()"
|
||||
);
|
||||
try {
|
||||
let error: unknown;
|
||||
try {
|
||||
runtime = await start();
|
||||
} catch (cause) {
|
||||
error = cause;
|
||||
}
|
||||
expect(String(error)).toContain('fixture initial audit failure');
|
||||
runtime = await start();
|
||||
expect(await db.playAuditMonth.count()).toBe(0);
|
||||
expect(await db.playAuditPolicy.count()).toBe(0);
|
||||
expect(await db.playAuditDiplomacyEvent.count()).toBe(0);
|
||||
expect(asRecord((await db.worldState.findFirstOrThrow()).meta).playAuditDiplomacy).toBeUndefined();
|
||||
expect(asRecord((await db.worldState.findFirstOrThrow()).meta).playAuditDocuments).toBeUndefined();
|
||||
expect(asRecord((await db.worldState.findFirstOrThrow()).meta).playAuditCollection).toBeUndefined();
|
||||
expect(
|
||||
(await db.nation.findMany()).every((nation) => asRecord(nation.meta)._playAuditPolicy === undefined)
|
||||
).toBe(true);
|
||||
expect((await db.turnDaemonLease.findMany()).every((lease) => !lease.clockReady)).toBe(true);
|
||||
expect(runtime.world.hasPendingAuditRecords()).toBe(false);
|
||||
expect(asRecord((await db.worldState.findFirstOrThrow()).meta).playAuditGap).toMatchObject({
|
||||
serverId,
|
||||
stage: 'persistence',
|
||||
});
|
||||
expect((await db.turnDaemonLease.findUniqueOrThrow({ where: { profile } })).clockReady).toBe(true);
|
||||
expect(await clock()).toEqual(before);
|
||||
await runtime.close();
|
||||
runtime = undefined;
|
||||
// Restart under the same broken audit table must not pause or accumulate retries.
|
||||
runtime = await start();
|
||||
expect(runtime.world.hasPendingAuditRecords()).toBe(false);
|
||||
expect((await db.turnDaemonLease.findUniqueOrThrow({ where: { profile } })).clockReady).toBe(true);
|
||||
} finally {
|
||||
await runtime?.close();
|
||||
runtime = undefined;
|
||||
await db.$executeRawUnsafe('DROP TRIGGER IF EXISTS audit_initial_fail ON play_audit_month');
|
||||
await db.$executeRawUnsafe('DROP FUNCTION IF EXISTS audit_initial_fail()');
|
||||
// Independent baseline fixture for the following normal-start tests.
|
||||
await db.playAuditDiplomacyEvent.deleteMany();
|
||||
await db.$executeRawUnsafe(
|
||||
"UPDATE world_state SET meta = meta - 'playAuditCollection' - 'playAuditDocuments' - 'playAuditDiplomacy' - 'playAuditGap'"
|
||||
);
|
||||
await db.$executeRawUnsafe("UPDATE nation SET meta = meta - '_playAuditPolicy'");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -337,4 +344,34 @@ integration('initial audit durability before runtime readiness', () => {
|
||||
runtime = await start();
|
||||
expect(asRecord((await db.worldState.findFirstOrThrow()).meta).playAuditDocuments).toEqual(marker);
|
||||
}, 30_000);
|
||||
it('isolates missing audit tables and bounded SQL waits but propagates core write failures', async () => {
|
||||
await runtime?.close();
|
||||
runtime = undefined;
|
||||
const nation = await db.nation.findUniqueOrThrow({ where: { id: 91990 } });
|
||||
await db.$transaction(async (tx) => {
|
||||
await tx.nation.update({ where: { id: nation.id }, data: { gold: nation.gold + 1 } });
|
||||
const missing = await withPlayAuditSavepoint(tx, () =>
|
||||
tx.$queryRawUnsafe('SELECT * FROM nonexistent_audit_fixture_table')
|
||||
);
|
||||
expect(missing.ok).toBe(false);
|
||||
const [settings] = await tx.$queryRaw<
|
||||
Array<{ timeout: string }>
|
||||
>`SELECT current_setting('statement_timeout') AS timeout`;
|
||||
const slow = await withPlayAuditSavepoint(tx, () => tx.$queryRawUnsafe('SELECT pg_sleep(2)::text'));
|
||||
expect(slow.ok).toBe(false);
|
||||
const [restored] = await tx.$queryRaw<
|
||||
Array<{ timeout: string }>
|
||||
>`SELECT current_setting('statement_timeout') AS timeout`;
|
||||
expect(restored).toEqual(settings);
|
||||
});
|
||||
expect((await db.nation.findUniqueOrThrow({ where: { id: nation.id } })).gold).toBe(nation.gold + 1);
|
||||
await expect(
|
||||
db.$transaction(async (tx) => {
|
||||
await tx.nation.update({ where: { id: nation.id }, data: { gold: nation.gold + 2 } });
|
||||
expect((await withPlayAuditSavepoint(tx, async () => 'audit-ok')).ok).toBe(true);
|
||||
throw new Error('core game write failed');
|
||||
})
|
||||
).rejects.toThrow('core game write failed');
|
||||
expect((await db.nation.findUniqueOrThrow({ where: { id: nation.id } })).gold).toBe(nation.gold + 1);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user