feat: 플레이 감사 월별 수집과 원자적 배치 저장 연결
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
import { asRecord } from '@sammo-ts/common';
|
||||
import type { InMemoryTurnWorld, TurnCalendarHandler } from '../turn/inMemoryWorld.js';
|
||||
import { buildAuditSnapshot, type AuditSettlement } from './snapshot.js';
|
||||
|
||||
interface MonthlyFlows {
|
||||
year: number;
|
||||
month: number;
|
||||
complete: boolean;
|
||||
entries: Record<string, AuditSettlement>;
|
||||
}
|
||||
|
||||
const readFlows = (world: InMemoryTurnWorld): MonthlyFlows => {
|
||||
const state = world.getState();
|
||||
const raw = asRecord(state.meta.playAuditFlows);
|
||||
const entries: Record<string, AuditSettlement> = {};
|
||||
const matches = raw.year === state.currentYear && raw.month === state.currentMonth;
|
||||
if (matches) {
|
||||
for (const [key, value] of Object.entries(asRecord(raw.entries))) {
|
||||
const row = asRecord(value);
|
||||
if (
|
||||
typeof row.nationId === 'number' &&
|
||||
(row.resource === 'gold' || row.resource === 'rice') &&
|
||||
typeof row.income === 'number' &&
|
||||
Number.isFinite(row.income) &&
|
||||
typeof row.paid === 'number' &&
|
||||
Number.isFinite(row.paid)
|
||||
) {
|
||||
entries[key] = { nationId: row.nationId, resource: row.resource, income: row.income, paid: row.paid };
|
||||
}
|
||||
}
|
||||
}
|
||||
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 queueAuditMonth = (world: InMemoryTurnWorld, kind: 'MONTH_END' | 'FINAL' = '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: state.lastTurnTick ?? null,
|
||||
kind,
|
||||
settlementsComplete: flows.complete,
|
||||
});
|
||||
};
|
||||
|
||||
export const createPlayAuditHandler = (getWorld: () => InMemoryTurnWorld | null): TurnCalendarHandler => ({
|
||||
beforeMonthChanged: (context) => {
|
||||
const world = getWorld();
|
||||
if (!world) return;
|
||||
queueAuditMonth(world);
|
||||
// 다음 달의 정산보다 먼저 활성화한다. 도입 당월은 complete=false로 남긴다.
|
||||
world.updateWorldMeta({
|
||||
playAuditFlows: { year: context.currentYear, month: context.currentMonth, complete: true, entries: {} },
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,82 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import type { GamePrisma, InputJsonValue } from '@sammo-ts/infra';
|
||||
import type { AuditCitySnapshot, AuditGeneralSnapshot, AuditNationSnapshot } from './snapshot.js';
|
||||
|
||||
export interface PendingAuditMonth {
|
||||
serverId: string;
|
||||
year: number;
|
||||
month: number;
|
||||
kind: 'MONTH_END' | 'FINAL';
|
||||
tick: number | null;
|
||||
settlementsComplete: boolean;
|
||||
nations: AuditNationSnapshot[];
|
||||
cities: AuditCitySnapshot[];
|
||||
generals: AuditGeneralSnapshot[];
|
||||
}
|
||||
|
||||
// JSON parameter 한 번에 전체 기수나 world를 전송하지 않는다.
|
||||
const BATCH_SIZE = 200;
|
||||
const asJson = (value: AuditNationSnapshot | AuditCitySnapshot | AuditGeneralSnapshot): InputJsonValue =>
|
||||
JSON.parse(JSON.stringify(value)) as InputJsonValue;
|
||||
|
||||
export const persistAuditMonth = async (
|
||||
tx: GamePrisma.TransactionClient,
|
||||
snapshot: PendingAuditMonth
|
||||
): Promise<void> => {
|
||||
if (
|
||||
!snapshot.serverId.trim() ||
|
||||
!Number.isInteger(snapshot.year) ||
|
||||
!Number.isInteger(snapshot.month) ||
|
||||
snapshot.month < 1 ||
|
||||
snapshot.month > 12
|
||||
) {
|
||||
throw new Error('Invalid play audit month identity');
|
||||
}
|
||||
const id = JSON.stringify([snapshot.serverId, snapshot.year, snapshot.month, snapshot.kind]);
|
||||
const hash = createHash('sha256').update(JSON.stringify(snapshot)).digest('hex');
|
||||
const saved = await tx.playAuditMonth.upsert({
|
||||
where: { id },
|
||||
create: {
|
||||
id,
|
||||
serverId: snapshot.serverId,
|
||||
year: snapshot.year,
|
||||
month: snapshot.month,
|
||||
kind: snapshot.kind,
|
||||
tick: snapshot.tick,
|
||||
settlementsComplete: snapshot.settlementsComplete,
|
||||
hash,
|
||||
},
|
||||
update: {},
|
||||
select: { hash: true },
|
||||
});
|
||||
if (saved.hash !== hash) throw new Error('Play audit month replay payload conflict');
|
||||
for (let offset = 0; offset < snapshot.nations.length; offset += BATCH_SIZE) {
|
||||
await tx.playAuditNation.createMany({
|
||||
skipDuplicates: true,
|
||||
data: snapshot.nations
|
||||
.slice(offset, offset + BATCH_SIZE)
|
||||
.map((nation) => ({ sampleId: id, nationId: nation.id, data: asJson(nation) })),
|
||||
});
|
||||
}
|
||||
for (let offset = 0; offset < snapshot.cities.length; offset += BATCH_SIZE) {
|
||||
await tx.playAuditCity.createMany({
|
||||
skipDuplicates: true,
|
||||
data: snapshot.cities
|
||||
.slice(offset, offset + BATCH_SIZE)
|
||||
.map((city) => ({ sampleId: id, cityId: city.id, nationId: city.nationId, data: asJson(city) })),
|
||||
});
|
||||
}
|
||||
for (let offset = 0; offset < snapshot.generals.length; offset += BATCH_SIZE) {
|
||||
await tx.playAuditGeneral.createMany({
|
||||
skipDuplicates: true,
|
||||
data: snapshot.generals.slice(offset, offset + BATCH_SIZE).map((general) => ({
|
||||
sampleId: id,
|
||||
generalId: general.id,
|
||||
nationId: general.nationId,
|
||||
cityId: general.cityId,
|
||||
npcState: general.npcState,
|
||||
data: asJson(general),
|
||||
})),
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -1,3 +1,4 @@
|
||||
import { persistAuditMonth } from '../playAudit/persistence.js';
|
||||
import { persistGeneralAccessScores, persistGeneralUpdates } from './generalBatchPersistence.js';
|
||||
import { areSeasonRecordsFinalized } from './seasonRecords.js';
|
||||
import {
|
||||
@@ -1138,6 +1139,7 @@ export const createDatabaseTurnHooks = async (
|
||||
pendingNationBettingOpens,
|
||||
pendingNationBettingFinishes,
|
||||
pendingYearbookSnapshots,
|
||||
pendingAuditMonths,
|
||||
pendingUnificationFinalizations,
|
||||
} = changes;
|
||||
const reservedTurnChanges = options?.reservedTurns?.peekDirtyState();
|
||||
@@ -1867,6 +1869,9 @@ export const createDatabaseTurnHooks = async (
|
||||
data: pendingLogRows,
|
||||
});
|
||||
}
|
||||
for (const snapshot of pendingAuditMonths) {
|
||||
await persistAuditMonth(prisma, snapshot);
|
||||
}
|
||||
for (const snapshot of pendingYearbookSnapshots) {
|
||||
await persistYearbookSnapshot(prisma, snapshot);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { PendingAuditMonth } from '../playAudit/persistence.js';
|
||||
import type {
|
||||
City,
|
||||
LogEntryDraft,
|
||||
@@ -199,6 +200,7 @@ export interface TurnWorldChanges {
|
||||
pendingNationBettingOpens: PendingNationBettingOpen[];
|
||||
pendingNationBettingFinishes: PendingNationBettingFinish[];
|
||||
pendingYearbookSnapshots: PendingYearbookSnapshot[];
|
||||
pendingAuditMonths: PendingAuditMonth[];
|
||||
pendingUnificationFinalizations: PendingUnificationFinalization[];
|
||||
}
|
||||
|
||||
@@ -239,6 +241,7 @@ export interface InMemoryTurnWorldStateSnapshot {
|
||||
pendingNationBettingOpens: PendingNationBettingOpen[];
|
||||
pendingNationBettingFinishes: PendingNationBettingFinish[];
|
||||
pendingYearbookSnapshots: PendingYearbookSnapshot[];
|
||||
pendingAuditMonths: PendingAuditMonth[];
|
||||
pendingUnificationFinalizations: PendingUnificationFinalization[];
|
||||
pendingRealtimeBacklogShiftTicks: number;
|
||||
}
|
||||
@@ -543,6 +546,7 @@ export class InMemoryTurnWorld {
|
||||
private readonly pendingNationBettingOpens: PendingNationBettingOpen[] = [];
|
||||
private readonly pendingNationBettingFinishes: PendingNationBettingFinish[] = [];
|
||||
private readonly pendingYearbookSnapshots: PendingYearbookSnapshot[] = [];
|
||||
private readonly pendingAuditMonths: PendingAuditMonth[] = [];
|
||||
private readonly pendingUnificationFinalizations: PendingUnificationFinalization[] = [];
|
||||
private pendingRealtimeBacklogShiftTicks = 0;
|
||||
private readonly scenarioConfig: ScenarioConfig;
|
||||
@@ -1091,6 +1095,7 @@ export class InMemoryTurnWorld {
|
||||
pendingNationBettingOpens: this.pendingNationBettingOpens,
|
||||
pendingNationBettingFinishes: this.pendingNationBettingFinishes,
|
||||
pendingYearbookSnapshots: this.pendingYearbookSnapshots,
|
||||
pendingAuditMonths: this.pendingAuditMonths,
|
||||
pendingUnificationFinalizations: this.pendingUnificationFinalizations,
|
||||
pendingRealtimeBacklogShiftTicks: this.pendingRealtimeBacklogShiftTicks,
|
||||
} satisfies InMemoryTurnWorldStateSnapshot);
|
||||
@@ -1137,6 +1142,7 @@ export class InMemoryTurnWorld {
|
||||
this.replaceArray(this.pendingNationBettingOpens, restored.pendingNationBettingOpens);
|
||||
this.replaceArray(this.pendingNationBettingFinishes, restored.pendingNationBettingFinishes);
|
||||
this.replaceArray(this.pendingYearbookSnapshots, restored.pendingYearbookSnapshots);
|
||||
this.replaceArray(this.pendingAuditMonths, restored.pendingAuditMonths);
|
||||
this.replaceArray(this.pendingUnificationFinalizations, restored.pendingUnificationFinalizations);
|
||||
this.pendingRealtimeBacklogShiftTicks = restored.pendingRealtimeBacklogShiftTicks ?? 0;
|
||||
}
|
||||
@@ -1352,6 +1358,10 @@ export class InMemoryTurnWorld {
|
||||
});
|
||||
}
|
||||
|
||||
queueAuditMonth(snapshot: PendingAuditMonth): void {
|
||||
this.pendingAuditMonths.push(structuredClone(snapshot));
|
||||
}
|
||||
|
||||
queueYearbookSnapshot(snapshot: PendingYearbookSnapshot): void {
|
||||
this.pendingYearbookSnapshots.push(structuredClone(snapshot));
|
||||
}
|
||||
@@ -2194,6 +2204,7 @@ export class InMemoryTurnWorld {
|
||||
turnTime: new Date(entry.turnTime.getTime()),
|
||||
}));
|
||||
const pendingYearbookSnapshots = structuredClone(this.pendingYearbookSnapshots);
|
||||
const pendingAuditMonths = structuredClone(this.pendingAuditMonths);
|
||||
const pendingUnificationFinalizations = structuredClone(this.pendingUnificationFinalizations);
|
||||
const accessScoreResetGeneralIds = Array.from(this.accessScoreResetGeneralIds).sort(
|
||||
(left, right) => left - right
|
||||
@@ -2226,6 +2237,7 @@ export class InMemoryTurnWorld {
|
||||
pendingNationBettingOpens,
|
||||
pendingNationBettingFinishes,
|
||||
pendingYearbookSnapshots,
|
||||
pendingAuditMonths,
|
||||
pendingUnificationFinalizations,
|
||||
};
|
||||
}
|
||||
@@ -2264,6 +2276,7 @@ export class InMemoryTurnWorld {
|
||||
this.pendingNationBettingOpens.splice(0, changes.pendingNationBettingOpens.length);
|
||||
this.pendingNationBettingFinishes.splice(0, changes.pendingNationBettingFinishes.length);
|
||||
this.pendingYearbookSnapshots.splice(0, changes.pendingYearbookSnapshots.length);
|
||||
this.pendingAuditMonths.splice(0, changes.pendingAuditMonths.length);
|
||||
this.pendingUnificationFinalizations.splice(0, changes.pendingUnificationFinalizations.length);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { recordAuditSettlement } from '../playAudit/collection.js';
|
||||
import { asNumber, asRecord } from '@sammo-ts/common';
|
||||
import {
|
||||
ActionLogger,
|
||||
@@ -175,8 +176,10 @@ const processIncomeForNation = (
|
||||
const incomeText = Math.round(incomeValue).toLocaleString('en-US');
|
||||
const incomeLog =
|
||||
type === 'gold' ? `이번 수입은 금 <C>${incomeText}</>입니다.` : `이번 수입은 쌀 <C>${incomeText}</>입니다.`;
|
||||
let paid = 0;
|
||||
for (const general of nationGenerals) {
|
||||
const pay = Math.round(getBill(general.dedication) * ratio);
|
||||
paid += pay;
|
||||
if (
|
||||
process.env.SEED_PARITY_MONTHLY_RESOURCE_TRACE === '1' &&
|
||||
(process.env.AI_TRACE_GENERAL_IDS ?? '').split(',').includes(String(general.id))
|
||||
@@ -203,6 +206,7 @@ const processIncomeForNation = (
|
||||
logger.pushGeneralActionLog(payLog, LogFormat.PLAIN);
|
||||
pushLogs(world, logger.flush());
|
||||
}
|
||||
recordAuditSettlement(world, { nationId: nation.id, resource: type, income: incomeValue, paid });
|
||||
};
|
||||
|
||||
export interface IncomeHandler extends TurnCalendarHandler {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createPlayAuditHandler } from '../playAudit/collection.js';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { createRuntimePauseGate } from './runtimePauseGate.js';
|
||||
|
||||
@@ -480,6 +481,7 @@ const createMonthlyCalendarRuntime = async (options: {
|
||||
options.monthlyEventHandler,
|
||||
options.hasEventAction('ProcessIncome') ? null : options.incomeHandler,
|
||||
createYearbookHandler({ profileName: options.profileName, getWorld: options.getWorld }).handler,
|
||||
createPlayAuditHandler(options.getWorld),
|
||||
monthlyBoundaryPreHandler,
|
||||
createNationTurnMonthlyHandler({ getWorld: options.getWorld }),
|
||||
monthlyNationStatsHandler,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { queueAuditMonth } from '../playAudit/collection.js';
|
||||
import { resolveMessageTargetIcon } from '@sammo-ts/logic';
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
@@ -177,6 +178,7 @@ export const createUnificationHandler = (options: {
|
||||
}
|
||||
|
||||
queueYearbookSnapshot(world, options.profileName, context.currentYear, context.currentMonth);
|
||||
queueAuditMonth(world, 'FINAL');
|
||||
world.queueUnificationFinalization({
|
||||
generationKey: `unification:${serverId}`,
|
||||
serverId,
|
||||
|
||||
Reference in New Issue
Block a user