부대 즉시 명령을 전용 모듈로 분리하고 저장과 갱신을 검증한다
This commit is contained in:
1 parent
81e101ffef
commit
cc1cfea33b
3 files changed
+518
-324
No files matched your search
@@ -0,0 +1,336 @@
|
||||
import { JosaUtil } from '@sammo-ts/common';
|
||||
import {
|
||||
isValidTroopNameWidth,
|
||||
LogCategory,
|
||||
LogFormat,
|
||||
LogScope,
|
||||
normalizeTroopName,
|
||||
resolveTroopSecretPermission,
|
||||
} from '@sammo-ts/logic';
|
||||
|
||||
import type { TurnDaemonCommand, TurnDaemonCommandResult } from '../lifecycle/types.js';
|
||||
import type { InMemoryTurnWorld } from './inMemoryWorld.js';
|
||||
import {
|
||||
hasScenarioStaticEventHandler,
|
||||
IMMEDIATE_TROOP_JOIN_MOVE_HANDLER,
|
||||
LEGACY_TROOP_JOIN_EVENT,
|
||||
} from './scenarioStaticEvents.js';
|
||||
|
||||
const TROOP_COMMAND_TYPES = ['troopCreate', 'troopJoin', 'troopExit', 'troopKick', 'troopRename'] as const;
|
||||
const troopCommandTypes = new Set<TurnDaemonCommand['type']>(TROOP_COMMAND_TYPES);
|
||||
|
||||
export type TroopCommand = Extract<TurnDaemonCommand, { type: (typeof TROOP_COMMAND_TYPES)[number] }>;
|
||||
|
||||
export const isTroopCommand = (command: TurnDaemonCommand): command is TroopCommand =>
|
||||
troopCommandTypes.has(command.type);
|
||||
|
||||
export const handleTroopCommand = (world: InMemoryTurnWorld, command: TroopCommand): TurnDaemonCommandResult => {
|
||||
switch (command.type) {
|
||||
case 'troopCreate':
|
||||
return handleTroopCreate(world, command);
|
||||
case 'troopJoin':
|
||||
return handleTroopJoin(world, command);
|
||||
case 'troopExit':
|
||||
return handleTroopExit(world, command);
|
||||
case 'troopKick':
|
||||
return handleTroopKick(world, command);
|
||||
case 'troopRename':
|
||||
return handleTroopRename(world, command);
|
||||
}
|
||||
};
|
||||
|
||||
function handleTroopJoin(
|
||||
world: InMemoryTurnWorld,
|
||||
command: Extract<TurnDaemonCommand, { type: 'troopJoin' }>
|
||||
): TurnDaemonCommandResult {
|
||||
const general = world.getGeneralById(command.generalId);
|
||||
if (!general) {
|
||||
return {
|
||||
type: 'troopJoin',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
troopId: command.troopId,
|
||||
reason: '장수 정보를 찾을 수 없습니다.',
|
||||
};
|
||||
}
|
||||
if (general.troopId !== 0) {
|
||||
return {
|
||||
type: 'troopJoin',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
troopId: command.troopId,
|
||||
reason: '이미 부대에 소속되어 있습니다.',
|
||||
};
|
||||
}
|
||||
if (general.nationId <= 0) {
|
||||
return {
|
||||
type: 'troopJoin',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
troopId: command.troopId,
|
||||
reason: '국가에 소속되어 있지 않습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
const troop = world.getTroopById(command.troopId);
|
||||
if (!troop || troop.nationId !== general.nationId) {
|
||||
return {
|
||||
type: 'troopJoin',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
troopId: command.troopId,
|
||||
reason: '부대가 올바르지 않습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
world.updateGeneral(command.generalId, {
|
||||
troopId: command.troopId,
|
||||
});
|
||||
if (
|
||||
hasScenarioStaticEventHandler(
|
||||
world.getScenarioConfig(),
|
||||
LEGACY_TROOP_JOIN_EVENT,
|
||||
IMMEDIATE_TROOP_JOIN_MOVE_HANDLER
|
||||
)
|
||||
) {
|
||||
const leader = world.getGeneralById(troop.id);
|
||||
if (
|
||||
leader &&
|
||||
leader.troopId === leader.id &&
|
||||
leader.nationId === general.nationId &&
|
||||
leader.cityId !== general.cityId
|
||||
) {
|
||||
const city = world.getCityById(leader.cityId);
|
||||
if (city) {
|
||||
world.updateGeneral(command.generalId, {
|
||||
troopId: command.troopId,
|
||||
cityId: leader.cityId,
|
||||
});
|
||||
const josaRo = JosaUtil.pick(city.name, '로');
|
||||
world.pushLog({
|
||||
scope: LogScope.GENERAL,
|
||||
category: LogCategory.ACTION,
|
||||
format: LogFormat.PLAIN,
|
||||
text: `부대 주둔지인 <G><b>${city.name}</b></>${josaRo} 즉시 이동합니다.`,
|
||||
generalId: general.id,
|
||||
meta: {},
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
type: 'troopJoin',
|
||||
ok: true,
|
||||
generalId: command.generalId,
|
||||
troopId: command.troopId,
|
||||
};
|
||||
}
|
||||
|
||||
function handleTroopCreate(
|
||||
world: InMemoryTurnWorld,
|
||||
command: Extract<TurnDaemonCommand, { type: 'troopCreate' }>
|
||||
): TurnDaemonCommandResult {
|
||||
const general = world.getGeneralById(command.generalId);
|
||||
if (!general) {
|
||||
return {
|
||||
type: 'troopCreate',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
reason: '장수 정보를 찾을 수 없습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
const troopName = normalizeTroopName(command.troopName);
|
||||
if (!troopName) {
|
||||
return { type: 'troopCreate', ok: false, generalId: command.generalId, reason: '부대 이름이 없습니다.' };
|
||||
}
|
||||
if (!isValidTroopNameWidth(troopName)) {
|
||||
return {
|
||||
type: 'troopCreate',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
reason: '부대 이름은 전각 9자 또는 반각 18자 이하여야 합니다.',
|
||||
};
|
||||
}
|
||||
if (general.troopId !== 0 || world.getTroopById(general.id)) {
|
||||
return {
|
||||
type: 'troopCreate',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
reason: '이미 부대에 소속되어 있습니다.',
|
||||
};
|
||||
}
|
||||
if (general.nationId <= 0 || !world.getNationById(general.nationId)) {
|
||||
return {
|
||||
type: 'troopCreate',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
reason: '국가에 소속되어 있지 않습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
const troop = world.createTroop({
|
||||
id: general.id,
|
||||
nationId: general.nationId,
|
||||
name: troopName,
|
||||
});
|
||||
if (!troop) {
|
||||
return {
|
||||
type: 'troopCreate',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
reason: '부대가 생성되지 않았습니다. 버그일 수 있습니다.',
|
||||
};
|
||||
}
|
||||
world.updateGeneral(general.id, { troopId: general.id });
|
||||
return {
|
||||
type: 'troopCreate',
|
||||
ok: true,
|
||||
generalId: general.id,
|
||||
troopId: troop.id,
|
||||
troopName: troop.name,
|
||||
};
|
||||
}
|
||||
|
||||
function handleTroopExit(
|
||||
world: InMemoryTurnWorld,
|
||||
command: Extract<TurnDaemonCommand, { type: 'troopExit' }>
|
||||
): TurnDaemonCommandResult {
|
||||
const general = world.getGeneralById(command.generalId);
|
||||
if (!general) {
|
||||
return {
|
||||
type: 'troopExit',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
reason: '장수 정보를 찾을 수 없습니다.',
|
||||
};
|
||||
}
|
||||
if (general.troopId === 0) {
|
||||
return {
|
||||
type: 'troopExit',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
reason: '부대에 소속되어 있지 않습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
if (general.troopId !== general.id) {
|
||||
world.updateGeneral(command.generalId, {
|
||||
troopId: 0,
|
||||
});
|
||||
return {
|
||||
type: 'troopExit',
|
||||
ok: true,
|
||||
generalId: command.generalId,
|
||||
wasLeader: false,
|
||||
};
|
||||
}
|
||||
|
||||
const troopId = general.troopId;
|
||||
const members = world.listGenerals().filter((entry) => entry.troopId === troopId);
|
||||
for (const member of members) {
|
||||
world.updateGeneral(member.id, { troopId: 0 });
|
||||
}
|
||||
world.removeTroop(troopId);
|
||||
return {
|
||||
type: 'troopExit',
|
||||
ok: true,
|
||||
generalId: command.generalId,
|
||||
wasLeader: true,
|
||||
};
|
||||
}
|
||||
|
||||
function handleTroopKick(
|
||||
world: InMemoryTurnWorld,
|
||||
command: Extract<TurnDaemonCommand, { type: 'troopKick' }>
|
||||
): TurnDaemonCommandResult {
|
||||
const fail = (reason: string): TurnDaemonCommandResult => ({
|
||||
type: 'troopKick',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
troopId: command.troopId,
|
||||
targetGeneralId: command.targetGeneralId,
|
||||
reason,
|
||||
});
|
||||
const actor = world.getGeneralById(command.generalId);
|
||||
if (!actor) {
|
||||
return fail('장수 정보를 찾을 수 없습니다.');
|
||||
}
|
||||
const troop = world.getTroopById(command.troopId);
|
||||
if (
|
||||
command.generalId !== command.troopId ||
|
||||
actor.troopId !== actor.id ||
|
||||
!troop ||
|
||||
troop.id !== actor.id ||
|
||||
troop.nationId !== actor.nationId
|
||||
) {
|
||||
return fail('권한이 부족합니다.');
|
||||
}
|
||||
|
||||
const target = world.getGeneralById(command.targetGeneralId);
|
||||
if (!target) {
|
||||
return fail('장수 정보를 찾을 수 없습니다.');
|
||||
}
|
||||
if (target.troopId === 0) {
|
||||
return fail('부대에 소속되어 있지 않습니다.');
|
||||
}
|
||||
if (target.troopId !== command.troopId) {
|
||||
return fail('다른 부대에 소속되어 있습니다.');
|
||||
}
|
||||
if (target.id === command.troopId) {
|
||||
return fail('부대장을 추방할 수 없습니다.');
|
||||
}
|
||||
|
||||
world.updateGeneral(target.id, { troopId: 0 });
|
||||
return {
|
||||
type: 'troopKick',
|
||||
ok: true,
|
||||
generalId: actor.id,
|
||||
troopId: troop.id,
|
||||
targetGeneralId: target.id,
|
||||
};
|
||||
}
|
||||
|
||||
function handleTroopRename(
|
||||
world: InMemoryTurnWorld,
|
||||
command: Extract<TurnDaemonCommand, { type: 'troopRename' }>
|
||||
): TurnDaemonCommandResult {
|
||||
const fail = (reason: string): TurnDaemonCommandResult => ({
|
||||
type: 'troopRename',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
troopId: command.troopId,
|
||||
reason,
|
||||
});
|
||||
const actor = world.getGeneralById(command.generalId);
|
||||
if (!actor) {
|
||||
return fail('장수 정보를 찾을 수 없습니다.');
|
||||
}
|
||||
|
||||
const nation = world.getNationById(actor.nationId);
|
||||
const permission = resolveTroopSecretPermission(actor, nation?.meta ?? {}, false);
|
||||
if (actor.id !== command.troopId && permission < 4) {
|
||||
return fail('권한이 부족합니다.');
|
||||
}
|
||||
|
||||
const troopName = normalizeTroopName(command.troopName);
|
||||
if (!troopName) {
|
||||
return fail('부대 이름이 없습니다.');
|
||||
}
|
||||
if (!isValidTroopNameWidth(troopName)) {
|
||||
return fail('부대 이름은 전각 9자 또는 반각 18자 이하여야 합니다.');
|
||||
}
|
||||
|
||||
const troop = world.getTroopById(command.troopId);
|
||||
if (!troop || actor.nationId <= 0 || troop.nationId !== actor.nationId) {
|
||||
return fail('부대가 없습니다.');
|
||||
}
|
||||
world.updateTroop(troop.id, { name: troopName });
|
||||
return {
|
||||
type: 'troopRename',
|
||||
ok: true,
|
||||
generalId: actor.id,
|
||||
troopId: troop.id,
|
||||
troopName,
|
||||
};
|
||||
}
|
||||
@@ -26,10 +26,7 @@ import {
|
||||
createItemModuleRegistry,
|
||||
GeneralActionPipeline,
|
||||
isDefenceTrainPenaltyWaivedByScenarioEffect,
|
||||
isValidTroopNameWidth,
|
||||
loadItemModules,
|
||||
normalizeTroopName,
|
||||
resolveTroopSecretPermission,
|
||||
resolveMessageTargetIcon,
|
||||
readDiplomacyMeta,
|
||||
type GeneralActionModule,
|
||||
@@ -59,11 +56,7 @@ import {
|
||||
} from './reservedTurnHandler.js';
|
||||
import { buildCommandEnv } from './reservedTurnCommands.js';
|
||||
import { openAuction } from '../auction/opener.js';
|
||||
import {
|
||||
hasScenarioStaticEventHandler,
|
||||
IMMEDIATE_TROOP_JOIN_MOVE_HANDLER,
|
||||
LEGACY_TROOP_JOIN_EVENT,
|
||||
} from './scenarioStaticEvents.js';
|
||||
import { handleTroopCommand, isTroopCommand, type TroopCommand } from './troopCommands.js';
|
||||
import {
|
||||
createGeneralFromSelectionPool,
|
||||
reserveSelectionPool,
|
||||
@@ -177,11 +170,6 @@ const requireCommandDatabase = (ctx: CommandHandlerContext): DatabaseClient => {
|
||||
|
||||
const ACTOR_BOUND_GENERAL_COMMAND_TYPE_LIST = [
|
||||
'tournamentAdjustGeneral',
|
||||
'troopCreate',
|
||||
'troopJoin',
|
||||
'troopExit',
|
||||
'troopKick',
|
||||
'troopRename',
|
||||
'vacation',
|
||||
'setMySetting',
|
||||
'dropItem',
|
||||
@@ -198,7 +186,7 @@ const ACTOR_BOUND_GENERAL_COMMAND_TYPE_LIST = [
|
||||
type ActorBoundGeneralCommandType = (typeof ACTOR_BOUND_GENERAL_COMMAND_TYPE_LIST)[number];
|
||||
const ACTOR_BOUND_GENERAL_COMMAND_TYPES = new Set<ActorBoundGeneralCommandType>(ACTOR_BOUND_GENERAL_COMMAND_TYPE_LIST);
|
||||
|
||||
type ActorBoundGeneralCommand = Extract<TurnDaemonCommand, { type: ActorBoundGeneralCommandType }>;
|
||||
type ActorBoundGeneralCommand = TroopCommand | Extract<TurnDaemonCommand, { type: ActorBoundGeneralCommandType }>;
|
||||
|
||||
const isActorBoundGeneralCommand = (command: TurnDaemonCommand): command is ActorBoundGeneralCommand =>
|
||||
ACTOR_BOUND_GENERAL_COMMAND_TYPES.has(command.type as ActorBoundGeneralCommandType);
|
||||
@@ -214,7 +202,7 @@ const rejectActorBoundGeneralCommand = (
|
||||
});
|
||||
|
||||
const validateActorBoundGeneralCommand = async (
|
||||
ctx: CommandHandlerContext,
|
||||
ctx: Pick<CommandHandlerContext, 'world' | 'commandDb'>,
|
||||
command: ActorBoundGeneralCommand
|
||||
): Promise<TurnDaemonCommandResult | null> => {
|
||||
if (!ctx.commandDb) {
|
||||
@@ -1348,307 +1336,6 @@ async function handleUpdateRuntimeSettings(
|
||||
};
|
||||
}
|
||||
|
||||
async function handleTroopJoin(
|
||||
ctx: CommandHandlerContext,
|
||||
command: Extract<TurnDaemonCommand, { type: 'troopJoin' }>
|
||||
): Promise<TurnDaemonCommandResult> {
|
||||
const { world } = ctx;
|
||||
const general = world.getGeneralById(command.generalId);
|
||||
if (!general) {
|
||||
return {
|
||||
type: 'troopJoin',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
troopId: command.troopId,
|
||||
reason: '장수 정보를 찾을 수 없습니다.',
|
||||
};
|
||||
}
|
||||
if (general.troopId !== 0) {
|
||||
return {
|
||||
type: 'troopJoin',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
troopId: command.troopId,
|
||||
reason: '이미 부대에 소속되어 있습니다.',
|
||||
};
|
||||
}
|
||||
if (general.nationId <= 0) {
|
||||
return {
|
||||
type: 'troopJoin',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
troopId: command.troopId,
|
||||
reason: '국가에 소속되어 있지 않습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
const troop = world.getTroopById(command.troopId);
|
||||
if (!troop || troop.nationId !== general.nationId) {
|
||||
return {
|
||||
type: 'troopJoin',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
troopId: command.troopId,
|
||||
reason: '부대가 올바르지 않습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
world.updateGeneral(command.generalId, {
|
||||
troopId: command.troopId,
|
||||
});
|
||||
if (
|
||||
hasScenarioStaticEventHandler(
|
||||
world.getScenarioConfig(),
|
||||
LEGACY_TROOP_JOIN_EVENT,
|
||||
IMMEDIATE_TROOP_JOIN_MOVE_HANDLER
|
||||
)
|
||||
) {
|
||||
const leader = world.getGeneralById(troop.id);
|
||||
if (
|
||||
leader &&
|
||||
leader.troopId === leader.id &&
|
||||
leader.nationId === general.nationId &&
|
||||
leader.cityId !== general.cityId
|
||||
) {
|
||||
const city = world.getCityById(leader.cityId);
|
||||
if (city) {
|
||||
world.updateGeneral(command.generalId, {
|
||||
troopId: command.troopId,
|
||||
cityId: leader.cityId,
|
||||
});
|
||||
const josaRo = JosaUtil.pick(city.name, '로');
|
||||
world.pushLog({
|
||||
scope: LogScope.GENERAL,
|
||||
category: LogCategory.ACTION,
|
||||
format: LogFormat.PLAIN,
|
||||
text: `부대 주둔지인 <G><b>${city.name}</b></>${josaRo} 즉시 이동합니다.`,
|
||||
generalId: general.id,
|
||||
meta: {},
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
type: 'troopJoin',
|
||||
ok: true,
|
||||
generalId: command.generalId,
|
||||
troopId: command.troopId,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleTroopCreate(
|
||||
ctx: CommandHandlerContext,
|
||||
command: Extract<TurnDaemonCommand, { type: 'troopCreate' }>
|
||||
): Promise<TurnDaemonCommandResult> {
|
||||
const { world } = ctx;
|
||||
const general = world.getGeneralById(command.generalId);
|
||||
if (!general) {
|
||||
return {
|
||||
type: 'troopCreate',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
reason: '장수 정보를 찾을 수 없습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
const troopName = normalizeTroopName(command.troopName);
|
||||
if (!troopName) {
|
||||
return { type: 'troopCreate', ok: false, generalId: command.generalId, reason: '부대 이름이 없습니다.' };
|
||||
}
|
||||
if (!isValidTroopNameWidth(troopName)) {
|
||||
return {
|
||||
type: 'troopCreate',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
reason: '부대 이름은 전각 9자 또는 반각 18자 이하여야 합니다.',
|
||||
};
|
||||
}
|
||||
if (general.troopId !== 0 || world.getTroopById(general.id)) {
|
||||
return {
|
||||
type: 'troopCreate',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
reason: '이미 부대에 소속되어 있습니다.',
|
||||
};
|
||||
}
|
||||
if (general.nationId <= 0 || !world.getNationById(general.nationId)) {
|
||||
return {
|
||||
type: 'troopCreate',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
reason: '국가에 소속되어 있지 않습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
const troop = world.createTroop({
|
||||
id: general.id,
|
||||
nationId: general.nationId,
|
||||
name: troopName,
|
||||
});
|
||||
if (!troop) {
|
||||
return {
|
||||
type: 'troopCreate',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
reason: '부대가 생성되지 않았습니다. 버그일 수 있습니다.',
|
||||
};
|
||||
}
|
||||
world.updateGeneral(general.id, { troopId: general.id });
|
||||
return {
|
||||
type: 'troopCreate',
|
||||
ok: true,
|
||||
generalId: general.id,
|
||||
troopId: troop.id,
|
||||
troopName: troop.name,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleTroopExit(
|
||||
ctx: CommandHandlerContext,
|
||||
command: Extract<TurnDaemonCommand, { type: 'troopExit' }>
|
||||
): Promise<TurnDaemonCommandResult> {
|
||||
const { world } = ctx;
|
||||
const general = world.getGeneralById(command.generalId);
|
||||
if (!general) {
|
||||
return {
|
||||
type: 'troopExit',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
reason: '장수 정보를 찾을 수 없습니다.',
|
||||
};
|
||||
}
|
||||
if (general.troopId === 0) {
|
||||
return {
|
||||
type: 'troopExit',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
reason: '부대에 소속되어 있지 않습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
if (general.troopId !== general.id) {
|
||||
world.updateGeneral(command.generalId, {
|
||||
troopId: 0,
|
||||
});
|
||||
return {
|
||||
type: 'troopExit',
|
||||
ok: true,
|
||||
generalId: command.generalId,
|
||||
wasLeader: false,
|
||||
};
|
||||
}
|
||||
|
||||
const troopId = general.troopId;
|
||||
const members = world.listGenerals().filter((entry) => entry.troopId === troopId);
|
||||
for (const member of members) {
|
||||
world.updateGeneral(member.id, { troopId: 0 });
|
||||
}
|
||||
world.removeTroop(troopId);
|
||||
return {
|
||||
type: 'troopExit',
|
||||
ok: true,
|
||||
generalId: command.generalId,
|
||||
wasLeader: true,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleTroopKick(
|
||||
ctx: CommandHandlerContext,
|
||||
command: Extract<TurnDaemonCommand, { type: 'troopKick' }>
|
||||
): Promise<TurnDaemonCommandResult> {
|
||||
const fail = (reason: string): TurnDaemonCommandResult => ({
|
||||
type: 'troopKick',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
troopId: command.troopId,
|
||||
targetGeneralId: command.targetGeneralId,
|
||||
reason,
|
||||
});
|
||||
const { world } = ctx;
|
||||
const actor = world.getGeneralById(command.generalId);
|
||||
if (!actor) {
|
||||
return fail('장수 정보를 찾을 수 없습니다.');
|
||||
}
|
||||
const troop = world.getTroopById(command.troopId);
|
||||
if (
|
||||
command.generalId !== command.troopId ||
|
||||
actor.troopId !== actor.id ||
|
||||
!troop ||
|
||||
troop.id !== actor.id ||
|
||||
troop.nationId !== actor.nationId
|
||||
) {
|
||||
return fail('권한이 부족합니다.');
|
||||
}
|
||||
|
||||
const target = world.getGeneralById(command.targetGeneralId);
|
||||
if (!target) {
|
||||
return fail('장수 정보를 찾을 수 없습니다.');
|
||||
}
|
||||
if (target.troopId === 0) {
|
||||
return fail('부대에 소속되어 있지 않습니다.');
|
||||
}
|
||||
if (target.troopId !== command.troopId) {
|
||||
return fail('다른 부대에 소속되어 있습니다.');
|
||||
}
|
||||
if (target.id === command.troopId) {
|
||||
return fail('부대장을 추방할 수 없습니다.');
|
||||
}
|
||||
|
||||
world.updateGeneral(target.id, { troopId: 0 });
|
||||
return {
|
||||
type: 'troopKick',
|
||||
ok: true,
|
||||
generalId: actor.id,
|
||||
troopId: troop.id,
|
||||
targetGeneralId: target.id,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleTroopRename(
|
||||
ctx: CommandHandlerContext,
|
||||
command: Extract<TurnDaemonCommand, { type: 'troopRename' }>
|
||||
): Promise<TurnDaemonCommandResult> {
|
||||
const fail = (reason: string): TurnDaemonCommandResult => ({
|
||||
type: 'troopRename',
|
||||
ok: false,
|
||||
generalId: command.generalId,
|
||||
troopId: command.troopId,
|
||||
reason,
|
||||
});
|
||||
const { world } = ctx;
|
||||
const actor = world.getGeneralById(command.generalId);
|
||||
if (!actor) {
|
||||
return fail('장수 정보를 찾을 수 없습니다.');
|
||||
}
|
||||
|
||||
const nation = world.getNationById(actor.nationId);
|
||||
const permission = resolveTroopSecretPermission(actor, nation?.meta ?? {}, false);
|
||||
if (actor.id !== command.troopId && permission < 4) {
|
||||
return fail('권한이 부족합니다.');
|
||||
}
|
||||
|
||||
const troopName = normalizeTroopName(command.troopName);
|
||||
if (!troopName) {
|
||||
return fail('부대 이름이 없습니다.');
|
||||
}
|
||||
if (!isValidTroopNameWidth(troopName)) {
|
||||
return fail('부대 이름은 전각 9자 또는 반각 18자 이하여야 합니다.');
|
||||
}
|
||||
|
||||
const troop = world.getTroopById(command.troopId);
|
||||
if (!troop || actor.nationId <= 0 || troop.nationId !== actor.nationId) {
|
||||
return fail('부대가 없습니다.');
|
||||
}
|
||||
world.updateTroop(troop.id, { name: troopName });
|
||||
return {
|
||||
type: 'troopRename',
|
||||
ok: true,
|
||||
generalId: actor.id,
|
||||
troopId: troop.id,
|
||||
troopName,
|
||||
};
|
||||
}
|
||||
|
||||
const ensurePrestartDeleteAfter = async (
|
||||
ctx: CommandHandlerContext,
|
||||
command: Extract<TurnDaemonCommand, { type: 'dieOnPrestart' | 'ensureDieOnPrestartStatus' }>,
|
||||
@@ -3289,13 +2976,6 @@ export const createTurnDaemonCommandHandler = (options: {
|
||||
>;
|
||||
|
||||
const handlers: HandlerMap = {
|
||||
troopCreate: (command) =>
|
||||
handleTroopCreate(ctx, command as Extract<TurnDaemonCommand, { type: 'troopCreate' }>),
|
||||
troopJoin: (command) => handleTroopJoin(ctx, command as Extract<TurnDaemonCommand, { type: 'troopJoin' }>),
|
||||
troopExit: (command) => handleTroopExit(ctx, command as Extract<TurnDaemonCommand, { type: 'troopExit' }>),
|
||||
troopKick: (command) => handleTroopKick(ctx, command as Extract<TurnDaemonCommand, { type: 'troopKick' }>),
|
||||
troopRename: (command) =>
|
||||
handleTroopRename(ctx, command as Extract<TurnDaemonCommand, { type: 'troopRename' }>),
|
||||
ensureDieOnPrestartStatus: (command) =>
|
||||
handleEnsureDieOnPrestartStatus(
|
||||
ctx,
|
||||
@@ -3392,6 +3072,14 @@ export const createTurnDaemonCommandHandler = (options: {
|
||||
command,
|
||||
executionContext?: TurnDaemonCommandExecutionContext
|
||||
): Promise<TurnDaemonCommandResult | null> => {
|
||||
if (isTroopCommand(command)) {
|
||||
const rejected = await validateActorBoundGeneralCommand(
|
||||
{ world: options.world, commandDb: executionContext?.db },
|
||||
command
|
||||
);
|
||||
return rejected ?? handleTroopCommand(options.world, command);
|
||||
}
|
||||
|
||||
const handler = handlers[command.type];
|
||||
if (!handler) {
|
||||
return null;
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { SystemClock } from '@sammo-ts/common';
|
||||
import {
|
||||
hasRealtimeReadModelInvalidation,
|
||||
parseReadModelOutboxPayload,
|
||||
readModelOutboxPayloadToChanges,
|
||||
resolveRealtimeReadModelInvalidation,
|
||||
SystemClock,
|
||||
type TurnDaemonCommand,
|
||||
} from '@sammo-ts/common';
|
||||
import { createGamePostgresConnector, type GamePrisma, type GamePrismaClient } from '@sammo-ts/infra';
|
||||
import type { MapDefinition, ScenarioConfig, ScenarioMeta, TurnSchedule } from '@sammo-ts/logic';
|
||||
|
||||
@@ -182,6 +189,7 @@ integration('immediate general action persistence', () => {
|
||||
},
|
||||
});
|
||||
await db.message.deleteMany({ where: { mailbox: { in: [generalId, generalId + 1] } } });
|
||||
await db.troop.deleteMany({ where: { troopLeaderId: generalId } });
|
||||
await db.general.deleteMany({ where: { id: { in: [generalId, generalId + 1] } } });
|
||||
await db.city.deleteMany({ where: { id: cityId } });
|
||||
await db.nation.deleteMany({ where: { id: { gte: existingNationId } } });
|
||||
@@ -292,6 +300,7 @@ integration('immediate general action persistence', () => {
|
||||
},
|
||||
});
|
||||
await db.message.deleteMany({ where: { mailbox: { in: [generalId, generalId + 1] } } });
|
||||
await db.troop.deleteMany({ where: { troopLeaderId: generalId } });
|
||||
await db.general.deleteMany({ where: { id: { in: [generalId, generalId + 1] } } });
|
||||
await db.city.deleteMany({ where: { id: cityId } });
|
||||
await db.nation.deleteMany({ where: { id: { gte: existingNationId } } });
|
||||
@@ -299,6 +308,167 @@ integration('immediate general action persistence', () => {
|
||||
await disconnect?.();
|
||||
});
|
||||
|
||||
it('commits troop commands with world state, read-model changes, and no lobby refresh', async () => {
|
||||
const memberId = generalId + 1;
|
||||
const memberUserId = 'immediate-troop-member';
|
||||
const leaderUserId = general.userId!;
|
||||
await db.general.update({ where: { id: generalId }, data: { nationId: existingNationId } });
|
||||
await db.general.create({
|
||||
data: {
|
||||
id: memberId,
|
||||
userId: memberUserId,
|
||||
name: '부대원',
|
||||
nationId: existingNationId,
|
||||
cityId,
|
||||
turnTime: general.turnTime,
|
||||
meta: { killturn: 24 },
|
||||
},
|
||||
});
|
||||
|
||||
const loaded = await loadTurnWorldFromDatabase({ databaseUrl: databaseUrl! });
|
||||
const world = new InMemoryTurnWorld(loaded.state, loaded.snapshot, {
|
||||
schedule: { entries: [{ startMinute: 0, tickMinutes: 10 }] },
|
||||
});
|
||||
const handler = createTurnDaemonCommandHandler({ world });
|
||||
const queue = new DatabaseTurnDaemonCommandQueue(db);
|
||||
await queue.initialize();
|
||||
const hooks = await createDatabaseTurnHooks(databaseUrl!, world);
|
||||
const stateManager = new EngineStateManager();
|
||||
stateManager.register('world', {
|
||||
capture: () => world.captureState(),
|
||||
restore: (saved) => world.restoreState(saved),
|
||||
});
|
||||
|
||||
type TroopCommand = Extract<TurnDaemonCommand, { type: `troop${string}` }>;
|
||||
const execute = (id: string, command: TroopCommand) =>
|
||||
stateManager.transaction(() =>
|
||||
hooks.hooks.executeCommand!(id, async (context) => {
|
||||
const result = await handler.handle({ ...command, requestId: id }, context);
|
||||
if (!result) throw new Error('Missing troop command result.');
|
||||
return result;
|
||||
})
|
||||
);
|
||||
const checkWorld = async (name: string | null, memberTroopId: number) => {
|
||||
const reloaded = await loadTurnWorldFromDatabase({ databaseUrl: databaseUrl! });
|
||||
const expectedTroop = name === null ? null : { id: generalId, nationId: existingNationId, name };
|
||||
expect(world.getTroopById(generalId)).toEqual(expectedTroop);
|
||||
expect(reloaded.snapshot.troops.find(({ id }) => id === generalId) ?? null).toEqual(expectedTroop);
|
||||
for (const [id, troopId] of [
|
||||
[generalId, name === null ? 0 : generalId],
|
||||
[memberId, memberTroopId],
|
||||
]) {
|
||||
expect(world.getGeneralById(id)?.troopId).toBe(troopId);
|
||||
expect(reloaded.snapshot.generals.find((entry) => entry.id === id)?.troopId).toBe(troopId);
|
||||
}
|
||||
};
|
||||
|
||||
const leader = { generalId, userId: leaderUserId };
|
||||
const member = { generalId: memberId, userId: memberUserId };
|
||||
const join = { type: 'troopJoin', ...member, troopId: generalId } as const;
|
||||
const steps: {
|
||||
command: TroopCommand;
|
||||
name: string | null;
|
||||
memberTroopId: number;
|
||||
changedGenerals: number[];
|
||||
}[] = [
|
||||
{
|
||||
command: { type: 'troopCreate', ...leader, troopName: '백마대' },
|
||||
name: '백마대',
|
||||
memberTroopId: 0,
|
||||
changedGenerals: [generalId],
|
||||
},
|
||||
{ command: join, name: '백마대', memberTroopId: generalId, changedGenerals: [memberId] },
|
||||
{
|
||||
command: { type: 'troopRename', ...leader, troopId: generalId, troopName: '청룡대' },
|
||||
name: '청룡대',
|
||||
memberTroopId: generalId,
|
||||
changedGenerals: [],
|
||||
},
|
||||
{
|
||||
command: { type: 'troopKick', ...leader, troopId: generalId, targetGeneralId: memberId },
|
||||
name: '청룡대',
|
||||
memberTroopId: 0,
|
||||
changedGenerals: [memberId],
|
||||
},
|
||||
{ command: join, name: '청룡대', memberTroopId: generalId, changedGenerals: [memberId] },
|
||||
{
|
||||
command: { type: 'troopExit', ...member },
|
||||
name: '청룡대',
|
||||
memberTroopId: 0,
|
||||
changedGenerals: [memberId],
|
||||
},
|
||||
{ command: join, name: '청룡대', memberTroopId: generalId, changedGenerals: [memberId] },
|
||||
{
|
||||
command: { type: 'troopExit', ...leader },
|
||||
name: null,
|
||||
memberTroopId: 0,
|
||||
changedGenerals: [generalId, memberId],
|
||||
},
|
||||
];
|
||||
try {
|
||||
for (const [index, { command, name, memberTroopId, changedGenerals }] of steps.entries()) {
|
||||
const id = `${requestId}:troop:${index}`;
|
||||
await db.inputEvent.create({
|
||||
data: {
|
||||
requestId: id,
|
||||
target: 'ENGINE',
|
||||
eventType: command.type,
|
||||
actorUserId: command.userId,
|
||||
payload: { ...command, requestId: id },
|
||||
},
|
||||
});
|
||||
expect(await queue.drain()).toMatchObject([{ ...command, requestId: id }]);
|
||||
if (command.type === 'troopRename') {
|
||||
const outboxCount = await db.readModelOutbox.count();
|
||||
await db.$executeRaw`ALTER TABLE read_model_outbox ADD CONSTRAINT troop_command_rollback CHECK (false) NOT VALID`;
|
||||
try {
|
||||
await expect(execute(id, command)).rejects.toThrow('troop_command_rollback');
|
||||
await checkWorld('백마대', generalId);
|
||||
expect(hooks.takeCommittedReadModelChangeReceipt()).toBeNull();
|
||||
await expect(db.readModelOutbox.count()).resolves.toBe(outboxCount);
|
||||
await expect(
|
||||
db.inputEvent.findUniqueOrThrow({ where: { requestId: id } })
|
||||
).resolves.toMatchObject({
|
||||
status: 'PROCESSING',
|
||||
result: null,
|
||||
});
|
||||
} finally {
|
||||
await db.$executeRaw`ALTER TABLE read_model_outbox DROP CONSTRAINT troop_command_rollback`;
|
||||
}
|
||||
}
|
||||
|
||||
const result = await execute(id, command);
|
||||
expect(result).toMatchObject({ type: command.type, ok: true, generalId: command.generalId });
|
||||
await expect(db.inputEvent.findUniqueOrThrow({ where: { requestId: id } })).resolves.toMatchObject({
|
||||
status: 'SUCCEEDED',
|
||||
result,
|
||||
});
|
||||
await checkWorld(name, memberTroopId);
|
||||
|
||||
const receipt = hooks.takeCommittedReadModelChangeReceipt()!;
|
||||
expect(receipt.invalidation.revisions.map(({ domain, entityId }) => [domain, entityId])).toEqual([
|
||||
['dashboard.global', 0],
|
||||
...changedGenerals.map((id) => ['general.content', id]),
|
||||
]);
|
||||
const row = await db.readModelOutbox.findUniqueOrThrow({ where: { id: receipt.outboxId } });
|
||||
const changes = readModelOutboxPayloadToChanges(parseReadModelOutboxPayload(row.payload)!);
|
||||
for (const id of [generalId, memberId, null]) {
|
||||
const invalidation = resolveRealtimeReadModelInvalidation(changes, {
|
||||
generalId: id,
|
||||
cityId,
|
||||
nationId: existingNationId,
|
||||
});
|
||||
expect(invalidation.lobby).toBe(false);
|
||||
expect(hasRealtimeReadModelInvalidation(invalidation)).toBe(
|
||||
id !== null && changedGenerals.includes(id)
|
||||
);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await hooks.close();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
'normal',
|
||||
'resigned',
|
||||
|
||||
Reference in new issue
Block a user