feat: make general creation daemon-atomic

This commit is contained in:
2026-07-31 00:33:03 +00:00
parent 115218ded8
commit c6a2a0da93
34 changed files with 2227 additions and 655 deletions
+3 -41
View File
@@ -1,6 +1,6 @@
import { randomUUID } from 'node:crypto';
import type { GameSessionTokenPayload } from '@sammo-ts/common/auth/gameToken';
import { parseGameSessionTokenPayload, type GameSessionTokenPayload } from '@sammo-ts/common/auth/gameToken';
import { isValid, parseISO } from 'date-fns';
interface RedisClientLike {
@@ -10,49 +10,11 @@ interface RedisClientLike {
const ACCESS_TOKEN_PREFIX = 'ga_';
const buildAccessKey = (profileName: string, token: string): string =>
`sammo:game:access:${profileName}:${token}`;
const buildAccessKey = (profileName: string, token: string): string => `sammo:game:access:${profileName}:${token}`;
const buildGatewayUsedKey = (profileName: string, sessionId: string): string =>
`sammo:game:gateway-used:${profileName}:${sessionId}`;
const parsePayload = (value: unknown): GameSessionTokenPayload | null => {
if (!value || typeof value !== 'object') {
return null;
}
const payload = value as Partial<GameSessionTokenPayload>;
if (payload.version !== 1) {
return null;
}
if (typeof payload.profile !== 'string') {
return null;
}
if (typeof payload.issuedAt !== 'string' || typeof payload.expiresAt !== 'string') {
return null;
}
if (typeof payload.sessionId !== 'string') {
return null;
}
if (!payload.user || typeof payload.user !== 'object') {
return null;
}
const user = payload.user as Partial<GameSessionTokenPayload['user']>;
if (
typeof user.id !== 'string' ||
typeof user.username !== 'string' ||
typeof user.displayName !== 'string' ||
!Array.isArray(user.roles) ||
(user.legacyMemberNo !== undefined &&
(!Number.isSafeInteger(user.legacyMemberNo) || user.legacyMemberNo <= 0))
) {
return null;
}
if (!payload.sanctions || typeof payload.sanctions !== 'object') {
return null;
}
return payload as GameSessionTokenPayload;
};
const resolveTtlSeconds = (expiresAt: string): number => {
const parsed = parseISO(expiresAt);
if (!isValid(parsed)) {
@@ -96,7 +58,7 @@ export class RedisAccessTokenStore {
return null;
}
try {
const payload = parsePayload(JSON.parse(raw));
const payload = parseGameSessionTokenPayload(JSON.parse(raw));
if (!payload) {
return null;
}
+125 -457
View File
@@ -1,36 +1,24 @@
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { randomBytes } from 'node:crypto';
import type { DatabaseClient, GameApiContext, WorldStateRow } from '../../context.js';
import type { GameApiContext, WorldStateRow } from '../../context.js';
import { authedProcedure, engineAuthedProcedure, router } from '../../trpc.js';
import { asNumber, asRecord, asStringArray, LiteHashDRBG } from '@sammo-ts/common';
import { asNumber, asRecord, asStringArray } from '@sammo-ts/common';
import {
isPersonalityTraitKey,
isWarTraitKey,
JOIN_PERSONALITY_TRAIT_KEYS,
loadPersonalityTraitModules,
loadWarTraitModules,
PersonalityTraitLoader,
PERSONALITY_TRAIT_KEYS,
WarTraitLoader,
WAR_TRAIT_KEYS,
} from '@sammo-ts/logic';
import {
appendInheritanceLog,
readInheritancePoint,
resolveInheritConstants,
setInheritancePoint,
} from '../../services/inheritance.js';
import {
getSelectionPoolStatus,
reserveSelectionPool,
resolveSelectionMaxGeneral,
} from '../../services/selectPool.js';
import { readInheritancePoint, resolveInheritConstants } from '../../services/inheritance.js';
import { getSelectionPoolStatus, reserveSelectionPool, resolveSelectionMaxGeneral } from '../../services/selectPool.js';
import { ConflictingTurnDaemonCommandError } from '../../daemon/databaseTransport.js';
const resolveSelectionCommandResult = (
result:
| Awaited<ReturnType<GameApiContext['turnDaemon']['requestCommand']>>
| null,
result: Awaited<ReturnType<GameApiContext['turnDaemon']['requestCommand']>> | null,
expectedType: 'selectPoolCreate' | 'selectPoolReselect'
): { ok: true; generalId: number } => {
if (!result) {
@@ -67,13 +55,66 @@ const resolveSelectionRequestId = (
if (!contextRequestId) {
return undefined;
}
const path =
operation === 'create'
? 'join.selectPoolGeneral'
: 'join.reselectPoolGeneral';
const path = operation === 'create' ? 'join.selectPoolGeneral' : 'join.reselectPoolGeneral';
return `${contextRequestId}:${path}`;
};
const resolveJoinCreateCommandResult = (
result: Awaited<ReturnType<GameApiContext['turnDaemon']['requestCommand']>> | null
): { ok: true; generalId: number } => {
if (!result) {
throw new TRPCError({
code: 'TIMEOUT',
message:
'장수 생성 요청은 접수됐지만 처리 결과를 아직 확인하지 못했습니다. 같은 요청으로 다시 시도해 주세요.',
});
}
if (result.type !== 'joinCreateGeneral') {
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 resolveJoinCreateRequestId = (
contextRequestId: string | undefined,
userId: string,
clientRequestId: string | undefined
): string | undefined => {
if (clientRequestId) {
return `join-create:${userId}:${clientRequestId}`;
}
return contextRequestId ? `${contextRequestId}:join.createGeneral` : undefined;
};
const requestJoinCreateCommand = async (
ctx: GameApiContext,
command: Parameters<GameApiContext['turnDaemon']['requestCommand']>[0]
) => {
try {
return await ctx.turnDaemon.requestCommand(command);
} catch (error) {
if (
error instanceof ConflictingTurnDaemonCommandError ||
(error instanceof Error && error.name === 'ConflictingTurnDaemonCommandError')
) {
throw new TRPCError({
code: 'CONFLICT',
message: '이미 접수된 장수 생성 요청과 입력이 다릅니다. 새 요청 번호로 다시 시도해 주세요.',
});
}
throw error;
}
};
const DEFAULT_JOIN_STAT = {
total: 165,
min: 15,
@@ -82,12 +123,8 @@ const DEFAULT_JOIN_STAT = {
bonusMax: 5,
};
const buildSpecialityAge = (
retirementYear: number,
age: number,
relativeYear: number,
divisor: number
): number => Math.max(Math.round((retirementYear - age) / divisor - relativeYear / 2), 3) + age;
const buildSpecialityAge = (retirementYear: number, age: number, relativeYear: number, divisor: number): number =>
Math.max(Math.round((retirementYear - age) / divisor - relativeYear / 2), 3) + age;
export const resolveJoinSpecialityAges = (options: {
retirementYear: number;
@@ -116,90 +153,30 @@ const resolveJoinStat = (worldState: WorldStateRow) => {
};
};
const resolveJoinPolicy = (worldState: WorldStateRow) => {
const config = asRecord(worldState.config);
const joinMode = typeof config.joinMode === 'string' ? config.joinMode : 'full';
const blockGeneralCreate =
typeof config.blockGeneralCreate === 'number' && Number.isFinite(config.blockGeneralCreate)
? Math.floor(config.blockGeneralCreate)
: 0;
return { joinMode, blockGeneralCreate };
};
const hashString = (value: string): number => {
let hash = 0;
for (let i = 0; i < value.length; i += 1) {
hash = (hash * 31 + value.charCodeAt(i)) >>> 0;
}
return hash;
};
const pickFromList = (values: string[], seed: string): string | null => {
if (!values.length) {
return null;
}
const index = hashString(seed) % values.length;
return values[index] ?? null;
};
const buildTurnTimeZones = (tickMinutes: number): string[] => {
const buildTurnTimeZones = (tickSeconds: number): string[] => {
const zones: string[] = [];
const legacyZoneSeconds = Math.max(1, Math.floor(tickSeconds / 60));
for (let i = 0; i < 60; i += 1) {
const totalMinutes = i * tickMinutes;
const hour = Math.floor(totalMinutes / 60) % 24;
const minute = totalMinutes % 60;
zones.push(`${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`);
const startSeconds = i * legacyZoneSeconds;
const endSeconds = startSeconds + legacyZoneSeconds - 1;
const format = (totalSeconds: number, fraction: string): string =>
`${String(Math.floor(totalSeconds / 60)).padStart(2, '0')}:${String(totalSeconds % 60).padStart(
2,
'0'
)}.${fraction}`;
zones.push(`${format(startSeconds, '000')} ~ ${format(endSeconds, '999')}`);
}
return zones;
};
const alignToTurnBase = (time: Date, tickMinutes: number): Date => {
const base = new Date(time.getFullYear(), time.getMonth(), time.getDate() - 1, 1, 0, 0, 0);
const elapsedMinutes = Math.floor((time.getTime() - base.getTime()) / 60000);
const alignedMinutes = elapsedMinutes - (elapsedMinutes % tickMinutes);
return new Date(base.getTime() + alignedMinutes * 60000);
};
const nextRangeInt = (rng: LiteHashDRBG, minInclusive: number, maxInclusive: number): number => {
if (maxInclusive <= minInclusive) {
return minInclusive;
}
return minInclusive + rng.nextInt(maxInclusive - minInclusive);
};
const pickWeightedIndex = (rng: LiteHashDRBG, weights: number[]): number => {
const total = weights.reduce((acc, value) => acc + value, 0);
if (total <= 0) {
return 0;
}
let cursor = rng.nextFloat1() * total;
for (let i = 0; i < weights.length; i += 1) {
cursor -= weights[i] ?? 0;
if (cursor <= 0) {
return i;
}
}
return weights.length - 1;
};
const buildRandomBonus = (rng: LiteHashDRBG, baseStats: [number, number, number]): [number, number, number] => {
const count = rng.nextInt(2) + 3;
const bonus: [number, number, number] = [0, 0, 0];
for (let i = 0; i < count; i += 1) {
const index = pickWeightedIndex(rng, baseStats);
bonus[index] += 1;
}
return bonus;
};
let cachedPersonalityOptions: Array<{ key: string; name: string; info: string }> | null = null;
const zJoinPersonality = z.enum(['Random', ...JOIN_PERSONALITY_TRAIT_KEYS]);
const loadPersonalityOptions = async () => {
if (cachedPersonalityOptions) {
return cachedPersonalityOptions;
}
const modules = await loadPersonalityTraitModules([...PERSONALITY_TRAIT_KEYS], new PersonalityTraitLoader());
const modules = await loadPersonalityTraitModules([...JOIN_PERSONALITY_TRAIT_KEYS], new PersonalityTraitLoader());
cachedPersonalityOptions = modules.map((trait) => ({
key: trait.key,
name: trait.name,
@@ -233,8 +210,7 @@ export const joinRouter = router({
const availableSpecialWar = asStringArray(configConst.availableSpecialWar);
const warKeys = availableSpecialWar.length > 0 ? availableSpecialWar : [...WAR_TRAIT_KEYS];
const [personalities, warSpecials, nationRows, userGeneralCount, npcGeneralCount] =
await Promise.all([
const [personalities, warSpecials, nationRows, userGeneralCount, npcGeneralCount] = await Promise.all([
loadPersonalityOptions(),
loadWarOptions(warKeys),
ctx.db.nation.findMany({
@@ -265,40 +241,24 @@ 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 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 },
const inheritCities = await ctx.db.city.findMany({
select: { id: true, name: true, level: true, region: true },
orderBy: { id: 'asc' },
});
const inheritCities =
inheritCitiesRaw.length > 0
? inheritCitiesRaw
: await ctx.db.city.findMany({
where: { level: { in: [5, 6] } },
select: { id: true, name: true, level: true, region: true },
orderBy: { id: 'asc' },
});
return {
rules: {
stat: resolveJoinStat(worldState),
allowCustomName: true,
allowCustomName: (Math.floor(asNumber(config.blockGeneralCreate, 0)) & 2) === 0,
},
user: {
id: ctx.auth?.user.id ?? '',
displayName: ctx.auth?.user.displayName ?? '',
},
personalities: [
{ key: 'Random', name: '???', info: '무작위 성격을 선택합니다.' },
...personalities,
],
personalities: [{ key: 'Random', name: '???', info: '무작위 성격을 선택합니다.' }, ...personalities],
warSpecials,
nations,
serverInfo: {
@@ -318,7 +278,7 @@ export const joinRouter = router({
inheritBornStatPoint: inheritConst.inheritBornStatPoint,
},
availableCities: inheritCities,
turnTimeZones: buildTurnTimeZones(tickMinutes),
turnTimeZones: buildTurnTimeZones(worldState.tickSeconds),
availableSpecialWar: warSpecials,
},
selectionPool,
@@ -363,12 +323,7 @@ export const joinRouter = router({
message: '이 서버에서는 카카오 인증을 완료해야 장수를 생성할 수 있습니다.',
});
}
const commandRequestId = resolveSelectionRequestId(
ctx.requestId,
userId,
input.clientRequestId,
'create'
);
const commandRequestId = resolveSelectionRequestId(ctx.requestId, userId, input.clientRequestId, 'create');
const result = await ctx.turnDaemon.requestCommand({
type: 'selectPoolCreate',
...(commandRequestId ? { requestId: commandRequestId } : {}),
@@ -408,15 +363,16 @@ export const joinRouter = router({
});
return resolveSelectionCommandResult(result, 'selectPoolReselect');
}),
createGeneral: authedProcedure
createGeneral: engineAuthedProcedure
.input(
z.object({
name: z.string().min(1).max(18),
leadership: z.number().int(),
strength: z.number().int(),
intel: z.number().int(),
pic: z.boolean().optional(),
character: z.string(),
pic: z.boolean(),
character: zJoinPersonality,
clientRequestId: z.string().uuid().optional(),
inheritSpecial: z.string().optional(),
inheritTurntimeZone: z.number().int().optional(),
inheritCity: z.number().int().optional(),
@@ -424,337 +380,49 @@ export const joinRouter = router({
})
)
.mutation(async ({ ctx, input }) => {
const userId = ctx.auth?.user.id;
if (!userId) {
const auth = ctx.auth;
if (!auth) {
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
if (ctx.auth?.identity?.canCreateGeneral === false) {
if (auth.identity?.canCreateGeneral === false) {
throw new TRPCError({
code: 'FORBIDDEN',
message: '이 서버에서는 카카오 인증을 완료해야 장수를 생성할 수 있습니다.',
});
}
const worldState = await ctx.db.worldState.findFirst();
if (!worldState) {
throw new TRPCError({
code: 'PRECONDITION_FAILED',
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) {
throw new TRPCError({
code: 'FORBIDDEN',
message: '장수 생성이 제한된 서버입니다.',
});
}
const inheritConst = resolveInheritConstants(worldState);
const configConst = asRecord(asRecord(worldState.config).const);
const availableSpecialWar = asStringArray(configConst.availableSpecialWar);
const inheritBonus = input.inheritBonusStat ?? null;
if (inheritBonus) {
const bonusSum = inheritBonus.reduce((acc, value) => acc + value, 0);
if (inheritBonus.some((value) => value < 0)) {
throw new TRPCError({
code: 'BAD_REQUEST',
message: '보너스 능력치가 음수입니다. 다시 가입해주세요!',
});
}
if (bonusSum !== 0 && (bonusSum < 3 || bonusSum > 5)) {
throw new TRPCError({
code: 'BAD_REQUEST',
message: '보너스 능력치 합이 잘못 지정되었습니다. 다시 가입해주세요!',
});
}
}
if (input.inheritSpecial !== undefined) {
if (!isWarTraitKey(input.inheritSpecial)) {
throw new TRPCError({
code: 'BAD_REQUEST',
message: '전투 특기가 잘못 지정되었습니다.',
});
}
if (availableSpecialWar.length > 0 && !availableSpecialWar.includes(input.inheritSpecial)) {
throw new TRPCError({
code: 'BAD_REQUEST',
message: '허용되지 않은 전투 특기입니다.',
});
}
}
if (input.inheritTurntimeZone !== undefined) {
if (input.inheritTurntimeZone < 0 || input.inheritTurntimeZone > 59) {
throw new TRPCError({
code: 'BAD_REQUEST',
message: '턴 시간 지정 범위가 올바르지 않습니다.',
});
}
}
const statRule = resolveJoinStat(worldState);
const statTotal = input.leadership + input.strength + input.intel;
if (
input.leadership < statRule.min ||
input.strength < statRule.min ||
input.intel < statRule.min ||
input.leadership > statRule.max ||
input.strength > statRule.max ||
input.intel > statRule.max
) {
throw new TRPCError({
code: 'BAD_REQUEST',
message: '능력치 범위를 벗어났습니다.',
});
}
if (statTotal > statRule.total) {
throw new TRPCError({
code: 'BAD_REQUEST',
message: `능력치 합이 ${statRule.total}을 초과했습니다.`,
});
}
const personalityOptions = await loadPersonalityOptions();
const personalityKeys = personalityOptions.map((trait) => trait.key);
const resolveGeneralName = async (): Promise<string> => {
if (joinPolicy.blockGeneralCreate !== 2) {
return input.name;
}
for (let attempt = 0; attempt < 5; attempt += 1) {
const candidate = randomBytes(5).toString('hex');
const exists = await ctx.db.general.findFirst({ where: { name: candidate } });
if (!exists) {
return candidate;
}
}
throw new TRPCError({
code: 'INTERNAL_SERVER_ERROR',
message: '랜덤 장수명 생성에 실패했습니다.',
});
};
const generalName = await resolveGeneralName();
const chosenPersonality =
input.character === 'Random'
? pickFromList(personalityKeys, `${userId}:${generalName}`) ?? 'None'
: isPersonalityTraitKey(input.character)
? input.character
: 'None';
const createGeneral = async (db: DatabaseClient) => {
const existing = await db.general.findFirst({ where: { userId } });
if (existing) {
throw new TRPCError({
code: 'PRECONDITION_FAILED',
message: '이미 장수가 생성되어 있습니다.',
});
}
const nameExists = await db.general.findFirst({ where: { name: generalName } });
if (nameExists) {
throw new TRPCError({
code: 'CONFLICT',
message: '이미 존재하는 장수명입니다.',
});
}
const maxId = await db.general.aggregate({ _max: { id: true } });
const nextId = (maxId._max.id ?? 0) + 1;
const cityList = await db.city.findMany({
select: { id: true, level: true, nationId: true, name: true },
orderBy: { id: 'asc' },
});
if (!cityList.length) {
throw new TRPCError({
code: 'PRECONDITION_FAILED',
message: '도시 정보를 찾을 수 없습니다.',
});
}
const neutralCities = cityList.filter((city) => city.level >= 5 && city.level <= 6 && city.nationId === 0);
const candidateCities =
neutralCities.length > 0 ? neutralCities : cityList.filter((city) => city.level >= 5 && city.level <= 6);
if (!candidateCities.length) {
throw new TRPCError({
code: 'PRECONDITION_FAILED',
message: '생성 가능한 도시가 없습니다.',
});
}
let inheritRequiredPoint = 0;
if (input.inheritCity !== undefined) {
inheritRequiredPoint += inheritConst.inheritBornCityPoint;
}
if (input.inheritSpecial !== undefined) {
inheritRequiredPoint += inheritConst.inheritBornSpecialPoint;
}
if (input.inheritTurntimeZone !== undefined) {
inheritRequiredPoint += inheritConst.inheritBornTurntimePoint;
}
if (inheritBonus && inheritBonus.reduce((acc, value) => acc + value, 0) > 0) {
inheritRequiredPoint += inheritConst.inheritBornStatPoint;
}
const currentPoint = await readInheritancePoint(db, userId, 'previous');
if (currentPoint < inheritRequiredPoint) {
throw new TRPCError({
code: 'BAD_REQUEST',
message: '유산 포인트가 부족합니다.',
});
}
const hiddenSeed = String(asRecord(worldState.meta).hiddenSeed ?? 'inherit');
const rng = new LiteHashDRBG(`${hiddenSeed}:MakeGeneral:${userId}:${generalName}`);
const bonusStatSum = inheritBonus ? inheritBonus.reduce((acc, value) => acc + value, 0) : 0;
const randomBonus =
!inheritBonus || bonusStatSum === 0
? buildRandomBonus(
rng,
[input.leadership, input.strength, input.intel]
)
: (inheritBonus as [number, number, number]);
const finalLeadership = input.leadership + randomBonus[0];
const finalStrength = input.strength + randomBonus[1];
const finalIntel = input.intel + randomBonus[2];
const age = 20 + (randomBonus[0] + randomBonus[1] + randomBonus[2]) * 2 - nextRangeInt(rng, 0, 1);
const selectedCity =
typeof input.inheritCity === 'number'
? candidateCities.find((city) => city.id === input.inheritCity)
: null;
if (input.inheritCity !== undefined && !selectedCity) {
throw new TRPCError({
code: 'BAD_REQUEST',
message: '지정한 도시를 찾을 수 없습니다.',
});
}
const cityIndex = nextRangeInt(rng, 0, candidateCities.length - 1);
const cityId = (selectedCity ?? candidateCities[cityIndex] ?? candidateCities[0]).id;
const defaultSpecialDomestic =
typeof configConst.defaultSpecialDomestic === 'string' ? configConst.defaultSpecialDomestic : 'None';
const defaultSpecialWar =
typeof configConst.defaultSpecialWar === 'string' ? configConst.defaultSpecialWar : 'None';
const retirementYear =
typeof configConst.retirementYear === 'number' && Number.isFinite(configConst.retirementYear)
? configConst.retirementYear
: 80;
const worldMeta = asRecord(worldState.meta);
const scenarioMeta = asRecord(worldMeta.scenarioMeta);
const startYear =
typeof scenarioMeta.startYear === 'number' && Number.isFinite(scenarioMeta.startYear)
? scenarioMeta.startYear
: worldState.currentYear;
const relativeYear = Math.max(
worldState.currentYear - startYear,
0
);
const scenarioId = Number(worldMeta.scenarioId ?? worldState.scenarioCode);
const specialityAges = resolveJoinSpecialityAges({
retirementYear,
age,
relativeYear,
scenarioId,
});
const specialWar =
input.inheritSpecial && isWarTraitKey(input.inheritSpecial) ? input.inheritSpecial : defaultSpecialWar;
const tickMinutes = Math.max(1, Math.round(worldState.tickSeconds / 60));
const baseTime = alignToTurnBase(new Date(), tickMinutes);
let turnTime = new Date(baseTime.getTime() + rng.nextFloat1() * tickMinutes * 60000);
if (input.inheritTurntimeZone !== undefined) {
const offsetMinutes = input.inheritTurntimeZone * tickMinutes + rng.nextFloat1() * tickMinutes;
turnTime = new Date(baseTime.getTime() + offsetMinutes * 60000);
}
if (turnTime.getTime() <= Date.now()) {
turnTime = new Date(turnTime.getTime() + tickMinutes * 60000);
}
const logEntries: string[] = [];
if (input.inheritSpecial && isWarTraitKey(input.inheritSpecial)) {
const [special] = await loadWarOptions([input.inheritSpecial]);
const specialName = special?.name ?? input.inheritSpecial;
logEntries.push(`${specialName} 전투 특기를 가진 천재 생성`);
}
if (input.inheritCity !== undefined && selectedCity) {
logEntries.push(`${selectedCity.name}에 장수 생성`);
}
if (inheritBonus && inheritBonus.reduce((acc, value) => acc + value, 0) > 0) {
logEntries.push(
`${inheritBonus[0]}, ${inheritBonus[1]}, ${inheritBonus[2]} 보너스 능력치로 생성`
);
}
if (input.inheritTurntimeZone !== undefined) {
const zones = buildTurnTimeZones(tickMinutes);
const zoneLabel = zones[input.inheritTurntimeZone];
if (zoneLabel) {
logEntries.push(`턴 시간 ${zoneLabel} 로 지정`);
}
}
const general = await db.general.create({
data: {
id: nextId,
userId,
name: generalName,
nationId: 0,
cityId,
troopId: 0,
npcState: 0,
leadership: finalLeadership,
strength: finalStrength,
intel: finalIntel,
personalCode: chosenPersonality ?? 'None',
specialCode: defaultSpecialDomestic,
special2Code: specialWar,
turnTime,
age,
startAge: age,
meta: {
createdBy: 'join',
ownerName: ctx.auth?.user.displayName ?? '',
killturn: 24,
specage: specialityAges.domestic,
specage2: specialityAges.war,
},
},
});
await db.generalAccessLog.upsert({
where: { generalId: general.id },
update: {
userId,
lastRefresh: new Date(),
},
create: {
generalId: general.id,
userId,
lastRefresh: new Date(),
},
});
if (inheritRequiredPoint > 0) {
await setInheritancePoint(db, userId, 'previous', currentPoint - inheritRequiredPoint);
}
for (const entry of logEntries) {
await appendInheritanceLog(db, userId, worldState.currentYear, worldState.currentMonth, entry);
}
return { ok: true, generalId: general.id };
};
return ctx.db.$transaction ? ctx.db.$transaction(createGeneral) : createGeneral(ctx.db);
const userId = auth.user.id;
const commandRequestId = resolveJoinCreateRequestId(ctx.requestId, userId, input.clientRequestId);
const result = await requestJoinCreateCommand(ctx, {
type: 'joinCreateGeneral',
...(commandRequestId ? { requestId: commandRequestId } : {}),
userId,
ownerDisplayName: auth.user.displayName,
seedOwnerIdentity: auth.user.legacyMemberNo ?? userId,
name: input.name,
leadership: input.leadership,
strength: input.strength,
intel: input.intel,
pic: input.pic,
character: input.character,
profileId: ctx.profile.id,
...(auth.user.picture !== undefined ? { ownerPicture: auth.user.picture } : {}),
...(auth.user.imageServer !== undefined ? { ownerImageServer: auth.user.imageServer } : {}),
...(auth.user.canUseGeneralPicture !== undefined
? {
ownerCanUsePicture: auth.user.canUseGeneralPicture,
}
: {}),
...(auth.sanctions.legacyPenalty !== undefined
? {
ownerLegacyPenalty: auth.sanctions.legacyPenalty,
}
: {}),
...(input.inheritSpecial !== undefined ? { inheritSpecial: input.inheritSpecial } : {}),
...(input.inheritTurntimeZone !== undefined ? { inheritTurntimeZone: input.inheritTurntimeZone } : {}),
...(input.inheritCity !== undefined ? { inheritCity: input.inheritCity } : {}),
...(input.inheritBonusStat !== undefined ? { inheritBonusStat: input.inheritBonusStat } : {}),
});
return resolveJoinCreateCommandResult(result);
}),
listPossessCandidates: authedProcedure
.input(
@@ -0,0 +1,508 @@
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.CREATE_GENERAL_DATABASE_URL;
const integration = describe.skipIf(!databaseUrl);
const profile = 'hwe:2';
const userId = 'create-general-integration-user';
const failureUserId = 'create-general-integration-failure-user';
const rejectedUserId = 'create-general-integration-rejected-user';
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('create_general_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 buildAuth = (id: string, displayName: string, legacyMemberNo: number): GameSessionTokenPayload => ({
version: 1,
profile,
issuedAt: '2026-07-30T00:00:00.000Z',
expiresAt: '2026-08-30T00:00:00.000Z',
sessionId: `create-general-${id}`,
user: {
id,
username: id,
displayName,
roles: ['user'],
legacyMemberNo,
picture: 'custom-owner.webp',
imageServer: 2,
canUseGeneralPicture: true,
},
sanctions: {
legacyPenalty: {
any: {
ban: { expire: 4_102_444_800, value: 1 },
expired: { expire: 1, value: 9 },
},
hwe: {
ban: { expire: 4_102_444_800, value: 2 },
chat: { expire: 4_102_444_800, value: 3 },
},
},
},
});
integration('generic general creation 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;
const buildContext = (requestId: string, auth: GameSessionTokenPayload): 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: '2', name: profile },
uploadDir: 'uploads',
uploadPath: '/uploads',
uploadPublicUrl: null,
auth,
accessTokenStore: new RedisAccessTokenStore(redisClient, profile),
flushStore: new InMemoryFlushStore(),
gameTokenSecret: 'create-general-test-secret',
};
};
const stopRuntime = async (reason: string): Promise<void> => {
if (!runtime) {
return;
}
await runtime.lifecycle.stop(reason);
await daemonLoop;
await runtime.close();
runtime = undefined;
daemonLoop = undefined;
};
const startRuntime = async (ownerId: string): Promise<void> => {
runtime = await createTurnDaemonRuntime({
profile,
databaseUrl: databaseUrl!,
enableDatabaseFlush: true,
enableLeaseHeartbeat: false,
leaseOwnerId: ownerId,
});
turnDaemon = new DatabaseTurnDaemonTransport(db, 10_000);
daemonLoop = runtime.lifecycle.start();
await expect(turnDaemon.requestStatus(10_000)).resolves.toMatchObject({
state: expect.any(String),
});
};
beforeAll(async () => {
assertDedicatedDatabase(databaseUrl!);
const previousSeed = process.env.INTEGRATION_WORLD_SEED;
process.env.INTEGRATION_WORLD_SEED = 'create-general-integration-seed';
try {
await seedScenarioToDatabase({
scenarioId: 2,
databaseUrl: databaseUrl!,
now: new Date('2099-07-30T12:00:00.000Z'),
installOptions: {
turnTermMinutes: 5,
npcMode: 0,
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();
await db.inheritanceLog.deleteMany({
where: { userId: { in: [userId, failureUserId] } },
});
await db.oldGeneral.deleteMany({
where: { serverId: { startsWith: 'create-general-old-' } },
});
await db.gameHistory.deleteMany({
where: { serverId: { startsWith: 'create-general-old-' } },
});
await db.gameHistory.createMany({
data: [1, 2, 3, 4].map((index) => ({
serverId: `create-general-old-${index}`,
date: new Date(`2026-0${5 - index}-01T00:00:00.000Z`),
winnerNation: 1,
map: 'miniche_b',
season: 1,
scenario: 2,
scenarioName: '통합 과거기',
env: {},
})),
});
await db.oldGeneral.create({
data: {
serverId: 'create-general-old-4',
generalNo: 1,
owner: userId,
name: '과거장수',
lastYearMonth: 18001,
turnTime: new Date('2026-01-01T00:00:00.000Z'),
data: {},
},
});
for (const ownerUserId of [userId, failureUserId]) {
await db.inheritancePoint.upsert({
where: {
userId_key: { userId: ownerUserId, key: 'previous' },
},
update: { value: 10_000 },
create: {
userId: ownerUserId,
key: 'previous',
value: 10_000,
},
});
}
for (const [key, value] of [
['active_action', 250.9],
['combat', 100.8],
] as const) {
await db.inheritancePoint.upsert({
where: { userId_key: { userId, key } },
update: { value },
create: { userId, key, value },
});
}
await startRuntime('create-general-integration-daemon');
}, 60_000);
afterAll(async () => {
await stopRuntime('create-general integration complete');
await closeDb?.();
}, 30_000);
it('commits one complete ref-shaped general and survives a daemon reload', async () => {
const auth = buildAuth(userId, '생성사용자', 4242);
const config = await appRouter.createCaller(buildContext('create-general-config', auth)).join.getConfig();
expect(config.personalities.map(({ key }) => key)).not.toContain('che_은둔');
expect(config.inherit.turnTimeZones[1]).toBe('00:05.000 ~ 00:09.999');
const city = await db.city.findFirstOrThrow({ orderBy: { id: 'asc' } });
const clientRequestId = '11111111-1111-4111-8111-111111111111';
const input = {
name: '일/반-장수#',
leadership: 55,
strength: 55,
intel: 55,
pic: true,
character: 'che_안전' as const,
clientRequestId,
inheritTurntimeZone: 7,
inheritCity: city.id,
inheritBonusStat: [2, 1, 1] as [number, number, number],
};
const first = await appRouter
.createCaller(buildContext('create-general-http-a', auth))
.join.createGeneral(input);
const retried = await appRouter
.createCaller(buildContext('create-general-http-b', auth))
.join.createGeneral(input);
expect(retried).toEqual(first);
const created = await db.general.findUniqueOrThrow({
where: { id: first.generalId },
});
expect(created).toMatchObject({
userId,
name: '일반장수',
nationId: 0,
cityId: city.id,
npcState: 0,
leadership: 57,
strength: 56,
intel: 56,
bornYear: 180,
deadYear: 300,
picture: 'custom-owner.webp',
imageServer: 2,
crewTypeId: 1100,
personalCode: 'che_안전',
penalty: {
ban: 2,
chat: 3,
},
});
expect(created.affinity).toBeGreaterThanOrEqual(1);
expect(created.affinity).toBeLessThanOrEqual(150);
expect(created.meta).toMatchObject({
createdBy: 'join',
ownerName: '생성사용자',
killturn: 6,
inherit_spent_dyn: 4500,
});
expect(runtime!.world.getGeneralById(created.id)).toMatchObject({
id: created.id,
userId,
name: created.name,
cityId: city.id,
inheritancePoints: {
previous: 7351,
},
});
expect(await db.general.count({ where: { userId } })).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.rankData.findUniqueOrThrow({
where: {
generalId_type: {
generalId: created.id,
type: 'inherit_spent_dyn',
},
},
})
).toMatchObject({ nationId: 0, value: 4500 });
const access = await db.generalAccessLog.findUniqueOrThrow({
where: { generalId: created.id },
});
expect(access).toMatchObject({ userId });
expect(
await db.inheritancePoint.findUniqueOrThrow({
where: { userId_key: { userId, key: 'previous' } },
})
).toMatchObject({ value: 7351 });
expect(await db.inheritancePoint.count({ where: { userId } })).toBe(1);
expect(await db.inheritanceLog.count({ where: { userId } })).toBe(9);
expect(
await db.inheritanceLog.findFirst({
where: {
userId,
text: '신규/복귀 생성으로 포인트 1500 지급',
},
})
).not.toBeNull();
const event = await db.inputEvent.findUniqueOrThrow({
where: { requestId: `join-create:${userId}:${clientRequestId}` },
});
expect(event).toMatchObject({
target: 'ENGINE',
status: 'SUCCEEDED',
attempts: 1,
actorUserId: userId,
});
expect(access.lastRefresh?.getTime()).toBe(event.createdAt.getTime());
const turnGridOffsetSeconds =
((created.turnTime.getTime() - runtime!.world.getState().lastTurnTime.getTime()) / 1000 + 300) % 300;
expect(turnGridOffsetSeconds).toBeGreaterThanOrEqual(35);
expect(turnGridOffsetSeconds).toBeLessThan(40);
await stopRuntime('verify generic join reload');
await startRuntime('create-general-integration-reloaded-daemon');
expect(runtime!.world.getGeneralById(created.id)).toMatchObject({
id: created.id,
userId,
name: created.name,
cityId: city.id,
inheritancePoints: {
previous: 7351,
},
});
await expect(
appRouter.createCaller(buildContext('create-general-conflict', auth)).join.createGeneral({
...input,
name: '다른장수',
})
).rejects.toMatchObject({ code: 'CONFLICT' });
expect(await db.general.count({ where: { userId } })).toBe(1);
}, 45_000);
it('rejects an unaffordable inheritance before consuming allocator state', async () => {
const auth = buildAuth(rejectedUserId, '거절사용자', 4444);
const requestUuid = '33333333-3333-4333-8333-333333333333';
const requestId = `join-create:${rejectedUserId}:${requestUuid}`;
const runtimeMetaBefore = runtime!.world.getState().meta;
const persistedMetaBefore = (await db.worldState.findFirstOrThrow()).meta;
await expect(
appRouter.createCaller(buildContext('create-general-rejected-http', auth)).join.createGeneral({
name: '포인트부족',
leadership: 55,
strength: 55,
intel: 55,
pic: false,
character: 'che_안전',
inheritSpecial: 'che_무쌍',
clientRequestId: requestUuid,
})
).rejects.toMatchObject({
code: 'BAD_REQUEST',
message: '유산 포인트가 부족합니다. 다시 가입해주세요!',
});
expect(await db.general.count({ where: { userId: rejectedUserId } })).toBe(0);
expect(runtime!.world.getState().meta).toEqual(runtimeMetaBefore);
expect((await db.worldState.findFirstOrThrow()).meta).toEqual(persistedMetaBefore);
await expect(db.inputEvent.findUniqueOrThrow({ where: { requestId } })).resolves.toMatchObject({
target: 'ENGINE',
status: 'SUCCEEDED',
attempts: 1,
actorUserId: rejectedUserId,
result: {
type: 'joinCreateGeneral',
ok: false,
code: 'BAD_REQUEST',
},
});
}, 30_000);
it('rolls back a hard failure and retries the ENGINE event exactly once', async () => {
const auth = buildAuth(failureUserId, '실패사용자', 4343);
const requestUuid = '22222222-2222-4222-8222-222222222222';
const requestId = `join-create:${failureUserId}:${requestUuid}`;
const triggerName = 'create_general_fail_first_log';
const functionName = 'create_general_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 generic join 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('create-general-failure-http', auth)).join.createGeneral({
name: '재시장수',
leadership: 55,
strength: 55,
intel: 55,
pic: false,
character: 'Random',
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.rankData.count({ where: { generalId: created.id } })).toBe(RANK_DATA_TYPES.length);
await expect(db.inputEvent.findUniqueOrThrow({ where: { requestId } })).resolves.toMatchObject({
status: 'SUCCEEDED',
attempts: 2,
actorUserId: failureUserId,
error: null,
});
}, 45_000);
it('rejects a forged ENGINE event whose actor does not own the command', async () => {
const requestId = 'join-create:forged-owner:forged-request';
await db.inputEvent.create({
data: {
requestId,
target: 'ENGINE',
eventType: 'joinCreateGeneral',
actorUserId: 'different-actor',
payload: {
type: 'joinCreateGeneral',
requestId,
userId: 'forged-owner',
ownerDisplayName: '위조사용자',
seedOwnerIdentity: 4545,
name: '위조장수',
leadership: 55,
strength: 55,
intel: 55,
pic: false,
character: 'che_안전',
profileId: 'hwe',
} as GamePrisma.InputJsonValue,
},
});
const deadline = Date.now() + 5_000;
let event = await db.inputEvent.findUniqueOrThrow({
where: { requestId },
});
while (event.status !== 'FAILED' && Date.now() < deadline) {
await new Promise((resolve) => setTimeout(resolve, 25));
event = await db.inputEvent.findUniqueOrThrow({
where: { requestId },
});
}
expect(event).toMatchObject({
status: 'FAILED',
actorUserId: 'different-actor',
attempts: 3,
error: expect.stringContaining('actor does not match'),
});
expect(await db.general.count({ where: { userId: 'forged-owner' } })).toBe(0);
expect(runtime!.world.listGenerals()).not.toEqual(
expect.arrayContaining([expect.objectContaining({ userId: 'forged-owner' })])
);
}, 10_000);
});
+4 -3
View File
@@ -281,9 +281,9 @@ describe('appRouter', () => {
});
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: null })).auth.status()).rejects.toMatchObject({
code: 'UNAUTHORIZED',
});
await expect(
appRouter
.createCaller(
@@ -346,6 +346,7 @@ describe('appRouter', () => {
leadership: 55,
strength: 55,
intel: 55,
pic: false,
character: 'Random',
})
).rejects.toMatchObject({
@@ -2,11 +2,7 @@ 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 { createTurnDaemonRuntime, seedScenarioToDatabase, type TurnDaemonRuntime } from '@sammo-ts/game-engine';
import {
createGamePostgresConnector,
type GamePrisma,
@@ -29,7 +25,7 @@ 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 schemaName = databaseUrl ? (new URL(databaseUrl).searchParams.get('schema') ?? '') : '';
const assertDedicatedDatabase = (rawUrl: string): void => {
const schema = new URL(rawUrl).searchParams.get('schema');
@@ -97,10 +93,7 @@ integration('scenario 903 select pool through the durable turn daemon', () => {
let turnDaemon: TurnDaemonTransport;
let worldStateId: number;
const buildContext = (
requestId: string,
actorAuth: GameSessionTokenPayload = auth
): GameApiContext => {
const buildContext = (requestId: string, actorAuth: GameSessionTokenPayload = auth): GameApiContext => {
const redisClient = {
get: async () => null,
set: async () => null,
@@ -257,12 +250,8 @@ integration('scenario 903 select pool through the durable turn daemon', () => {
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(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(
@@ -293,9 +282,7 @@ integration('scenario 903 select pool through the durable turn daemon', () => {
const reselection = await appRouter
.createCaller(buildContext('select-pool-reserve-reselection'))
.join.getSelectionPool();
const target = reselection.candidates.find(
(candidate) => candidate.generalName !== initial.name
)!;
const target = reselection.candidates.find((candidate) => candidate.generalName !== initial.name)!;
await expect(
appRouter
.createCaller(buildContext('select-pool-reselect'))
@@ -328,9 +315,11 @@ integration('scenario 903 select pool through the durable turn daemon', () => {
},
});
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.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 } },
@@ -345,9 +334,7 @@ integration('scenario 903 select pool through the durable turn daemon', () => {
patch: { meta: { postReselectionFlush: 1 } },
})
).resolves.toMatchObject({ type: 'patchGeneral', ok: true });
await expect(
db.general.findUniqueOrThrow({ where: { id: initial.id } })
).resolves.toMatchObject({
await expect(db.general.findUniqueOrThrow({ where: { id: initial.id } })).resolves.toMatchObject({
name: target.generalName,
leadership: target.leadership,
strength: target.strength,
@@ -376,23 +363,19 @@ integration('scenario 903 select pool through the durable turn daemon', () => {
.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,
})
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_안전',
})
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({
@@ -408,12 +391,10 @@ integration('scenario 903 select pool through the durable turn daemon', () => {
const candidate = reservation.candidates[0]!;
await expect(
appRouter
.createCaller(buildContext('select-pool-foreign-token', foreignAuth))
.join.selectPoolGeneral({
uniqueName: candidate.uniqueName,
personality: 'che_안전',
})
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);
@@ -422,25 +403,22 @@ integration('scenario 903 select pool through the durable turn daemon', () => {
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_안전',
})
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_안전',
})
appRouter.createCaller(buildContext('select-pool-generic-bypass', otherAuth)).join.createGeneral({
name: '우회장수',
leadership: 55,
strength: 55,
intel: 55,
pic: false,
character: 'che_안전',
})
).rejects.toMatchObject({ message: '장수 선택 목록에서 장수를 골라 주세요.' });
const input = {
@@ -453,24 +431,19 @@ integration('scenario 903 select pool through the durable turn daemon', () => {
});
const runtimeAllocatorBefore = runtime!.world.getState().meta.lastGeneralId;
const persistedAllocatorBefore = (
(await db.worldState.findUniqueOrThrow({ where: { id: worldStateId } }))
.meta as Record<string, unknown>
(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',
})
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
((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);
@@ -534,21 +507,15 @@ integration('scenario 903 select pool through the durable turn daemon', () => {
try {
await expect(
appRouter
.createCaller(buildContext('select-pool-failure-http', failureAuth))
.join.selectPoolGeneral({
uniqueName: candidate.uniqueName,
personality: 'che_안전',
clientRequestId: requestUuid,
})
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}"()`
);
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 } });
@@ -560,9 +527,7 @@ integration('scenario 903 select pool through the durable turn daemon', () => {
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.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(
@@ -570,9 +535,7 @@ integration('scenario 903 select pool through the durable turn daemon', () => {
where: { meta: { path: ['ownerUserId'], equals: failureUserId } },
})
).toBe(2);
await expect(
db.inputEvent.findUniqueOrThrow({ where: { requestId } })
).resolves.toMatchObject({
await expect(db.inputEvent.findUniqueOrThrow({ where: { requestId } })).resolves.toMatchObject({
status: 'SUCCEEDED',
attempts: 2,
actorUserId: failureUserId,