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
+1
View File
@@ -34,6 +34,7 @@
"@fastify/cors": "^11.2.0",
"@fastify/static": "^9.0.0",
"@sammo-ts/common": "workspace:*",
"@sammo-ts/game-engine": "workspace:*",
"@sammo-ts/infra": "workspace:*",
"@sammo-ts/logic": "workspace:*",
"@trpc/server": "^11.8.1",
+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;
@@ -300,6 +300,16 @@ describe('battle sim processor', () => {
expect(strong.killed).toBeGreaterThan(baseline.killed ?? 0);
});
it('applies the event-domestic trait carried by an imported general', () => {
const baseline = processBattleSimJob(buildPayload('battle'));
const payload = buildPayload('battle');
payload.attackerGeneral.special = 'che_event_무쌍';
const eventDomestic = processBattleSimJob(payload);
expect(eventDomestic.killed).toBeGreaterThan(baseline.killed ?? 0);
expect(eventDomestic).not.toEqual(baseline);
});
it('keeps StrongAttacker city combat identical but applies MoreEffect to it', () => {
const baselinePayload = buildPayload('battle');
baselinePayload.defenderGenerals = [];
@@ -427,6 +427,7 @@ describe('battle simulator general import permissions', () => {
bookCode: null,
itemCode: null,
personalCode: null,
specialCode: null,
special2Code: null,
meta: {},
...overrides,
@@ -447,6 +448,7 @@ describe('battle simulator general import permissions', () => {
weaponCode: 'che_의천검',
bookCode: 'che_손자병법',
itemCode: 'che_옥새',
specialCode: 'che_event_신산',
meta: {
dex1: 10000,
rank_warnum: 33,
@@ -483,6 +485,7 @@ describe('battle simulator general import permissions', () => {
warnum: 33,
killnum: 22,
killcrew: 1111,
special: 'che_event_신산',
});
const redacted = await foreign.battle.getGeneralDetail({ generalId: ally.id });
@@ -499,6 +502,7 @@ describe('battle simulator general import permissions', () => {
warnum: 0,
killnum: 0,
killcrew: 0,
special: 'che_event_신산',
});
});
@@ -2,7 +2,11 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { createGamePostgresConnector, type GamePrismaClient } from '@sammo-ts/infra';
import { DuplicateInputEventError, executeInputEvent } from '../src/inputEventBoundary.js';
import { ConflictingTurnDaemonCommandError, DatabaseTurnDaemonTransport } from '../src/daemon/databaseTransport.js';
import {
ConflictingTurnDaemonCommandError,
DatabaseTurnDaemonTransport,
FailedTurnDaemonCommandError,
} from '../src/daemon/databaseTransport.js';
const databaseUrl = process.env.INPUT_EVENT_DATABASE_URL;
const integration = describe.skipIf(!databaseUrl);
@@ -144,4 +148,25 @@ integration('API input event boundary', () => {
ConflictingTurnDaemonCommandError
);
});
it('distinguishes a stored terminal engine failure from a result timeout', async () => {
const transport = new DatabaseTurnDaemonTransport(db, 100);
const requestId = 'integration:api:engine-failed';
const command = { type: 'vacation' as const, requestId, generalId: 7 };
await transport.sendCommand(command);
await db.inputEvent.update({
where: { requestId },
data: {
status: 'FAILED',
error: 'injected terminal engine failure',
completedAt: new Date(),
},
});
await expect(transport.requestCommand(command)).rejects.toMatchObject({
name: FailedTurnDaemonCommandError.name,
requestId,
storedError: 'injected terminal engine failure',
});
});
});
+23
View File
@@ -274,6 +274,29 @@ describe('appRouter', () => {
});
});
it('reports the authenticated game access-token identity', async () => {
const caller = appRouter.createCaller(buildContext({ auth: buildAuth() }));
await expect(caller.auth.status()).resolves.toEqual({ userId: 'user-1' });
});
it('rejects unauthenticated or game-blocked auth status checks', async () => {
await expect(
appRouter.createCaller(buildContext({ auth: null })).auth.status()
).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
await expect(
appRouter
.createCaller(
buildContext({
auth: buildAuth({
suspendedUntil: '2099-01-01T00:00:00.000Z',
}),
})
)
.auth.status()
).rejects.toMatchObject({ code: 'FORBIDDEN' });
});
it('does not apply an expired or message-only restriction to other game APIs', async () => {
const caller = appRouter.createCaller(
buildContext({
@@ -0,0 +1,582 @@
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { RANK_DATA_TYPES } from '@sammo-ts/common';
import type { GameSessionTokenPayload } from '@sammo-ts/common/auth/gameToken';
import {
createTurnDaemonRuntime,
seedScenarioToDatabase,
type TurnDaemonRuntime,
} from '@sammo-ts/game-engine';
import {
createGamePostgresConnector,
type GamePrisma,
type GamePrismaClient,
type RedisConnector,
} from '@sammo-ts/infra';
import { RedisAccessTokenStore } from '../src/auth/accessTokenStore.js';
import { InMemoryFlushStore } from '../src/auth/flushStore.js';
import { InMemoryBattleSimTransport } from '../src/battleSim/inMemoryTransport.js';
import type { GameApiContext } from '../src/context.js';
import { DatabaseTurnDaemonTransport } from '../src/daemon/databaseTransport.js';
import type { TurnDaemonTransport } from '../src/daemon/transport.js';
import { appRouter } from '../src/router.js';
const databaseUrl = process.env.SELECT_POOL_DATABASE_URL;
const integration = describe.skipIf(!databaseUrl);
const userId = 'select-pool-integration-user';
const otherUserId = 'select-pool-integration-other-user';
const foreignUserId = 'select-pool-integration-foreign-user';
const failureUserId = 'select-pool-integration-failure-user';
const profile = 'hwe:903';
const schemaName = databaseUrl ? new URL(databaseUrl).searchParams.get('schema') ?? '' : '';
const assertDedicatedDatabase = (rawUrl: string): void => {
const schema = new URL(rawUrl).searchParams.get('schema');
if (!schema?.endsWith('select_pool_integration')) {
throw new Error(`Refusing to mutate non-dedicated schema: ${schema ?? '(missing)'}`);
}
if (!/^[a-z0-9_]+$/.test(schema)) {
throw new Error(`Refusing unsafe schema name: ${schema}`);
}
};
const auth: GameSessionTokenPayload = {
version: 1,
profile,
issuedAt: '2026-07-30T00:00:00.000Z',
expiresAt: '2026-08-30T00:00:00.000Z',
sessionId: 'select-pool-integration-session',
user: {
id: userId,
username: 'select-pool-user',
displayName: '선택사용자',
roles: ['user'],
},
sanctions: {},
};
const otherAuth: GameSessionTokenPayload = {
...auth,
sessionId: 'select-pool-integration-other-session',
user: {
...auth.user,
id: otherUserId,
username: 'select-pool-other',
displayName: '다른사용자',
},
};
const foreignAuth: GameSessionTokenPayload = {
...auth,
sessionId: 'select-pool-integration-foreign-session',
user: {
...auth.user,
id: foreignUserId,
username: 'select-pool-foreign',
displayName: '외국사용자',
},
};
const failureAuth: GameSessionTokenPayload = {
...auth,
sessionId: 'select-pool-integration-failure-session',
user: {
...auth.user,
id: failureUserId,
username: 'select-pool-failure',
displayName: '실패사용자',
},
};
integration('scenario 903 select pool through the durable turn daemon', () => {
let db: GamePrismaClient;
let closeDb: (() => Promise<void>) | undefined;
let runtime: TurnDaemonRuntime | undefined;
let daemonLoop: Promise<void> | undefined;
let turnDaemon: TurnDaemonTransport;
let worldStateId: number;
const buildContext = (
requestId: string,
actorAuth: GameSessionTokenPayload = auth
): GameApiContext => {
const redisClient = {
get: async () => null,
set: async () => null,
};
return {
requestId,
db,
redis: redisClient as unknown as RedisConnector['client'],
turnDaemon,
battleSim: new InMemoryBattleSimTransport(),
profile: { id: 'hwe', scenario: '903', name: profile },
uploadDir: 'uploads',
uploadPath: '/uploads',
uploadPublicUrl: null,
auth: actorAuth,
accessTokenStore: new RedisAccessTokenStore(redisClient, profile),
flushStore: new InMemoryFlushStore(),
gameTokenSecret: 'select-pool-test-secret',
};
};
beforeAll(async () => {
assertDedicatedDatabase(databaseUrl!);
const previousSeed = process.env.INTEGRATION_WORLD_SEED;
process.env.INTEGRATION_WORLD_SEED = 'select-pool-integration-seed';
try {
await seedScenarioToDatabase({
scenarioId: 903,
databaseUrl: databaseUrl!,
now: new Date('2099-07-30T12:00:00.000Z'),
installOptions: {
turnTermMinutes: 5,
npcMode: 2,
showImgLevel: 3,
serverId: profile,
season: 1,
},
});
} finally {
if (previousSeed === undefined) {
delete process.env.INTEGRATION_WORLD_SEED;
} else {
process.env.INTEGRATION_WORLD_SEED = previousSeed;
}
}
const connector = createGamePostgresConnector({ url: databaseUrl! });
await connector.connect();
db = connector.prisma;
closeDb = () => connector.disconnect();
await db.inputEvent.deleteMany();
await db.logEntry.deleteMany();
worldStateId = (await db.worldState.findFirstOrThrow()).id;
runtime = await createTurnDaemonRuntime({
profile,
databaseUrl: databaseUrl!,
enableDatabaseFlush: true,
enableLeaseHeartbeat: false,
leaseOwnerId: 'select-pool-integration-daemon',
});
turnDaemon = new DatabaseTurnDaemonTransport(db, 10_000);
daemonLoop = runtime.lifecycle.start();
await expect(turnDaemon.requestStatus(10_000)).resolves.toMatchObject({
state: expect.any(String),
});
}, 60_000);
afterAll(async () => {
if (runtime) {
await runtime.lifecycle.stop('select-pool integration complete');
await daemonLoop;
await runtime.close();
}
await closeDb?.();
}, 30_000);
it('creates and reselects in one durable DB and in-memory command boundary', async () => {
await expect(
appRouter.createCaller(buildContext('select-pool-public-lobby')).lobby.info()
).resolves.toMatchObject({ selectionPoolEnabled: true });
await expect(
appRouter.createCaller(buildContext('select-pool-config')).join.getConfig()
).resolves.toMatchObject({
serverInfo: {
currentYear: 180,
currentMonth: 1,
tickMinutes: 5,
maxGeneral: 500,
},
});
const [firstReservation, concurrentReservation] = await Promise.all([
appRouter.createCaller(buildContext('select-pool-reserve-a')).join.getSelectionPool(),
appRouter.createCaller(buildContext('select-pool-reserve-b')).join.getSelectionPool(),
]);
expect(concurrentReservation).toEqual(firstReservation);
expect(firstReservation.candidates).toHaveLength(14);
expect(await db.selectPoolEntry.count({ where: { ownerUserId: userId } })).toBe(14);
const attempts = await Promise.allSettled([
appRouter.createCaller(buildContext('select-pool-create-a')).join.selectPoolGeneral({
uniqueName: firstReservation.candidates[0]!.uniqueName,
personality: 'che_안전',
}),
appRouter.createCaller(buildContext('select-pool-create-b')).join.selectPoolGeneral({
uniqueName: firstReservation.candidates[1]!.uniqueName,
personality: 'che_유지',
}),
]);
expect(attempts.filter((attempt) => attempt.status === 'fulfilled')).toHaveLength(1);
expect(attempts.filter((attempt) => attempt.status === 'rejected')).toHaveLength(1);
const initial = await db.general.findFirstOrThrow({ where: { userId } });
const initialRuntime = runtime!.world.getGeneralById(initial.id);
expect(initialRuntime).toMatchObject({
id: initial.id,
userId,
name: initial.name,
imageServer: initial.imageServer,
stats: {
leadership: initial.leadership,
strength: initial.strength,
intelligence: initial.intel,
},
});
expect(initial.id).toBeGreaterThan(
Math.max(
...runtime!.world
.listGenerals()
.filter((general) => general.id !== initial.id)
.map((general) => general.id)
)
);
expect(
await db.generalTurn.findMany({
where: { generalId: initial.id },
orderBy: { turnIdx: 'asc' },
select: { turnIdx: true, actionCode: true, arg: true },
})
).toEqual(
Array.from({ length: 30 }, (_, turnIdx) => ({
turnIdx,
actionCode: '휴식',
arg: {},
}))
);
await expect(
db.generalTurnRevision.findUniqueOrThrow({ where: { generalId: initial.id } })
).resolves.toMatchObject({ revision: 0, leaseOwner: null, leaseExpiresAt: null });
const initialRankRows = await db.rankData.findMany({
where: { generalId: initial.id },
orderBy: { type: 'asc' },
select: { nationId: true, type: true, value: true },
});
expect(initialRankRows).toHaveLength(RANK_DATA_TYPES.length);
expect(initialRankRows.map(({ type }) => type).sort()).toEqual(
[...RANK_DATA_TYPES].sort()
);
expect(initialRankRows.every(({ nationId, value }) => nationId === 0 && value === 0)).toBe(
true
);
expect(await db.selectPoolEntry.count({ where: { generalId: initial.id } })).toBe(1);
expect(await db.selectPoolEntry.count({ where: { ownerUserId: userId } })).toBe(0);
expect(
await db.logEntry.count({
where: { meta: { path: ['ownerUserId'], equals: userId } },
})
).toBe(2);
await expect(
appRouter.createCaller(buildContext('select-pool-cooldown')).join.getSelectionPool()
).rejects.toMatchObject({ message: '아직 다시 고를 수 없습니다' });
const cooledAt = '2026-07-29T00:00:00.000Z';
await expect(
turnDaemon.requestCommand({
type: 'patchGeneral',
requestId: 'select-pool-cooldown-patch',
generalId: initial.id,
patch: {
meta: {
next_change: cooledAt,
nextChangeAt: cooledAt,
},
},
})
).resolves.toMatchObject({ type: 'patchGeneral', ok: true, generalId: initial.id });
const reselection = await appRouter
.createCaller(buildContext('select-pool-reserve-reselection'))
.join.getSelectionPool();
const target = reselection.candidates.find(
(candidate) => candidate.generalName !== initial.name
)!;
await expect(
appRouter
.createCaller(buildContext('select-pool-reselect'))
.join.reselectPoolGeneral({ uniqueName: target.uniqueName })
).resolves.toEqual({ ok: true, generalId: initial.id });
const updated = await db.general.findUniqueOrThrow({ where: { id: initial.id } });
expect(updated).toMatchObject({
id: initial.id,
userId,
name: target.generalName,
leadership: target.leadership,
strength: target.strength,
intel: target.intel,
personalCode: initial.personalCode,
specialCode: target.specialDomestic,
imageServer: target.imageServer,
picture: target.picture,
});
expect(runtime!.world.getGeneralById(initial.id)).toMatchObject({
id: initial.id,
userId,
name: target.generalName,
imageServer: target.imageServer,
picture: target.picture,
stats: {
leadership: target.leadership,
strength: target.strength,
intelligence: target.intel,
},
});
expect(await db.selectPoolEntry.count({ where: { generalId: initial.id } })).toBe(1);
expect(
await db.selectPoolEntry.findUniqueOrThrow({ where: { uniqueName: target.uniqueName } })
).toMatchObject({ generalId: initial.id, ownerUserId: null, reservedUntil: null });
expect(
await db.logEntry.count({
where: { meta: { path: ['ownerUserId'], equals: userId } },
})
).toBe(4);
await expect(
turnDaemon.requestCommand({
type: 'patchGeneral',
requestId: 'select-pool-post-reselection-flush',
generalId: initial.id,
patch: { meta: { postReselectionFlush: 1 } },
})
).resolves.toMatchObject({ type: 'patchGeneral', ok: true });
await expect(
db.general.findUniqueOrThrow({ where: { id: initial.id } })
).resolves.toMatchObject({
name: target.generalName,
leadership: target.leadership,
strength: target.strength,
intel: target.intel,
});
const fullWorld = await db.worldState.findUniqueOrThrow({ where: { id: worldStateId } });
const fullConfig = fullWorld.config as Record<string, unknown>;
await db.worldState.update({
where: { id: worldStateId },
data: { config: { ...fullConfig, maxGeneral: 1 } as GamePrisma.InputJsonValue },
});
const secondCooledAt = '2026-07-28T00:00:00.000Z';
await turnDaemon.requestCommand({
type: 'patchGeneral',
requestId: 'select-pool-full-cooldown-patch',
generalId: initial.id,
patch: {
meta: {
next_change: secondCooledAt,
nextChangeAt: secondCooledAt,
},
},
});
const fullReselection = await appRouter
.createCaller(buildContext('select-pool-full-reselection-reserve'))
.join.getSelectionPool();
await expect(
appRouter
.createCaller(buildContext('select-pool-full-reselection'))
.join.reselectPoolGeneral({
uniqueName: fullReselection.candidates[0]!.uniqueName,
})
).resolves.toEqual({ ok: true, generalId: initial.id });
const otherReservation = await appRouter
.createCaller(buildContext('select-pool-full-new-user-reserve', otherAuth))
.join.getSelectionPool();
await expect(
appRouter
.createCaller(buildContext('select-pool-full-new-user-create', otherAuth))
.join.selectPoolGeneral({
uniqueName: otherReservation.candidates[0]!.uniqueName,
personality: 'che_안전',
})
).rejects.toMatchObject({ message: '더 이상 등록 할 수 없습니다.' });
expect(await db.general.count({ where: { userId: otherUserId } })).toBe(0);
await db.worldState.update({
where: { id: worldStateId },
data: { config: fullConfig as GamePrisma.InputJsonValue },
});
}, 30_000);
it('keeps a stable ENGINE event for retries and rejects reservation bypasses', async () => {
const reservation = await appRouter
.createCaller(buildContext('select-pool-other-reserve', otherAuth))
.join.getSelectionPool();
const candidate = reservation.candidates[0]!;
await expect(
appRouter
.createCaller(buildContext('select-pool-foreign-token', foreignAuth))
.join.selectPoolGeneral({
uniqueName: candidate.uniqueName,
personality: 'che_안전',
})
).rejects.toMatchObject({ message: '유효한 장수 목록이 없습니다.' });
expect(await db.general.count({ where: { userId: foreignUserId } })).toBe(0);
await db.selectPoolEntry.update({
where: { uniqueName: candidate.uniqueName },
data: { reservedUntil: new Date(Date.now() - 60_000) },
});
await expect(
appRouter
.createCaller(buildContext('select-pool-expired-token', otherAuth))
.join.selectPoolGeneral({
uniqueName: candidate.uniqueName,
personality: 'che_안전',
})
).rejects.toMatchObject({ message: '유효한 장수 목록이 없습니다.' });
expect(await db.general.count({ where: { userId: otherUserId } })).toBe(0);
await expect(
appRouter
.createCaller(buildContext('select-pool-generic-bypass', otherAuth))
.join.createGeneral({
name: '우회장수',
leadership: 55,
strength: 55,
intel: 55,
character: 'che_안전',
})
).rejects.toMatchObject({ message: '장수 선택 목록에서 장수를 골라 주세요.' });
const input = {
uniqueName: reservation.candidates[1]!.uniqueName,
personality: 'che_안전',
};
await db.selectPoolEntry.updateMany({
where: { ownerUserId: otherUserId, generalId: null },
data: { reservedUntil: new Date(Date.now() + 60_000) },
});
const runtimeAllocatorBefore = runtime!.world.getState().meta.lastGeneralId;
const persistedAllocatorBefore = (
(await db.worldState.findUniqueOrThrow({ where: { id: worldStateId } }))
.meta as Record<string, unknown>
).lastGeneralId;
await expect(
appRouter
.createCaller(buildContext('select-pool-invalid-personality', otherAuth))
.join.selectPoolGeneral({
...input,
personality: 'not-a-personality',
clientRequestId: '11111111-1111-4111-8111-111111111111',
})
).rejects.toMatchObject({ message: '올바르지 않은 성격입니다.' });
expect(runtime!.world.getState().meta.lastGeneralId).toBe(runtimeAllocatorBefore);
expect(
(
(await db.worldState.findUniqueOrThrow({ where: { id: worldStateId } }))
.meta as Record<string, unknown>
).lastGeneralId
).toBe(persistedAllocatorBefore);
expect(await db.general.count({ where: { userId: otherUserId } })).toBe(0);
const stableClientRequestId = '22222222-2222-4222-8222-222222222222';
const stableInput = { ...input, clientRequestId: stableClientRequestId };
const first = await appRouter
.createCaller(buildContext('select-pool-http-attempt-a', otherAuth))
.join.selectPoolGeneral(stableInput);
const retried = await appRouter
.createCaller(buildContext('select-pool-http-attempt-b', otherAuth))
.join.selectPoolGeneral(stableInput);
expect(retried).toEqual(first);
expect(await db.general.count({ where: { userId: otherUserId } })).toBe(1);
await expect(
db.inputEvent.findUniqueOrThrow({
where: {
requestId: `select-pool:${otherUserId}:${stableClientRequestId}:create`,
},
})
).resolves.toMatchObject({
status: 'SUCCEEDED',
attempts: 1,
actorUserId: otherUserId,
});
}, 30_000);
it('rolls back a hard failure and retries the same ENGINE event exactly once', async () => {
const reservation = await appRouter
.createCaller(buildContext('select-pool-failure-reserve', failureAuth))
.join.getSelectionPool();
const candidate = reservation.candidates[0]!;
const requestUuid = '33333333-3333-4333-8333-333333333333';
const requestId = `select-pool:${failureUserId}:${requestUuid}:create`;
const triggerName = 'select_pool_fail_first_log';
const functionName = 'select_pool_fail_first_log_fn';
await db.$executeRawUnsafe(`
CREATE OR REPLACE FUNCTION "${schemaName}"."${functionName}"()
RETURNS trigger AS $$
BEGIN
IF NEW.meta ->> 'ownerUserId' = '${failureUserId}'
AND EXISTS (
SELECT 1
FROM "${schemaName}"."input_event"
WHERE "request_id" = '${requestId}'
AND "status" = 'PROCESSING'
AND "attempts" = 1
)
THEN
RAISE EXCEPTION 'injected first selection log failure';
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql
`);
await db.$executeRawUnsafe(`
CREATE TRIGGER "${triggerName}"
BEFORE INSERT ON "${schemaName}"."log_entry"
FOR EACH ROW EXECUTE FUNCTION "${schemaName}"."${functionName}"()
`);
try {
await expect(
appRouter
.createCaller(buildContext('select-pool-failure-http', failureAuth))
.join.selectPoolGeneral({
uniqueName: candidate.uniqueName,
personality: 'che_안전',
clientRequestId: requestUuid,
})
).resolves.toMatchObject({ ok: true, generalId: expect.any(Number) });
} finally {
await db.$executeRawUnsafe(
`DROP TRIGGER IF EXISTS "${triggerName}" ON "${schemaName}"."log_entry"`
);
await db.$executeRawUnsafe(
`DROP FUNCTION IF EXISTS "${schemaName}"."${functionName}"()`
);
}
const created = await db.general.findFirstOrThrow({ where: { userId: failureUserId } });
expect(runtime!.world.getGeneralById(created.id)).toMatchObject({
id: created.id,
userId: failureUserId,
name: created.name,
});
expect(await db.general.count({ where: { userId: failureUserId } })).toBe(1);
expect(await db.generalTurn.count({ where: { generalId: created.id } })).toBe(30);
expect(await db.generalTurnRevision.count({ where: { generalId: created.id } })).toBe(1);
expect(await db.rankData.count({ where: { generalId: created.id } })).toBe(
RANK_DATA_TYPES.length
);
expect(await db.generalAccessLog.count({ where: { generalId: created.id } })).toBe(1);
expect(await db.selectPoolEntry.count({ where: { generalId: created.id } })).toBe(1);
expect(
await db.logEntry.count({
where: { meta: { path: ['ownerUserId'], equals: failureUserId } },
})
).toBe(2);
await expect(
db.inputEvent.findUniqueOrThrow({ where: { requestId } })
).resolves.toMatchObject({
status: 'SUCCEEDED',
attempts: 2,
actorUserId: failureUserId,
error: null,
});
}, 30_000);
});
+75
View File
@@ -0,0 +1,75 @@
import fs from 'node:fs/promises';
import path from 'node:path';
import { describe, expect, it } from 'vitest';
import { LiteHashDRBG, RandUtil } from '@sammo-ts/common';
import {
buildSelectPoolSeed,
claimWeightedSelectionCandidates,
} from '../src/services/selectPool.js';
interface PoolResource {
data: Array<
[
string,
number,
number,
number,
string,
[number, number, number, number, number],
0 | 1,
string,
]
>;
}
const loadWeightedRows = async (): Promise<Array<[{ id: number }, number]>> => {
const filePath = path.resolve(
import.meta.dirname,
'../../../resources/general-pool/SPoolUnderU30.json'
);
const resource = JSON.parse(await fs.readFile(filePath, 'utf8')) as PoolResource;
return resource.data.map((row, index) => [
{ id: index + 1 },
row[5].reduce((sum, value) => sum + value, 0),
]);
};
const drawVector = async (
hiddenSeed: string
): Promise<{ selected: number[]; draws: number[] }> => {
const weighted = await loadWeightedRows();
const now = new Date('2026-07-30T03:34:56.000Z');
const draws: number[] = [];
const selected = await claimWeightedSelectionCandidates({
weighted,
rng: new RandUtil(new LiteHashDRBG(buildSelectPoolSeed(hiddenSeed, 42, now))),
count: 14,
claim: async () => true,
onDraw: (candidate) => draws.push(candidate.id),
});
return { selected: selected.map((candidate) => candidate.id), draws };
};
describe('select pool Ref RNG parity', () => {
it('uses the legacy seed serialization and fixed UnderS30 draw vector', async () => {
const now = new Date('2026-07-30T03:34:56.000Z');
expect(buildSelectPoolSeed('vector-hidden', 42, now)).toBe(
'str(13,vector-hidden)|str(10,selectPool)|int(42)|str(19,2026-07-30 12:34:56)'
);
await expect(drawVector('vector-hidden')).resolves.toEqual({
selected: [72, 1283, 110, 1659, 608, 1408, 1543, 1573, 1096, 1081, 278, 1256, 872, 1369],
draws: [72, 1283, 110, 1659, 608, 1408, 1543, 1573, 1096, 1081, 278, 1256, 872, 1369],
});
});
it('consumes duplicate draws without removing the candidate from the weighted pool', async () => {
await expect(drawVector('vector-hidden-28')).resolves.toEqual({
selected: [314, 865, 1485, 1382, 110, 550, 27, 368, 399, 1298, 152, 39, 189, 760],
draws: [314, 865, 1485, 1382, 110, 550, 27, 368, 399, 1298, 27, 152, 39, 189, 760],
});
});
});
+10 -1
View File
@@ -11,6 +11,12 @@
"@sammo-ts/common/*": [
"../../packages/common/src/*"
],
"@sammo-ts/game-engine": [
"../../app/game-engine/src/index.ts"
],
"@sammo-ts/game-engine/*": [
"../../app/game-engine/src/*"
],
"@sammo-ts/infra": [
"../../packages/infra/src/index.ts"
],
@@ -39,6 +45,9 @@
},
{
"path": "../../packages/logic"
},
{
"path": "../game-engine"
}
]
}
}