feat: 실행 중 게임 옵션 변경을 지원

Gateway 관리 화면에서 현재 기수의 장수 생성 제한, 유저 자동턴, 턴 간격을 내구성 action으로 변경한다.

턴 간격 변경은 논리 tick과 현재 게임 시각을 보존하며 DB와 Redis의 tick 기반 시각을 재투영하고 기존 로그 timestamp는 유지한다.
This commit is contained in:
2026-08-17 16:05:07 +00:00
parent 50e7d894e4
commit ca6823d409
26 changed files with 1680 additions and 115 deletions
@@ -348,7 +348,7 @@ export class TurnDaemonLifecycle {
return;
}
if (result.type === 'shiftSchedule' && result.ok) {
if ((result.type === 'shiftSchedule' || result.type === 'updateRuntimeSettings') && result.ok) {
this.status.lastTurnTime = result.lastTurnTime;
this.status.checkpoint = result.checkpoint;
await this.stateStore.saveCheckpoint(result.checkpoint);
@@ -368,6 +368,30 @@ const zShiftSchedule = z.object({
.refine((value) => value !== 0),
});
const zRuntimeAutorunOption = z.enum(['develop', 'warp', 'recruit', 'recruit_high', 'train', 'battle', 'chief']);
const zUpdateRuntimeSettings = z.object({
type: z.literal('updateRuntimeSettings'),
actionId: z.string().uuid(),
settings: z
.object({
turnTermMinutes: z
.number()
.int()
.refine((value) => [1, 2, 5, 10, 20, 30, 60, 120].includes(value))
.optional(),
blockGeneralCreate: z.union([z.literal(0), z.literal(1), z.literal(2)]).optional(),
autorunUser: z
.object({
limitMinutes: z.number().int().min(1).max(43200),
options: z.array(zRuntimeAutorunOption).min(1),
})
.nullable()
.optional(),
})
.refine((settings) => Object.values(settings).some((value) => value !== undefined)),
});
const normalizeAuctionFinalize: CommandNormalizer<'auctionFinalize'> = (envelope) => {
const command = parseWith(zAuctionFinalize, envelope.command);
if (!command) {
@@ -660,6 +684,14 @@ const normalizeShiftSchedule: CommandNormalizer<'shiftSchedule'> = (envelope) =>
return { ...command, requestId: envelope.requestId };
};
const normalizeUpdateRuntimeSettings: CommandNormalizer<'updateRuntimeSettings'> = (envelope) => {
const command = parseWith(zUpdateRuntimeSettings, envelope.command);
if (!command) {
return null;
}
return { ...command, requestId: envelope.requestId };
};
const normalizers: CommandNormalizerMap = {
auctionFinalize: normalizeAuctionFinalize,
auctionOpen: normalizeAuctionOpen,
@@ -699,6 +731,7 @@ const normalizers: CommandNormalizerMap = {
resume: normalizeResume,
shutdown: normalizeShutdown,
shiftSchedule: normalizeShiftSchedule,
updateRuntimeSettings: normalizeUpdateRuntimeSettings,
};
export const normalizeTurnDaemonCommand = (envelope: TurnDaemonCommandEnvelope): TurnDaemonCommand | null => {
+3 -6
View File
@@ -149,7 +149,7 @@ export const createWorldReadModelSignature = (world: InMemoryTurnWorld): string
currentYear: state.currentYear,
currentMonth: state.currentMonth,
tickSeconds: state.tickSeconds,
config: world.getScenarioConfig(),
config: world.getWorldConfig(),
meta: projectWorldMeta(state.meta),
});
};
@@ -438,11 +438,7 @@ export const createReadModelChangeJournal = (changes: RealtimeReadModelChanges):
if (changes.worldChanged) {
journal.mark('world.content').mark('map.world');
}
if (
changes.mapChanged ||
(changes.mapCityIds ?? []).length > 0 ||
(changes.mapNationIds ?? []).length > 0
) {
if (changes.mapChanged || (changes.mapCityIds ?? []).length > 0 || (changes.mapNationIds ?? []).length > 0) {
journal.mark('map.world');
}
if ((changes.frontStatusGeneralIds ?? []).length > 0 || changes.frontStatusChanged) {
@@ -1119,6 +1115,7 @@ export const createDatabaseTurnHooks = async (
clockMode: state.clockMode ?? 'manual',
clockWallAnchor: state.clockWallAnchor ?? state.lastTurnTime,
lastTurnTick: BigInt(state.lastTurnTick ?? world.dateToGameTick(state.lastTurnTime)),
config: asJson(world.getWorldConfig()),
meta: asJson(state.meta),
};
const persist = async (
@@ -15,6 +15,7 @@ export interface GatewayAdminActionRecord {
handledAt?: string | null;
handler?: string | null;
detail?: string | null;
payload?: Record<string, unknown>;
install?: {
scenarioId?: number;
turnTermMinutes?: number;
@@ -103,6 +104,7 @@ export const createGatewayAdminActionConsumer = async (
handledAt: action.handledAt?.toISOString() ?? null,
handler: action.handler,
detail: action.detail,
payload: normalizeMeta(action.payload),
};
let result: GatewayAdminActionResult;
try {
@@ -33,13 +33,13 @@ const isWorldUnited = (world: InMemoryTurnWorld): boolean => {
export class InMemoryTurnProcessor implements TurnProcessor {
// 인메모리 월드로 턴을 실행하고 월/연 갱신까지 처리한다.
private readonly world: InMemoryTurnWorld;
private readonly tickMinutes: number;
private readonly tickMinutesOverride?: number;
private readonly beforeExecuteGeneral?: (general: TurnGeneral) => Promise<void>;
private readonly afterExecuteGeneral?: (general: TurnGeneral, result: TurnGeneralExecutionResult) => Promise<void>;
constructor(world: InMemoryTurnWorld, options: InMemoryTurnProcessorOptions = {}) {
this.world = world;
this.tickMinutes = resolveTickMinutes(world, options.tickMinutes);
this.tickMinutesOverride = options.tickMinutes;
this.beforeExecuteGeneral = options.beforeExecuteGeneral;
this.afterExecuteGeneral = options.afterExecuteGeneral;
}
@@ -53,6 +53,7 @@ export class InMemoryTurnProcessor implements TurnProcessor {
this.world.updateWorldMeta({
refreshLimit: calculateAccessRefreshLimit(this.world.getState().tickSeconds),
});
const tickMinutes = resolveTickMinutes(this.world, this.tickMinutesOverride);
let processedGenerals = 0;
let processedTurns = 0;
@@ -61,7 +62,7 @@ export class InMemoryTurnProcessor implements TurnProcessor {
let nextCheckpoint: TurnCheckpoint | undefined = undefined;
const previousLastTurnTime = this.world.getState().lastTurnTime;
const firstTickTime = getNextTickTime(previousLastTurnTime, this.tickMinutes);
const firstTickTime = getNextTickTime(previousLastTurnTime, tickMinutes);
// Ref processes `turntime < monthlyBoundary` before the monthly turn. A
// general exactly on the boundary therefore runs only after that month
// has advanced, on the daemon's following pass.
@@ -114,7 +115,7 @@ export class InMemoryTurnProcessor implements TurnProcessor {
}
if (!partial) {
let nextTickTime = getNextTickTime(this.world.getState().lastTurnTime, this.tickMinutes);
let nextTickTime = getNextTickTime(this.world.getState().lastTurnTime, tickMinutes);
while (!isWorldUnited(this.world) && nextTickTime.getTime() <= targetTime.getTime()) {
if (processedTurns >= budget.catchUpCap || isBudgetExpired()) {
partial = true;
@@ -125,7 +126,7 @@ export class InMemoryTurnProcessor implements TurnProcessor {
if (isWorldUnited(this.world)) {
break;
}
nextTickTime = getNextTickTime(this.world.getState().lastTurnTime, this.tickMinutes);
nextTickTime = getNextTickTime(this.world.getState().lastTurnTime, tickMinutes);
}
}
+96 -18
View File
@@ -145,6 +145,7 @@ export interface TurnWorldChanges {
export interface InMemoryTurnWorldStateSnapshot {
schedule: TurnSchedule;
state: TurnWorldState;
worldConfig: Record<string, unknown>;
checkpoint?: TurnCheckpoint;
generals: Array<[number, TurnGeneral]>;
cities: Array<[number, City]>;
@@ -181,6 +182,7 @@ export interface InMemoryTurnWorldStateSnapshot {
export interface InMemoryTurnWorldInspection {
state: TurnWorldState;
worldConfig: Record<string, unknown>;
checkpoint?: TurnCheckpoint;
generals: TurnGeneral[];
cities: City[];
@@ -447,6 +449,7 @@ export class InMemoryTurnWorld {
private readonly pendingYearbookSnapshots: PendingYearbookSnapshot[] = [];
private readonly pendingUnificationFinalizations: PendingUnificationFinalization[] = [];
private readonly scenarioConfig: ScenarioConfig;
private readonly worldConfig: Record<string, unknown>;
private readonly unitSet?: UnitSetDefinition;
private checkpoint?: TurnCheckpoint;
private state: TurnWorldState;
@@ -483,6 +486,10 @@ export class InMemoryTurnWorld {
meta: { ...state.meta, lastTurnTime: lastTurnTime.toISOString() },
};
this.scenarioConfig = snapshot.scenarioConfig;
// Runtime callbacks created before the world keep the original object
// reference. Mutate this object in place so a live settings action is
// observed by monthly handlers without restarting the daemon.
this.worldConfig = snapshot.worldConfig ?? {};
this.unitSet = snapshot.unitSet;
this.schedule = options.schedule;
this.generalTurnHandler =
@@ -597,6 +604,7 @@ export class InMemoryTurnWorld {
return structuredClone({
schedule: this.schedule,
state: this.state,
worldConfig: this.worldConfig,
checkpoint: this.checkpoint,
generals: Array.from(this.generals.entries()),
cities: Array.from(this.cities.entries()),
@@ -636,6 +644,10 @@ export class InMemoryTurnWorld {
const restored = structuredClone(snapshot);
this.schedule = restored.schedule;
this.state = restored.state;
for (const key of Object.keys(this.worldConfig)) {
delete this.worldConfig[key];
}
Object.assign(this.worldConfig, restored.worldConfig);
this.checkpoint = restored.checkpoint;
this.replaceMap(this.generals, restored.generals);
this.replaceMap(this.cities, restored.cities);
@@ -673,6 +685,7 @@ export class InMemoryTurnWorld {
inspectState(): InMemoryTurnWorldInspection {
return structuredClone({
state: this.state,
worldConfig: this.worldConfig,
checkpoint: this.checkpoint,
generals: Array.from(this.generals.values()),
cities: Array.from(this.cities.values()),
@@ -698,46 +711,107 @@ export class InMemoryTurnWorld {
};
}
updateWorldConfig(patch: Record<string, unknown>): void {
Object.assign(this.worldConfig, patch);
}
markGeneralAccessScoreReset(generalId: number): void {
if (Number.isSafeInteger(generalId) && generalId > 0) {
this.accessScoreResetGeneralIds.add(generalId);
}
}
changeTurnTerm(tickMinutes: number): void {
changeTurnTerm(
tickMinutes: number,
wallNow = new Date()
): {
changed: boolean;
previousTurnTermMinutes: number;
turnTermMinutes: number;
previousClockBaseTime: string;
clockBaseTime: string;
shiftedGenerals: number;
lastTurnTime: string;
} {
if (!Number.isInteger(tickMinutes) || tickMinutes <= 0) {
throw new Error('Turn term must be a positive integer.');
}
const previousTickSeconds = this.state.tickSeconds;
const nextTickSeconds = tickMinutes * 60;
if (previousTickSeconds === nextTickSeconds) {
return;
}
const previousClock = this.getGameClock();
const anchorTick = this.state.clockTick ?? previousClock.tick;
const previousClockBaseTime = previousClock.baseTime.toISOString();
if (previousTickSeconds === nextTickSeconds) {
this.updateWorldConfig({ turnTermMinutes: tickMinutes });
return {
changed: false,
previousTurnTermMinutes: previousTickSeconds / 60,
turnTermMinutes: tickMinutes,
previousClockBaseTime,
clockBaseTime: previousClockBaseTime,
shiftedGenerals: 0,
lastTurnTime: this.state.lastTurnTime.toISOString(),
};
}
const currentWallAnchor = this.state.clockWallAnchor ?? previousClock.wallAnchor;
const anchorWall = wallNow.getTime() < currentWallAnchor.getTime() ? currentWallAnchor : wallNow;
const anchorTick = previousClock.nowTick(anchorWall);
const anchorDisplay = previousClock.tickToDate(anchorTick);
const nextBaseTime = GameClock.baseTimeForProjection(anchorDisplay, anchorTick, nextTickSeconds);
const ratio = nextTickSeconds / previousTickSeconds;
const baseTime = this.state.lastTurnTime.getTime();
const nextGeneralTimes = new Map(
Array.from(this.generals.values(), (general) => [
general.id,
new Date(baseTime + (general.turnTime.getTime() - baseTime) * ratio),
])
);
const nextClock = new GameClock({
baseTime: nextBaseTime,
tick: anchorTick,
mode: this.state.clockMode ?? 'manual',
wallAnchor: anchorWall,
turnSeconds: nextTickSeconds,
});
const lastTurnTick = this.state.lastTurnTick ?? previousClock.dateToTick(this.state.lastTurnTime);
const nextLastTurnTime = nextClock.tickToDate(lastTurnTick);
this.schedule = { entries: [{ startMinute: 0, tickMinutes }] };
this.state = {
...this.state,
tickSeconds: nextTickSeconds,
clockBaseTime: nextBaseTime,
clockTick: anchorTick,
clockWallAnchor: new Date(anchorWall.getTime()),
lastTurnTick,
lastTurnTime: nextLastTurnTime,
meta: {
...this.state.meta,
turnterm: tickMinutes,
lastTurnTime: nextLastTurnTime.toISOString(),
},
};
this.updateWorldConfig({ turnTermMinutes: tickMinutes });
for (const general of this.generals.values()) {
const nextTurnTime = nextGeneralTimes.get(general.id);
if (!nextTurnTime) {
throw new Error(`Missing projected turn time for general ${general.id}.`);
}
this.updateGeneral(general.id, { turnTime: nextTurnTime });
const turnTick = general.turnTick ?? previousClock.dateToTick(general.turnTime);
const recentWarTick =
general.recentWarTick ??
(general.recentWarTime ? previousClock.dateToTick(general.recentWarTime) : null);
this.updateGeneral(general.id, {
turnTick,
turnTime: nextClock.tickToDate(turnTick),
recentWarTick,
recentWarTime: recentWarTick === null ? null : nextClock.tickToDate(recentWarTick),
});
}
if (this.checkpoint) {
const checkpointTick =
this.checkpoint.turnTick ?? previousClock.dateToTick(new Date(this.checkpoint.turnTime));
this.checkpoint = {
...this.checkpoint,
turnTick: checkpointTick,
turnTime: nextClock.tickToDate(checkpointTick).toISOString(),
};
}
return {
changed: true,
previousTurnTermMinutes: previousTickSeconds / 60,
turnTermMinutes: tickMinutes,
previousClockBaseTime,
clockBaseTime: nextBaseTime.toISOString(),
shiftedGenerals: this.generals.size,
lastTurnTime: nextLastTurnTime.toISOString(),
};
}
pushLog(entry: LogEntryDraft): void {
@@ -793,6 +867,10 @@ export class InMemoryTurnWorld {
return this.scenarioConfig;
}
getWorldConfig(): Record<string, unknown> {
return this.worldConfig;
}
getUnitSet(): UnitSetDefinition | undefined {
return this.unitSet;
}
@@ -0,0 +1,244 @@
import { randomUUID } from 'node:crypto';
import {
buildGameEventChannel,
GameClock,
isRecord,
writeTournamentProjection,
type RuntimeAutorunUserOption,
type RuntimeGameSettingsPatch,
type TurnDaemonCommand,
type TurnDaemonCommandResult,
} from '@sammo-ts/common';
import type { GamePrisma, GamePrismaClient } from '@sammo-ts/infra';
import type { GatewayAdminActionRecord, GatewayAdminActionResult } from './gatewayAdminActions.js';
interface RuntimeSettingsRedisClient {
get(key: string): Promise<string | null>;
set(key: string, value: string, options?: { NX?: boolean; PX?: number }): Promise<unknown>;
del(key: string): Promise<unknown>;
eval(script: string, options: { keys: string[]; arguments: string[] }): Promise<unknown>;
publish?(channel: string, message: string): Promise<unknown>;
}
type TournamentClockState = {
nextAt?: string;
bettingCloseAt?: string;
runtimeSettingsActionIds?: string[];
[key: string]: unknown;
};
const TURN_TERMS = new Set([1, 2, 5, 10, 20, 30, 60, 120]);
const AUTORUN_OPTIONS = new Set<RuntimeAutorunUserOption>([
'develop',
'warp',
'recruit',
'recruit_high',
'train',
'battle',
'chief',
]);
const asJson = (value: unknown): GamePrisma.InputJsonValue => value as GamePrisma.InputJsonValue;
const isUniqueConflict = (error: unknown): boolean =>
typeof error === 'object' && error !== null && 'code' in error && error.code === 'P2002';
const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
const normalizeSettings = (value: unknown): RuntimeGameSettingsPatch | null => {
if (!isRecord(value)) return null;
const settings: RuntimeGameSettingsPatch = {};
if (value.turnTermMinutes !== undefined) {
if (!Number.isInteger(value.turnTermMinutes) || !TURN_TERMS.has(value.turnTermMinutes as number)) return null;
settings.turnTermMinutes = value.turnTermMinutes as number;
}
if (value.blockGeneralCreate !== undefined) {
if (![0, 1, 2].includes(value.blockGeneralCreate as number)) return null;
settings.blockGeneralCreate = value.blockGeneralCreate as 0 | 1 | 2;
}
if (value.autorunUser !== undefined) {
if (value.autorunUser === null) {
settings.autorunUser = null;
} else {
if (!isRecord(value.autorunUser)) return null;
const limitMinutes = value.autorunUser.limitMinutes;
const options = value.autorunUser.options;
if (
!Number.isInteger(limitMinutes) ||
(limitMinutes as number) < 1 ||
(limitMinutes as number) > 43200 ||
!Array.isArray(options) ||
options.length === 0 ||
!options.every(
(option): option is RuntimeAutorunUserOption =>
typeof option === 'string' && AUTORUN_OPTIONS.has(option as RuntimeAutorunUserOption)
)
) {
return null;
}
settings.autorunUser = {
limitMinutes: limitMinutes as number,
options: Array.from(new Set(options)),
};
}
}
return Object.keys(settings).length > 0 ? settings : null;
};
const ensureEngineCommand = async (
db: GamePrismaClient,
actionId: string,
settings: RuntimeGameSettingsPatch
): Promise<{ requestId: string; result?: TurnDaemonCommandResult; failed?: string }> => {
const requestId = `gateway-runtime:${actionId}`;
const command: TurnDaemonCommand = {
type: 'updateRuntimeSettings',
requestId,
actionId,
settings,
};
try {
await db.inputEvent.create({
data: {
requestId,
target: 'ENGINE',
eventType: command.type,
payload: asJson(command),
},
});
} catch (error) {
if (!isUniqueConflict(error)) throw error;
const existing = await db.inputEvent.findUniqueOrThrow({
where: { requestId },
select: { eventType: true, payload: true },
});
const payload = existing.payload as Partial<TurnDaemonCommand>;
if (
existing.eventType !== command.type ||
payload.type !== command.type ||
payload.actionId !== actionId ||
JSON.stringify(payload.settings) !== JSON.stringify(settings)
) {
return { requestId, failed: '같은 action ID에 다른 런타임 설정 payload가 이미 존재합니다.' };
}
}
const event = await db.inputEvent.findUniqueOrThrow({
where: { requestId },
select: { status: true, result: true, error: true },
});
if (event.status === 'FAILED') {
return { requestId, failed: event.error ?? '게임 엔진 런타임 설정 변경이 실패했습니다.' };
}
if (event.status !== 'SUCCEEDED') return { requestId };
return { requestId, result: event.result as TurnDaemonCommandResult };
};
const reprojectTournamentClock = async (
redis: RuntimeSettingsRedisClient,
profileName: string,
actionId: string,
result: Extract<TurnDaemonCommandResult, { type: 'updateRuntimeSettings'; ok: true }>
): Promise<boolean> => {
const stateKey = `sammo:${profileName}:tournament:state`;
const sourceKeys = {
stateKey,
sourceRevisionKey: `sammo:${profileName}:tournament:source-revision`,
sourceRevisionChannel: `sammo:${profileName}:tournament:source-changed`,
realtimeEventChannel: buildGameEventChannel(profileName),
};
const lockKey = `${stateKey}:mutation-lock`;
const token = randomUUID();
const deadline = Date.now() + 2_000;
while (Date.now() < deadline) {
const acquired = await redis.set(lockKey, token, { NX: true, PX: 30_000 });
if (acquired) {
try {
const rawState = await redis.get(stateKey);
if (!rawState) return false;
const state = JSON.parse(rawState) as TournamentClockState;
const applied = Array.isArray(state.runtimeSettingsActionIds)
? state.runtimeSettingsActionIds.filter((entry): entry is string => typeof entry === 'string')
: [];
if (applied.includes(actionId)) return true;
const previousClock = new GameClock({
baseTime: new Date(result.previousClockBaseTime),
tick: 0,
mode: 'manual',
wallAnchor: new Date(result.previousClockBaseTime),
turnSeconds: result.previousTurnTermMinutes * 60,
});
const nextClock = new GameClock({
baseTime: new Date(result.clockBaseTime),
tick: 0,
mode: 'manual',
wallAnchor: new Date(result.clockBaseTime),
turnSeconds: result.turnTermMinutes * 60,
});
const reproject = (value: string | undefined): string | undefined => {
if (!value) return value;
const parsed = new Date(value);
if (Number.isNaN(parsed.getTime())) return value;
return nextClock.tickToDate(previousClock.dateToTick(parsed)).toISOString();
};
const nextState: TournamentClockState = {
...state,
nextAt: reproject(state.nextAt),
bettingCloseAt: reproject(state.bettingCloseAt),
runtimeSettingsActionIds: [...applied, actionId],
};
await writeTournamentProjection(redis, sourceKeys, [{ key: stateKey, value: nextState }]);
return true;
} finally {
if ((await redis.get(lockKey)) === token) await redis.del(lockKey);
}
}
await sleep(10);
}
throw new Error('토너먼트 턴 간격 변경 lock을 획득하지 못했습니다.');
};
export const applyRuntimeGameSettings = async (options: {
action: GatewayAdminActionRecord;
profileName: string;
db: GamePrismaClient;
redis?: RuntimeSettingsRedisClient;
}): Promise<GatewayAdminActionResult> => {
const { action, profileName, db, redis } = options;
if (!action.id) return { status: 'FAILED', detail: '런타임 설정 action ID가 없습니다.' };
const settings = normalizeSettings(action.payload?.settings);
if (!settings) return { status: 'FAILED', detail: '런타임 설정 payload가 올바르지 않습니다.' };
const engine = await ensureEngineCommand(db, action.id, settings);
if (engine.failed) return { status: 'FAILED', detail: engine.failed };
if (!engine.result) return { status: 'REQUESTED', detail: `게임 엔진 처리 대기 중: ${engine.requestId}` };
if (engine.result.type !== 'updateRuntimeSettings' || !engine.result.ok) {
return {
status: 'FAILED',
detail:
engine.result.type === 'updateRuntimeSettings'
? engine.result.reason
: '게임 엔진이 다른 결과를 반환했습니다.',
};
}
if (engine.result.termChanged && !redis) {
return {
status: 'PARTIAL',
detail: `DB 설정은 적용됐지만 Redis 토너먼트 시각 동기화를 기다리는 중입니다: ${engine.requestId}`,
};
}
const tournamentReprojected =
engine.result.termChanged && redis
? await reprojectTournamentClock(redis, profileName, action.id, engine.result)
: false;
const summary = [
`${engine.result.turnTermMinutes}`,
settings.blockGeneralCreate === undefined ? null : `장수 생성 ${settings.blockGeneralCreate}`,
settings.autorunUser === undefined
? null
: settings.autorunUser === null
? '유저 자동턴 끔'
: `유저 자동턴 ${settings.autorunUser.limitMinutes}`,
engine.result.termChanged ? `장수 ${engine.result.shiftedGenerals}명 시각 보정` : null,
tournamentReprojected ? '토너먼트 시각 보정' : null,
].filter((entry): entry is string => entry !== null);
return { status: 'APPLIED', detail: summary.join(' · ') };
};
+16 -4
View File
@@ -89,6 +89,7 @@ import { buildCommandEnv } from './reservedTurnCommands.js';
import { DatabaseTurnDaemonLease, TurnDaemonLeaseUnavailableError } from '../lifecycle/databaseTurnDaemonLease.js';
import { EngineStateManager } from './engineStateManager.js';
import { applyRuntimeClockShift } from './runtimeClockShift.js';
import { applyRuntimeGameSettings } from './runtimeGameSettings.js';
export interface TurnDaemonRuntimeOptions {
profile: string;
@@ -442,7 +443,7 @@ const createMonthlyCalendarRuntime = async (options: {
profileName: options.profileName,
getWorld: options.getWorld,
getRedisClient: options.getRedisClient,
getWorldConfig: () => options.snapshot.worldConfig ?? null,
getWorldConfig: () => options.getWorld()?.getWorldConfig() ?? options.snapshot.worldConfig ?? null,
getNationPowerRollCount: () => cache.nationPowerRollCount,
getTournamentRollConsumed: () => cache.tournamentRollConsumed,
now: () => options.getWorld()?.getGameNow(new Date(options.clock.nowMs())) ?? new Date(options.clock.nowMs()),
@@ -451,7 +452,7 @@ const createMonthlyCalendarRuntime = async (options: {
profileName: options.profileName,
getWorld: options.getWorld,
getRedisClient: options.getRedisClient,
getWorldConfig: () => options.snapshot.worldConfig ?? null,
getWorldConfig: () => options.getWorld()?.getWorldConfig() ?? options.snapshot.worldConfig ?? null,
getNationPowerRollCount: () => cache.nationPowerRollCount,
onTournamentRollConsumed: (consumed) => {
cache.tournamentRollConsumed = consumed;
@@ -599,6 +600,17 @@ const createStartedAdminActionConsumer = async (options: {
redis: options.redisConnector?.client,
});
}
if (action.action === 'UPDATE_RUNTIME_SETTINGS') {
if (!options.commandConnector) {
return { status: 'FAILED', detail: '게임 command database 연결이 없습니다.' };
}
return applyRuntimeGameSettings({
action,
profileName,
db: options.commandConnector.prisma,
redis: options.redisConnector?.client,
});
}
switch (action.action) {
case 'RESUME':
options.controlQueue.enqueue({ type: 'resume', reason });
@@ -766,7 +778,6 @@ const createTurnDaemonRuntimeWithLease = async (
const stateStore = new InMemoryTurnStateStore(world);
let fastForwardPreparedMonth = '';
const processor = new InMemoryTurnProcessor(world, {
tickMinutes,
beforeExecuteGeneral: reservedTurnStoreHandle
? async (general) => {
if (options.exclusiveFastForward) {
@@ -959,7 +970,8 @@ const createTurnDaemonRuntimeWithLease = async (
{
clock,
controlQueue: resolvedControlQueue,
getNextTickTime: (lastTurnTime) => getNextTickTime(lastTurnTime, tickMinutes),
getNextTickTime: (lastTurnTime) =>
getNextTickTime(lastTurnTime, Math.max(1, Math.round(world.getState().tickSeconds / 60))),
stateStore,
processor,
hooks,
+134 -1
View File
@@ -5,7 +5,14 @@ import type {
TurnDaemonCommandResult,
} from '../lifecycle/types.js';
import { GamePrisma, type DatabaseClient } from '@sammo-ts/infra';
import { asRecord, isCanonicalIsoTimestamp, JosaUtil, LiteHashDRBG, RandUtil } from '@sammo-ts/common';
import {
asRecord,
GAME_TICKS_PER_TURN,
isCanonicalIsoTimestamp,
JosaUtil,
LiteHashDRBG,
RandUtil,
} from '@sammo-ts/common';
import {
LogCategory,
LogFormat,
@@ -921,6 +928,130 @@ async function handleShiftSchedule(
};
}
async function handleUpdateRuntimeSettings(
ctx: CommandHandlerContext,
command: Extract<TurnDaemonCommand, { type: 'updateRuntimeSettings' }>
): Promise<TurnDaemonCommandResult> {
if (!ctx.commandDb) {
return {
type: 'updateRuntimeSettings',
ok: false,
actionId: command.actionId,
reason: '런타임 설정 변경은 데이터베이스 transaction 경계에서만 실행할 수 있습니다.',
};
}
const operationalAcceptedAt = await resolveOperationalAcceptedAt(ctx.commandDb, command);
if (command.settings.blockGeneralCreate !== undefined) {
ctx.world.updateWorldConfig({ blockGeneralCreate: command.settings.blockGeneralCreate });
}
if (command.settings.autorunUser !== undefined) {
ctx.world.updateWorldMeta({
autorun_user:
command.settings.autorunUser === null
? null
: {
limit_minutes: command.settings.autorunUser.limitMinutes,
options: Object.fromEntries(
command.settings.autorunUser.options.map((option) => [option, true])
),
},
});
}
const currentState = ctx.world.getState();
const currentTermMinutes = Math.max(1, Math.round(currentState.tickSeconds / 60));
const term =
command.settings.turnTermMinutes === undefined
? {
changed: false,
previousTurnTermMinutes: currentTermMinutes,
turnTermMinutes: currentTermMinutes,
previousClockBaseTime: (currentState.clockBaseTime ?? currentState.lastTurnTime).toISOString(),
clockBaseTime: (currentState.clockBaseTime ?? currentState.lastTurnTime).toISOString(),
shiftedGenerals: 0,
lastTurnTime: currentState.lastTurnTime.toISOString(),
}
: ctx.world.changeTurnTerm(command.settings.turnTermMinutes, operationalAcceptedAt);
let reprojectedAuctions = 0;
let reprojectedMessages = 0;
let reprojectedVotes = 0;
if (term.changed) {
const ticksPerSecond = BigInt(GAME_TICKS_PER_TURN / (term.turnTermMinutes * 60));
const baseTime = new Date(term.clockBaseTime);
reprojectedAuctions = await ctx.commandDb.$executeRaw(
GamePrisma.sql`
UPDATE auction
SET close_at = CAST(${baseTime} AS timestamp)
+ (close_tick / ${ticksPerSecond}) * INTERVAL '1 second'
+ (((close_tick % ${ticksPerSecond}) * 1000) / ${ticksPerSecond}) * INTERVAL '1 millisecond',
updated_at = NOW()
WHERE close_tick IS NOT NULL
`
);
reprojectedMessages = await ctx.commandDb.$executeRaw(
GamePrisma.sql`
UPDATE message
SET time = CASE
WHEN time_tick IS NULL THEN time
ELSE CAST(${baseTime} AS timestamp)
+ (time_tick / ${ticksPerSecond}) * INTERVAL '1 second'
+ (((time_tick % ${ticksPerSecond}) * 1000) / ${ticksPerSecond}) * INTERVAL '1 millisecond'
END,
valid_until = CASE
WHEN valid_until_tick IS NULL THEN valid_until
ELSE CAST(${baseTime} AS timestamp)
+ (valid_until_tick / ${ticksPerSecond}) * INTERVAL '1 second'
+ (((valid_until_tick % ${ticksPerSecond}) * 1000) / ${ticksPerSecond}) * INTERVAL '1 millisecond'
END
WHERE time_tick IS NOT NULL OR valid_until_tick IS NOT NULL
`
);
reprojectedVotes = await ctx.commandDb.$executeRaw(
GamePrisma.sql`
UPDATE vote_poll
SET start_at = CASE
WHEN start_tick IS NULL THEN start_at
ELSE CAST(${baseTime} AS timestamp)
+ (start_tick / ${ticksPerSecond}) * INTERVAL '1 second'
+ (((start_tick % ${ticksPerSecond}) * 1000) / ${ticksPerSecond}) * INTERVAL '1 millisecond'
END,
end_at = CASE
WHEN end_tick IS NULL THEN end_at
ELSE CAST(${baseTime} AS timestamp)
+ (end_tick / ${ticksPerSecond}) * INTERVAL '1 second'
+ (((end_tick % ${ticksPerSecond}) * 1000) / ${ticksPerSecond}) * INTERVAL '1 millisecond'
END
WHERE start_tick IS NOT NULL OR end_tick IS NOT NULL
`
);
ctx.world.pushLog({
scope: LogScope.SYSTEM,
category: LogCategory.HISTORY,
text: `<R>★</>턴시간이 <C>${term.turnTermMinutes}분</>으로 변경됩니다.`,
});
}
return {
type: 'updateRuntimeSettings',
ok: true,
actionId: command.actionId,
settings: command.settings,
termChanged: term.changed,
previousTurnTermMinutes: term.previousTurnTermMinutes,
turnTermMinutes: term.turnTermMinutes,
previousClockBaseTime: term.previousClockBaseTime,
clockBaseTime: term.clockBaseTime,
lastTurnTime: term.lastTurnTime,
shiftedGenerals: term.shiftedGenerals,
reprojectedAuctions,
reprojectedMessages,
reprojectedVotes,
checkpoint: ctx.world.getCheckpoint(),
};
}
async function handleTroopJoin(
ctx: CommandHandlerContext,
command: Extract<TurnDaemonCommand, { type: 'troopJoin' }>
@@ -2505,6 +2636,8 @@ export const createTurnDaemonCommandHandler = (options: {
handleSelectPoolReselect(ctx, command as Extract<TurnDaemonCommand, { type: 'selectPoolReselect' }>),
shiftSchedule: (command) =>
handleShiftSchedule(ctx, command as Extract<TurnDaemonCommand, { type: 'shiftSchedule' }>),
updateRuntimeSettings: (command) =>
handleUpdateRuntimeSettings(ctx, command as Extract<TurnDaemonCommand, { type: 'updateRuntimeSettings' }>),
};
return {