feat: execute MyPage immediate actions in daemon
This commit is contained in:
@@ -93,11 +93,13 @@ const zDieOnPrestart = z.object({
|
||||
|
||||
const zBuildNationCandidate = z.object({
|
||||
type: z.literal('buildNationCandidate'),
|
||||
userId: z.string().min(1),
|
||||
generalId: zFiniteNumber,
|
||||
});
|
||||
|
||||
const zInstantRetreat = z.object({
|
||||
type: z.literal('instantRetreat'),
|
||||
userId: z.string().min(1),
|
||||
generalId: zFiniteNumber,
|
||||
});
|
||||
|
||||
|
||||
@@ -1892,3 +1892,259 @@ export const createReservedTurnHandler = async (options: {
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export type ImmediateGeneralActionKey = 'che_거병' | 'che_접경귀환';
|
||||
|
||||
export type ImmediateGeneralActionExecutor = {
|
||||
execute(input: {
|
||||
actionKey: ImmediateGeneralActionKey;
|
||||
generalId: number;
|
||||
rng: RandUtil;
|
||||
refreshKillturn?: boolean;
|
||||
}): Promise<{ ok: boolean; reason?: string }>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Ref의 MyPage 즉시 행동은 예약 턴과 같은 command/action-module stack을
|
||||
* 실행하지만 장수의 turnTime과 예약 큐는 진행시키지 않는다.
|
||||
*/
|
||||
export const createImmediateGeneralActionExecutor = async (options: {
|
||||
world: InMemoryTurnWorld;
|
||||
reservedTurns?: InMemoryReservedTurnStore;
|
||||
scenarioMeta?: ScenarioMeta;
|
||||
map?: MapDefinition;
|
||||
commandProfile?: TurnCommandProfile;
|
||||
getAdditionalOccupiedUniqueItemKeys?: () =>
|
||||
Iterable<string | null | undefined> | Promise<Iterable<string | null | undefined>>;
|
||||
}): Promise<ImmediateGeneralActionExecutor> => {
|
||||
const env = buildCommandEnv(options.world.getScenarioConfig(), options.world.getUnitSet());
|
||||
const commandProfile = options.commandProfile ?? DEFAULT_TURN_COMMAND_PROFILE;
|
||||
const { general: definitions } = await buildReservedTurnDefinitions({
|
||||
env,
|
||||
commandProfile,
|
||||
defaultActionKey: DEFAULT_ACTION,
|
||||
});
|
||||
const generalModuleLoader = new GeneralTurnCommandLoader();
|
||||
const contextBuilders = new Map<string, ActionContextBuilder>();
|
||||
for (const actionKey of ['che_거병', 'che_접경귀환'] as const) {
|
||||
if (!definitions.has(actionKey)) {
|
||||
continue;
|
||||
}
|
||||
const module = await generalModuleLoader.load(actionKey);
|
||||
contextBuilders.set(actionKey, module.actionContextBuilder ?? defaultActionContextBuilder);
|
||||
}
|
||||
|
||||
const itemRegistry = createItemModuleRegistry(await loadItemModules([...ITEM_KEYS]));
|
||||
const uniqueConfig = resolveUniqueConfig(asRecord(options.world.getScenarioConfig().const));
|
||||
if (Object.keys(uniqueConfig.allItems).length === 0) {
|
||||
uniqueConfig.allItems = buildLegacyDefaultUniqueItemPool(itemRegistry);
|
||||
}
|
||||
|
||||
return {
|
||||
async execute(input) {
|
||||
const definition = definitions.get(input.actionKey);
|
||||
if (!definition) {
|
||||
return {
|
||||
ok: false,
|
||||
reason:
|
||||
input.actionKey === 'che_거병'
|
||||
? '거병할 수 없는 모드입니다.'
|
||||
: '접경귀환을 사용할 수 없는 모드입니다.',
|
||||
};
|
||||
}
|
||||
|
||||
const general = options.world.getGeneralById(input.generalId);
|
||||
if (!general) {
|
||||
return { ok: false, reason: '장수 정보를 찾을 수 없습니다.' };
|
||||
}
|
||||
const city = options.world.getCityById(general.cityId) ?? undefined;
|
||||
const nation = general.nationId > 0 ? options.world.getNationById(general.nationId) : null;
|
||||
const args = definition.parseArgs({});
|
||||
if (args === null) {
|
||||
return { ok: false, reason: '인자가 올바르지 않습니다.' };
|
||||
}
|
||||
|
||||
const state = options.world.getState();
|
||||
const constraintEnv = {
|
||||
...resolveConstraintEnv(state, options.scenarioMeta, env),
|
||||
...(options.map ? { map: options.map } : {}),
|
||||
...(options.world.getUnitSet() ? { unitSet: options.world.getUnitSet() } : {}),
|
||||
cities: options.world.listCities(),
|
||||
nations: options.world.listNations(),
|
||||
};
|
||||
const constraintArgs = withCanonicalArgumentAliases(extractArgsRecord(args));
|
||||
const constraintCtx = buildConstraintContext(general, city, nation, constraintArgs, constraintEnv);
|
||||
const view = new WorldStateView(options.world, constraintEnv, constraintArgs, {
|
||||
general,
|
||||
city,
|
||||
nation,
|
||||
});
|
||||
const constraintResult = evaluateConstraints(
|
||||
definition.buildConstraints(constraintCtx, args),
|
||||
constraintCtx,
|
||||
view
|
||||
);
|
||||
if (constraintResult.kind !== 'allow') {
|
||||
const reason =
|
||||
constraintResult.kind === 'deny' ? constraintResult.reason : '조건을 확인할 수 없습니다.';
|
||||
const failureText =
|
||||
definition.formatConstraintFailure?.(reason, constraintCtx, args, view) ??
|
||||
`${reason} ${definition.name} 실패.`;
|
||||
if (input.actionKey === 'che_접경귀환') {
|
||||
options.world.pushLog({
|
||||
...createActionLog(failureText),
|
||||
generalId: general.id,
|
||||
});
|
||||
}
|
||||
return { ok: false, reason: failureText };
|
||||
}
|
||||
|
||||
if (input.actionKey === 'che_거병' && !options.reservedTurns) {
|
||||
throw new Error('Immediate uprising requires the reserved-turn store.');
|
||||
}
|
||||
|
||||
const additionalOccupiedUniqueItemKeys = (await options.getAdditionalOccupiedUniqueItemKeys?.()) ?? [];
|
||||
const seedBase = buildSeedBase(state);
|
||||
const uniqueLottery = buildUniqueLotteryRunner({
|
||||
world: state,
|
||||
worldView: options.world,
|
||||
scenarioMeta: options.scenarioMeta,
|
||||
seedBase,
|
||||
itemRegistry,
|
||||
uniqueConfig,
|
||||
getAdditionalOccupiedUniqueItemKeys: () => additionalOccupiedUniqueItemKeys,
|
||||
});
|
||||
const startYear = resolveStartYear(state, options.scenarioMeta);
|
||||
const baseContext: ActionContextBase = {
|
||||
general,
|
||||
city,
|
||||
nation,
|
||||
worldView: {
|
||||
listGenerals: () => options.world.listGenerals(),
|
||||
listGeneralsByCity: (cityId) =>
|
||||
options.world.listGenerals().filter((candidate) => candidate.cityId === cityId),
|
||||
listNations: () => options.world.listNations(),
|
||||
},
|
||||
rng: input.rng,
|
||||
time: {
|
||||
year: state.currentYear,
|
||||
month: state.currentMonth,
|
||||
startYear,
|
||||
},
|
||||
uniqueLottery,
|
||||
};
|
||||
const actionContext =
|
||||
buildActionContext(
|
||||
input.actionKey,
|
||||
baseContext,
|
||||
{
|
||||
world: state,
|
||||
scenarioConfig: options.world.getScenarioConfig(),
|
||||
scenarioMeta: options.scenarioMeta,
|
||||
map: options.map,
|
||||
unitSet: options.world.getUnitSet(),
|
||||
worldRef: options.world,
|
||||
actionArgs: constraintArgs,
|
||||
createGeneralId: () => options.world.getNextGeneralId(),
|
||||
createNationId: () => options.world.getNextNationId(),
|
||||
seedBase,
|
||||
},
|
||||
contextBuilders
|
||||
) ?? baseContext;
|
||||
|
||||
const resolution = resolveGeneralAction(
|
||||
definition,
|
||||
actionContext,
|
||||
{
|
||||
now: general.turnTime,
|
||||
schedule: {
|
||||
entries: [
|
||||
{
|
||||
startMinute: 0,
|
||||
tickMinutes: Math.max(1, Math.floor(state.tickSeconds / 60)),
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
args
|
||||
);
|
||||
|
||||
if (input.actionKey === 'che_접경귀환' && (resolution.general as TurnGeneral).cityId === general.cityId) {
|
||||
for (const log of resolution.logs) {
|
||||
options.world.pushLog(log);
|
||||
}
|
||||
return { ok: false, reason: '가까운 아국 도시가 없습니다.' };
|
||||
}
|
||||
|
||||
const progressionLogs: LogEntryDraft[] = [];
|
||||
let nextGeneral = resolution.general as TurnGeneral;
|
||||
if (input.actionKey === 'che_거병') {
|
||||
const activeActionAmount =
|
||||
(
|
||||
definition as GeneralActionDefinition & {
|
||||
getInheritanceActiveActionAmount?: (context: ActionContextBase, args: unknown) => number;
|
||||
}
|
||||
).getInheritanceActiveActionAmount?.(actionContext, args) ?? 0;
|
||||
const nextMeta = {
|
||||
...nextGeneral.meta,
|
||||
inherit_active_action:
|
||||
readMetaNumber(asRecord(nextGeneral.meta), 'inherit_active_action', 0) + activeActionAmount,
|
||||
...(input.refreshKillturn ? { killturn: readMetaNumber(asRecord(state.meta), 'killturn', 0) } : {}),
|
||||
};
|
||||
nextGeneral = applyLegacyGeneralProgression(
|
||||
{
|
||||
...nextGeneral,
|
||||
meta: nextMeta,
|
||||
lastTurn: {
|
||||
command: definition.name,
|
||||
arg: extractArgsRecord(args),
|
||||
},
|
||||
},
|
||||
general,
|
||||
input.actionKey,
|
||||
env,
|
||||
progressionLogs
|
||||
);
|
||||
}
|
||||
|
||||
for (const createdNation of resolution.created?.nations ?? []) {
|
||||
if (!options.world.addNation(createdNation)) {
|
||||
throw new Error(`Immediate action could not create nation ${createdNation.id}.`);
|
||||
}
|
||||
options.reservedTurns?.ensureNationTurns(createdNation.id, 12);
|
||||
options.reservedTurns?.ensureNationTurns(createdNation.id, 11);
|
||||
}
|
||||
if (resolution.dirty?.city && resolution.city) {
|
||||
options.world.updateCity(resolution.city.id, resolution.city);
|
||||
}
|
||||
if (resolution.dirty?.nation && resolution.nation) {
|
||||
options.world.updateNation(resolution.nation.id, resolution.nation);
|
||||
}
|
||||
for (const patch of resolution.patches?.generals ?? []) {
|
||||
options.world.updateGeneral(patch.id, patch.patch as Partial<TurnGeneral>);
|
||||
}
|
||||
for (const patch of resolution.patches?.cities ?? []) {
|
||||
options.world.updateCity(patch.id, patch.patch);
|
||||
}
|
||||
for (const patch of resolution.patches?.nations ?? []) {
|
||||
options.world.updateNation(patch.id, patch.patch);
|
||||
}
|
||||
for (const effect of resolution.effects) {
|
||||
if (effect.type === 'diplomacy:patch') {
|
||||
options.world.applyDiplomacyPatch({
|
||||
srcNationId: effect.srcNationId,
|
||||
destNationId: effect.destNationId,
|
||||
patch: effect.patch,
|
||||
});
|
||||
} else if (effect.type === 'message:add') {
|
||||
options.world.queueMessage(effect.draft);
|
||||
}
|
||||
}
|
||||
for (const log of [...resolution.logs, ...progressionLogs]) {
|
||||
options.world.pushLog(log);
|
||||
}
|
||||
options.world.updateGeneral(input.generalId, nextGeneral);
|
||||
return { ok: true };
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
@@ -724,6 +724,11 @@ const createTurnDaemonRuntimeWithLease = async (
|
||||
const resolvedControlQueue = options.controlQueue ?? databaseCommandQueue ?? controlQueue;
|
||||
const commandHandler = createTurnDaemonCommandHandler({
|
||||
world,
|
||||
reservedTurns: reservedTurnStoreHandle?.store,
|
||||
scenarioMeta: snapshot.scenarioMeta,
|
||||
map: snapshot.map,
|
||||
commandProfile,
|
||||
getAdditionalOccupiedUniqueItemKeys: () => occupiedAuctionUniqueItemKeys,
|
||||
auctionFinalizer: auctionFinalizer ?? undefined,
|
||||
auctionBidder: auctionBidder ?? undefined,
|
||||
tournamentRewardFinalizer: tournamentRewardFinalizer ?? undefined,
|
||||
|
||||
@@ -23,7 +23,10 @@ import {
|
||||
resolveUniqueConfig,
|
||||
rollUniqueLottery,
|
||||
type ItemModule,
|
||||
type MapDefinition,
|
||||
type ScenarioMeta,
|
||||
type TriggerValue,
|
||||
type TurnCommandProfile,
|
||||
} from '@sammo-ts/logic';
|
||||
import { simpleSerialize } from '@sammo-ts/logic/war/utils.js';
|
||||
import {
|
||||
@@ -33,7 +36,9 @@ import {
|
||||
removeEquippedItem,
|
||||
} from '@sammo-ts/logic/items/index.js';
|
||||
import type { InMemoryTurnWorld } from './inMemoryWorld.js';
|
||||
import type { InMemoryReservedTurnStore } from './reservedTurnStore.js';
|
||||
import type { TurnGeneral } from './types.js';
|
||||
import { createImmediateGeneralActionExecutor, type ImmediateGeneralActionExecutor } from './reservedTurnHandler.js';
|
||||
import { openAuction } from '../auction/opener.js';
|
||||
import {
|
||||
hasScenarioStaticEventHandler,
|
||||
@@ -121,6 +126,7 @@ interface CommandHandlerContext {
|
||||
auctionFinalizer?: AuctionFinalizer;
|
||||
auctionBidder?: AuctionBidder;
|
||||
tournamentRewardFinalizer?: TournamentRewardFinalizer;
|
||||
getImmediateGeneralActionExecutor?: () => Promise<ImmediateGeneralActionExecutor>;
|
||||
}
|
||||
|
||||
const requireCommandDatabase = (ctx: CommandHandlerContext): DatabaseClient => {
|
||||
@@ -150,6 +156,30 @@ const resolveCommandAcceptedAt = async (
|
||||
return event.createdAt;
|
||||
};
|
||||
|
||||
const assertImmediateGeneralActionActor = async (
|
||||
ctx: CommandHandlerContext,
|
||||
command: Extract<TurnDaemonCommand, { type: 'buildNationCandidate' | 'instantRetreat' }>,
|
||||
general: TurnGeneral
|
||||
): Promise<void> => {
|
||||
if (general.userId !== command.userId) {
|
||||
throw new Error(`${command.type} general owner does not match command user.`);
|
||||
}
|
||||
if (!command.requestId) {
|
||||
return;
|
||||
}
|
||||
const db = requireCommandDatabase(ctx);
|
||||
const event = await db.inputEvent.findUnique({
|
||||
where: { requestId: command.requestId },
|
||||
select: { actorUserId: true },
|
||||
});
|
||||
if (!event) {
|
||||
throw new Error(`ENGINE input event ${command.requestId} is missing.`);
|
||||
}
|
||||
if (event.actorUserId !== command.userId) {
|
||||
throw new Error(`ENGINE input event actor does not match ${command.type} user.`);
|
||||
}
|
||||
};
|
||||
|
||||
async function handleJoinCreateGeneral(
|
||||
ctx: CommandHandlerContext,
|
||||
command: Extract<TurnDaemonCommand, { type: 'joinCreateGeneral' }>
|
||||
@@ -990,17 +1020,10 @@ async function handleBuildNationCandidate(
|
||||
type: 'buildNationCandidate',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
reason: '장수 정보를 찾을 수 없습니다.',
|
||||
};
|
||||
}
|
||||
if (general.nationId !== 0) {
|
||||
return {
|
||||
type: 'buildNationCandidate',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
reason: '이미 국가에 소속되어 있습니다.',
|
||||
reason: '장수가 없습니다',
|
||||
};
|
||||
}
|
||||
await assertImmediateGeneralActionActor(ctx, command, general);
|
||||
|
||||
const worldState = world.getState();
|
||||
const opentime = worldState.meta.opentime as string | undefined;
|
||||
@@ -1009,11 +1032,43 @@ async function handleBuildNationCandidate(
|
||||
type: 'buildNationCandidate',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
reason: '가오픈 기간이 아닙니다.',
|
||||
reason: '게임이 시작되었습니다.',
|
||||
};
|
||||
}
|
||||
if (general.nationId !== 0) {
|
||||
return {
|
||||
type: 'buildNationCandidate',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
reason: '이미 국가에 소속되어있습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
return { type: 'buildNationCandidate', ok: true, generalId: command.generalId };
|
||||
if (!ctx.getImmediateGeneralActionExecutor) {
|
||||
throw new Error('Immediate general action runtime is not configured.');
|
||||
}
|
||||
const hiddenSeed = asRecord(worldState.meta).hiddenSeed ?? asRecord(worldState.meta).seed ?? worldState.id;
|
||||
const executor = await ctx.getImmediateGeneralActionExecutor();
|
||||
const execution = await executor.execute({
|
||||
actionKey: 'che_거병',
|
||||
generalId: command.generalId,
|
||||
rng: new RandUtil(
|
||||
new LiteHashDRBG(
|
||||
simpleSerialize(
|
||||
typeof hiddenSeed === 'string' || typeof hiddenSeed === 'number' ? hiddenSeed : String(hiddenSeed),
|
||||
'BuildNationCandidate',
|
||||
command.generalId
|
||||
)
|
||||
)
|
||||
),
|
||||
refreshKillturn: true,
|
||||
});
|
||||
return {
|
||||
type: 'buildNationCandidate',
|
||||
ok: execution.ok,
|
||||
generalId: command.generalId,
|
||||
...(execution.reason ? { reason: execution.reason } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
async function handleInstantRetreat(
|
||||
@@ -1021,16 +1076,6 @@ async function handleInstantRetreat(
|
||||
command: Extract<TurnDaemonCommand, { type: 'instantRetreat' }>
|
||||
): Promise<TurnDaemonCommandResult> {
|
||||
const { world } = ctx;
|
||||
const general = world.getGeneralById(command.generalId);
|
||||
if (!general) {
|
||||
return {
|
||||
type: 'instantRetreat',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
reason: '장수 정보를 찾을 수 없습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
const config = world.getScenarioConfig();
|
||||
const availableInstantAction = config.const.availableInstantAction as Record<string, boolean> | undefined;
|
||||
if (!availableInstantAction?.instantRetreat) {
|
||||
@@ -1038,11 +1083,48 @@ async function handleInstantRetreat(
|
||||
type: 'instantRetreat',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
reason: '즉시 귀환이 허용되지 않는 서버입니다.',
|
||||
reason: '접경귀환을 사용할 수 없는 시나리오입니다.',
|
||||
};
|
||||
}
|
||||
const general = world.getGeneralById(command.generalId);
|
||||
if (!general) {
|
||||
return {
|
||||
type: 'instantRetreat',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
reason: '장수가 없습니다',
|
||||
};
|
||||
}
|
||||
await assertImmediateGeneralActionActor(ctx, command, general);
|
||||
|
||||
return { type: 'instantRetreat', ok: true, generalId: command.generalId };
|
||||
if (!ctx.getImmediateGeneralActionExecutor) {
|
||||
throw new Error('Immediate general action runtime is not configured.');
|
||||
}
|
||||
const state = world.getState();
|
||||
const hiddenSeed = asRecord(state.meta).hiddenSeed ?? asRecord(state.meta).seed ?? state.id;
|
||||
const executor = await ctx.getImmediateGeneralActionExecutor();
|
||||
const execution = await executor.execute({
|
||||
actionKey: 'che_접경귀환',
|
||||
generalId: command.generalId,
|
||||
rng: new RandUtil(
|
||||
new LiteHashDRBG(
|
||||
simpleSerialize(
|
||||
typeof hiddenSeed === 'string' || typeof hiddenSeed === 'number' ? hiddenSeed : String(hiddenSeed),
|
||||
'InstantRetreat',
|
||||
command.generalId,
|
||||
state.currentYear,
|
||||
state.currentMonth,
|
||||
general.cityId
|
||||
)
|
||||
)
|
||||
),
|
||||
});
|
||||
return {
|
||||
type: 'instantRetreat',
|
||||
ok: execution.ok,
|
||||
generalId: command.generalId,
|
||||
...(execution.reason ? { reason: execution.reason } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
async function handleVacation(
|
||||
@@ -1952,15 +2034,45 @@ async function handleVoteReward(
|
||||
|
||||
export const createTurnDaemonCommandHandler = (options: {
|
||||
world: InMemoryTurnWorld;
|
||||
reservedTurns?: InMemoryReservedTurnStore;
|
||||
scenarioMeta?: ScenarioMeta;
|
||||
map?: MapDefinition;
|
||||
commandProfile?: TurnCommandProfile;
|
||||
getAdditionalOccupiedUniqueItemKeys?: () => Iterable<string | null | undefined>;
|
||||
auctionFinalizer?: AuctionFinalizer;
|
||||
auctionBidder?: AuctionBidder;
|
||||
tournamentRewardFinalizer?: TournamentRewardFinalizer;
|
||||
}): TurnDaemonCommandHandler => {
|
||||
let immediateGeneralActionExecutor: Promise<ImmediateGeneralActionExecutor> | null = null;
|
||||
const ctx: CommandHandlerContext = {
|
||||
world: options.world,
|
||||
auctionFinalizer: options.auctionFinalizer,
|
||||
auctionBidder: options.auctionBidder,
|
||||
tournamentRewardFinalizer: options.tournamentRewardFinalizer,
|
||||
getImmediateGeneralActionExecutor: () => {
|
||||
immediateGeneralActionExecutor ??= createImmediateGeneralActionExecutor({
|
||||
world: options.world,
|
||||
reservedTurns: options.reservedTurns,
|
||||
scenarioMeta: options.scenarioMeta,
|
||||
map: options.map,
|
||||
commandProfile: options.commandProfile,
|
||||
getAdditionalOccupiedUniqueItemKeys: async () => {
|
||||
if (ctx.commandDb) {
|
||||
const rows = await ctx.commandDb.auction.findMany({
|
||||
where: {
|
||||
type: 'UNIQUE_ITEM',
|
||||
status: { in: ['OPEN', 'FINALIZING'] },
|
||||
targetCode: { not: null },
|
||||
},
|
||||
select: { targetCode: true },
|
||||
});
|
||||
return rows.map((row) => row.targetCode);
|
||||
}
|
||||
return options.getAdditionalOccupiedUniqueItemKeys?.() ?? [];
|
||||
},
|
||||
});
|
||||
return immediateGeneralActionExecutor;
|
||||
},
|
||||
};
|
||||
|
||||
type HandlerMap = Partial<
|
||||
|
||||
@@ -0,0 +1,596 @@
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
|
||||
import { SystemClock } from '@sammo-ts/common';
|
||||
import { createGamePostgresConnector, type GamePrisma, type GamePrismaClient } from '@sammo-ts/infra';
|
||||
import type { MapDefinition, ScenarioConfig, ScenarioMeta, TurnSchedule } from '@sammo-ts/logic';
|
||||
|
||||
import { DatabaseTurnDaemonCommandQueue } from '../src/lifecycle/databaseCommandQueue.js';
|
||||
import { TurnDaemonLifecycle } from '../src/lifecycle/turnDaemonLifecycle.js';
|
||||
import { createDatabaseTurnHooks } from '../src/turn/databaseHooks.js';
|
||||
import { EngineStateManager } from '../src/turn/engineStateManager.js';
|
||||
import { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js';
|
||||
import { createReservedTurnStore } from '../src/turn/reservedTurnStore.js';
|
||||
import type { TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js';
|
||||
import { createTurnDaemonCommandHandler } from '../src/turn/worldCommandHandler.js';
|
||||
import { loadTurnWorldFromDatabase } from '../src/turn/worldLoader.js';
|
||||
|
||||
const databaseUrl = process.env.IMMEDIATE_ACTION_DATABASE_URL;
|
||||
const integration = describe.skipIf(!databaseUrl);
|
||||
const worldId = 991_731;
|
||||
const generalId = 991_731;
|
||||
const cityId = 991_731;
|
||||
const existingNationId = 991_730;
|
||||
const requestId = 'integration:engine:immediate-action-uprising';
|
||||
const occupiedUniqueItem = 'che_무기_12_칠성검';
|
||||
|
||||
const assertDedicatedDatabase = (rawUrl: string): void => {
|
||||
const schema = new URL(rawUrl).searchParams.get('schema');
|
||||
if (!schema?.endsWith('immediate_action_integration')) {
|
||||
throw new Error(`Refusing to mutate non-dedicated schema: ${schema ?? '(missing)'}`);
|
||||
}
|
||||
};
|
||||
|
||||
const map: MapDefinition = {
|
||||
id: 'immediate-action-integration',
|
||||
name: '즉시 행동 통합',
|
||||
cities: [
|
||||
{
|
||||
id: cityId,
|
||||
name: '낙양',
|
||||
level: 5,
|
||||
region: 1,
|
||||
position: { x: 0, y: 0 },
|
||||
connections: [],
|
||||
max: {
|
||||
population: 100_000,
|
||||
agriculture: 2_000,
|
||||
commerce: 2_000,
|
||||
security: 2_000,
|
||||
defence: 2_000,
|
||||
wall: 2_000,
|
||||
},
|
||||
initial: {
|
||||
population: 10_000,
|
||||
agriculture: 1_000,
|
||||
commerce: 1_000,
|
||||
security: 1_000,
|
||||
defence: 1_000,
|
||||
wall: 1_000,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const scenarioMeta: ScenarioMeta = {
|
||||
title: '즉시 행동 통합',
|
||||
startYear: 180,
|
||||
life: null,
|
||||
fiction: null,
|
||||
history: [],
|
||||
ignoreDefaultEvents: false,
|
||||
};
|
||||
|
||||
const scenarioConfig: ScenarioConfig = {
|
||||
stat: { total: 300, min: 10, max: 100, npcTotal: 150, npcMax: 50, npcMin: 10, chiefMin: 65 },
|
||||
iconPath: '',
|
||||
map: {},
|
||||
const: {
|
||||
openingPartYear: 3,
|
||||
baseRice: 2_000,
|
||||
allItems: {
|
||||
weapon: {
|
||||
[occupiedUniqueItem]: 1,
|
||||
},
|
||||
},
|
||||
maxUniqueItemLimit: [[-1, 1]],
|
||||
minMonthToAllowInheritItem: 0,
|
||||
},
|
||||
environment: {
|
||||
mapName: 'che',
|
||||
unitSet: 'che',
|
||||
},
|
||||
};
|
||||
|
||||
const state: TurnWorldState = {
|
||||
id: worldId,
|
||||
currentYear: 180,
|
||||
currentMonth: 1,
|
||||
tickSeconds: 600,
|
||||
lastTurnTime: new Date('2026-07-31T00:00:00.000Z'),
|
||||
meta: {
|
||||
hiddenSeed: 'immediate-action-integration',
|
||||
killturn: 24,
|
||||
opentime: '2026-08-01T00:00:00.000Z',
|
||||
scenarioId: 1000,
|
||||
},
|
||||
};
|
||||
|
||||
const general: TurnGeneral = {
|
||||
id: generalId,
|
||||
userId: 'immediate-action-user',
|
||||
name: '통합장수',
|
||||
nationId: 0,
|
||||
cityId,
|
||||
troopId: 0,
|
||||
stats: { leadership: 70, strength: 60, intelligence: 50 },
|
||||
turnTime: new Date('2026-07-31T00:10:00.000Z'),
|
||||
recentWarTime: null,
|
||||
role: {
|
||||
items: { horse: null, weapon: null, book: null, item: null },
|
||||
personality: null,
|
||||
specialDomestic: null,
|
||||
specialWar: null,
|
||||
},
|
||||
triggerState: { flags: {}, counters: {}, modifiers: {}, meta: {} },
|
||||
meta: {
|
||||
killturn: 3,
|
||||
inherit_active_action: 0,
|
||||
inheritRandomUnique: true,
|
||||
leadership_exp: 0,
|
||||
strength_exp: 0,
|
||||
intel_exp: 0,
|
||||
},
|
||||
penalty: {},
|
||||
officerLevel: 0,
|
||||
experience: 0,
|
||||
dedication: 0,
|
||||
injury: 0,
|
||||
gold: 1_000,
|
||||
rice: 1_000,
|
||||
crew: 0,
|
||||
crewTypeId: 0,
|
||||
train: 0,
|
||||
atmos: 0,
|
||||
age: 20,
|
||||
npcState: 0,
|
||||
};
|
||||
|
||||
integration('immediate general action persistence', () => {
|
||||
let db: GamePrismaClient;
|
||||
let disconnect: (() => Promise<void>) | undefined;
|
||||
|
||||
beforeAll(async () => {
|
||||
assertDedicatedDatabase(databaseUrl!);
|
||||
const connector = createGamePostgresConnector({ url: databaseUrl! });
|
||||
await connector.connect();
|
||||
db = connector.prisma;
|
||||
disconnect = () => connector.disconnect();
|
||||
|
||||
await db.inputEvent.deleteMany({ where: { requestId } });
|
||||
await db.auction.deleteMany({ where: { targetCode: occupiedUniqueItem } });
|
||||
await db.logEntry.deleteMany({
|
||||
where: {
|
||||
OR: [{ generalId }, { nationId: { gte: existingNationId } }, { text: { contains: general.name } }],
|
||||
},
|
||||
});
|
||||
await db.nationTurn.deleteMany({ where: { nationId: { gte: existingNationId } } });
|
||||
await db.diplomacy.deleteMany({
|
||||
where: {
|
||||
OR: [{ srcNationId: { gte: existingNationId } }, { destNationId: { gte: existingNationId } }],
|
||||
},
|
||||
});
|
||||
await db.general.deleteMany({ where: { id: generalId } });
|
||||
await db.city.deleteMany({ where: { id: cityId } });
|
||||
await db.nation.deleteMany({ where: { id: { gte: existingNationId } } });
|
||||
await db.worldState.deleteMany({ where: { id: worldId } });
|
||||
|
||||
await db.worldState.create({
|
||||
data: {
|
||||
id: worldId,
|
||||
scenarioCode: 'immediate-action-integration',
|
||||
currentYear: state.currentYear,
|
||||
currentMonth: state.currentMonth,
|
||||
tickSeconds: state.tickSeconds,
|
||||
config: JSON.parse(JSON.stringify(scenarioConfig)) as GamePrisma.InputJsonValue,
|
||||
meta: state.meta as GamePrisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
await db.nation.create({
|
||||
data: {
|
||||
id: existingNationId,
|
||||
name: general.name,
|
||||
color: '#111111',
|
||||
capitalCityId: 0,
|
||||
chiefGeneralId: 0,
|
||||
gold: 0,
|
||||
rice: 0,
|
||||
tech: 0,
|
||||
level: 1,
|
||||
typeCode: 'che_중립',
|
||||
meta: {},
|
||||
},
|
||||
});
|
||||
await db.city.create({
|
||||
data: {
|
||||
id: cityId,
|
||||
name: '낙양',
|
||||
level: 5,
|
||||
nationId: 0,
|
||||
supplyState: 1,
|
||||
frontState: 0,
|
||||
population: 10_000,
|
||||
populationMax: 100_000,
|
||||
agriculture: 1_000,
|
||||
agricultureMax: 2_000,
|
||||
commerce: 1_000,
|
||||
commerceMax: 2_000,
|
||||
security: 1_000,
|
||||
securityMax: 2_000,
|
||||
defence: 1_000,
|
||||
defenceMax: 2_000,
|
||||
wall: 1_000,
|
||||
wallMax: 2_000,
|
||||
region: 1,
|
||||
},
|
||||
});
|
||||
await db.general.create({
|
||||
data: {
|
||||
id: general.id,
|
||||
userId: general.userId,
|
||||
name: general.name,
|
||||
nationId: general.nationId,
|
||||
cityId: general.cityId,
|
||||
troopId: general.troopId,
|
||||
npcState: general.npcState,
|
||||
leadership: general.stats.leadership,
|
||||
strength: general.stats.strength,
|
||||
intel: general.stats.intelligence,
|
||||
officerLevel: general.officerLevel,
|
||||
experience: general.experience,
|
||||
dedication: general.dedication,
|
||||
gold: general.gold,
|
||||
rice: general.rice,
|
||||
crew: general.crew,
|
||||
crewTypeId: general.crewTypeId,
|
||||
train: general.train,
|
||||
atmos: general.atmos,
|
||||
turnTime: general.turnTime,
|
||||
age: general.age,
|
||||
meta: general.meta as GamePrisma.InputJsonValue,
|
||||
penalty: general.penalty as GamePrisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
if (!db) {
|
||||
await disconnect?.();
|
||||
return;
|
||||
}
|
||||
await db.inputEvent.deleteMany({ where: { requestId } });
|
||||
await db.auction.deleteMany({ where: { targetCode: occupiedUniqueItem } });
|
||||
await db.logEntry.deleteMany({
|
||||
where: {
|
||||
OR: [{ generalId }, { nationId: { gte: existingNationId } }, { text: { contains: general.name } }],
|
||||
},
|
||||
});
|
||||
await db.nationTurn.deleteMany({ where: { nationId: { gte: existingNationId } } });
|
||||
await db.diplomacy.deleteMany({
|
||||
where: {
|
||||
OR: [{ srcNationId: { gte: existingNationId } }, { destNationId: { gte: existingNationId } }],
|
||||
},
|
||||
});
|
||||
await db.general.deleteMany({ where: { id: generalId } });
|
||||
await db.city.deleteMany({ where: { id: cityId } });
|
||||
await db.nation.deleteMany({ where: { id: { gte: existingNationId } } });
|
||||
await db.worldState.deleteMany({ where: { id: worldId } });
|
||||
await disconnect?.();
|
||||
});
|
||||
|
||||
it('flushes and reloads the nation, diplomacy, officer turns, logs, and general state together', async () => {
|
||||
const snapshot: TurnWorldSnapshot = {
|
||||
generals: [general],
|
||||
cities: [
|
||||
{
|
||||
id: cityId,
|
||||
name: '낙양',
|
||||
level: 5,
|
||||
nationId: 0,
|
||||
state: 0,
|
||||
supplyState: 1,
|
||||
frontState: 0,
|
||||
population: 10_000,
|
||||
populationMax: 100_000,
|
||||
agriculture: 1_000,
|
||||
agricultureMax: 2_000,
|
||||
commerce: 1_000,
|
||||
commerceMax: 2_000,
|
||||
security: 1_000,
|
||||
securityMax: 2_000,
|
||||
defence: 1_000,
|
||||
defenceMax: 2_000,
|
||||
wall: 1_000,
|
||||
wallMax: 2_000,
|
||||
meta: {},
|
||||
},
|
||||
],
|
||||
nations: [
|
||||
{
|
||||
id: existingNationId,
|
||||
name: general.name,
|
||||
color: '#111111',
|
||||
capitalCityId: 0,
|
||||
chiefGeneralId: 0,
|
||||
gold: 0,
|
||||
rice: 0,
|
||||
level: 1,
|
||||
typeCode: 'che_중립',
|
||||
power: 0,
|
||||
meta: {},
|
||||
},
|
||||
],
|
||||
troops: [],
|
||||
diplomacy: [],
|
||||
events: [],
|
||||
initialEvents: [],
|
||||
scenarioConfig,
|
||||
scenarioMeta,
|
||||
map,
|
||||
};
|
||||
const schedule: TurnSchedule = { entries: [{ startMinute: 0, tickMinutes: 10 }] };
|
||||
const world = new InMemoryTurnWorld(state, snapshot, { schedule });
|
||||
const reservedTurns = await createReservedTurnStore({ databaseUrl: databaseUrl! });
|
||||
const handler = createTurnDaemonCommandHandler({
|
||||
world,
|
||||
reservedTurns: reservedTurns.store,
|
||||
scenarioMeta,
|
||||
map,
|
||||
});
|
||||
const hooks = await createDatabaseTurnHooks(databaseUrl!, world, {
|
||||
reservedTurns: reservedTurns.store,
|
||||
});
|
||||
await db.auction.createMany({
|
||||
data: (['OPEN', 'FINALIZING'] as const).map((status) => ({
|
||||
type: 'UNIQUE_ITEM' as const,
|
||||
targetCode: occupiedUniqueItem,
|
||||
hostGeneralId: generalId,
|
||||
hostName: general.name,
|
||||
detail: {},
|
||||
status,
|
||||
closeAt: new Date('2026-08-01T00:00:00.000Z'),
|
||||
})),
|
||||
});
|
||||
await db.inputEvent.create({
|
||||
data: {
|
||||
requestId,
|
||||
target: 'ENGINE',
|
||||
eventType: 'buildNationCandidate',
|
||||
actorUserId: general.userId,
|
||||
payload: {
|
||||
type: 'buildNationCandidate',
|
||||
requestId,
|
||||
userId: general.userId,
|
||||
generalId,
|
||||
} as GamePrisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
|
||||
const stateManager = new EngineStateManager();
|
||||
stateManager.register('world', {
|
||||
capture: () => world.captureState(),
|
||||
restore: (captured) => world.restoreState(captured),
|
||||
});
|
||||
stateManager.register('reservedTurns', {
|
||||
capture: () => reservedTurns.store.captureState(),
|
||||
restore: (captured) => reservedTurns.store.restoreState(captured),
|
||||
});
|
||||
const stateStore = {
|
||||
loadLastTurnTime: async () => new Date(state.lastTurnTime),
|
||||
loadNextGeneralTurnTime: async () => null,
|
||||
saveLastTurnTime: async () => {},
|
||||
loadCheckpoint: async () => undefined,
|
||||
saveCheckpoint: async () => {},
|
||||
};
|
||||
const processor = {
|
||||
run: async () => {
|
||||
throw new Error('scheduled turn must not run in the immediate-action integration test');
|
||||
},
|
||||
};
|
||||
const buildLifecycle = (
|
||||
queue: DatabaseTurnDaemonCommandQueue,
|
||||
lifecycleHooks: ConstructorParameters<typeof TurnDaemonLifecycle>[0]['hooks']
|
||||
) =>
|
||||
new TurnDaemonLifecycle(
|
||||
{
|
||||
clock: new SystemClock(),
|
||||
controlQueue: queue,
|
||||
commandResponder: queue,
|
||||
getNextTickTime: () => new Date(Date.now() + 3_600_000),
|
||||
stateStore,
|
||||
processor,
|
||||
commandHandler: handler,
|
||||
hooks: lifecycleHooks,
|
||||
stateManager,
|
||||
},
|
||||
{
|
||||
profile: 'immediate-action-integration',
|
||||
defaultBudget: { budgetMs: 100, maxGenerals: 1, catchUpCap: 1 },
|
||||
}
|
||||
);
|
||||
const waitForEvent = async (status: 'PENDING' | 'SUCCEEDED') => {
|
||||
for (let attempt = 0; attempt < 200; attempt += 1) {
|
||||
const event = await db.inputEvent.findUnique({ where: { requestId } });
|
||||
if (event?.status === status && (status !== 'SUCCEEDED' || event.lockedBy === null)) {
|
||||
return event;
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 25));
|
||||
}
|
||||
throw new Error(`Timed out waiting for ${requestId} to become ${status}.`);
|
||||
};
|
||||
|
||||
try {
|
||||
const firstQueue = new DatabaseTurnDaemonCommandQueue(db);
|
||||
await firstQueue.initialize();
|
||||
let observeInjectedFailure: (() => void) | undefined;
|
||||
const injectedFailureObserved = new Promise<void>((resolve) => {
|
||||
observeInjectedFailure = resolve;
|
||||
});
|
||||
const firstLifecycle = buildLifecycle(firstQueue, {
|
||||
...hooks.hooks,
|
||||
executeCommand: async (_failedRequestId, execute) =>
|
||||
db.$transaction(async (transaction) => {
|
||||
await execute({ db: transaction });
|
||||
throw new Error('injected immediate-action commit failure');
|
||||
}),
|
||||
onRunError: async () => {
|
||||
observeInjectedFailure?.();
|
||||
},
|
||||
});
|
||||
const firstLoop = firstLifecycle.start();
|
||||
await injectedFailureObserved;
|
||||
await firstLifecycle.stop('injected failure observed');
|
||||
await firstLoop;
|
||||
|
||||
await expect(waitForEvent('PENDING')).resolves.toMatchObject({
|
||||
attempts: 1,
|
||||
error: 'injected immediate-action commit failure',
|
||||
});
|
||||
expect(world.getGeneralById(generalId)).toMatchObject({
|
||||
nationId: 0,
|
||||
officerLevel: 0,
|
||||
role: { items: { weapon: null } },
|
||||
});
|
||||
expect(world.listNations().map((nation) => nation.id)).toEqual([existingNationId]);
|
||||
expect(reservedTurns.store.peekDirtyState()).toEqual({
|
||||
generalIds: [],
|
||||
generalInitializationIds: [],
|
||||
generalLeaseIds: [],
|
||||
nationKeys: [],
|
||||
nationInitializationKeys: [],
|
||||
nationLeaseKeys: [],
|
||||
});
|
||||
await expect(db.nation.findUnique({ where: { id: existingNationId + 1 } })).resolves.toBeNull();
|
||||
await expect(db.general.findUniqueOrThrow({ where: { id: generalId } })).resolves.toMatchObject({
|
||||
nationId: 0,
|
||||
officerLevel: 0,
|
||||
});
|
||||
|
||||
const retryQueue = new DatabaseTurnDaemonCommandQueue(db);
|
||||
await retryQueue.initialize();
|
||||
const retryLifecycle = buildLifecycle(retryQueue, hooks.hooks);
|
||||
const retryLoop = retryLifecycle.start();
|
||||
await expect(waitForEvent('SUCCEEDED')).resolves.toMatchObject({
|
||||
attempts: 2,
|
||||
actorUserId: general.userId,
|
||||
result: expect.objectContaining({
|
||||
type: 'buildNationCandidate',
|
||||
ok: true,
|
||||
generalId,
|
||||
}),
|
||||
});
|
||||
await retryLifecycle.stop('retry committed');
|
||||
await retryLoop;
|
||||
} finally {
|
||||
await hooks.close();
|
||||
await reservedTurns.close();
|
||||
}
|
||||
|
||||
const persistedGeneral = await db.general.findUniqueOrThrow({ where: { id: generalId } });
|
||||
expect(persistedGeneral).toMatchObject({
|
||||
nationId: existingNationId + 1,
|
||||
officerLevel: 12,
|
||||
experience: 100,
|
||||
dedication: 100,
|
||||
turnTime: general.turnTime,
|
||||
lastTurn: { command: '거병', arg: {} },
|
||||
weaponCode: 'None',
|
||||
meta: expect.objectContaining({
|
||||
inherit_active_action: 1,
|
||||
killturn: 24,
|
||||
belong: 1,
|
||||
officer_city: 0,
|
||||
}),
|
||||
});
|
||||
await expect(db.nation.findUniqueOrThrow({ where: { id: existingNationId + 1 } })).resolves.toMatchObject({
|
||||
name: `㉥${general.name}`,
|
||||
chiefGeneralId: generalId,
|
||||
rice: 2_000,
|
||||
meta: expect.objectContaining({ gennum: 1, secretlimit: 1 }),
|
||||
});
|
||||
await expect(
|
||||
db.diplomacy.findMany({
|
||||
where: {
|
||||
OR: [{ srcNationId: existingNationId + 1 }, { destNationId: existingNationId + 1 }],
|
||||
},
|
||||
})
|
||||
).resolves.toHaveLength(2);
|
||||
for (const officerLevel of [11, 12]) {
|
||||
await expect(
|
||||
db.nationTurn.findMany({
|
||||
where: {
|
||||
nationId: existingNationId + 1,
|
||||
officerLevel,
|
||||
},
|
||||
orderBy: { turnIdx: 'asc' },
|
||||
})
|
||||
).resolves.toEqual(
|
||||
Array.from({ length: 12 }, (_, turnIdx) =>
|
||||
expect.objectContaining({
|
||||
officerLevel,
|
||||
turnIdx,
|
||||
actionCode: '휴식',
|
||||
arg: {},
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
await expect(
|
||||
db.logEntry.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ scope: 'GENERAL', category: 'ACTION', generalId },
|
||||
{ scope: 'GENERAL', category: 'HISTORY', generalId },
|
||||
{ scope: 'NATION', category: 'HISTORY', nationId: existingNationId + 1 },
|
||||
{ scope: 'SYSTEM', category: 'SUMMARY' },
|
||||
{ scope: 'SYSTEM', category: 'HISTORY' },
|
||||
],
|
||||
},
|
||||
})
|
||||
).resolves.toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
scope: 'GENERAL',
|
||||
category: 'ACTION',
|
||||
generalId,
|
||||
text: expect.stringContaining('거병에 성공하였습니다. <1>00:10</>'),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
scope: 'GENERAL',
|
||||
category: 'HISTORY',
|
||||
generalId,
|
||||
text: expect.stringContaining('낙양'),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
scope: 'NATION',
|
||||
category: 'HISTORY',
|
||||
nationId: existingNationId + 1,
|
||||
text: expect.stringContaining('통합장수'),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
scope: 'SYSTEM',
|
||||
category: 'SUMMARY',
|
||||
text: expect.stringContaining('거병하였습니다'),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
scope: 'SYSTEM',
|
||||
category: 'HISTORY',
|
||||
text: expect.stringContaining('【거병】'),
|
||||
}),
|
||||
])
|
||||
);
|
||||
|
||||
const reloaded = await loadTurnWorldFromDatabase({ databaseUrl: databaseUrl! });
|
||||
expect(reloaded.snapshot.generals.find((entry) => entry.id === generalId)).toMatchObject({
|
||||
nationId: existingNationId + 1,
|
||||
officerLevel: 12,
|
||||
experience: 100,
|
||||
dedication: 100,
|
||||
turnTime: general.turnTime,
|
||||
});
|
||||
expect(reloaded.snapshot.nations.find((entry) => entry.id === existingNationId + 1)).toMatchObject({
|
||||
name: `㉥${general.name}`,
|
||||
chiefGeneralId: generalId,
|
||||
rice: 2_000,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,13 +1,42 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import type { ScenarioEffectKey, TurnSchedule } from '@sammo-ts/logic';
|
||||
import { LiteHashDRBG, RandUtil } from '@sammo-ts/common';
|
||||
import type { MapDefinition, ScenarioEffectKey, TurnSchedule } from '@sammo-ts/logic';
|
||||
import { simpleSerialize } from '@sammo-ts/logic/war/utils.js';
|
||||
|
||||
import { InMemoryTurnWorld } from '../src/turn/inMemoryWorld.js';
|
||||
import type { InMemoryReservedTurnStore } from '../src/turn/reservedTurnStore.js';
|
||||
import { createImmediateGeneralActionExecutor } from '../src/turn/reservedTurnHandler.js';
|
||||
import type { TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js';
|
||||
import { createTurnDaemonCommandHandler } from '../src/turn/worldCommandHandler.js';
|
||||
|
||||
const schedule: TurnSchedule = { entries: [{ startMinute: 0, tickMinutes: 10 }] };
|
||||
|
||||
const buildMapCity = (id: number, connections: number[]): MapDefinition['cities'][number] => ({
|
||||
id,
|
||||
name: `도시${id}`,
|
||||
level: 1,
|
||||
region: 1,
|
||||
position: { x: id, y: id },
|
||||
connections,
|
||||
max: {
|
||||
population: 100_000,
|
||||
agriculture: 1_000,
|
||||
commerce: 1_000,
|
||||
security: 1_000,
|
||||
defence: 1_000,
|
||||
wall: 1_000,
|
||||
},
|
||||
initial: {
|
||||
population: 10_000,
|
||||
agriculture: 100,
|
||||
commerce: 100,
|
||||
security: 100,
|
||||
defence: 100,
|
||||
wall: 100,
|
||||
},
|
||||
});
|
||||
|
||||
const buildGeneral = (overrides: Partial<TurnGeneral> = {}): TurnGeneral => ({
|
||||
id: 7,
|
||||
userId: 'user-7',
|
||||
@@ -102,6 +131,76 @@ const buildWorld = (
|
||||
return { world, handler: createTurnDaemonCommandHandler({ world }) };
|
||||
};
|
||||
|
||||
const buildImmediateActionWorld = (options: {
|
||||
general: TurnGeneral;
|
||||
cities: TurnWorldSnapshot['cities'];
|
||||
nations: TurnWorldSnapshot['nations'];
|
||||
map: MapDefinition;
|
||||
availableInstantRetreat?: boolean;
|
||||
lastTurnTime?: Date;
|
||||
scenarioConst?: Record<string, unknown>;
|
||||
}) => {
|
||||
const state: TurnWorldState = {
|
||||
id: 1,
|
||||
currentYear: 180,
|
||||
currentMonth: 1,
|
||||
tickSeconds: 600,
|
||||
lastTurnTime: options.lastTurnTime ?? new Date('0180-01-01T00:00:00Z'),
|
||||
meta: {
|
||||
hiddenSeed: 'immediate-action-test',
|
||||
killturn: 24,
|
||||
opentime: '0180-02-01T00:00:00.000Z',
|
||||
scenarioId: 1000,
|
||||
},
|
||||
};
|
||||
const scenarioMeta = {
|
||||
title: '즉시 행동 테스트',
|
||||
startYear: 180,
|
||||
life: null,
|
||||
fiction: null,
|
||||
history: [],
|
||||
ignoreDefaultEvents: false,
|
||||
};
|
||||
const snapshot: TurnWorldSnapshot = {
|
||||
generals: [options.general],
|
||||
cities: options.cities,
|
||||
nations: options.nations,
|
||||
troops: [],
|
||||
diplomacy: [],
|
||||
events: [],
|
||||
initialEvents: [],
|
||||
scenarioConfig: {
|
||||
stat: { total: 300, min: 10, max: 100, npcTotal: 150, npcMax: 50, npcMin: 10, chiefMin: 65 },
|
||||
iconPath: '',
|
||||
map: {},
|
||||
const: {
|
||||
openingPartYear: 3,
|
||||
baseRice: 2_000,
|
||||
availableInstantAction: {
|
||||
instantRetreat: options.availableInstantRetreat ?? false,
|
||||
},
|
||||
...(options.scenarioConst ?? {}),
|
||||
},
|
||||
environment: {
|
||||
mapName: 'test',
|
||||
unitSet: 'test',
|
||||
},
|
||||
},
|
||||
scenarioMeta,
|
||||
map: options.map,
|
||||
};
|
||||
const world = new InMemoryTurnWorld(state, snapshot, { schedule });
|
||||
const ensureNationTurns = vi.fn();
|
||||
const reservedTurns = { ensureNationTurns } as unknown as InMemoryReservedTurnStore;
|
||||
const handler = createTurnDaemonCommandHandler({
|
||||
world,
|
||||
reservedTurns,
|
||||
scenarioMeta,
|
||||
map: options.map,
|
||||
});
|
||||
return { world, handler, ensureNationTurns, reservedTurns, scenarioMeta };
|
||||
};
|
||||
|
||||
describe('my information world commands', () => {
|
||||
it('normalizes legacy settings and charges myset only when defence mode changes', async () => {
|
||||
const fixture = buildWorld();
|
||||
@@ -183,4 +282,474 @@ describe('my information world commands', () => {
|
||||
).resolves.toMatchObject({ ok: true });
|
||||
expect(fixture.world.getGeneralById(7)?.role.items.horse).toBeNull();
|
||||
});
|
||||
|
||||
it('executes pre-open uprising through the action stack without advancing the turn clock', async () => {
|
||||
const general = buildGeneral({
|
||||
nationId: 0,
|
||||
cityId: 1,
|
||||
turnTime: new Date('0180-01-01T00:10:00Z'),
|
||||
experience: 0,
|
||||
dedication: 0,
|
||||
meta: {
|
||||
killturn: 3,
|
||||
inherit_active_action: 2,
|
||||
leadership_exp: 0,
|
||||
strength_exp: 0,
|
||||
intel_exp: 0,
|
||||
},
|
||||
});
|
||||
const fixture = buildImmediateActionWorld({
|
||||
general,
|
||||
cities: [
|
||||
{
|
||||
id: 1,
|
||||
name: '낙양',
|
||||
nationId: 0,
|
||||
supplyState: 1,
|
||||
meta: {},
|
||||
} as TurnWorldSnapshot['cities'][number],
|
||||
],
|
||||
nations: [
|
||||
{
|
||||
id: 1,
|
||||
name: general.name,
|
||||
color: '#111111',
|
||||
typeCode: 'che_중립',
|
||||
level: 1,
|
||||
capitalCityId: 0,
|
||||
chiefGeneralId: 0,
|
||||
gold: 0,
|
||||
rice: 0,
|
||||
power: 0,
|
||||
meta: {},
|
||||
},
|
||||
],
|
||||
map: {
|
||||
id: 'test',
|
||||
name: 'test',
|
||||
cities: [buildMapCity(1, [])],
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
fixture.handler.handle({
|
||||
type: 'buildNationCandidate',
|
||||
userId: general.userId!,
|
||||
generalId: general.id,
|
||||
})
|
||||
).resolves.toMatchObject({ ok: true });
|
||||
|
||||
const createdNation = fixture.world.listNations().find((nation) => nation.id === 2);
|
||||
expect(createdNation).toMatchObject({
|
||||
name: `㉥${general.name}`,
|
||||
color: '#330000',
|
||||
typeCode: 'che_중립',
|
||||
level: 0,
|
||||
capitalCityId: 0,
|
||||
chiefGeneralId: general.id,
|
||||
gold: 0,
|
||||
rice: 2_000,
|
||||
meta: {
|
||||
rate: 20,
|
||||
bill: 100,
|
||||
strategic_cmd_limit: 12,
|
||||
surlimit: 72,
|
||||
secretlimit: 1,
|
||||
gennum: 1,
|
||||
},
|
||||
});
|
||||
expect(fixture.world.getGeneralById(general.id)).toMatchObject({
|
||||
nationId: 2,
|
||||
officerLevel: 12,
|
||||
experience: 100,
|
||||
dedication: 100,
|
||||
turnTime: general.turnTime,
|
||||
lastTurn: { command: '거병', arg: {} },
|
||||
meta: {
|
||||
belong: 1,
|
||||
officer_city: 0,
|
||||
inherit_active_action: 3,
|
||||
killturn: 24,
|
||||
},
|
||||
});
|
||||
expect(fixture.ensureNationTurns.mock.calls).toEqual([
|
||||
[2, 12],
|
||||
[2, 11],
|
||||
]);
|
||||
expect(fixture.world.getDiplomacyEntry(1, 2)).toMatchObject({ state: 2, term: 0 });
|
||||
expect(fixture.world.getDiplomacyEntry(2, 1)).toMatchObject({ state: 2, term: 0 });
|
||||
const { logs } = fixture.world.consumeDirtyState();
|
||||
expect(logs.map((entry) => entry.text)).toEqual(
|
||||
expect.arrayContaining([
|
||||
'거병에 성공하였습니다. <1>00:10</>',
|
||||
expect.stringContaining('낙양'),
|
||||
expect.stringContaining('세력을 결성하였습니다.'),
|
||||
])
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects a penalized uprising before allocating a nation or writing a log', async () => {
|
||||
const general = buildGeneral({
|
||||
nationId: 0,
|
||||
cityId: 1,
|
||||
penalty: { noFoundNation: true },
|
||||
});
|
||||
const fixture = buildImmediateActionWorld({
|
||||
general,
|
||||
cities: [{ id: 1, name: '낙양', nationId: 0, supplyState: 1, meta: {} }] as TurnWorldSnapshot['cities'],
|
||||
nations: [],
|
||||
map: {
|
||||
id: 'test',
|
||||
name: 'test',
|
||||
cities: [buildMapCity(1, [])],
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
fixture.handler.handle({
|
||||
type: 'buildNationCandidate',
|
||||
userId: general.userId!,
|
||||
generalId: general.id,
|
||||
})
|
||||
).resolves.toMatchObject({ ok: false });
|
||||
expect(fixture.world.listNations()).toEqual([]);
|
||||
expect(fixture.world.getGeneralById(general.id)).toMatchObject({
|
||||
nationId: 0,
|
||||
experience: general.experience,
|
||||
dedication: general.dedication,
|
||||
});
|
||||
expect(fixture.ensureNationTurns).not.toHaveBeenCalled();
|
||||
expect(fixture.world.consumeDirtyState().logs).toEqual([]);
|
||||
});
|
||||
|
||||
it('uses the Ref generic unique seed independently from the immediate-action RNG', async () => {
|
||||
const general = buildGeneral({
|
||||
nationId: 0,
|
||||
cityId: 1,
|
||||
meta: {
|
||||
killturn: 3,
|
||||
inheritRandomUnique: true,
|
||||
leadership_exp: 0,
|
||||
strength_exp: 0,
|
||||
intel_exp: 0,
|
||||
},
|
||||
});
|
||||
const map = {
|
||||
id: 'test',
|
||||
name: 'test',
|
||||
cities: [buildMapCity(1, [])],
|
||||
};
|
||||
const fixture = buildImmediateActionWorld({
|
||||
general,
|
||||
cities: [{ id: 1, name: '낙양', nationId: 0, supplyState: 1, meta: {} }] as TurnWorldSnapshot['cities'],
|
||||
nations: [],
|
||||
map,
|
||||
scenarioConst: {
|
||||
allItems: {
|
||||
weapon: {
|
||||
che_무기_12_칠성검: 1,
|
||||
},
|
||||
},
|
||||
maxUniqueItemLimit: [[-1, 1]],
|
||||
minMonthToAllowInheritItem: 0,
|
||||
},
|
||||
});
|
||||
const actionRng = new RandUtil(new LiteHashDRBG('immediate-action-main-rng'));
|
||||
const nextFloat = vi.spyOn(actionRng, 'nextFloat1');
|
||||
const nextInt = vi.spyOn(actionRng, 'nextInt');
|
||||
const nextIntInclusive = vi.spyOn(actionRng, 'nextIntInclusive');
|
||||
const executor = await createImmediateGeneralActionExecutor({
|
||||
world: fixture.world,
|
||||
reservedTurns: fixture.reservedTurns,
|
||||
scenarioMeta: fixture.scenarioMeta,
|
||||
map,
|
||||
});
|
||||
|
||||
await expect(
|
||||
executor.execute({
|
||||
actionKey: 'che_거병',
|
||||
generalId: general.id,
|
||||
rng: actionRng,
|
||||
refreshKillturn: true,
|
||||
})
|
||||
).resolves.toEqual({ ok: true });
|
||||
expect(fixture.world.getGeneralById(general.id)?.role.items.weapon).toBe('che_무기_12_칠성검');
|
||||
expect(fixture.world.consumeDirtyState().logs.some((entry) => entry.text.includes('【아이템】'))).toBe(true);
|
||||
expect(nextFloat).not.toHaveBeenCalled();
|
||||
expect(nextInt).not.toHaveBeenCalled();
|
||||
expect(nextIntInclusive).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('preserves the Ref uprising precheck order and messages after the game starts', async () => {
|
||||
const general = buildGeneral({ nationId: 1, cityId: 1 });
|
||||
const fixture = buildImmediateActionWorld({
|
||||
general,
|
||||
cities: [{ id: 1, name: '낙양', nationId: 1, supplyState: 1, meta: {} }] as TurnWorldSnapshot['cities'],
|
||||
nations: [],
|
||||
map: {
|
||||
id: 'test',
|
||||
name: 'test',
|
||||
cities: [buildMapCity(1, [])],
|
||||
},
|
||||
lastTurnTime: new Date('0180-03-01T00:00:00.000Z'),
|
||||
});
|
||||
|
||||
await expect(
|
||||
fixture.handler.handle({
|
||||
type: 'buildNationCandidate',
|
||||
userId: general.userId!,
|
||||
generalId: general.id,
|
||||
})
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
reason: '게임이 시작되었습니다.',
|
||||
});
|
||||
});
|
||||
|
||||
it('executes instant retreat with the legacy seed and leaves the reserved turn untouched', async () => {
|
||||
const originalLastTurn = { command: '훈련', arg: { marker: 1 } };
|
||||
const general = buildGeneral({
|
||||
nationId: 1,
|
||||
cityId: 2,
|
||||
turnTime: new Date('0180-01-01T00:10:00Z'),
|
||||
lastTurn: originalLastTurn,
|
||||
});
|
||||
const map = {
|
||||
id: 'test',
|
||||
name: 'test',
|
||||
cities: [buildMapCity(1, [2]), buildMapCity(2, [1])],
|
||||
};
|
||||
const cities = [
|
||||
{ id: 1, name: '낙양', nationId: 1, supplyState: 1, meta: {} },
|
||||
{ id: 2, name: '장안', nationId: 2, supplyState: 1, meta: {} },
|
||||
] as TurnWorldSnapshot['cities'];
|
||||
const nations = [
|
||||
{
|
||||
id: 1,
|
||||
name: '아국',
|
||||
color: '#111111',
|
||||
typeCode: 'che_중립',
|
||||
level: 1,
|
||||
capitalCityId: 1,
|
||||
chiefGeneralId: general.id,
|
||||
gold: 0,
|
||||
rice: 0,
|
||||
power: 0,
|
||||
meta: {},
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: '타국',
|
||||
color: '#222222',
|
||||
typeCode: 'che_중립',
|
||||
level: 1,
|
||||
capitalCityId: 2,
|
||||
chiefGeneralId: 0,
|
||||
gold: 0,
|
||||
rice: 0,
|
||||
power: 0,
|
||||
meta: {},
|
||||
},
|
||||
] as TurnWorldSnapshot['nations'];
|
||||
const fixture = buildImmediateActionWorld({
|
||||
general,
|
||||
cities,
|
||||
nations,
|
||||
map,
|
||||
availableInstantRetreat: true,
|
||||
});
|
||||
|
||||
await expect(
|
||||
fixture.handler.handle({
|
||||
type: 'instantRetreat',
|
||||
userId: general.userId!,
|
||||
generalId: general.id,
|
||||
})
|
||||
).resolves.toMatchObject({
|
||||
ok: true,
|
||||
});
|
||||
expect(fixture.world.getGeneralById(general.id)).toMatchObject({
|
||||
cityId: 1,
|
||||
turnTime: general.turnTime,
|
||||
lastTurn: originalLastTurn,
|
||||
});
|
||||
expect(fixture.world.consumeDirtyState().logs.map((entry) => entry.text)).toContain(
|
||||
'<G><b>낙양</b></>으로 접경귀환했습니다.'
|
||||
);
|
||||
});
|
||||
|
||||
it('chooses equal-distance retreat cities in the Ref map BFS connection order', async () => {
|
||||
const general = buildGeneral({ nationId: 1, cityId: 2 });
|
||||
const map = {
|
||||
id: 'test',
|
||||
name: 'test',
|
||||
cities: [buildMapCity(1, [2]), buildMapCity(2, [3, 1]), buildMapCity(3, [2])],
|
||||
};
|
||||
const fixture = buildImmediateActionWorld({
|
||||
general,
|
||||
cities: [
|
||||
{ id: 1, name: '첫째', nationId: 1, supplyState: 1, meta: {} },
|
||||
{ id: 3, name: '셋째', nationId: 1, supplyState: 1, meta: {} },
|
||||
{ id: 2, name: '출발', nationId: 2, supplyState: 1, meta: {} },
|
||||
] as TurnWorldSnapshot['cities'],
|
||||
nations: [
|
||||
{
|
||||
id: 1,
|
||||
name: '아국',
|
||||
color: '#111111',
|
||||
typeCode: 'che_중립',
|
||||
level: 1,
|
||||
capitalCityId: 1,
|
||||
chiefGeneralId: general.id,
|
||||
gold: 0,
|
||||
rice: 0,
|
||||
power: 0,
|
||||
meta: {},
|
||||
},
|
||||
],
|
||||
map,
|
||||
availableInstantRetreat: true,
|
||||
});
|
||||
const expectedIndex = new RandUtil(
|
||||
new LiteHashDRBG(
|
||||
simpleSerialize('immediate-action-test', 'InstantRetreat', general.id, 180, 1, general.cityId)
|
||||
)
|
||||
).nextIntInclusive(1);
|
||||
|
||||
await expect(
|
||||
fixture.handler.handle({
|
||||
type: 'instantRetreat',
|
||||
userId: general.userId!,
|
||||
generalId: general.id,
|
||||
})
|
||||
).resolves.toMatchObject({ ok: true });
|
||||
expect(fixture.world.getGeneralById(general.id)?.cityId).toBe([3, 1][expectedIndex]);
|
||||
});
|
||||
|
||||
it('rejects an immediate action when the command user does not own the runtime general', async () => {
|
||||
const general = buildGeneral({ nationId: 0, cityId: 1 });
|
||||
const fixture = buildImmediateActionWorld({
|
||||
general,
|
||||
cities: [{ id: 1, name: '낙양', nationId: 0, supplyState: 1, meta: {} }] as TurnWorldSnapshot['cities'],
|
||||
nations: [],
|
||||
map: {
|
||||
id: 'test',
|
||||
name: 'test',
|
||||
cities: [buildMapCity(1, [])],
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
fixture.handler.handle({
|
||||
type: 'buildNationCandidate',
|
||||
userId: 'different-user',
|
||||
generalId: general.id,
|
||||
})
|
||||
).rejects.toThrow('general owner does not match command user');
|
||||
expect(fixture.world.listNations()).toEqual([]);
|
||||
});
|
||||
|
||||
it('attributes an instant-retreat constraint failure to the session general log', async () => {
|
||||
const general = buildGeneral({ nationId: 0, cityId: 1 });
|
||||
const fixture = buildImmediateActionWorld({
|
||||
general,
|
||||
cities: [{ id: 1, name: '낙양', nationId: 0, supplyState: 1, meta: {} }] as TurnWorldSnapshot['cities'],
|
||||
nations: [],
|
||||
map: {
|
||||
id: 'test',
|
||||
name: 'test',
|
||||
cities: [buildMapCity(1, [])],
|
||||
},
|
||||
availableInstantRetreat: true,
|
||||
});
|
||||
|
||||
await expect(
|
||||
fixture.handler.handle({
|
||||
type: 'instantRetreat',
|
||||
userId: general.userId!,
|
||||
generalId: general.id,
|
||||
})
|
||||
).resolves.toMatchObject({ ok: false });
|
||||
expect(fixture.world.consumeDirtyState().logs).toEqual([
|
||||
expect.objectContaining({
|
||||
scope: 'GENERAL',
|
||||
category: 'ACTION',
|
||||
generalId: general.id,
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it('persists the ref failure log when instant retreat has no reachable supplied city', async () => {
|
||||
const general = buildGeneral({ nationId: 1, cityId: 2 });
|
||||
const fixture = buildImmediateActionWorld({
|
||||
general,
|
||||
cities: [
|
||||
{ id: 1, name: '낙양', nationId: 1, supplyState: 0, meta: {} },
|
||||
{ id: 2, name: '장안', nationId: 2, supplyState: 1, meta: {} },
|
||||
] as TurnWorldSnapshot['cities'],
|
||||
nations: [
|
||||
{
|
||||
id: 1,
|
||||
name: '아국',
|
||||
color: '#111111',
|
||||
typeCode: 'che_중립',
|
||||
level: 1,
|
||||
capitalCityId: 1,
|
||||
chiefGeneralId: general.id,
|
||||
gold: 0,
|
||||
rice: 0,
|
||||
power: 0,
|
||||
meta: {},
|
||||
},
|
||||
],
|
||||
map: {
|
||||
id: 'test',
|
||||
name: 'test',
|
||||
cities: [buildMapCity(1, [2]), buildMapCity(2, [1])],
|
||||
},
|
||||
availableInstantRetreat: true,
|
||||
});
|
||||
|
||||
await expect(
|
||||
fixture.handler.handle({
|
||||
type: 'instantRetreat',
|
||||
userId: general.userId!,
|
||||
generalId: general.id,
|
||||
})
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
reason: '가까운 아국 도시가 없습니다.',
|
||||
});
|
||||
expect(fixture.world.getGeneralById(general.id)?.cityId).toBe(2);
|
||||
expect(fixture.world.consumeDirtyState().logs.map((entry) => entry.text)).toContain(
|
||||
'3칸 이내에 아국 도시가 없습니다.'
|
||||
);
|
||||
});
|
||||
|
||||
it('checks the Ref instant-retreat scenario gate before looking up the general', async () => {
|
||||
const general = buildGeneral({ nationId: 1, cityId: 1 });
|
||||
const fixture = buildImmediateActionWorld({
|
||||
general,
|
||||
cities: [{ id: 1, name: '낙양', nationId: 1, supplyState: 1, meta: {} }] as TurnWorldSnapshot['cities'],
|
||||
nations: [],
|
||||
map: {
|
||||
id: 'test',
|
||||
name: 'test',
|
||||
cities: [buildMapCity(1, [])],
|
||||
},
|
||||
availableInstantRetreat: false,
|
||||
});
|
||||
fixture.world.removeGeneral(general.id);
|
||||
|
||||
await expect(
|
||||
fixture.handler.handle({
|
||||
type: 'instantRetreat',
|
||||
userId: general.userId!,
|
||||
generalId: general.id,
|
||||
})
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
reason: '접경귀환을 사용할 수 없는 시나리오입니다.',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user