feat: execute MyPage immediate actions in daemon
This commit is contained in:
@@ -4,7 +4,9 @@ import { z } from 'zod';
|
|||||||
import { LogCategory, LogScope } from '@sammo-ts/infra';
|
import { LogCategory, LogScope } from '@sammo-ts/infra';
|
||||||
import { asRecord } from '@sammo-ts/common';
|
import { asRecord } from '@sammo-ts/common';
|
||||||
|
|
||||||
import { authedProcedure, router } from '../../trpc.js';
|
import type { GameApiContext } from '../../context.js';
|
||||||
|
import { authedProcedure, engineAuthedProcedure, router } from '../../trpc.js';
|
||||||
|
import { ConflictingTurnDaemonCommandError } from '../../daemon/databaseTransport.js';
|
||||||
import { resolveAccessWindows } from '../../services/generalAccess.js';
|
import { resolveAccessWindows } from '../../services/generalAccess.js';
|
||||||
import { getMyGeneral } from '../shared/general.js';
|
import { getMyGeneral } from '../shared/general.js';
|
||||||
import { resolveNationNotice } from '../nation/shared.js';
|
import { resolveNationNotice } from '../nation/shared.js';
|
||||||
@@ -17,8 +19,73 @@ const zGeneralSettings = z.object({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const zGeneralLogType = z.enum(['generalHistory', 'battleDetail', 'battleResult', 'generalAction']);
|
const zGeneralLogType = z.enum(['generalHistory', 'battleDetail', 'battleResult', 'generalAction']);
|
||||||
|
const zImmediateActionInput = z
|
||||||
|
.object({
|
||||||
|
clientRequestId: z.string().uuid().optional(),
|
||||||
|
})
|
||||||
|
.optional();
|
||||||
const MAIN_RECORD_LIMIT = 15;
|
const MAIN_RECORD_LIMIT = 15;
|
||||||
|
|
||||||
|
const resolveImmediateActionRequestId = (
|
||||||
|
contextRequestId: string | undefined,
|
||||||
|
userId: string,
|
||||||
|
clientRequestId: string | undefined,
|
||||||
|
action: 'buildNationCandidate' | 'instantRetreat'
|
||||||
|
): string | undefined => {
|
||||||
|
if (clientRequestId) {
|
||||||
|
return `general:${action}:${userId}:${clientRequestId}`;
|
||||||
|
}
|
||||||
|
return contextRequestId ? `${contextRequestId}:general.${action}` : undefined;
|
||||||
|
};
|
||||||
|
|
||||||
|
const requestImmediateAction = async (
|
||||||
|
ctx: GameApiContext,
|
||||||
|
input: { clientRequestId?: string } | undefined,
|
||||||
|
action: 'buildNationCandidate' | 'instantRetreat'
|
||||||
|
): Promise<{ ok: true }> => {
|
||||||
|
const userId = ctx.auth?.user.id;
|
||||||
|
if (!userId) {
|
||||||
|
throw new TRPCError({ code: 'UNAUTHORIZED' });
|
||||||
|
}
|
||||||
|
const general = await getMyGeneral(ctx);
|
||||||
|
const requestId = resolveImmediateActionRequestId(ctx.requestId, userId, input?.clientRequestId, action);
|
||||||
|
try {
|
||||||
|
const result = await ctx.turnDaemon.requestCommand({
|
||||||
|
type: action,
|
||||||
|
...(requestId ? { requestId } : {}),
|
||||||
|
userId,
|
||||||
|
generalId: general.id,
|
||||||
|
});
|
||||||
|
if (!result) {
|
||||||
|
throw new TRPCError({
|
||||||
|
code: 'TIMEOUT',
|
||||||
|
message: '요청은 접수됐지만 처리 결과를 아직 확인하지 못했습니다. 같은 요청으로 다시 시도해 주세요.',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (result.type !== action) {
|
||||||
|
throw new TRPCError({
|
||||||
|
code: 'INTERNAL_SERVER_ERROR',
|
||||||
|
message: '턴 데몬이 올바르지 않은 즉시 행동 결과를 반환했습니다.',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (!result.ok) {
|
||||||
|
throw new TRPCError({ code: 'BAD_REQUEST', message: result.reason });
|
||||||
|
}
|
||||||
|
return { ok: true };
|
||||||
|
} catch (error) {
|
||||||
|
if (
|
||||||
|
error instanceof ConflictingTurnDaemonCommandError ||
|
||||||
|
(error instanceof Error && error.name === 'ConflictingTurnDaemonCommandError')
|
||||||
|
) {
|
||||||
|
throw new TRPCError({
|
||||||
|
code: 'CONFLICT',
|
||||||
|
message: '이미 접수된 즉시 행동 요청과 입력이 다릅니다. 새 요청 번호로 다시 시도해 주세요.',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const trimRecentRecords = <Entry extends { id: number }>(entries: Entry[], cursor: number): Entry[] => {
|
const trimRecentRecords = <Entry extends { id: number }>(entries: Entry[], cursor: number): Entry[] => {
|
||||||
if (entries.length === 0) {
|
if (entries.length === 0) {
|
||||||
return entries;
|
return entries;
|
||||||
@@ -224,34 +291,12 @@ export const generalRouter = router({
|
|||||||
}
|
}
|
||||||
return { ok: true };
|
return { ok: true };
|
||||||
}),
|
}),
|
||||||
buildNationCandidate: authedProcedure.mutation(async ({ ctx }) => {
|
buildNationCandidate: engineAuthedProcedure
|
||||||
const general = await getMyGeneral(ctx);
|
.input(zImmediateActionInput)
|
||||||
const result = await ctx.turnDaemon.requestCommand({
|
.mutation(({ ctx, input }) => requestImmediateAction(ctx, input, 'buildNationCandidate')),
|
||||||
type: 'buildNationCandidate',
|
instantRetreat: engineAuthedProcedure
|
||||||
generalId: general.id,
|
.input(zImmediateActionInput)
|
||||||
});
|
.mutation(({ ctx, input }) => requestImmediateAction(ctx, input, 'instantRetreat')),
|
||||||
if (!result || result.type !== 'buildNationCandidate') {
|
|
||||||
throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR', message: 'Unexpected response' });
|
|
||||||
}
|
|
||||||
if (!result.ok) {
|
|
||||||
throw new TRPCError({ code: 'BAD_REQUEST', message: result.reason });
|
|
||||||
}
|
|
||||||
return { ok: true };
|
|
||||||
}),
|
|
||||||
instantRetreat: authedProcedure.mutation(async ({ ctx }) => {
|
|
||||||
const general = await getMyGeneral(ctx);
|
|
||||||
const result = await ctx.turnDaemon.requestCommand({
|
|
||||||
type: 'instantRetreat',
|
|
||||||
generalId: general.id,
|
|
||||||
});
|
|
||||||
if (!result || result.type !== 'instantRetreat') {
|
|
||||||
throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR', message: 'Unexpected response' });
|
|
||||||
}
|
|
||||||
if (!result.ok) {
|
|
||||||
throw new TRPCError({ code: 'BAD_REQUEST', message: result.reason });
|
|
||||||
}
|
|
||||||
return { ok: true };
|
|
||||||
}),
|
|
||||||
vacation: authedProcedure.mutation(async ({ ctx }) => {
|
vacation: authedProcedure.mutation(async ({ ctx }) => {
|
||||||
const general = await getMyGeneral(ctx);
|
const general = await getMyGeneral(ctx);
|
||||||
const result = await ctx.turnDaemon.requestCommand({
|
const result = await ctx.turnDaemon.requestCommand({
|
||||||
|
|||||||
@@ -230,6 +230,63 @@ describe('in-game my information ownership', () => {
|
|||||||
})
|
})
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['buildNationCandidate', 'buildNationCandidate'],
|
||||||
|
['instantRetreat', 'instantRetreat'],
|
||||||
|
] as const)('dispatches %s only for the session-owned general', async (procedure, commandType) => {
|
||||||
|
const clientRequestId = '11111111-1111-4111-8111-111111111111';
|
||||||
|
const requestCommand = vi.fn(async () => ({
|
||||||
|
type: commandType,
|
||||||
|
ok: true,
|
||||||
|
generalId: 7,
|
||||||
|
}));
|
||||||
|
const fixture = createContext({ requestCommand });
|
||||||
|
const caller = appRouter.createCaller(fixture.context);
|
||||||
|
|
||||||
|
await expect(caller.general[procedure]({ clientRequestId })).resolves.toEqual({ ok: true });
|
||||||
|
expect(requestCommand).toHaveBeenCalledWith({
|
||||||
|
type: commandType,
|
||||||
|
requestId: `general:${commandType}:user-7:${clientRequestId}`,
|
||||||
|
userId: 'user-7',
|
||||||
|
generalId: 7,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns the daemon compatibility failure without performing an API-side mutation', async () => {
|
||||||
|
const requestCommand = vi.fn(async () => ({
|
||||||
|
type: 'instantRetreat' as const,
|
||||||
|
ok: false,
|
||||||
|
generalId: 7,
|
||||||
|
reason: '가까운 아국 도시가 없습니다.',
|
||||||
|
}));
|
||||||
|
const fixture = createContext({ requestCommand });
|
||||||
|
const caller = appRouter.createCaller(fixture.context);
|
||||||
|
|
||||||
|
await expect(caller.general.instantRetreat()).rejects.toMatchObject({
|
||||||
|
code: 'BAD_REQUEST',
|
||||||
|
message: '가까운 아국 도시가 없습니다.',
|
||||||
|
});
|
||||||
|
expect(fixture.db.general.update).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns a retryable timeout while preserving the client request identity', async () => {
|
||||||
|
const requestCommand = vi.fn(async () => null);
|
||||||
|
const fixture = createContext({ requestCommand });
|
||||||
|
const caller = appRouter.createCaller(fixture.context);
|
||||||
|
const clientRequestId = '22222222-2222-4222-8222-222222222222';
|
||||||
|
|
||||||
|
await expect(caller.general.instantRetreat({ clientRequestId })).rejects.toMatchObject({
|
||||||
|
code: 'TIMEOUT',
|
||||||
|
message: expect.stringContaining('같은 요청으로 다시 시도'),
|
||||||
|
});
|
||||||
|
expect(requestCommand).toHaveBeenCalledWith({
|
||||||
|
type: 'instantRetreat',
|
||||||
|
requestId: `general:instantRetreat:user-7:${clientRequestId}`,
|
||||||
|
userId: 'user-7',
|
||||||
|
generalId: 7,
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('battle-center general and user permissions', () => {
|
describe('battle-center general and user permissions', () => {
|
||||||
|
|||||||
@@ -93,11 +93,13 @@ const zDieOnPrestart = z.object({
|
|||||||
|
|
||||||
const zBuildNationCandidate = z.object({
|
const zBuildNationCandidate = z.object({
|
||||||
type: z.literal('buildNationCandidate'),
|
type: z.literal('buildNationCandidate'),
|
||||||
|
userId: z.string().min(1),
|
||||||
generalId: zFiniteNumber,
|
generalId: zFiniteNumber,
|
||||||
});
|
});
|
||||||
|
|
||||||
const zInstantRetreat = z.object({
|
const zInstantRetreat = z.object({
|
||||||
type: z.literal('instantRetreat'),
|
type: z.literal('instantRetreat'),
|
||||||
|
userId: z.string().min(1),
|
||||||
generalId: zFiniteNumber,
|
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 resolvedControlQueue = options.controlQueue ?? databaseCommandQueue ?? controlQueue;
|
||||||
const commandHandler = createTurnDaemonCommandHandler({
|
const commandHandler = createTurnDaemonCommandHandler({
|
||||||
world,
|
world,
|
||||||
|
reservedTurns: reservedTurnStoreHandle?.store,
|
||||||
|
scenarioMeta: snapshot.scenarioMeta,
|
||||||
|
map: snapshot.map,
|
||||||
|
commandProfile,
|
||||||
|
getAdditionalOccupiedUniqueItemKeys: () => occupiedAuctionUniqueItemKeys,
|
||||||
auctionFinalizer: auctionFinalizer ?? undefined,
|
auctionFinalizer: auctionFinalizer ?? undefined,
|
||||||
auctionBidder: auctionBidder ?? undefined,
|
auctionBidder: auctionBidder ?? undefined,
|
||||||
tournamentRewardFinalizer: tournamentRewardFinalizer ?? undefined,
|
tournamentRewardFinalizer: tournamentRewardFinalizer ?? undefined,
|
||||||
|
|||||||
@@ -23,7 +23,10 @@ import {
|
|||||||
resolveUniqueConfig,
|
resolveUniqueConfig,
|
||||||
rollUniqueLottery,
|
rollUniqueLottery,
|
||||||
type ItemModule,
|
type ItemModule,
|
||||||
|
type MapDefinition,
|
||||||
|
type ScenarioMeta,
|
||||||
type TriggerValue,
|
type TriggerValue,
|
||||||
|
type TurnCommandProfile,
|
||||||
} from '@sammo-ts/logic';
|
} from '@sammo-ts/logic';
|
||||||
import { simpleSerialize } from '@sammo-ts/logic/war/utils.js';
|
import { simpleSerialize } from '@sammo-ts/logic/war/utils.js';
|
||||||
import {
|
import {
|
||||||
@@ -33,7 +36,9 @@ import {
|
|||||||
removeEquippedItem,
|
removeEquippedItem,
|
||||||
} from '@sammo-ts/logic/items/index.js';
|
} from '@sammo-ts/logic/items/index.js';
|
||||||
import type { InMemoryTurnWorld } from './inMemoryWorld.js';
|
import type { InMemoryTurnWorld } from './inMemoryWorld.js';
|
||||||
|
import type { InMemoryReservedTurnStore } from './reservedTurnStore.js';
|
||||||
import type { TurnGeneral } from './types.js';
|
import type { TurnGeneral } from './types.js';
|
||||||
|
import { createImmediateGeneralActionExecutor, type ImmediateGeneralActionExecutor } from './reservedTurnHandler.js';
|
||||||
import { openAuction } from '../auction/opener.js';
|
import { openAuction } from '../auction/opener.js';
|
||||||
import {
|
import {
|
||||||
hasScenarioStaticEventHandler,
|
hasScenarioStaticEventHandler,
|
||||||
@@ -121,6 +126,7 @@ interface CommandHandlerContext {
|
|||||||
auctionFinalizer?: AuctionFinalizer;
|
auctionFinalizer?: AuctionFinalizer;
|
||||||
auctionBidder?: AuctionBidder;
|
auctionBidder?: AuctionBidder;
|
||||||
tournamentRewardFinalizer?: TournamentRewardFinalizer;
|
tournamentRewardFinalizer?: TournamentRewardFinalizer;
|
||||||
|
getImmediateGeneralActionExecutor?: () => Promise<ImmediateGeneralActionExecutor>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const requireCommandDatabase = (ctx: CommandHandlerContext): DatabaseClient => {
|
const requireCommandDatabase = (ctx: CommandHandlerContext): DatabaseClient => {
|
||||||
@@ -150,6 +156,30 @@ const resolveCommandAcceptedAt = async (
|
|||||||
return event.createdAt;
|
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(
|
async function handleJoinCreateGeneral(
|
||||||
ctx: CommandHandlerContext,
|
ctx: CommandHandlerContext,
|
||||||
command: Extract<TurnDaemonCommand, { type: 'joinCreateGeneral' }>
|
command: Extract<TurnDaemonCommand, { type: 'joinCreateGeneral' }>
|
||||||
@@ -990,17 +1020,10 @@ async function handleBuildNationCandidate(
|
|||||||
type: 'buildNationCandidate',
|
type: 'buildNationCandidate',
|
||||||
ok: false,
|
ok: false,
|
||||||
generalId: command.generalId,
|
generalId: command.generalId,
|
||||||
reason: '장수 정보를 찾을 수 없습니다.',
|
reason: '장수가 없습니다',
|
||||||
};
|
|
||||||
}
|
|
||||||
if (general.nationId !== 0) {
|
|
||||||
return {
|
|
||||||
type: 'buildNationCandidate',
|
|
||||||
ok: false,
|
|
||||||
generalId: command.generalId,
|
|
||||||
reason: '이미 국가에 소속되어 있습니다.',
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
await assertImmediateGeneralActionActor(ctx, command, general);
|
||||||
|
|
||||||
const worldState = world.getState();
|
const worldState = world.getState();
|
||||||
const opentime = worldState.meta.opentime as string | undefined;
|
const opentime = worldState.meta.opentime as string | undefined;
|
||||||
@@ -1009,11 +1032,43 @@ async function handleBuildNationCandidate(
|
|||||||
type: 'buildNationCandidate',
|
type: 'buildNationCandidate',
|
||||||
ok: false,
|
ok: false,
|
||||||
generalId: command.generalId,
|
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(
|
async function handleInstantRetreat(
|
||||||
@@ -1021,16 +1076,6 @@ async function handleInstantRetreat(
|
|||||||
command: Extract<TurnDaemonCommand, { type: 'instantRetreat' }>
|
command: Extract<TurnDaemonCommand, { type: 'instantRetreat' }>
|
||||||
): Promise<TurnDaemonCommandResult> {
|
): Promise<TurnDaemonCommandResult> {
|
||||||
const { world } = ctx;
|
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 config = world.getScenarioConfig();
|
||||||
const availableInstantAction = config.const.availableInstantAction as Record<string, boolean> | undefined;
|
const availableInstantAction = config.const.availableInstantAction as Record<string, boolean> | undefined;
|
||||||
if (!availableInstantAction?.instantRetreat) {
|
if (!availableInstantAction?.instantRetreat) {
|
||||||
@@ -1038,11 +1083,48 @@ async function handleInstantRetreat(
|
|||||||
type: 'instantRetreat',
|
type: 'instantRetreat',
|
||||||
ok: false,
|
ok: false,
|
||||||
generalId: command.generalId,
|
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(
|
async function handleVacation(
|
||||||
@@ -1952,15 +2034,45 @@ async function handleVoteReward(
|
|||||||
|
|
||||||
export const createTurnDaemonCommandHandler = (options: {
|
export const createTurnDaemonCommandHandler = (options: {
|
||||||
world: InMemoryTurnWorld;
|
world: InMemoryTurnWorld;
|
||||||
|
reservedTurns?: InMemoryReservedTurnStore;
|
||||||
|
scenarioMeta?: ScenarioMeta;
|
||||||
|
map?: MapDefinition;
|
||||||
|
commandProfile?: TurnCommandProfile;
|
||||||
|
getAdditionalOccupiedUniqueItemKeys?: () => Iterable<string | null | undefined>;
|
||||||
auctionFinalizer?: AuctionFinalizer;
|
auctionFinalizer?: AuctionFinalizer;
|
||||||
auctionBidder?: AuctionBidder;
|
auctionBidder?: AuctionBidder;
|
||||||
tournamentRewardFinalizer?: TournamentRewardFinalizer;
|
tournamentRewardFinalizer?: TournamentRewardFinalizer;
|
||||||
}): TurnDaemonCommandHandler => {
|
}): TurnDaemonCommandHandler => {
|
||||||
|
let immediateGeneralActionExecutor: Promise<ImmediateGeneralActionExecutor> | null = null;
|
||||||
const ctx: CommandHandlerContext = {
|
const ctx: CommandHandlerContext = {
|
||||||
world: options.world,
|
world: options.world,
|
||||||
auctionFinalizer: options.auctionFinalizer,
|
auctionFinalizer: options.auctionFinalizer,
|
||||||
auctionBidder: options.auctionBidder,
|
auctionBidder: options.auctionBidder,
|
||||||
tournamentRewardFinalizer: options.tournamentRewardFinalizer,
|
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<
|
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 { 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 type { TurnGeneral, TurnWorldSnapshot, TurnWorldState } from '../src/turn/types.js';
|
||||||
import { createTurnDaemonCommandHandler } from '../src/turn/worldCommandHandler.js';
|
import { createTurnDaemonCommandHandler } from '../src/turn/worldCommandHandler.js';
|
||||||
|
|
||||||
const schedule: TurnSchedule = { entries: [{ startMinute: 0, tickMinutes: 10 }] };
|
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 => ({
|
const buildGeneral = (overrides: Partial<TurnGeneral> = {}): TurnGeneral => ({
|
||||||
id: 7,
|
id: 7,
|
||||||
userId: 'user-7',
|
userId: 'user-7',
|
||||||
@@ -102,6 +131,76 @@ const buildWorld = (
|
|||||||
return { world, handler: createTurnDaemonCommandHandler({ world }) };
|
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', () => {
|
describe('my information world commands', () => {
|
||||||
it('normalizes legacy settings and charges myset only when defence mode changes', async () => {
|
it('normalizes legacy settings and charges myset only when defence mode changes', async () => {
|
||||||
const fixture = buildWorld();
|
const fixture = buildWorld();
|
||||||
@@ -183,4 +282,474 @@ describe('my information world commands', () => {
|
|||||||
).resolves.toMatchObject({ ok: true });
|
).resolves.toMatchObject({ ok: true });
|
||||||
expect(fixture.world.getGeneralById(7)?.role.items.horse).toBeNull();
|
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: '접경귀환을 사용할 수 없는 시나리오입니다.',
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -23,6 +23,11 @@ type FixtureState = {
|
|||||||
permission: 'head' | 'member';
|
permission: 'head' | 'member';
|
||||||
myset: number;
|
myset: number;
|
||||||
scenarioEffect?: string | null;
|
scenarioEffect?: string | null;
|
||||||
|
instantRetreatEnabled?: boolean;
|
||||||
|
instantRetreatAttempts?: number;
|
||||||
|
instantRetreatInputs?: Array<Record<string, unknown>>;
|
||||||
|
generalMeQueries?: number;
|
||||||
|
generalLogQueries?: number;
|
||||||
settingMutations: Array<Record<string, unknown>>;
|
settingMutations: Array<Record<string, unknown>>;
|
||||||
accessPages: string[];
|
accessPages: string[];
|
||||||
};
|
};
|
||||||
@@ -149,7 +154,10 @@ const install = async (page: Page, state: FixtureState) => {
|
|||||||
payload?.json ?? payload?.input?.json ?? (payload as Record<string, unknown> | undefined) ?? {};
|
payload?.json ?? payload?.input?.json ?? (payload as Record<string, unknown> | undefined) ?? {};
|
||||||
if (operation === 'lobby.info') return response({ myGeneral: { id: 7, name: '검증장수' } });
|
if (operation === 'lobby.info') return response({ myGeneral: { id: 7, name: '검증장수' } });
|
||||||
if (operation === 'join.getConfig') return response({});
|
if (operation === 'join.getConfig') return response({});
|
||||||
if (operation === 'general.me') return response(myGeneral(state));
|
if (operation === 'general.me') {
|
||||||
|
state.generalMeQueries = (state.generalMeQueries ?? 0) + 1;
|
||||||
|
return response(myGeneral(state));
|
||||||
|
}
|
||||||
if (operation === 'world.getState')
|
if (operation === 'world.getState')
|
||||||
return response({
|
return response({
|
||||||
currentYear: 185,
|
currentYear: 185,
|
||||||
@@ -157,7 +165,11 @@ const install = async (page: Page, state: FixtureState) => {
|
|||||||
tickSeconds: 600,
|
tickSeconds: 600,
|
||||||
config: {
|
config: {
|
||||||
npcMode: 0,
|
npcMode: 0,
|
||||||
const: { availableInstantAction: {} },
|
const: {
|
||||||
|
availableInstantAction: {
|
||||||
|
instantRetreat: state.instantRetreatEnabled ?? false,
|
||||||
|
},
|
||||||
|
},
|
||||||
environment: { scenarioEffect: state.scenarioEffect ?? null },
|
environment: { scenarioEffect: state.scenarioEffect ?? null },
|
||||||
},
|
},
|
||||||
meta: {
|
meta: {
|
||||||
@@ -179,8 +191,24 @@ const install = async (page: Page, state: FixtureState) => {
|
|||||||
{ generalId: 7, name: '검증장수', refresh: 240, refreshScoreTotal: 24 },
|
{ generalId: 7, name: '검증장수', refresh: 240, refreshScoreTotal: 24 },
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
if (operation === 'general.getMyLog')
|
if (operation === 'general.getMyLog') {
|
||||||
|
state.generalLogQueries = (state.generalLogQueries ?? 0) + 1;
|
||||||
return response({ type: 'generalAction', logs: [{ id: 1, text: '<Y>기록</>' }] });
|
return response({ type: 'generalAction', logs: [{ id: 1, text: '<Y>기록</>' }] });
|
||||||
|
}
|
||||||
|
if (operation === 'general.instantRetreat') {
|
||||||
|
state.instantRetreatInputs?.push(jsonInput);
|
||||||
|
state.instantRetreatAttempts = (state.instantRetreatAttempts ?? 0) + 1;
|
||||||
|
if (state.instantRetreatAttempts === 1) {
|
||||||
|
return {
|
||||||
|
error: {
|
||||||
|
message: '요청 처리 결과를 확인하지 못했습니다.',
|
||||||
|
code: -32000,
|
||||||
|
data: { code: 'TIMEOUT', httpStatus: 408, path: operation },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return response({ ok: true });
|
||||||
|
}
|
||||||
if (operation === 'general.setMySetting') {
|
if (operation === 'general.setMySetting') {
|
||||||
state.settingMutations.push(jsonInput);
|
state.settingMutations.push(jsonInput);
|
||||||
state.myset = Math.max(0, state.myset - 1);
|
state.myset = Math.max(0, state.myset - 1);
|
||||||
@@ -404,6 +432,54 @@ test('내 정보&설정 keeps the legacy 1000px/500px geometry and saves in plac
|
|||||||
await persistParityArtifact(page, 'core-my-page-mobile', mobile);
|
await persistParityArtifact(page, 'core-my-page-mobile', mobile);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('내 정보 즉시행동은 timeout 재시도 ID를 유지하고 성공 후 새 ID를 만든다', async ({ page }) => {
|
||||||
|
const state: FixtureState = {
|
||||||
|
permission: 'head',
|
||||||
|
myset: 3,
|
||||||
|
instantRetreatEnabled: true,
|
||||||
|
instantRetreatAttempts: 0,
|
||||||
|
instantRetreatInputs: [],
|
||||||
|
generalMeQueries: 0,
|
||||||
|
generalLogQueries: 0,
|
||||||
|
settingMutations: [],
|
||||||
|
accessPages: [],
|
||||||
|
};
|
||||||
|
const dialogs: string[] = [];
|
||||||
|
page.on('dialog', async (dialog) => {
|
||||||
|
dialogs.push(`${dialog.type()}:${dialog.message()}`);
|
||||||
|
await dialog.accept();
|
||||||
|
});
|
||||||
|
await install(page, state);
|
||||||
|
await page.goto('my-page');
|
||||||
|
|
||||||
|
const instantRetreatButton = page.getByRole('button', { name: '접경 귀환' });
|
||||||
|
await expect(instantRetreatButton).toBeVisible();
|
||||||
|
await expect.poll(() => state.generalMeQueries).toBe(1);
|
||||||
|
|
||||||
|
await instantRetreatButton.click();
|
||||||
|
await expect.poll(() => state.instantRetreatInputs?.length).toBe(1);
|
||||||
|
await expect
|
||||||
|
.poll(() => dialogs.some((message) => message.includes('요청 처리 결과를 확인하지 못했습니다.')))
|
||||||
|
.toBe(true);
|
||||||
|
expect(state.generalMeQueries).toBe(1);
|
||||||
|
|
||||||
|
await instantRetreatButton.click();
|
||||||
|
await expect.poll(() => state.instantRetreatInputs?.length).toBe(2);
|
||||||
|
await expect.poll(() => state.generalMeQueries).toBe(2);
|
||||||
|
await expect.poll(() => state.generalLogQueries).toBe(8);
|
||||||
|
await page.evaluate(() => new Promise<void>((resolveFrame) => requestAnimationFrame(() => resolveFrame())));
|
||||||
|
|
||||||
|
await instantRetreatButton.click();
|
||||||
|
await expect.poll(() => state.instantRetreatInputs?.length).toBe(3);
|
||||||
|
|
||||||
|
const requestIds = state.instantRetreatInputs?.map((input) => input.clientRequestId);
|
||||||
|
expect(requestIds?.[0]).toEqual(expect.stringMatching(/^[0-9a-f-]{36}$/i));
|
||||||
|
expect(requestIds?.[1]).toBe(requestIds?.[0]);
|
||||||
|
expect(requestIds?.[2]).toEqual(expect.stringMatching(/^[0-9a-f-]{36}$/i));
|
||||||
|
expect(requestIds?.[2]).not.toBe(requestIds?.[1]);
|
||||||
|
expect(state.instantRetreatInputs?.every((input) => !('generalId' in input))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
test('감찰부 keeps the selector interaction and shows the permission error path', async ({ page }) => {
|
test('감찰부 keeps the selector interaction and shows the permission error path', async ({ page }) => {
|
||||||
const head: FixtureState = { permission: 'head', myset: 3, settingMutations: [], accessPages: [] };
|
const head: FixtureState = { permission: 'head', myset: 3, settingMutations: [], accessPages: [] };
|
||||||
await install(page, head);
|
await install(page, head);
|
||||||
|
|||||||
@@ -37,6 +37,15 @@ const screenMode = ref<ScreenMode>('auto');
|
|||||||
const customCss = ref('');
|
const customCss = ref('');
|
||||||
const cssSaving = ref(false);
|
const cssSaving = ref(false);
|
||||||
let cssTimer: number | null = null;
|
let cssTimer: number | null = null;
|
||||||
|
const immediateActionRequestIds = reactive({
|
||||||
|
buildNationCandidate: crypto.randomUUID(),
|
||||||
|
instantRetreat: crypto.randomUUID(),
|
||||||
|
});
|
||||||
|
|
||||||
|
const resetImmediateActionRequestIds = () => {
|
||||||
|
immediateActionRequestIds.buildNationCandidate = crypto.randomUUID();
|
||||||
|
immediateActionRequestIds.instantRetreat = crypto.randomUUID();
|
||||||
|
};
|
||||||
|
|
||||||
const form = reactive<SettingForm>({
|
const form = reactive<SettingForm>({
|
||||||
tnmt: 1,
|
tnmt: 1,
|
||||||
@@ -181,6 +190,7 @@ const loadPage = async () => {
|
|||||||
Object.assign(form, general.settings);
|
Object.assign(form, general.settings);
|
||||||
}
|
}
|
||||||
await Promise.all(logTypes.map((type) => loadLog(type)));
|
await Promise.all(logTypes.map((type) => loadLog(type)));
|
||||||
|
resetImmediateActionRequestIds();
|
||||||
} catch (cause) {
|
} catch (cause) {
|
||||||
error.value = errorText(cause);
|
error.value = errorText(cause);
|
||||||
} finally {
|
} finally {
|
||||||
@@ -391,7 +401,9 @@ onMounted(() => {
|
|||||||
class="action-button"
|
class="action-button"
|
||||||
@click="
|
@click="
|
||||||
confirmMutation('거병 이후 장수를 삭제할 수 없게됩니다. 거병하시겠습니까?', () =>
|
confirmMutation('거병 이후 장수를 삭제할 수 없게됩니다. 거병하시겠습니까?', () =>
|
||||||
trpc.general.buildNationCandidate.mutate()
|
trpc.general.buildNationCandidate.mutate({
|
||||||
|
clientRequestId: immediateActionRequestIds.buildNationCandidate,
|
||||||
|
})
|
||||||
)
|
)
|
||||||
"
|
"
|
||||||
>
|
>
|
||||||
@@ -403,20 +415,19 @@ onMounted(() => {
|
|||||||
<button
|
<button
|
||||||
class="action-button"
|
class="action-button"
|
||||||
@click="
|
@click="
|
||||||
confirmMutation('아군 접경으로 이동할까요?', () => trpc.general.instantRetreat.mutate())
|
confirmMutation('아군 접경으로 이동할까요?', () =>
|
||||||
|
trpc.general.instantRetreat.mutate({
|
||||||
|
clientRequestId: immediateActionRequestIds.instantRetreat,
|
||||||
|
})
|
||||||
|
)
|
||||||
"
|
"
|
||||||
>
|
>
|
||||||
접경 귀환
|
접경 귀환
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div v-if="actionAvailability.selectOtherGeneral && selectionPoolStatus?.enabled" class="action-line">
|
||||||
v-if="actionAvailability.selectOtherGeneral && selectionPoolStatus?.enabled"
|
|
||||||
class="action-line"
|
|
||||||
>
|
|
||||||
다른 장수 선택
|
다른 장수 선택
|
||||||
<template v-if="formatSelectionAvailableAt">
|
<template v-if="formatSelectionAvailableAt"> ({{ formatSelectionAvailableAt }} 부터) </template>
|
||||||
({{ formatSelectionAvailableAt }} 부터)
|
|
||||||
</template>
|
|
||||||
<br />
|
<br />
|
||||||
<RouterLink class="action-button select-general-link" to="/select-general">
|
<RouterLink class="action-button select-general-link" to="/select-general">
|
||||||
다른 장수 선택
|
다른 장수 선택
|
||||||
|
|||||||
@@ -70,8 +70,8 @@ export type TurnDaemonCommand =
|
|||||||
}
|
}
|
||||||
| { type: 'troopRename'; requestId?: string; generalId: number; troopId: number; troopName: string }
|
| { type: 'troopRename'; requestId?: string; generalId: number; troopId: number; troopName: string }
|
||||||
| { type: 'dieOnPrestart'; requestId?: string; generalId: number }
|
| { type: 'dieOnPrestart'; requestId?: string; generalId: number }
|
||||||
| { type: 'buildNationCandidate'; requestId?: string; generalId: number }
|
| { type: 'buildNationCandidate'; requestId?: string; userId: string; generalId: number }
|
||||||
| { type: 'instantRetreat'; requestId?: string; generalId: number }
|
| { type: 'instantRetreat'; requestId?: string; userId: string; generalId: number }
|
||||||
| { type: 'vacation'; requestId?: string; generalId: number }
|
| { type: 'vacation'; requestId?: string; generalId: number }
|
||||||
| {
|
| {
|
||||||
type: 'setMySetting';
|
type: 'setMySetting';
|
||||||
|
|||||||
@@ -30,6 +30,9 @@ export interface UprisingContext extends ActionContextBase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const ACTION_NAME = '거병';
|
const ACTION_NAME = '거병';
|
||||||
|
const formatHourMinute = (date: Date): string =>
|
||||||
|
`${String(date.getUTCHours()).padStart(2, '0')}:${String(date.getUTCMinutes()).padStart(2, '0')}`;
|
||||||
|
|
||||||
const truncateLegacyWidth = (value: string, maxWidth: number): string => {
|
const truncateLegacyWidth = (value: string, maxWidth: number): string => {
|
||||||
let result = '';
|
let result = '';
|
||||||
let width = 0;
|
let width = 0;
|
||||||
@@ -119,7 +122,7 @@ export class ActionDefinition<
|
|||||||
|
|
||||||
const cityName = context.city?.name ?? '??';
|
const cityName = context.city?.name ?? '??';
|
||||||
|
|
||||||
context.addLog(`거병에 성공하였습니다.`, {
|
context.addLog(`거병에 성공하였습니다. <1>${formatHourMinute(uprisingCtx.general.turnTime)}</>`, {
|
||||||
category: LogCategory.ACTION,
|
category: LogCategory.ACTION,
|
||||||
format: LogFormat.MONTH,
|
format: LogFormat.MONTH,
|
||||||
});
|
});
|
||||||
@@ -128,18 +131,21 @@ export class ActionDefinition<
|
|||||||
category: LogCategory.SUMMARY,
|
category: LogCategory.SUMMARY,
|
||||||
format: LogFormat.MONTH,
|
format: LogFormat.MONTH,
|
||||||
});
|
});
|
||||||
context.addLog(
|
context.addLog(`<Y><b>【거병】</b></><D><b>${general.name}</b></>${josaYi} 세력을 결성하였습니다.`, {
|
||||||
`<Y><b>【거병】</b></><D><b>${general.name}</b></>${josaYi} 세력을 결성하였습니다.`,
|
scope: LogScope.SYSTEM,
|
||||||
{
|
category: LogCategory.HISTORY,
|
||||||
scope: LogScope.SYSTEM,
|
format: LogFormat.YEAR_MONTH,
|
||||||
category: LogCategory.HISTORY,
|
});
|
||||||
format: LogFormat.YEAR_MONTH,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
context.addLog(`<G><b>${cityName}</b></>에서 거병`, {
|
context.addLog(`<G><b>${cityName}</b></>에서 거병`, {
|
||||||
category: LogCategory.HISTORY,
|
category: LogCategory.HISTORY,
|
||||||
format: LogFormat.YEAR_MONTH,
|
format: LogFormat.YEAR_MONTH,
|
||||||
});
|
});
|
||||||
|
context.addLog(`<Y>${general.name}</>${josaYi} <G><b>${cityName}</b></>에서 거병`, {
|
||||||
|
scope: LogScope.NATION,
|
||||||
|
nationId: newNationId,
|
||||||
|
category: LogCategory.HISTORY,
|
||||||
|
format: LogFormat.YEAR_MONTH,
|
||||||
|
});
|
||||||
|
|
||||||
tryApplyUniqueLottery(context, {
|
tryApplyUniqueLottery(context, {
|
||||||
acquireType: '아이템',
|
acquireType: '아이템',
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ import { LogCategory, LogFormat, LogScope } from '@sammo-ts/logic/logging/types.
|
|||||||
import { JosaUtil } from '@sammo-ts/common';
|
import { JosaUtil } from '@sammo-ts/common';
|
||||||
import type { ActionContextBuilder } from '@sammo-ts/logic/actions/turn/actionContext.js';
|
import type { ActionContextBuilder } from '@sammo-ts/logic/actions/turn/actionContext.js';
|
||||||
import type { TurnCommandEnv } from '@sammo-ts/logic/actions/turn/commandEnv.js';
|
import type { TurnCommandEnv } from '@sammo-ts/logic/actions/turn/commandEnv.js';
|
||||||
import { searchDistance } from '@sammo-ts/logic/world/distance.js';
|
|
||||||
import type { MapDefinition } from '@sammo-ts/logic/world/types.js';
|
import type { MapDefinition } from '@sammo-ts/logic/world/types.js';
|
||||||
import type { GeneralTurnCommandSpec } from './index.js';
|
import type { GeneralTurnCommandSpec } from './index.js';
|
||||||
|
|
||||||
@@ -23,9 +22,7 @@ type InclusiveRandomGenerator = GeneralActionResolveContext['rng'] & {
|
|||||||
|
|
||||||
const legacyChoiceIndex = (rng: GeneralActionResolveContext['rng'], length: number): number => {
|
const legacyChoiceIndex = (rng: GeneralActionResolveContext['rng'], length: number): number => {
|
||||||
const inclusive = rng as InclusiveRandomGenerator;
|
const inclusive = rng as InclusiveRandomGenerator;
|
||||||
return inclusive.nextIntInclusive
|
return inclusive.nextIntInclusive ? inclusive.nextIntInclusive(length - 1) : rng.nextInt(0, length);
|
||||||
? inclusive.nextIntInclusive(length - 1)
|
|
||||||
: rng.nextInt(0, length);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export interface BorderReturnResolveContext<
|
export interface BorderReturnResolveContext<
|
||||||
@@ -66,26 +63,32 @@ export class ActionDefinition<
|
|||||||
return { effects: [] };
|
return { effects: [] };
|
||||||
}
|
}
|
||||||
|
|
||||||
const distanceByCity = searchDistance(map, general.cityId, 3);
|
const cityById = new Map(allCities.map((city) => [city.id, city]));
|
||||||
const candidates = allCities
|
const mapCityById = new Map(map.cities.map((city) => [city.id, city]));
|
||||||
.filter((city) => city.nationId === nation.id && city.supplyState === 1)
|
const visited = new Set([general.cityId]);
|
||||||
.map((city) => ({ city, distance: distanceByCity[city.id] }))
|
let frontier = [general.cityId];
|
||||||
.filter((entry) => typeof entry.distance === 'number' && Number.isFinite(entry.distance));
|
let nearestCities: City[] = [];
|
||||||
|
for (let distance = 1; distance <= 3 && frontier.length > 0; distance += 1) {
|
||||||
if (candidates.length === 0) {
|
const nextFrontier: number[] = [];
|
||||||
context.addLog('3칸 이내에 아국 도시가 없습니다.', {
|
for (const cityId of frontier) {
|
||||||
scope: LogScope.GENERAL,
|
for (const connectedCityId of mapCityById.get(cityId)?.connections ?? []) {
|
||||||
category: LogCategory.ACTION,
|
if (visited.has(connectedCityId)) {
|
||||||
format: LogFormat.MONTH,
|
continue;
|
||||||
|
}
|
||||||
|
visited.add(connectedCityId);
|
||||||
|
nextFrontier.push(connectedCityId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
nearestCities = nextFrontier.flatMap((cityId) => {
|
||||||
|
const city = cityById.get(cityId);
|
||||||
|
return city?.nationId === nation.id && city.supplyState === 1 ? [city] : [];
|
||||||
});
|
});
|
||||||
return { effects: [] };
|
if (nearestCities.length > 0) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
frontier = nextFrontier;
|
||||||
}
|
}
|
||||||
|
|
||||||
const minDistance = Math.min(...candidates.map((entry) => entry.distance as number));
|
|
||||||
const nearestCities = candidates
|
|
||||||
.filter((entry) => entry.distance === minDistance)
|
|
||||||
.map((entry) => entry.city);
|
|
||||||
|
|
||||||
if (nearestCities.length === 0) {
|
if (nearestCities.length === 0) {
|
||||||
context.addLog('3칸 이내에 아국 도시가 없습니다.', {
|
context.addLog('3칸 이내에 아국 도시가 없습니다.', {
|
||||||
scope: LogScope.GENERAL,
|
scope: LogScope.GENERAL,
|
||||||
|
|||||||
Reference in New Issue
Block a user