feat: port scenario 903 select-pool flow

This commit is contained in:
2026-07-30 23:27:59 +00:00
parent 9bd057456b
commit 115218ded8
80 changed files with 6859 additions and 48 deletions
+3 -1
View File
@@ -41,7 +41,9 @@ const parsePayload = (value: unknown): GameSessionTokenPayload | null => {
typeof user.id !== 'string' ||
typeof user.username !== 'string' ||
typeof user.displayName !== 'string' ||
!Array.isArray(user.roles)
!Array.isArray(user.roles) ||
(user.legacyMemberNo !== undefined &&
(!Number.isSafeInteger(user.legacyMemberNo) || user.legacyMemberNo <= 0))
) {
return null;
}
+7 -2
View File
@@ -19,7 +19,9 @@ import {
createTraitCatalog,
createOfficerLevelActionModules,
DOMESTIC_TRAIT_KEYS,
EVENT_DOMESTIC_TRAIT_KEYS,
loadDomesticTraitModules,
loadEventDomesticTraitModules,
loadNationTraitModules,
loadPersonalityTraitModules,
loadWarTraitModules,
@@ -52,7 +54,10 @@ const itemWarModules: WarActionModule[] = createItemActionModules(
).war;
const crewTypeWarTriggerRegistry = createCrewTypeWarTriggerRegistry();
const traitCatalog = createTraitCatalog({
domestic: await loadDomesticTraitModules([...DOMESTIC_TRAIT_KEYS]),
domestic: [
...(await loadDomesticTraitModules([...DOMESTIC_TRAIT_KEYS])),
...(await loadEventDomesticTraitModules([...EVENT_DOMESTIC_TRAIT_KEYS])),
],
war: await loadWarTraitModules([...WAR_TRAIT_KEYS]),
personality: await loadPersonalityTraitModules([...PERSONALITY_TRAIT_KEYS]),
nation: await loadNationTraitModules([...NATION_TRAIT_KEYS]),
@@ -145,7 +150,7 @@ const mapGeneralPayload = (payload: BattleSimJobPayload['attackerGeneral']): Gen
officerLevel: payload.officer_level,
role: {
personality: payload.personal,
specialDomestic: null,
specialDomestic: payload.special ?? null,
specialWar: payload.special2,
items: {
horse: normalizeItemCode(payload.horse),
+1
View File
@@ -8,6 +8,7 @@ export const zBattleSimGeneral = z.object({
nation: z.number().int().positive(),
turntime: z.string().min(1),
personal: z.string().nullable(),
special: z.string().nullable().optional(),
special2: z.string().nullable(),
crew: z.number().int().min(0),
crewtype: z.number().int().positive(),
@@ -1,5 +1,7 @@
import {
ITEM_KEYS,
EVENT_DOMESTIC_TRAIT_KEYS,
loadEventDomesticTraitModules,
loadItemModules,
loadNationTraitModules,
loadPersonalityTraitModules,
@@ -95,22 +97,26 @@ const toTraitOption = (module: TraitModule): BattleSimTraitOption => ({
let cachedTraitOptions: Promise<{
nationTypes: BattleSimTraitOption[];
eventDomesticTraits: BattleSimTraitOption[];
warTraits: BattleSimTraitOption[];
personalities: BattleSimTraitOption[];
}> | null = null;
export const loadBattleSimTraitOptions = async (): Promise<{
nationTypes: BattleSimTraitOption[];
eventDomesticTraits: BattleSimTraitOption[];
warTraits: BattleSimTraitOption[];
personalities: BattleSimTraitOption[];
}> => {
if (!cachedTraitOptions) {
cachedTraitOptions = Promise.all([
loadNationTraitModules([...NATION_TRAIT_KEYS]),
loadEventDomesticTraitModules([...EVENT_DOMESTIC_TRAIT_KEYS]),
loadWarTraitModules([...WAR_TRAIT_KEYS]),
loadPersonalityTraitModules([...PERSONALITY_TRAIT_KEYS]),
]).then(([nationTraits, warTraits, personalities]) => ({
]).then(([nationTraits, eventDomesticTraits, warTraits, personalities]) => ({
nationTypes: nationTraits.map(toTraitOption),
eventDomesticTraits: eventDomesticTraits.map(toTraitOption),
warTraits: warTraits.map(toTraitOption),
personalities: personalities.map(toTraitOption),
}));
+1
View File
@@ -10,6 +10,7 @@ export interface BattleSimGeneralPayload {
nation: number;
turntime: string;
personal: string | null;
special?: string | null;
special2: string | null;
crew: number;
crewtype: number;
+16 -2
View File
@@ -29,6 +29,16 @@ export class ConflictingTurnDaemonCommandError extends Error {
}
}
export class FailedTurnDaemonCommandError extends Error {
constructor(
readonly requestId: string,
readonly storedError: string | null
) {
super(storedError ?? `Engine input event ${requestId} failed.`);
this.name = 'FailedTurnDaemonCommandError';
}
}
export class DatabaseTurnDaemonTransport implements TurnDaemonTransport {
constructor(
private readonly db: DatabaseClient,
@@ -45,6 +55,10 @@ export class DatabaseTurnDaemonTransport implements TurnDaemonTransport {
target: 'ENGINE',
eventType: command.type,
payload: asJson(durableCommand),
actorUserId:
'userId' in command && typeof command.userId === 'string'
? command.userId
: null,
},
});
} catch (error) {
@@ -80,13 +94,13 @@ export class DatabaseTurnDaemonTransport implements TurnDaemonTransport {
while (Date.now() < deadline) {
const event = await this.db.inputEvent.findUnique({
where: { requestId },
select: { status: true, result: true },
select: { status: true, result: true, error: true },
});
if (event?.status === 'SUCCEEDED') {
return event.result as T;
}
if (event?.status === 'FAILED') {
return null;
throw new FailedTurnDaemonCommandError(requestId, event.error);
}
await delay(Math.min(50, Math.max(1, deadline - Date.now())));
}
+8 -1
View File
@@ -5,7 +5,7 @@ import { isAfter, isValid, parseISO } from 'date-fns';
import { z } from 'zod';
import type { GameSessionTokenPayload } from '@sammo-ts/common/auth/gameToken';
import { procedure, router } from '../../trpc.js';
import { authedProcedure, procedure, router } from '../../trpc.js';
const parseDate = (value: string): Date | null => {
const parsed = parseISO(value);
@@ -45,6 +45,13 @@ const verifyGatewayToken = (
};
export const authRouter = router({
status: authedProcedure.query(({ ctx }) => {
const userId = ctx.auth?.user.id;
if (!userId) {
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
return { userId };
}),
exchangeGatewayToken: procedure
.input(z.object({ gatewayToken: z.string().min(1) }))
.mutation(async ({ ctx, input }) => {
+3
View File
@@ -112,6 +112,7 @@ export const battleRouter = router({
crewTypes,
},
nationTypes: traits.nationTypes,
eventDomesticTraits: traits.eventDomesticTraits,
warTraits: traits.warTraits,
personalities: traits.personalities,
items,
@@ -207,6 +208,7 @@ export const battleRouter = router({
bookCode: true,
itemCode: true,
personalCode: true,
specialCode: true,
special2Code: true,
meta: true,
},
@@ -241,6 +243,7 @@ export const battleRouter = router({
injury: general.injury,
rice: general.rice,
personal: normalizeOptionalKey(general.personalCode),
special: normalizeOptionalKey(general.specialCode),
special2: normalizeOptionalKey(general.special2Code),
crew: general.crew,
crewtype: general.crewTypeId,
+165 -3
View File
@@ -2,8 +2,8 @@ import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { randomBytes } from 'node:crypto';
import type { DatabaseClient, WorldStateRow } from '../../context.js';
import { authedProcedure, router } from '../../trpc.js';
import type { DatabaseClient, GameApiContext, WorldStateRow } from '../../context.js';
import { authedProcedure, engineAuthedProcedure, router } from '../../trpc.js';
import { asNumber, asRecord, asStringArray, LiteHashDRBG } from '@sammo-ts/common';
import {
isPersonalityTraitKey,
@@ -21,6 +21,58 @@ import {
resolveInheritConstants,
setInheritancePoint,
} from '../../services/inheritance.js';
import {
getSelectionPoolStatus,
reserveSelectionPool,
resolveSelectionMaxGeneral,
} from '../../services/selectPool.js';
const resolveSelectionCommandResult = (
result:
| Awaited<ReturnType<GameApiContext['turnDaemon']['requestCommand']>>
| null,
expectedType: 'selectPoolCreate' | 'selectPoolReselect'
): { ok: true; generalId: number } => {
if (!result) {
throw new TRPCError({
code: 'TIMEOUT',
message:
'장수 선택 요청은 접수됐지만 처리 결과를 아직 확인하지 못했습니다. 같은 요청으로 다시 시도해 주세요.',
});
}
if (result.type !== expectedType) {
throw new TRPCError({
code: 'INTERNAL_SERVER_ERROR',
message: '턴 데몬이 올바르지 않은 장수 선택 결과를 반환했습니다.',
});
}
if (!result.ok) {
throw new TRPCError({
code: result.code,
message: result.reason,
});
}
return { ok: true, generalId: result.generalId };
};
const resolveSelectionRequestId = (
contextRequestId: string | undefined,
userId: string,
clientRequestId: string | undefined,
operation: 'create' | 'reselect'
): string | undefined => {
if (clientRequestId) {
return `select-pool:${userId}:${clientRequestId}:${operation}`;
}
if (!contextRequestId) {
return undefined;
}
const path =
operation === 'create'
? 'join.selectPoolGeneral'
: 'join.reselectPoolGeneral';
return `${contextRequestId}:${path}`;
};
const DEFAULT_JOIN_STAT = {
total: 165,
@@ -181,10 +233,12 @@ export const joinRouter = router({
const availableSpecialWar = asStringArray(configConst.availableSpecialWar);
const warKeys = availableSpecialWar.length > 0 ? availableSpecialWar : [...WAR_TRAIT_KEYS];
const [personalities, warSpecials, nationRows] = await Promise.all([
const [personalities, warSpecials, nationRows, userGeneralCount, npcGeneralCount] =
await Promise.all([
loadPersonalityOptions(),
loadWarOptions(warKeys),
ctx.db.nation.findMany({
where: { id: { gt: 0 } },
select: {
id: true,
name: true,
@@ -193,6 +247,8 @@ export const joinRouter = router({
},
orderBy: { id: 'asc' },
}),
ctx.db.general.count({ where: { npcState: { lt: 2 } } }),
ctx.db.general.count({ where: { npcState: { gte: 2 } } }),
]);
const nations = nationRows.map((nation) => {
@@ -209,7 +265,13 @@ export const joinRouter = router({
const inheritTotalPoint = ctx.auth?.user.id
? await readInheritancePoint(ctx.db, ctx.auth.user.id, 'previous')
: 0;
const selectionPool = await getSelectionPoolStatus(
ctx.db,
worldState,
ctx.auth?.user.id ?? ''
);
const tickMinutes = Math.max(1, Math.round(worldState.tickSeconds / 60));
const maxGeneral = resolveSelectionMaxGeneral(worldState);
const inheritCitiesRaw = await ctx.db.city.findMany({
where: { level: { in: [5, 6] }, nationId: 0 },
select: { id: true, name: true, level: true, region: true },
@@ -239,6 +301,14 @@ export const joinRouter = router({
],
warSpecials,
nations,
serverInfo: {
currentYear: worldState.currentYear,
currentMonth: worldState.currentMonth,
tickMinutes,
maxGeneral,
userGeneralCount,
npcGeneralCount,
},
inherit: {
totalPoint: inheritTotalPoint,
costs: {
@@ -251,8 +321,93 @@ export const joinRouter = router({
turnTimeZones: buildTurnTimeZones(tickMinutes),
availableSpecialWar: warSpecials,
},
selectionPool,
};
}),
getSelectionPool: authedProcedure.mutation(async ({ ctx }) => {
const userId = ctx.auth?.user.id;
if (!userId) {
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
const worldState = await ctx.db.worldState.findFirst();
if (!worldState) {
throw new TRPCError({
code: 'PRECONDITION_FAILED',
message: 'World state is not initialized.',
});
}
return reserveSelectionPool({
db: ctx.db,
worldState,
userId,
seedOwnerIdentity: ctx.auth?.user.legacyMemberNo ?? userId,
});
}),
selectPoolGeneral: engineAuthedProcedure
.input(
z.object({
uniqueName: z.string().min(1).max(20),
personality: z.string().min(1),
clientRequestId: z.string().uuid().optional(),
})
)
.mutation(async ({ ctx, input }) => {
const auth = ctx.auth;
if (!auth) {
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
const userId = auth.user.id;
if (auth.identity?.canCreateGeneral === false) {
throw new TRPCError({
code: 'FORBIDDEN',
message: '이 서버에서는 카카오 인증을 완료해야 장수를 생성할 수 있습니다.',
});
}
const commandRequestId = resolveSelectionRequestId(
ctx.requestId,
userId,
input.clientRequestId,
'create'
);
const result = await ctx.turnDaemon.requestCommand({
type: 'selectPoolCreate',
...(commandRequestId ? { requestId: commandRequestId } : {}),
userId,
ownerDisplayName: auth.user.displayName,
uniqueName: input.uniqueName,
personality: input.personality,
seedOwnerIdentity: auth.user.legacyMemberNo ?? userId,
});
return resolveSelectionCommandResult(result, 'selectPoolCreate');
}),
reselectPoolGeneral: engineAuthedProcedure
.input(
z.object({
uniqueName: z.string().min(1).max(20),
clientRequestId: z.string().uuid().optional(),
})
)
.mutation(async ({ ctx, input }) => {
const auth = ctx.auth;
if (!auth) {
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
const userId = auth.user.id;
const commandRequestId = resolveSelectionRequestId(
ctx.requestId,
userId,
input.clientRequestId,
'reselect'
);
const result = await ctx.turnDaemon.requestCommand({
type: 'selectPoolReselect',
...(commandRequestId ? { requestId: commandRequestId } : {}),
userId,
ownerDisplayName: auth.user.displayName,
uniqueName: input.uniqueName,
});
return resolveSelectionCommandResult(result, 'selectPoolReselect');
}),
createGeneral: authedProcedure
.input(
z.object({
@@ -287,6 +442,13 @@ export const joinRouter = router({
message: 'World state is not initialized.',
});
}
const selectionPool = await getSelectionPoolStatus(ctx.db, worldState, userId);
if (selectionPool.enabled) {
throw new TRPCError({
code: 'PRECONDITION_FAILED',
message: '장수 선택 목록에서 장수를 골라 주세요.',
});
}
const joinPolicy = resolveJoinPolicy(worldState);
if (joinPolicy.blockGeneralCreate === 1) {
+4 -1
View File
@@ -1,6 +1,7 @@
import { TRPCError } from '@trpc/server';
import { zWorldStateConfig, zWorldStateMeta } from '../../context.js';
import { isSelectionPoolWorld } from '../../services/selectPool.js';
import { procedure, router } from '../../trpc.js';
export const lobbyRouter = router({
@@ -27,12 +28,13 @@ export const lobbyRouter = router({
if (ctx.auth?.user.id) {
const general = await ctx.db.general.findFirst({
where: { userId: ctx.auth.user.id },
select: { name: true, picture: true },
select: { name: true, picture: true, imageServer: true },
});
if (general) {
myGeneral = {
name: general.name,
picture: general.picture,
imageServer: general.imageServer,
};
}
}
@@ -51,6 +53,7 @@ export const lobbyRouter = router({
turntime: worldState.meta.turntime ?? '',
otherTextInfo: worldState.meta.otherTextInfo ?? '',
isUnited: worldState.meta.isUnited ?? 0,
selectionPoolEnabled: isSelectionPoolWorld(rawWorldState),
myGeneral,
};
}),
+13
View File
@@ -5,11 +5,14 @@ import { asNumber, asRecord } from '@sammo-ts/common';
import {
createIncomeActionContext,
DomesticTraitLoader,
EventDomesticTraitLoader,
isDomesticTraitKey,
isEventDomesticTraitKey,
isNationTraitKey,
isPersonalityTraitKey,
isWarTraitKey,
loadDomesticTraitModules,
loadEventDomesticTraitModules,
loadNationTraitModules,
loadPersonalityTraitModules,
loadWarTraitModules,
@@ -301,12 +304,22 @@ export const loadTraitNames = async (keys: Array<string | null>, kind: keyof Tra
if (kind === 'domestic') {
const filtered = missing.filter((key) => isDomesticTraitKey(key));
const eventFiltered = missing.filter((key) => isEventDomesticTraitKey(key));
if (filtered.length) {
const modules = await loadDomesticTraitModules(filtered, new DomesticTraitLoader());
for (const module of modules) {
cache.set(module.key, { name: module.name, info: module.info ?? '' });
}
}
if (eventFiltered.length) {
const modules = await loadEventDomesticTraitModules(
eventFiltered,
new EventDomesticTraitLoader()
);
for (const module of modules) {
cache.set(module.key, { name: module.name, info: module.info ?? '' });
}
}
} else if (kind === 'war') {
const filtered = missing.filter((key) => isWarTraitKey(key));
if (filtered.length) {
+12
View File
@@ -0,0 +1,12 @@
export {
buildSelectPoolSeed,
claimWeightedSelectionCandidates,
getSelectionPoolStatus,
isSelectionPoolWorld,
reserveSelectionPool,
resolveSelectionMaxGeneral,
SelectPoolError,
type SelectPoolCandidateDto,
type SelectPoolCandidateInfo,
type SelectPoolReservationDto,
} from '@sammo-ts/game-engine';
+5
View File
@@ -71,6 +71,11 @@ export const router = t.router;
export const procedure = t.procedure.use(inputEventMiddleware);
export const authedProcedure: typeof procedure = procedure.use(requireAuthMiddleware);
// 턴 데몬이 ENGINE input_event와 world/DB 변경을 자체 transaction으로
// 커밋하는 mutation에 사용한다. API input-event transaction으로 한 번 더
// 감싸면 daemon이 아직 commit되지 않은 command를 볼 수 없어 교착된다.
export const engineAuthedProcedure: typeof procedure = t.procedure.use(requireAuthMiddleware);
// 페이지 조회 계측처럼 game state/input-event 원장과 무관한 세션 보조
// mutation에 사용한다. gameplay state 변경에는 사용하지 않는다.
export const sessionActivityProcedure = t.procedure;