feat: 플레이 감사 월별 수집과 원자적 배치 저장 연결

This commit is contained in:
2026-09-16 02:37:38 +00:00
parent 4de3175279
commit 35155e6b59
14 changed files with 594 additions and 12 deletions
@@ -1,3 +1,4 @@
import { createPlayAuditHandler } from '../src/playAudit/collection.js';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { LogCategory, LogScope, type TurnCommandEnv } from '@sammo-ts/logic';
import { createGamePostgresConnector, type GamePrismaClient } from '@sammo-ts/infra';
@@ -35,6 +36,7 @@ integration('monthly pre-update persistence', () => {
await db.nation.deleteMany({ where: { id: nationId } });
await db.worldState.deleteMany({ where: { scenarioCode: 'monthly-boundary-pre-persistence' } });
await db.yearbookHistory.deleteMany({ where: { profileName: { in: [yearbookProfile, yearbookServerId] } } });
await db.playAuditMonth.deleteMany({ where: { serverId: yearbookServerId } });
await db.logEntry.deleteMany({ where: { text: { in: archivedLogTexts } } });
});
@@ -46,6 +48,7 @@ integration('monthly pre-update persistence', () => {
await db.nation.deleteMany({ where: { id: nationId } });
await db.worldState.deleteMany({ where: { scenarioCode: 'monthly-boundary-pre-persistence' } });
await db.yearbookHistory.deleteMany({ where: { profileName: { in: [yearbookProfile, yearbookServerId] } } });
await db.playAuditMonth.deleteMany({ where: { serverId: yearbookServerId } });
await db.logEntry.deleteMany({ where: { text: { in: archivedLogTexts } } });
await closeDb?.();
});
@@ -184,7 +187,12 @@ integration('monthly pre-update persistence', () => {
});
world = new InMemoryTurnWorld(loaded.state, loaded.snapshot, {
schedule: { entries: [{ startMinute: 0, tickMinutes: 10 }] },
calendarHandler: composeCalendarHandlers(yearbook.handler, boundary, nations),
calendarHandler: composeCalendarHandlers(
yearbook.handler,
createPlayAuditHandler(() => world),
boundary,
nations
),
});
const hooks = await createDatabaseTurnHooks(databaseUrl!, world, { profileName: yearbookProfile });
try {
@@ -227,6 +235,17 @@ integration('monthly pre-update persistence', () => {
currentMonth: 1,
meta: expect.objectContaining({ develcost: 40 }),
});
const audit = await db.playAuditMonth.findFirstOrThrow({
where: { serverId: yearbookServerId },
include: { nations: true, generals: true, cities: true },
});
expect(audit).toMatchObject({ year: 200, month: 12, kind: 'MONTH_END', settlementsComplete: false });
expect(audit.nations.find((row) => row.nationId === nationId)?.data).toMatchObject({ appliedRate: 10 });
expect(audit.generals).toHaveLength(generalIds.length);
expect(audit.cities).toHaveLength(cityIds.length);
expect(world.peekDirtyState().pendingAuditMonths).toEqual([]);
const reloaded = await loadTurnWorldFromDatabase({ databaseUrl: databaseUrl! });
expect(reloaded!.state.meta.playAuditFlows).toMatchObject({ year: 201, month: 1, complete: true });
const cityRows = await db.city.findMany({
where: { id: { in: cityIds } },
orderBy: { id: 'asc' },
@@ -0,0 +1,175 @@
import { describe, expect, it } from 'vitest';
import type { City, Nation } from '@sammo-ts/logic';
import { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js';
import type { TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js';
import { createPlayAuditHandler, queueAuditMonth, recordAuditSettlement } from '../src/playAudit/collection.js';
const turnTime = new Date('0200-01-01T00:00:00.000Z');
const buildGeneral = (id: number, nationId: number): TurnGeneral => ({
id,
name: `장수${id}`,
nationId,
cityId: nationId,
troopId: 0,
stats: { leadership: 80, strength: 70, intelligence: 60 },
experience: 1_000,
dedication: 900,
officerLevel: 1,
role: {
personality: null,
specialDomestic: null,
specialWar: null,
items: { horse: null, weapon: null, book: null, item: null },
},
injury: 0,
gold: 2_000,
rice: 2_000,
crew: 0,
crewTypeId: 0,
train: 0,
atmos: 0,
age: 30,
npcState: nationId === 0 ? 2 : 0,
triggerState: { flags: {}, counters: {}, modifiers: {}, meta: {} },
meta: { killturn: 24 },
turnTime,
});
const buildCity = (id: number, nationId: number): City => ({
id,
name: `도시${id}`,
nationId,
level: 1,
state: 0,
population: 10_000,
populationMax: 20_000,
agriculture: 1_000,
agricultureMax: 2_000,
commerce: 1_000,
commerceMax: 2_000,
security: 1_000,
securityMax: 2_000,
supplyState: 1,
frontState: 0,
defence: 1_000,
defenceMax: 2_000,
wall: 1_000,
wallMax: 2_000,
meta: {},
});
const buildNation = (id: number, power: number, meta: Nation['meta']): Nation => ({
id,
name: id === 0 ? '재야' : `국가${id}`,
color: '#777777',
capitalCityId: id === 0 ? null : id,
chiefGeneralId: null,
gold: 10_000,
rice: 20_000,
power,
level: id === 0 ? 0 : 1,
typeCode: 'che_중립',
meta,
});
const buildWorld = () => {
const state: TurnWorldState = {
id: 1,
currentYear: 200,
currentMonth: 1,
tickSeconds: 600,
lastTurnTime: turnTime,
meta: { serverId: 'yearbook-projection-test' },
};
const snapshot: TurnWorldSnapshot = {
scenarioConfig: {
stat: { total: 300, min: 10, max: 100, npcTotal: 150, npcMax: 50, npcMin: 10, chiefMin: 70 },
iconPath: '',
map: {},
const: {},
environment: { mapName: 'test', unitSet: 'test' },
},
scenarioMeta: {
title: '연감 테스트',
startYear: 200,
life: null,
fiction: 0,
history: [],
ignoreDefaultEvents: false,
},
map: { id: 'test', name: 'test', cities: [] },
nations: [
{
...buildNation(0, 90, { gennum: 90, tech: 90 }),
name: '오염된 재야',
color: '#ffffff',
level: 9,
},
buildNation(1, 777, { gennum: 9, tech: 100 }),
buildNation(2, 0, { tech: 100 }),
],
cities: [buildCity(0, 0), buildCity(1, 1), buildCity(2, 2)],
generals: [buildGeneral(1, 0), buildGeneral(2, 0), buildGeneral(3, 1), buildGeneral(4, 2), buildGeneral(5, 2)],
troops: [],
diplomacy: [],
events: [],
initialEvents: [],
};
const world = new InMemoryTurnWorld(state, snapshot, {
schedule: { entries: [{ startMinute: 0, tickMinutes: 10 }] },
});
return world;
};
describe('play audit collection durability state', () => {
it('restores pending snapshots and monthly flows on rollback and acknowledges only persisted rows', () => {
const world = buildWorld();
const before = world.captureState();
recordAuditSettlement(world, { nationId: 1, resource: 'gold', income: 943.5, paid: 123 });
queueAuditMonth(world);
expect(world.peekDirtyState().pendingAuditMonths).toHaveLength(1);
world.restoreState(before);
expect(world.peekDirtyState().pendingAuditMonths).toHaveLength(0);
expect(world.getState().meta.playAuditFlows).toBeUndefined();
queueAuditMonth(world);
const saved = world.peekDirtyState();
queueAuditMonth(world, 'FINAL');
world.acknowledgeDirtyState(saved);
expect(world.peekDirtyState().pendingAuditMonths.map((row) => row.kind)).toEqual(['FINAL']);
});
it('keeps partial adoption unknown then attributes income to the new month across reload state', async () => {
const world = buildWorld();
const handler = createPlayAuditHandler(() => world);
await handler.beforeMonthChanged!({
previousYear: 200,
previousMonth: 1,
currentYear: 200,
currentMonth: 2,
turnTime,
});
expect(world.peekDirtyState().pendingAuditMonths[0]!.settlementsComplete).toBe(false);
const next = world.captureState();
next.state.currentMonth = 2;
world.restoreState(next);
recordAuditSettlement(world, { nationId: 1, resource: 'gold', income: 943.5, paid: 123 });
const reloaded = buildWorld();
reloaded.restoreState(world.captureState());
queueAuditMonth(reloaded);
const feb = reloaded.peekDirtyState().pendingAuditMonths.at(-1)!;
expect(feb.month).toBe(2);
expect(feb.settlementsComplete).toBe(true);
expect(feb.nations.find((row) => row.id === 1)).toMatchObject({
incomeGold: 943.5,
paidGold: 123,
incomeRice: 0,
});
});
it('does not replace missing season identity with a profile or create a false snapshot', () => {
const world = buildWorld();
const state = world.captureState();
delete state.state.meta.serverId;
world.restoreState(state);
queueAuditMonth(world);
expect(world.peekDirtyState().pendingAuditMonths).toEqual([]);
});
});
@@ -0,0 +1,74 @@
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { createGamePostgresConnector, type GamePrismaClient } from '@sammo-ts/infra';
import { persistAuditMonth, type PendingAuditMonth } from '../src/playAudit/persistence.js';
import { buildAuditSnapshot } from '../src/playAudit/snapshot.js';
const databaseUrl = process.env.INPUT_EVENT_DATABASE_URL;
const integration = describe.skipIf(!databaseUrl);
const serverId = 'play-audit-persistence-fixture-20260916';
integration('play audit transactional month persistence', () => {
let db: GamePrismaClient;
let close: () => Promise<void>;
const snapshot: PendingAuditMonth = {
serverId,
year: 200,
month: 1,
tick: 10,
kind: 'MONTH_END',
settlementsComplete: true,
...buildAuditSnapshot({
nations: [
{
id: 1,
name: '감사국',
color: '#ffffff',
capitalCityId: null,
chiefGeneralId: null,
gold: 100,
rice: 200,
power: 0,
level: 1,
typeCode: 'che_중립',
meta: {},
},
],
cities: [],
generals: [],
settlements: [],
settlementsComplete: true,
}),
};
beforeAll(async () => {
const connector = createGamePostgresConnector({ url: databaseUrl! });
await connector.connect();
db = connector.prisma;
close = () => connector.disconnect();
});
afterAll(async () => {
await db.playAuditMonth.deleteMany({ where: { serverId } });
await close();
});
it('rolls back all audit rows, reloads exact data, rejects conflicting replay and deduplicates retries', async () => {
await expect(
db.$transaction(async (tx) => {
await tx.nation.create({ data: { id: 999_916, name: 'rollback audit', color: '#ffffff' } });
await persistAuditMonth(tx, snapshot);
throw new Error('fixture rollback');
})
).rejects.toThrow('fixture rollback');
expect(await db.playAuditMonth.count({ where: { serverId } })).toBe(0);
expect(await db.nation.findUnique({ where: { id: 999_916 } })).toBeNull();
await db.$transaction((tx) => persistAuditMonth(tx, snapshot));
await db.$transaction((tx) => persistAuditMonth(tx, snapshot));
const saved = await db.playAuditMonth.findFirstOrThrow({ where: { serverId }, include: { nations: true } });
expect(saved.nations.map((row) => row.data)).toEqual(snapshot.nations);
expect(await db.playAuditMonth.count({ where: { serverId } })).toBe(1);
await expect(db.$transaction((tx) => persistAuditMonth(tx, { ...snapshot, tick: 11 }))).rejects.toThrow(
'replay payload conflict'
);
expect((await db.playAuditMonth.findUniqueOrThrow({ where: { id: saved.id } })).tick).toBe(10);
await db.playAuditMonth.delete({ where: { id: saved.id } });
expect(await db.playAuditNation.count({ where: { sampleId: saved.id } })).toBe(0);
});
});
@@ -116,6 +116,7 @@ describe('durable read-model change journal mapping', () => {
pendingNationBettingOpens: [],
pendingNationBettingFinishes: [],
pendingYearbookSnapshots: [],
pendingAuditMonths: [],
pendingUnificationFinalizations: [],
} satisfies TurnWorldChanges;
const readModelChanges = createEmptyRealtimeReadModelChanges();