feat: port NPC possession through turn daemon
This commit is contained in:
@@ -1,8 +1,7 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
|
||||
import type { GamePrisma } from '@sammo-ts/infra';
|
||||
import { GamePrisma, type DatabaseClient } from '@sammo-ts/infra';
|
||||
|
||||
import type { DatabaseClient } from '../context.js';
|
||||
import type { TurnDaemonTransport } from './transport.js';
|
||||
import type { TurnDaemonCommand, TurnDaemonCommandResult, TurnDaemonStatus } from './types.js';
|
||||
|
||||
@@ -39,6 +38,16 @@ export class FailedTurnDaemonCommandError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export class RejectedNpcPossessionCommandError extends Error {
|
||||
constructor(
|
||||
readonly code: 'PRECONDITION_FAILED',
|
||||
message: string
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'RejectedNpcPossessionCommandError';
|
||||
}
|
||||
}
|
||||
|
||||
export class DatabaseTurnDaemonTransport implements TurnDaemonTransport {
|
||||
constructor(
|
||||
private readonly db: DatabaseClient,
|
||||
@@ -48,20 +57,63 @@ export class DatabaseTurnDaemonTransport implements TurnDaemonTransport {
|
||||
async sendCommand(command: TurnDaemonCommand): Promise<string> {
|
||||
const requestId = ('requestId' in command ? command.requestId : undefined) ?? randomUUID();
|
||||
const durableCommand = JSON.parse(JSON.stringify({ ...command, requestId })) as TurnDaemonCommand;
|
||||
try {
|
||||
await this.db.inputEvent.create({
|
||||
data: {
|
||||
requestId,
|
||||
target: 'ENGINE',
|
||||
eventType: command.type,
|
||||
payload: asJson(durableCommand),
|
||||
actorUserId:
|
||||
'userId' in command && typeof command.userId === 'string'
|
||||
? command.userId
|
||||
: null,
|
||||
},
|
||||
if (command.type === 'npcPossessGeneral') {
|
||||
const existing = await this.db.inputEvent.findUnique({
|
||||
where: { requestId },
|
||||
select: { eventType: true, payload: true },
|
||||
});
|
||||
if (existing) {
|
||||
if (
|
||||
existing.eventType !== command.type ||
|
||||
stableJson(existing.payload) !== stableJson(durableCommand)
|
||||
) {
|
||||
throw new ConflictingTurnDaemonCommandError(requestId);
|
||||
}
|
||||
return requestId;
|
||||
}
|
||||
}
|
||||
try {
|
||||
if (command.type === 'npcPossessGeneral' && this.db.$transaction) {
|
||||
const rejectionReason = await this.db.$transaction(async (transaction) => {
|
||||
await transaction.$executeRaw(
|
||||
GamePrisma.sql`SELECT pg_advisory_xact_lock(hashtextextended('npc-possession', 1))`
|
||||
);
|
||||
await transaction.$executeRaw(
|
||||
GamePrisma.sql`SELECT pg_advisory_xact_lock(hashtextextended(${`npc-possession:${command.userId}`}, 1))`
|
||||
);
|
||||
const acceptedAt = new Date(Math.floor(Date.now() / 1000) * 1000);
|
||||
const token = await transaction.npcSelectionToken.findFirst({
|
||||
where: {
|
||||
ownerUserId: command.userId,
|
||||
nonce: command.tokenNonce,
|
||||
validUntil: { gte: acceptedAt },
|
||||
},
|
||||
select: { pickResult: true },
|
||||
});
|
||||
if (!token) {
|
||||
return '유효한 장수 목록이 없습니다.';
|
||||
}
|
||||
if (
|
||||
!token.pickResult ||
|
||||
typeof token.pickResult !== 'object' ||
|
||||
Array.isArray(token.pickResult) ||
|
||||
!Object.hasOwn(token.pickResult, String(command.generalId))
|
||||
) {
|
||||
return '선택한 장수가 목록에 없습니다.';
|
||||
}
|
||||
await this.createInputEvent(transaction, durableCommand, requestId, acceptedAt);
|
||||
return null;
|
||||
});
|
||||
if (rejectionReason) {
|
||||
throw new RejectedNpcPossessionCommandError('PRECONDITION_FAILED', rejectionReason);
|
||||
}
|
||||
} else {
|
||||
await this.createInputEvent(this.db, durableCommand, requestId);
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof RejectedNpcPossessionCommandError) {
|
||||
throw error;
|
||||
}
|
||||
const isUniqueConflict =
|
||||
typeof error === 'object' && error !== null && 'code' in error && error.code === 'P2002';
|
||||
if (!isUniqueConflict) {
|
||||
@@ -78,6 +130,24 @@ export class DatabaseTurnDaemonTransport implements TurnDaemonTransport {
|
||||
return requestId;
|
||||
}
|
||||
|
||||
private async createInputEvent(
|
||||
db: DatabaseClient,
|
||||
command: TurnDaemonCommand,
|
||||
requestId: string,
|
||||
createdAt?: Date
|
||||
): Promise<void> {
|
||||
await db.inputEvent.create({
|
||||
data: {
|
||||
requestId,
|
||||
target: 'ENGINE',
|
||||
eventType: command.type,
|
||||
payload: asJson(command),
|
||||
actorUserId: 'userId' in command && typeof command.userId === 'string' ? command.userId : null,
|
||||
...(createdAt ? { createdAt } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async requestCommand(command: TurnDaemonCommand, timeoutMs?: number): Promise<TurnDaemonCommandResult | null> {
|
||||
const requestId = await this.sendCommand(command);
|
||||
return this.waitForResult<TurnDaemonCommandResult>(requestId, timeoutMs);
|
||||
|
||||
@@ -15,7 +15,11 @@ import {
|
||||
} from '@sammo-ts/logic';
|
||||
import { readInheritancePoint, resolveInheritConstants } from '../../services/inheritance.js';
|
||||
import { getSelectionPoolStatus, reserveSelectionPool, resolveSelectionMaxGeneral } from '../../services/selectPool.js';
|
||||
import { ConflictingTurnDaemonCommandError } from '../../daemon/databaseTransport.js';
|
||||
import {
|
||||
ConflictingTurnDaemonCommandError,
|
||||
RejectedNpcPossessionCommandError,
|
||||
} from '../../daemon/databaseTransport.js';
|
||||
import { NpcPossessionError, reserveNpcPossessionCandidates } from '@sammo-ts/game-engine';
|
||||
|
||||
const resolveSelectionCommandResult = (
|
||||
result: Awaited<ReturnType<GameApiContext['turnDaemon']['requestCommand']>> | null,
|
||||
@@ -115,6 +119,71 @@ const requestJoinCreateCommand = async (
|
||||
}
|
||||
};
|
||||
|
||||
const resolveNpcPossessionCommandResult = (
|
||||
result: Awaited<ReturnType<GameApiContext['turnDaemon']['requestCommand']>> | null
|
||||
): { ok: true; generalId: number } => {
|
||||
if (!result) {
|
||||
throw new TRPCError({
|
||||
code: 'TIMEOUT',
|
||||
message:
|
||||
'NPC 빙의 요청은 접수됐지만 처리 결과를 아직 확인하지 못했습니다. 같은 요청으로 다시 시도해 주세요.',
|
||||
});
|
||||
}
|
||||
if (result.type !== 'npcPossessGeneral') {
|
||||
throw new TRPCError({
|
||||
code: 'INTERNAL_SERVER_ERROR',
|
||||
message: '턴 데몬이 올바르지 않은 NPC 빙의 결과를 반환했습니다.',
|
||||
});
|
||||
}
|
||||
if (!result.ok) {
|
||||
throw new TRPCError({
|
||||
code: result.code,
|
||||
message: result.reason,
|
||||
});
|
||||
}
|
||||
return { ok: true, generalId: result.generalId };
|
||||
};
|
||||
|
||||
const resolveNpcPossessionRequestId = (
|
||||
contextRequestId: string | undefined,
|
||||
userId: string,
|
||||
clientRequestId: string | undefined
|
||||
): string | undefined => {
|
||||
if (clientRequestId) {
|
||||
return `npc-possess:${userId}:${clientRequestId}`;
|
||||
}
|
||||
return contextRequestId ? `${contextRequestId}:join.possessGeneral` : undefined;
|
||||
};
|
||||
|
||||
const requestNpcPossessionCommand = async (
|
||||
ctx: GameApiContext,
|
||||
command: Parameters<GameApiContext['turnDaemon']['requestCommand']>[0]
|
||||
) => {
|
||||
try {
|
||||
return await ctx.turnDaemon.requestCommand(command);
|
||||
} catch (error) {
|
||||
if (
|
||||
error instanceof RejectedNpcPossessionCommandError ||
|
||||
(error instanceof Error && error.name === 'RejectedNpcPossessionCommandError')
|
||||
) {
|
||||
throw new TRPCError({
|
||||
code: 'PRECONDITION_FAILED',
|
||||
message: error.message,
|
||||
});
|
||||
}
|
||||
if (
|
||||
error instanceof ConflictingTurnDaemonCommandError ||
|
||||
(error instanceof Error && error.name === 'ConflictingTurnDaemonCommandError')
|
||||
) {
|
||||
throw new TRPCError({
|
||||
code: 'CONFLICT',
|
||||
message: '이미 접수된 NPC 빙의 요청과 입력이 다릅니다. 새 요청 번호로 다시 시도해 주세요.',
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
const DEFAULT_JOIN_STAT = {
|
||||
total: 165,
|
||||
min: 15,
|
||||
@@ -257,6 +326,7 @@ export const joinRouter = router({
|
||||
user: {
|
||||
id: ctx.auth?.user.id ?? '',
|
||||
displayName: ctx.auth?.user.displayName ?? '',
|
||||
canCreateGeneral: ctx.auth?.identity?.canCreateGeneral !== false,
|
||||
},
|
||||
personalities: [{ key: 'Random', name: '???', info: '무작위 성격을 선택합니다.' }, ...personalities],
|
||||
warSpecials,
|
||||
@@ -282,6 +352,9 @@ export const joinRouter = router({
|
||||
availableSpecialWar: warSpecials,
|
||||
},
|
||||
selectionPool,
|
||||
npcPossession: {
|
||||
enabled: asNumber(config.npcMode ?? config.npcmode, 0) === 1,
|
||||
},
|
||||
};
|
||||
}),
|
||||
getSelectionPool: authedProcedure.mutation(async ({ ctx }) => {
|
||||
@@ -427,155 +500,77 @@ export const joinRouter = router({
|
||||
listPossessCandidates: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
limit: z.number().int().min(1).max(50).optional(),
|
||||
offset: z.number().int().min(0).optional(),
|
||||
})
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const limit = input.limit ?? 20;
|
||||
const offset = input.offset ?? 0;
|
||||
|
||||
const candidates = await ctx.db.general.findMany({
|
||||
where: {
|
||||
userId: null,
|
||||
npcState: { gte: 2 },
|
||||
},
|
||||
orderBy: { id: 'asc' },
|
||||
skip: offset,
|
||||
take: limit,
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
npcState: true,
|
||||
nationId: true,
|
||||
cityId: true,
|
||||
leadership: true,
|
||||
strength: true,
|
||||
intel: true,
|
||||
age: true,
|
||||
officerLevel: true,
|
||||
personalCode: true,
|
||||
specialCode: true,
|
||||
special2Code: true,
|
||||
picture: true,
|
||||
imageServer: true,
|
||||
},
|
||||
});
|
||||
|
||||
const [nationRows, cityRows] = await Promise.all([
|
||||
ctx.db.nation.findMany({ select: { id: true, name: true, color: true } }),
|
||||
ctx.db.city.findMany({ select: { id: true, name: true } }),
|
||||
]);
|
||||
const nationMap = new Map(nationRows.map((nation) => [nation.id, nation]));
|
||||
const cityMap = new Map(cityRows.map((city) => [city.id, city]));
|
||||
|
||||
return candidates.map((candidate) => {
|
||||
const nation = nationMap.get(candidate.nationId);
|
||||
const city = cityMap.get(candidate.cityId);
|
||||
return {
|
||||
id: candidate.id,
|
||||
name: candidate.name,
|
||||
npcState: candidate.npcState,
|
||||
nation: nation
|
||||
? { id: nation.id, name: nation.name, color: nation.color }
|
||||
: { id: 0, name: '재야', color: '#666666' },
|
||||
city: city ? { id: city.id, name: city.name } : null,
|
||||
stats: {
|
||||
leadership: candidate.leadership,
|
||||
strength: candidate.strength,
|
||||
intelligence: candidate.intel,
|
||||
},
|
||||
age: candidate.age,
|
||||
officerLevel: candidate.officerLevel,
|
||||
personality: candidate.personalCode,
|
||||
special: candidate.specialCode,
|
||||
specialWar: candidate.special2Code,
|
||||
picture: candidate.picture,
|
||||
imageServer: candidate.imageServer,
|
||||
};
|
||||
});
|
||||
}),
|
||||
possessGeneral: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
generalId: z.number().int().positive(),
|
||||
refresh: z.boolean().optional(),
|
||||
keepIds: z.array(z.number().int().positive()).max(5).optional(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const userId = ctx.auth?.user.id;
|
||||
if (!userId) {
|
||||
const auth = ctx.auth;
|
||||
if (!auth) {
|
||||
throw new TRPCError({ code: 'UNAUTHORIZED' });
|
||||
}
|
||||
const existing = await ctx.db.general.findFirst({ where: { userId } });
|
||||
if (existing) {
|
||||
if (auth.identity?.canCreateGeneral === false) {
|
||||
throw new TRPCError({
|
||||
code: 'PRECONDITION_FAILED',
|
||||
message: '이미 장수가 생성되어 있습니다.',
|
||||
code: 'FORBIDDEN',
|
||||
message: '이 서버에서는 카카오 인증을 완료해야 장수를 생성할 수 있습니다.',
|
||||
});
|
||||
}
|
||||
|
||||
await ctx.db.$transaction!(async (db) => {
|
||||
const [candidate, worldState] = await Promise.all([
|
||||
db.general.findUnique({
|
||||
where: { id: input.generalId },
|
||||
select: { npcState: true, meta: true },
|
||||
}),
|
||||
db.worldState.findFirst({
|
||||
select: { currentYear: true, currentMonth: true },
|
||||
}),
|
||||
]);
|
||||
if (!candidate || candidate.npcState < 2 || !worldState) {
|
||||
throw new TRPCError({
|
||||
code: 'NOT_FOUND',
|
||||
message: '빙의 가능한 장수를 찾지 못했습니다.',
|
||||
});
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const updated = await db.general.updateMany({
|
||||
where: {
|
||||
id: input.generalId,
|
||||
userId: null,
|
||||
npcState: candidate.npcState,
|
||||
},
|
||||
data: {
|
||||
userId,
|
||||
npcState: 1,
|
||||
meta: {
|
||||
...asRecord(candidate.meta),
|
||||
npc_org: candidate.npcState,
|
||||
owner_name: ctx.auth?.user.displayName ?? '',
|
||||
pickYearMonth: worldState.currentYear * 12 + worldState.currentMonth - 1,
|
||||
killturn: 6,
|
||||
defence_train: 80,
|
||||
},
|
||||
updatedAt: now,
|
||||
},
|
||||
const worldState = await ctx.db.worldState.findFirst();
|
||||
if (!worldState) {
|
||||
throw new TRPCError({
|
||||
code: 'PRECONDITION_FAILED',
|
||||
message: 'World state is not initialized.',
|
||||
});
|
||||
if (updated.count === 0) {
|
||||
throw new TRPCError({
|
||||
code: 'NOT_FOUND',
|
||||
message: '빙의 가능한 장수를 찾지 못했습니다.',
|
||||
});
|
||||
}
|
||||
await db.generalAccessLog.upsert({
|
||||
where: { generalId: input.generalId },
|
||||
update: {
|
||||
userId,
|
||||
lastRefresh: now,
|
||||
refresh: 0,
|
||||
refreshTotal: 0,
|
||||
refreshScore: 0,
|
||||
refreshScoreTotal: 0,
|
||||
},
|
||||
create: {
|
||||
generalId: input.generalId,
|
||||
userId,
|
||||
lastRefresh: now,
|
||||
},
|
||||
}
|
||||
try {
|
||||
return await reserveNpcPossessionCandidates({
|
||||
db: ctx.db,
|
||||
worldState,
|
||||
userId: auth.user.id,
|
||||
ownerIdentity: auth.user.legacyMemberNo ?? auth.user.id,
|
||||
refresh: input.refresh,
|
||||
keepIds: input.keepIds,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof NpcPossessionError) {
|
||||
throw new TRPCError({ code: error.code, message: error.message });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}),
|
||||
possessGeneral: engineAuthedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
generalId: z.number().int().positive(),
|
||||
tokenNonce: z.number().int().nonnegative(),
|
||||
clientRequestId: z.string().uuid().optional(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const auth = ctx.auth;
|
||||
if (!auth) {
|
||||
throw new TRPCError({ code: 'UNAUTHORIZED' });
|
||||
}
|
||||
if (auth.identity?.canCreateGeneral === false) {
|
||||
throw new TRPCError({
|
||||
code: 'FORBIDDEN',
|
||||
message: '이 서버에서는 카카오 인증을 완료해야 장수를 생성할 수 있습니다.',
|
||||
});
|
||||
}
|
||||
const userId = auth.user.id;
|
||||
const commandRequestId = resolveNpcPossessionRequestId(ctx.requestId, userId, input.clientRequestId);
|
||||
const result = await requestNpcPossessionCommand(ctx, {
|
||||
type: 'npcPossessGeneral',
|
||||
...(commandRequestId ? { requestId: commandRequestId } : {}),
|
||||
userId,
|
||||
ownerDisplayName: auth.user.displayName,
|
||||
profileId: ctx.profile.id,
|
||||
...(auth.sanctions.legacyPenalty !== undefined
|
||||
? { ownerLegacyPenalty: auth.sanctions.legacyPenalty }
|
||||
: {}),
|
||||
generalId: input.generalId,
|
||||
tokenNonce: input.tokenNonce,
|
||||
});
|
||||
|
||||
return { ok: true };
|
||||
return resolveNpcPossessionCommandResult(result);
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { TRPCError } from '@trpc/server';
|
||||
|
||||
import { zWorldStateConfig, zWorldStateMeta } from '../../context.js';
|
||||
import { isSelectionPoolWorld } from '../../services/selectPool.js';
|
||||
import { isSelectionPoolWorld, resolveSelectionMaxGeneral } from '../../services/selectPool.js';
|
||||
import { procedure, router } from '../../trpc.js';
|
||||
|
||||
export const lobbyRouter = router({
|
||||
@@ -20,8 +20,8 @@ export const lobbyRouter = router({
|
||||
meta: zWorldStateMeta.parse(rawWorldState.meta),
|
||||
};
|
||||
|
||||
const userCnt = await ctx.db.general.count({ where: { npcState: 0 } });
|
||||
const npcCnt = await ctx.db.general.count({ where: { npcState: { gt: 0 } } });
|
||||
const userCnt = await ctx.db.general.count({ where: { npcState: { lt: 2 } } });
|
||||
const npcCnt = await ctx.db.general.count({ where: { npcState: { gte: 2 } } });
|
||||
const nationCnt = await ctx.db.nation.count({ where: { level: { gt: 0 } } });
|
||||
|
||||
let myGeneral = null;
|
||||
@@ -43,7 +43,7 @@ export const lobbyRouter = router({
|
||||
year: worldState.currentYear,
|
||||
month: worldState.currentMonth,
|
||||
userCnt,
|
||||
maxUserCnt: worldState.config.maxUserCnt ?? 500,
|
||||
maxUserCnt: resolveSelectionMaxGeneral(rawWorldState),
|
||||
npcCnt,
|
||||
nationCnt,
|
||||
turnTerm: worldState.tickSeconds / 60,
|
||||
@@ -54,6 +54,7 @@ export const lobbyRouter = router({
|
||||
otherTextInfo: worldState.meta.otherTextInfo ?? '',
|
||||
isUnited: worldState.meta.isUnited ?? 0,
|
||||
selectionPoolEnabled: isSelectionPoolWorld(rawWorldState),
|
||||
npcPossessionEnabled: worldState.config.npcMode === 1,
|
||||
myGeneral,
|
||||
};
|
||||
}),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { TRPCError } from '@trpc/server';
|
||||
import { asRecord } from '@sammo-ts/common';
|
||||
import { asNumber, asRecord } from '@sammo-ts/common';
|
||||
import { LogCategory, LogScope } from '@sammo-ts/infra';
|
||||
import { z } from 'zod';
|
||||
|
||||
@@ -173,6 +173,33 @@ const readFiniteMetaNumber = (meta: Record<string, unknown>, key: string): numbe
|
||||
return typeof value === 'number' && Number.isFinite(value) ? value : 0;
|
||||
};
|
||||
|
||||
const resolveExperienceLevel = (experience: number, maxLevel: number): number => {
|
||||
const level = experience < 1_000 ? Math.trunc(experience / 100) : Math.trunc(Math.sqrt(experience / 10));
|
||||
return Math.max(0, Math.min(level, maxLevel));
|
||||
};
|
||||
|
||||
const resolveHonorText = (experience: number): string => {
|
||||
if (experience < 640) return '전무';
|
||||
if (experience < 2_560) return '무명';
|
||||
if (experience < 5_760) return '신동';
|
||||
if (experience < 10_240) return '약간';
|
||||
if (experience < 16_000) return '평범';
|
||||
if (experience < 23_040) return '지역적';
|
||||
if (experience < 31_360) return '전국적';
|
||||
if (experience < 40_960) return '세계적';
|
||||
if (experience < 45_000) return '유명';
|
||||
if (experience < 51_840) return '명사';
|
||||
if (experience < 55_000) return '호걸';
|
||||
if (experience < 64_000) return '효웅';
|
||||
if (experience < 77_440) return '영웅';
|
||||
return '구세주';
|
||||
};
|
||||
|
||||
const resolveDedicationText = (dedication: number, maxLevel: number): string => {
|
||||
const level = Math.max(0, Math.min(Math.ceil(Math.sqrt(dedication) / 10), maxLevel));
|
||||
return level === 0 ? '무품관' : `${maxLevel - level + 1}품관`;
|
||||
};
|
||||
|
||||
const compareString = (left: string, right: string): number => {
|
||||
if (left === right) {
|
||||
return 0;
|
||||
@@ -180,16 +207,21 @@ const compareString = (left: string, right: string): number => {
|
||||
return left < right ? -1 : 1;
|
||||
};
|
||||
|
||||
const sortNpcList = <T extends {
|
||||
name: string;
|
||||
nationId: number;
|
||||
statTotal: number;
|
||||
leadership: number;
|
||||
strength: number;
|
||||
intelligence: number;
|
||||
experience: number;
|
||||
dedication: number;
|
||||
}>(rows: T[], sort: NpcListSort): T[] =>
|
||||
const sortNpcList = <
|
||||
T extends {
|
||||
name: string;
|
||||
nationId: number;
|
||||
statTotal: number;
|
||||
leadership: number;
|
||||
strength: number;
|
||||
intelligence: number;
|
||||
experience: number;
|
||||
dedication: number;
|
||||
},
|
||||
>(
|
||||
rows: T[],
|
||||
sort: NpcListSort
|
||||
): T[] =>
|
||||
rows.sort((left, right) => {
|
||||
switch (sort) {
|
||||
case 2:
|
||||
@@ -450,18 +482,28 @@ export const publicRouter = router({
|
||||
z
|
||||
.object({
|
||||
sort: z.number().int().min(1).max(8).catch(1).optional(),
|
||||
includeAllWithToken: z.boolean().optional(),
|
||||
})
|
||||
.optional()
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const sort = (input?.sort ?? 1) as NpcListSort;
|
||||
const [generals, nations] = await Promise.all([
|
||||
const includeAllWithToken = input?.includeAllWithToken === true;
|
||||
if (includeAllWithToken && !ctx.auth) {
|
||||
throw new TRPCError({ code: 'UNAUTHORIZED' });
|
||||
}
|
||||
const now = new Date(Math.floor(Date.now() / 1000) * 1000);
|
||||
const [generals, nations, activeTokens, worldState] = await Promise.all([
|
||||
ctx.db.general.findMany({
|
||||
where: { npcState: { gt: 0 } },
|
||||
...(includeAllWithToken ? {} : { where: { npcState: { gt: 0 } } }),
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
picture: true,
|
||||
imageServer: true,
|
||||
npcState: true,
|
||||
age: true,
|
||||
officerLevel: true,
|
||||
nationId: true,
|
||||
leadership: true,
|
||||
strength: true,
|
||||
@@ -476,8 +518,19 @@ export const publicRouter = router({
|
||||
orderBy: { id: 'asc' },
|
||||
}),
|
||||
ctx.db.nation.findMany({
|
||||
select: { id: true, name: true },
|
||||
select: { id: true, name: true, level: true },
|
||||
}),
|
||||
includeAllWithToken
|
||||
? ctx.db.npcSelectionToken.findMany({
|
||||
where: { validUntil: { gte: now } },
|
||||
select: { pickResult: true },
|
||||
})
|
||||
: [],
|
||||
includeAllWithToken
|
||||
? ctx.db.worldState.findFirst({
|
||||
select: { config: true },
|
||||
})
|
||||
: null,
|
||||
]);
|
||||
|
||||
const personalityKeys = generals.map((general) => normalizeTraitKey(general.personalCode));
|
||||
@@ -488,12 +541,21 @@ export const publicRouter = router({
|
||||
loadTraitNames(domesticKeys, 'domestic'),
|
||||
loadTraitNames(warKeys, 'war'),
|
||||
]);
|
||||
const nationMap = new Map(nations.map((nation) => [nation.id, nation.name]));
|
||||
const nationMap = new Map(nations.map((nation) => [nation.id, nation]));
|
||||
const worldConfig = asRecord(worldState?.config);
|
||||
const worldConstants = asRecord(worldConfig.const);
|
||||
const maxLevel = Math.max(0, Math.floor(asNumber(worldConstants.maxLevel, 255)));
|
||||
const maxDedLevel = Math.max(0, Math.floor(asNumber(worldConstants.maxDedLevel, 30)));
|
||||
|
||||
// Legacy select_pool rows preceded possessed NPC rows before its stable-value sort.
|
||||
const pool = generals.filter((general) => general.npcState >= 2);
|
||||
const possessed = generals.filter((general) => general.npcState === 1);
|
||||
const rows = [...pool, ...possessed].map((general) => {
|
||||
// Legacy public NPC list put pool rows before possessed rows. The token-aware
|
||||
// selection list instead consumes the raw id-ordered full list before its own comparator.
|
||||
const sourceRows = includeAllWithToken
|
||||
? generals
|
||||
: [
|
||||
...generals.filter((general) => general.npcState >= 2),
|
||||
...generals.filter((general) => general.npcState === 1),
|
||||
];
|
||||
const rows = sourceRows.map((general) => {
|
||||
const meta = asRecord(general.meta);
|
||||
const personalityKey = normalizeTraitKey(general.personalCode);
|
||||
const domesticKey = normalizeTraitKey(general.specialCode);
|
||||
@@ -510,11 +572,19 @@ export const publicRouter = router({
|
||||
return {
|
||||
id: general.id,
|
||||
name: general.name,
|
||||
picture: general.picture,
|
||||
imageServer: general.imageServer,
|
||||
npcState: general.npcState,
|
||||
ownerName,
|
||||
level: readFiniteMetaNumber(meta, 'explevel'),
|
||||
age: general.age,
|
||||
level: includeAllWithToken
|
||||
? resolveExperienceLevel(general.experience, maxLevel)
|
||||
: readFiniteMetaNumber(meta, 'explevel'),
|
||||
officerLevel: general.officerLevel,
|
||||
killturn: readFiniteMetaNumber(meta, 'killturn'),
|
||||
nationId: general.nationId,
|
||||
nationName: nationMap.get(general.nationId) ?? '-',
|
||||
nationName: nationMap.get(general.nationId)?.name ?? '-',
|
||||
nationLevel: nationMap.get(general.nationId)?.level ?? 0,
|
||||
personality: personalityKey
|
||||
? {
|
||||
key: personalityKey,
|
||||
@@ -541,13 +611,24 @@ export const publicRouter = router({
|
||||
strength: general.strength,
|
||||
intelligence: general.intel,
|
||||
experience: general.experience,
|
||||
experienceText: resolveHonorText(general.experience),
|
||||
dedication: general.dedication,
|
||||
dedicationText: resolveDedicationText(general.dedication, maxDedLevel),
|
||||
};
|
||||
});
|
||||
const tokenKeepCounts = Object.fromEntries(
|
||||
activeTokens.flatMap((token) =>
|
||||
Object.entries(asRecord(token.pickResult)).flatMap(([generalId, value]) => {
|
||||
const keepCount = asNumber(asRecord(value).keepCount, Number.NaN);
|
||||
return Number.isFinite(keepCount) ? [[generalId, Math.max(0, Math.floor(keepCount))]] : [];
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
return {
|
||||
sort,
|
||||
generals: sortNpcList(rows, sort),
|
||||
generals: includeAllWithToken ? rows : sortNpcList(rows, sort),
|
||||
tokenKeepCounts,
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -0,0 +1,657 @@
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
|
||||
import type { GameSessionTokenPayload } from '@sammo-ts/common/auth/gameToken';
|
||||
import { createTurnDaemonRuntime, seedScenarioToDatabase, type TurnDaemonRuntime } from '@sammo-ts/game-engine';
|
||||
import { createGamePostgresConnector, 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.NPC_POSSESSION_DATABASE_URL;
|
||||
const integration = describe.skipIf(!databaseUrl);
|
||||
const profile = 'hwe:2';
|
||||
const userId = 'npc-possession-integration-user';
|
||||
const otherUserId = 'npc-possession-integration-other';
|
||||
const failureUserId = 'npc-possession-integration-failure';
|
||||
const rejectedUserId = 'npc-possession-integration-rejected';
|
||||
const delayedUserId = 'npc-possession-integration-delayed';
|
||||
const cleanupUserId = 'npc-possession-integration-cleanup';
|
||||
const raceUserId = 'npc-possession-integration-race';
|
||||
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('npc_possession_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-31T00:00:00.000Z',
|
||||
expiresAt: '2026-08-31T00:00:00.000Z',
|
||||
sessionId: `npc-possession-${id}`,
|
||||
user: {
|
||||
id,
|
||||
username: id,
|
||||
displayName,
|
||||
roles: ['user'],
|
||||
legacyMemberNo,
|
||||
},
|
||||
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 },
|
||||
},
|
||||
},
|
||||
},
|
||||
identity: {
|
||||
kakaoVerified: true,
|
||||
canCreateGeneral: true,
|
||||
requiresKakaoVerification: false,
|
||||
graceEndsAt: null,
|
||||
},
|
||||
});
|
||||
|
||||
integration('mode 1 NPC possession through token reservation and the durable daemon', () => {
|
||||
let db: GamePrismaClient;
|
||||
let closeDb: (() => Promise<void>) | undefined;
|
||||
let runtime: TurnDaemonRuntime | undefined;
|
||||
let daemonLoop: Promise<void> | undefined;
|
||||
let turnDaemon: TurnDaemonTransport;
|
||||
|
||||
const auth = buildAuth(userId, '빙의사용자', 7_701);
|
||||
const otherAuth = buildAuth(otherUserId, '다른사용자', 7_702);
|
||||
const failureAuth = buildAuth(failureUserId, '재시도사용자', 7_703);
|
||||
const rejectedAuth = buildAuth(rejectedUserId, '거절사용자', 7_704);
|
||||
const delayedAuth = buildAuth(delayedUserId, '지연사용자', 7_705);
|
||||
const cleanupAuth = buildAuth(cleanupUserId, '정리사용자', 7_706);
|
||||
const raceAuth = buildAuth(raceUserId, '경합사용자', 7_707);
|
||||
|
||||
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: '2', name: profile },
|
||||
uploadDir: 'uploads',
|
||||
uploadPath: '/uploads',
|
||||
uploadPublicUrl: null,
|
||||
auth: actorAuth,
|
||||
accessTokenStore: new RedisAccessTokenStore(redisClient, profile),
|
||||
flushStore: new InMemoryFlushStore(),
|
||||
gameTokenSecret: 'npc-possession-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 = 'npc-possession-integration-seed';
|
||||
try {
|
||||
await seedScenarioToDatabase({
|
||||
scenarioId: 2,
|
||||
databaseUrl: databaseUrl!,
|
||||
now: new Date('2099-07-31T12:00:00.000Z'),
|
||||
installOptions: {
|
||||
turnTermMinutes: 5,
|
||||
npcMode: 1,
|
||||
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.npcSelectionToken.deleteMany();
|
||||
const city = await db.city.findFirstOrThrow({ orderBy: { id: 'asc' } });
|
||||
await db.general.createMany({
|
||||
data: Array.from({ length: 24 }, (_, index) => ({
|
||||
id: index + 1,
|
||||
userId: null,
|
||||
name: `빙의후보${index + 1}`,
|
||||
nationId: 0,
|
||||
cityId: city.id,
|
||||
npcState: 2,
|
||||
leadership: 40 + index,
|
||||
strength: 50 + index,
|
||||
intel: 60 + index,
|
||||
turnTime: new Date('2099-07-31T12:05:00.000Z'),
|
||||
personalCode: 'che_안전',
|
||||
specialCode: 'che_인덕',
|
||||
special2Code: 'che_무쌍',
|
||||
picture: 'default.jpg',
|
||||
imageServer: 0,
|
||||
meta: { killturn: 6 },
|
||||
penalty: {},
|
||||
})),
|
||||
});
|
||||
await startRuntime('npc-possession-integration-daemon');
|
||||
}, 60_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await stopRuntime('npc possession integration complete');
|
||||
await closeDb?.();
|
||||
}, 30_000);
|
||||
|
||||
it('reserves at most five exact type-2 NPCs and preserves Ref refresh/keep timing', async () => {
|
||||
const config = await appRouter.createCaller(buildContext('npc-possession-config')).join.getConfig();
|
||||
expect(config.npcPossession).toEqual({ enabled: true });
|
||||
|
||||
const [first, concurrentSameOwner] = await Promise.all([
|
||||
appRouter.createCaller(buildContext('npc-possession-token-a')).join.listPossessCandidates({}),
|
||||
appRouter.createCaller(buildContext('npc-possession-token-concurrent')).join.listPossessCandidates({}),
|
||||
]);
|
||||
expect(concurrentSameOwner).toEqual(first);
|
||||
expect(await db.npcSelectionToken.count({ where: { ownerUserId: userId } })).toBe(1);
|
||||
expect(first.candidates.length).toBeGreaterThan(0);
|
||||
expect(first.candidates.length).toBeLessThanOrEqual(5);
|
||||
expect(new Set(first.candidates.map(({ id }) => id)).size).toBe(first.candidates.length);
|
||||
expect(first.pickMoreSeconds).toBe(0);
|
||||
expect(first.candidates.every(({ keepCount }) => keepCount === 3)).toBe(true);
|
||||
const rows = await db.general.findMany({
|
||||
where: { id: { in: first.candidates.map(({ id }) => id) } },
|
||||
select: { id: true, userId: true, npcState: true },
|
||||
});
|
||||
expect(rows).toHaveLength(first.candidates.length);
|
||||
expect(rows.every((row) => row.userId === null && row.npcState === 2)).toBe(true);
|
||||
|
||||
const reused = await appRouter
|
||||
.createCaller(buildContext('npc-possession-token-b'))
|
||||
.join.listPossessCandidates({});
|
||||
expect(reused).toEqual(first);
|
||||
|
||||
const kept = first.candidates[0]!;
|
||||
const refreshed = await appRouter
|
||||
.createCaller(buildContext('npc-possession-token-refresh'))
|
||||
.join.listPossessCandidates({ refresh: true, keepIds: [kept.id] });
|
||||
expect(refreshed.tokenNonce).not.toBe(first.tokenNonce);
|
||||
expect(refreshed.pickMoreSeconds).toBeGreaterThan(0);
|
||||
expect(refreshed.candidates.find(({ id }) => id === kept.id)?.keepCount).toBe(2);
|
||||
|
||||
await expect(
|
||||
appRouter
|
||||
.createCaller(buildContext('npc-possession-token-too-early'))
|
||||
.join.listPossessCandidates({ refresh: true, keepIds: [] })
|
||||
).rejects.toMatchObject({
|
||||
code: 'PRECONDITION_FAILED',
|
||||
message: '아직 다시 뽑을 수 없습니다',
|
||||
});
|
||||
|
||||
const other = await appRouter
|
||||
.createCaller(buildContext('npc-possession-token-other', otherAuth))
|
||||
.join.listPossessCandidates({});
|
||||
const firstIds = new Set(refreshed.candidates.map(({ id }) => id));
|
||||
expect(other.candidates.some(({ id }) => firstIds.has(id))).toBe(false);
|
||||
}, 30_000);
|
||||
|
||||
it('commits exactly one of two concurrent picks and keeps retry, logs, token and reload atomic', async () => {
|
||||
const reservation = await appRouter
|
||||
.createCaller(buildContext('npc-possession-token-current'))
|
||||
.join.listPossessCandidates({});
|
||||
const firstCandidate = reservation.candidates[0]!;
|
||||
const secondCandidate = reservation.candidates[1]!;
|
||||
const firstClientRequestId = '11111111-1111-4111-8111-111111111111';
|
||||
const secondClientRequestId = '22222222-2222-4222-8222-222222222222';
|
||||
const firstInput = {
|
||||
generalId: firstCandidate.id,
|
||||
tokenNonce: reservation.tokenNonce,
|
||||
clientRequestId: firstClientRequestId,
|
||||
};
|
||||
const secondInput = {
|
||||
generalId: secondCandidate.id,
|
||||
tokenNonce: reservation.tokenNonce,
|
||||
clientRequestId: secondClientRequestId,
|
||||
};
|
||||
const concurrent = await Promise.allSettled([
|
||||
appRouter.createCaller(buildContext('npc-possession-http-a')).join.possessGeneral(firstInput),
|
||||
appRouter.createCaller(buildContext('npc-possession-http-b')).join.possessGeneral(secondInput),
|
||||
]);
|
||||
expect(concurrent.filter(({ status }) => status === 'fulfilled')).toHaveLength(1);
|
||||
expect(concurrent.filter(({ status }) => status === 'rejected')).toHaveLength(1);
|
||||
const fulfilledIndex = concurrent.findIndex(({ status }) => status === 'fulfilled');
|
||||
const candidate = fulfilledIndex === 0 ? firstCandidate : secondCandidate;
|
||||
const input = fulfilledIndex === 0 ? firstInput : secondInput;
|
||||
const clientRequestId = input.clientRequestId;
|
||||
const first = concurrent[fulfilledIndex]!;
|
||||
if (first.status !== 'fulfilled') {
|
||||
throw new Error('Exactly one NPC possession must succeed.');
|
||||
}
|
||||
const retried = await appRouter
|
||||
.createCaller(buildContext('npc-possession-http-retry'))
|
||||
.join.possessGeneral(input);
|
||||
expect(retried).toEqual(first.value);
|
||||
|
||||
const persisted = await db.general.findUniqueOrThrow({ where: { id: candidate.id } });
|
||||
expect(persisted).toMatchObject({
|
||||
userId,
|
||||
npcState: 1,
|
||||
penalty: {
|
||||
ban: 2,
|
||||
chat: 3,
|
||||
},
|
||||
});
|
||||
expect(persisted.meta).toMatchObject({
|
||||
npc_org: 2,
|
||||
ownerName: '빙의사용자',
|
||||
owner_name: '빙의사용자',
|
||||
killturn: 6,
|
||||
defence_train: 80,
|
||||
permission: 'normal',
|
||||
});
|
||||
expect(runtime!.world.getGeneralById(candidate.id)).toMatchObject({
|
||||
userId,
|
||||
npcState: 1,
|
||||
penalty: {
|
||||
ban: 2,
|
||||
chat: 3,
|
||||
},
|
||||
});
|
||||
expect(await db.general.count({ where: { userId } })).toBe(1);
|
||||
expect(await db.npcSelectionToken.findUnique({ where: { ownerUserId: userId } })).toBeNull();
|
||||
const access = await db.generalAccessLog.findUniqueOrThrow({ where: { generalId: candidate.id } });
|
||||
expect(access).toMatchObject({
|
||||
userId,
|
||||
refresh: 0,
|
||||
refreshTotal: 0,
|
||||
refreshScore: 0,
|
||||
refreshScoreTotal: 0,
|
||||
});
|
||||
const requestId = `npc-possess:${userId}:${clientRequestId}`;
|
||||
const event = await db.inputEvent.findUniqueOrThrow({ where: { requestId } });
|
||||
expect(event).toMatchObject({
|
||||
target: 'ENGINE',
|
||||
eventType: 'npcPossessGeneral',
|
||||
status: 'SUCCEEDED',
|
||||
attempts: 1,
|
||||
actorUserId: userId,
|
||||
});
|
||||
expect(access.lastRefresh?.getTime()).toBe(event.createdAt.getTime());
|
||||
const logs = await db.logEntry.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ generalId: candidate.id, text: { contains: '빙의되다' } },
|
||||
{ text: { contains: '빙의</>됩니다' } },
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(logs).toHaveLength(2);
|
||||
await expect(
|
||||
appRouter.createCaller(buildContext('npc-possession-lobby-after')).lobby.info()
|
||||
).resolves.toMatchObject({
|
||||
userCnt: 1,
|
||||
npcCnt: 23,
|
||||
npcPossessionEnabled: true,
|
||||
selectionPoolEnabled: false,
|
||||
myGeneral: {
|
||||
name: candidate.name,
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
appRouter.createCaller(buildContext('npc-possession-conflict')).join.possessGeneral({
|
||||
...input,
|
||||
generalId: candidate.id === firstCandidate.id ? secondCandidate.id : firstCandidate.id,
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'CONFLICT' });
|
||||
|
||||
await stopRuntime('verify NPC possession reload');
|
||||
await startRuntime('npc-possession-integration-reloaded-daemon');
|
||||
expect(runtime!.world.getGeneralById(candidate.id)).toMatchObject({
|
||||
userId,
|
||||
npcState: 1,
|
||||
penalty: {
|
||||
ban: 2,
|
||||
chat: 3,
|
||||
},
|
||||
});
|
||||
}, 45_000);
|
||||
|
||||
it('keeps an accepted token through wall-clock expiry until the queued ENGINE event finishes', async () => {
|
||||
const reservation = await appRouter
|
||||
.createCaller(buildContext('npc-possession-delayed-token', delayedAuth))
|
||||
.join.listPossessCandidates({});
|
||||
const candidate = reservation.candidates[0]!;
|
||||
const clientRequestId = '88888888-8888-4888-8888-888888888888';
|
||||
const requestId = `npc-possess:${delayedUserId}:${clientRequestId}`;
|
||||
const input = {
|
||||
generalId: candidate.id,
|
||||
tokenNonce: reservation.tokenNonce,
|
||||
clientRequestId,
|
||||
};
|
||||
|
||||
await stopRuntime('hold accepted NPC possession past token expiry');
|
||||
turnDaemon = new DatabaseTurnDaemonTransport(db, 100);
|
||||
await expect(
|
||||
appRouter.createCaller(buildContext('npc-possession-delayed-http', delayedAuth)).join.possessGeneral(input)
|
||||
).rejects.toMatchObject({ code: 'TIMEOUT' });
|
||||
|
||||
const event = await db.inputEvent.findUniqueOrThrow({ where: { requestId } });
|
||||
const acceptedSecond = new Date(Math.floor(event.createdAt.getTime() / 1000) * 1000);
|
||||
await db.npcSelectionToken.update({
|
||||
where: { ownerUserId: delayedUserId },
|
||||
data: { validUntil: acceptedSecond },
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 1_100));
|
||||
|
||||
await appRouter
|
||||
.createCaller(buildContext('npc-possession-cleanup-token', cleanupAuth))
|
||||
.join.listPossessCandidates({});
|
||||
await expect(
|
||||
db.npcSelectionToken.findUnique({ where: { ownerUserId: delayedUserId } })
|
||||
).resolves.not.toBeNull();
|
||||
await expect(
|
||||
appRouter
|
||||
.createCaller(buildContext('npc-possession-delayed-refresh', delayedAuth))
|
||||
.join.listPossessCandidates({ refresh: true, keepIds: [] })
|
||||
).rejects.toMatchObject({
|
||||
code: 'CONFLICT',
|
||||
message: 'NPC 빙의 요청 처리 중에는 후보를 다시 뽑을 수 없습니다.',
|
||||
});
|
||||
|
||||
await startRuntime('npc-possession-delayed-retry-daemon');
|
||||
await expect(
|
||||
appRouter.createCaller(buildContext('npc-possession-delayed-retry', delayedAuth)).join.possessGeneral(input)
|
||||
).resolves.toEqual({ ok: true, generalId: candidate.id });
|
||||
await expect(db.inputEvent.findUniqueOrThrow({ where: { requestId } })).resolves.toMatchObject({
|
||||
status: 'SUCCEEDED',
|
||||
attempts: 1,
|
||||
});
|
||||
expect(await db.general.count({ where: { userId: delayedUserId } })).toBe(1);
|
||||
}, 45_000);
|
||||
|
||||
it('serializes durable enqueue before a token refresh can replace its nonce', async () => {
|
||||
const reservation = await appRouter
|
||||
.createCaller(buildContext('npc-possession-race-token', raceAuth))
|
||||
.join.listPossessCandidates({});
|
||||
const candidate = reservation.candidates[0]!;
|
||||
const clientRequestId = '99999999-9999-4999-8999-999999999999';
|
||||
const requestId = `npc-possess:${raceUserId}:${clientRequestId}`;
|
||||
const input = {
|
||||
generalId: candidate.id,
|
||||
tokenNonce: reservation.tokenNonce,
|
||||
clientRequestId,
|
||||
};
|
||||
|
||||
await stopRuntime('hold NPC possession enqueue behind the reservation lock');
|
||||
turnDaemon = new DatabaseTurnDaemonTransport(db, 100);
|
||||
|
||||
let releaseLock!: () => void;
|
||||
let markLockReady!: () => void;
|
||||
const lockReady = new Promise<void>((resolve) => {
|
||||
markLockReady = resolve;
|
||||
});
|
||||
const lockRelease = new Promise<void>((resolve) => {
|
||||
releaseLock = resolve;
|
||||
});
|
||||
const blocker = db.$transaction(
|
||||
async (transaction) => {
|
||||
await transaction.$executeRaw(
|
||||
GamePrisma.sql`SELECT pg_advisory_xact_lock(hashtextextended('npc-possession', 1))`
|
||||
);
|
||||
markLockReady();
|
||||
await lockRelease;
|
||||
},
|
||||
{ timeout: 5_000 }
|
||||
);
|
||||
await lockReady;
|
||||
|
||||
const enqueue = appRouter
|
||||
.createCaller(buildContext('npc-possession-race-http', raceAuth))
|
||||
.join.possessGeneral(input);
|
||||
await new Promise((resolve) => setTimeout(resolve, 150));
|
||||
await expect(db.inputEvent.findUnique({ where: { requestId } })).resolves.toBeNull();
|
||||
|
||||
releaseLock();
|
||||
await blocker;
|
||||
await expect(enqueue).rejects.toMatchObject({ code: 'TIMEOUT' });
|
||||
await expect(
|
||||
appRouter
|
||||
.createCaller(buildContext('npc-possession-race-refresh', raceAuth))
|
||||
.join.listPossessCandidates({ refresh: true, keepIds: [] })
|
||||
).rejects.toMatchObject({
|
||||
code: 'CONFLICT',
|
||||
message: 'NPC 빙의 요청 처리 중에는 후보를 다시 뽑을 수 없습니다.',
|
||||
});
|
||||
await expect(db.npcSelectionToken.findUnique({ where: { ownerUserId: raceUserId } })).resolves.toMatchObject({
|
||||
nonce: reservation.tokenNonce,
|
||||
});
|
||||
|
||||
await startRuntime('npc-possession-race-retry-daemon');
|
||||
await expect(
|
||||
appRouter.createCaller(buildContext('npc-possession-race-retry', raceAuth)).join.possessGeneral(input)
|
||||
).resolves.toEqual({ ok: true, generalId: candidate.id });
|
||||
}, 45_000);
|
||||
|
||||
it('rolls back a late log failure and retries the same ENGINE event once', async () => {
|
||||
const reservation = await appRouter
|
||||
.createCaller(buildContext('npc-possession-failure-token', failureAuth))
|
||||
.join.listPossessCandidates({});
|
||||
const candidate = reservation.candidates[0]!;
|
||||
const clientRequestId = '33333333-3333-4333-8333-333333333333';
|
||||
const requestId = `npc-possess:${failureUserId}:${clientRequestId}`;
|
||||
const triggerName = 'npc_possession_fail_first_log';
|
||||
const functionName = 'npc_possession_fail_first_log_fn';
|
||||
|
||||
await db.$executeRawUnsafe(`
|
||||
CREATE OR REPLACE FUNCTION "${schemaName}"."${functionName}"()
|
||||
RETURNS trigger AS $$
|
||||
BEGIN
|
||||
IF NEW.text LIKE '%재시도사용자%'
|
||||
AND EXISTS (
|
||||
SELECT 1
|
||||
FROM "${schemaName}"."input_event"
|
||||
WHERE "request_id" = '${requestId}'
|
||||
AND "status" = 'PROCESSING'
|
||||
AND "attempts" = 1
|
||||
)
|
||||
THEN
|
||||
RAISE EXCEPTION 'injected first NPC possession 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('npc-possession-failure-http', failureAuth)).join.possessGeneral({
|
||||
generalId: candidate.id,
|
||||
tokenNonce: reservation.tokenNonce,
|
||||
clientRequestId,
|
||||
})
|
||||
).resolves.toEqual({ ok: true, generalId: candidate.id });
|
||||
} finally {
|
||||
await db.$executeRawUnsafe(`DROP TRIGGER IF EXISTS "${triggerName}" ON "${schemaName}"."log_entry"`);
|
||||
await db.$executeRawUnsafe(`DROP FUNCTION IF EXISTS "${schemaName}"."${functionName}"()`);
|
||||
}
|
||||
|
||||
expect(await db.general.count({ where: { userId: failureUserId } })).toBe(1);
|
||||
expect(runtime!.world.getGeneralById(candidate.id)).toMatchObject({
|
||||
userId: failureUserId,
|
||||
npcState: 1,
|
||||
});
|
||||
expect(await db.npcSelectionToken.findUnique({ where: { ownerUserId: failureUserId } })).toBeNull();
|
||||
await expect(db.inputEvent.findUniqueOrThrow({ where: { requestId } })).resolves.toMatchObject({
|
||||
status: 'SUCCEEDED',
|
||||
attempts: 2,
|
||||
actorUserId: failureUserId,
|
||||
error: null,
|
||||
});
|
||||
expect(
|
||||
await db.logEntry.count({
|
||||
where: { text: { contains: '재시도사용자' } },
|
||||
})
|
||||
).toBe(2);
|
||||
}, 45_000);
|
||||
|
||||
it('rejects wrong mode, foreign nonce, unlisted ID, expiry and a full server without mutation', async () => {
|
||||
await db.npcSelectionToken.deleteMany({ where: { ownerUserId: cleanupUserId } });
|
||||
const worldState = await db.worldState.findFirstOrThrow();
|
||||
const originalConfig = worldState.config as GamePrisma.InputJsonObject;
|
||||
await db.worldState.update({
|
||||
where: { id: worldState.id },
|
||||
data: {
|
||||
config: {
|
||||
...originalConfig,
|
||||
npcMode: 0,
|
||||
},
|
||||
},
|
||||
});
|
||||
await expect(
|
||||
appRouter
|
||||
.createCaller(buildContext('npc-possession-reject-mode-token', rejectedAuth))
|
||||
.join.listPossessCandidates({})
|
||||
).rejects.toMatchObject({
|
||||
code: 'PRECONDITION_FAILED',
|
||||
message: '빙의 가능한 서버가 아닙니다',
|
||||
});
|
||||
|
||||
await db.worldState.update({
|
||||
where: { id: worldState.id },
|
||||
data: { config: originalConfig },
|
||||
});
|
||||
const reservation = await appRouter
|
||||
.createCaller(buildContext('npc-possession-reject-token', rejectedAuth))
|
||||
.join.listPossessCandidates({});
|
||||
const foreignToken = await db.npcSelectionToken.findUniqueOrThrow({
|
||||
where: { ownerUserId: otherUserId },
|
||||
});
|
||||
await expect(
|
||||
appRouter.createCaller(buildContext('npc-possession-reject-foreign', rejectedAuth)).join.possessGeneral({
|
||||
generalId: reservation.candidates[0]!.id,
|
||||
tokenNonce: foreignToken.nonce,
|
||||
clientRequestId: '44444444-4444-4444-8444-444444444444',
|
||||
})
|
||||
).rejects.toMatchObject({
|
||||
code: 'PRECONDITION_FAILED',
|
||||
message: '유효한 장수 목록이 없습니다.',
|
||||
});
|
||||
|
||||
const reservedIds = new Set(reservation.candidates.map(({ id }) => id));
|
||||
const unlisted = await db.general.findFirstOrThrow({
|
||||
where: {
|
||||
userId: null,
|
||||
npcState: 2,
|
||||
id: { notIn: [...reservedIds] },
|
||||
},
|
||||
});
|
||||
await expect(
|
||||
appRouter.createCaller(buildContext('npc-possession-reject-unlisted', rejectedAuth)).join.possessGeneral({
|
||||
generalId: unlisted.id,
|
||||
tokenNonce: reservation.tokenNonce,
|
||||
clientRequestId: '55555555-5555-4555-8555-555555555555',
|
||||
})
|
||||
).rejects.toMatchObject({
|
||||
code: 'PRECONDITION_FAILED',
|
||||
message: '선택한 장수가 목록에 없습니다.',
|
||||
});
|
||||
|
||||
await db.npcSelectionToken.update({
|
||||
where: { ownerUserId: rejectedUserId },
|
||||
data: { validUntil: new Date('2000-01-01T00:00:00.000Z') },
|
||||
});
|
||||
await expect(
|
||||
appRouter.createCaller(buildContext('npc-possession-reject-expired', rejectedAuth)).join.possessGeneral({
|
||||
generalId: reservation.candidates[0]!.id,
|
||||
tokenNonce: reservation.tokenNonce,
|
||||
clientRequestId: '66666666-6666-4666-8666-666666666666',
|
||||
})
|
||||
).rejects.toMatchObject({
|
||||
code: 'PRECONDITION_FAILED',
|
||||
message: '유효한 장수 목록이 없습니다.',
|
||||
});
|
||||
|
||||
const fresh = await appRouter
|
||||
.createCaller(buildContext('npc-possession-reject-fresh-token', rejectedAuth))
|
||||
.join.listPossessCandidates({});
|
||||
const activeCount = await db.general.count({ where: { npcState: { lt: 2 } } });
|
||||
await db.worldState.update({
|
||||
where: { id: worldState.id },
|
||||
data: {
|
||||
config: {
|
||||
...originalConfig,
|
||||
npcMode: 1,
|
||||
maxGeneral: activeCount,
|
||||
},
|
||||
},
|
||||
});
|
||||
await expect(
|
||||
appRouter.createCaller(buildContext('npc-possession-reject-cap', rejectedAuth)).join.possessGeneral({
|
||||
generalId: fresh.candidates[0]!.id,
|
||||
tokenNonce: fresh.tokenNonce,
|
||||
clientRequestId: '77777777-7777-4777-8777-777777777777',
|
||||
})
|
||||
).rejects.toMatchObject({
|
||||
code: 'PRECONDITION_FAILED',
|
||||
message: '더 이상 등록 할 수 없습니다.',
|
||||
});
|
||||
await db.worldState.update({
|
||||
where: { id: worldState.id },
|
||||
data: { config: originalConfig },
|
||||
});
|
||||
|
||||
expect(await db.general.count({ where: { userId: rejectedUserId } })).toBe(0);
|
||||
expect(runtime!.world.listGenerals().some(({ userId: owner }) => owner === rejectedUserId)).toBe(false);
|
||||
}, 45_000);
|
||||
});
|
||||
@@ -16,12 +16,16 @@ const profile: GameProfile = {
|
||||
name: 'che:default',
|
||||
};
|
||||
|
||||
const buildContext = (): GameApiContext => {
|
||||
const buildContext = (auth: GameSessionTokenPayload | null = null): GameApiContext => {
|
||||
const generalRows = [
|
||||
{
|
||||
id: 10,
|
||||
name: '관우',
|
||||
picture: '10.jpg',
|
||||
imageServer: 0,
|
||||
npcState: 1,
|
||||
age: 42,
|
||||
officerLevel: 5,
|
||||
nationId: 1,
|
||||
leadership: 90,
|
||||
strength: 95,
|
||||
@@ -31,12 +35,16 @@ const buildContext = (): GameApiContext => {
|
||||
personalCode: 'None',
|
||||
specialCode: 'None',
|
||||
special2Code: 'None',
|
||||
meta: { owner_name: '악령 관우', explevel: 4 },
|
||||
meta: { owner_name: '악령 관우', explevel: 4, killturn: 7 },
|
||||
},
|
||||
{
|
||||
id: 20,
|
||||
name: '조운',
|
||||
picture: '20.jpg',
|
||||
imageServer: 1,
|
||||
npcState: 2,
|
||||
age: 35,
|
||||
officerLevel: 0,
|
||||
nationId: 0,
|
||||
leadership: 90,
|
||||
strength: 95,
|
||||
@@ -48,16 +56,61 @@ const buildContext = (): GameApiContext => {
|
||||
special2Code: 'None',
|
||||
meta: { owner_name: '노출 금지', explevel: 5 },
|
||||
},
|
||||
{
|
||||
id: 30,
|
||||
name: '유비',
|
||||
picture: '30.jpg',
|
||||
imageServer: 0,
|
||||
npcState: 0,
|
||||
age: 44,
|
||||
officerLevel: 12,
|
||||
nationId: 1,
|
||||
leadership: 80,
|
||||
strength: 70,
|
||||
intel: 85,
|
||||
experience: 16_000,
|
||||
dedication: 10_000,
|
||||
personalCode: 'None',
|
||||
specialCode: 'None',
|
||||
special2Code: 'None',
|
||||
meta: { owner_name: '노출 금지', explevel: 9 },
|
||||
},
|
||||
];
|
||||
const db = {
|
||||
general: {
|
||||
findMany: async (args: { where: { npcState: { gt: number } } }) => {
|
||||
expect(args.where).toEqual({ npcState: { gt: 0 } });
|
||||
findMany: async (args: { where?: { npcState: { gt: number } } }) => {
|
||||
if (args.where) {
|
||||
expect(args.where).toEqual({ npcState: { gt: 0 } });
|
||||
return generalRows.filter((general) => general.npcState > 0);
|
||||
}
|
||||
return generalRows;
|
||||
},
|
||||
},
|
||||
nation: {
|
||||
findMany: async () => [{ id: 1, name: '촉' }],
|
||||
findMany: async () => [{ id: 1, name: '촉', level: 5 }],
|
||||
},
|
||||
npcSelectionToken: {
|
||||
findMany: async (args: { where: { validUntil: { gte: Date } } }) => {
|
||||
expect(args.where.validUntil.gte).toBeInstanceOf(Date);
|
||||
return [
|
||||
{
|
||||
pickResult: {
|
||||
10: { keepCount: 2 },
|
||||
invalid: { keepCount: 'bad' },
|
||||
},
|
||||
},
|
||||
{
|
||||
pickResult: {
|
||||
20: { keepCount: -1 },
|
||||
},
|
||||
},
|
||||
];
|
||||
},
|
||||
},
|
||||
worldState: {
|
||||
findFirst: async () => ({
|
||||
config: { const: { maxLevel: 255, maxDedLevel: 30 } },
|
||||
}),
|
||||
},
|
||||
};
|
||||
const redis = {
|
||||
@@ -70,7 +123,7 @@ const buildContext = (): GameApiContext => {
|
||||
turnDaemon: new InMemoryTurnDaemonTransport(),
|
||||
battleSim: new InMemoryBattleSimTransport(),
|
||||
profile,
|
||||
auth: null as GameSessionTokenPayload | null,
|
||||
auth,
|
||||
uploadDir: 'uploads',
|
||||
uploadPath: '/uploads',
|
||||
uploadPublicUrl: null,
|
||||
@@ -89,11 +142,17 @@ describe('public.getNpcList', () => {
|
||||
{
|
||||
id: 10,
|
||||
name: '관우',
|
||||
picture: '10.jpg',
|
||||
imageServer: 0,
|
||||
npcState: 1,
|
||||
ownerName: '악령 관우',
|
||||
age: 42,
|
||||
level: 4,
|
||||
officerLevel: 5,
|
||||
killturn: 7,
|
||||
nationId: 1,
|
||||
nationName: '촉',
|
||||
nationLevel: 5,
|
||||
personality: null,
|
||||
specialDomestic: null,
|
||||
specialWar: null,
|
||||
@@ -102,16 +161,24 @@ describe('public.getNpcList', () => {
|
||||
strength: 95,
|
||||
intelligence: 75,
|
||||
experience: 800,
|
||||
experienceText: '무명',
|
||||
dedication: 700,
|
||||
dedicationText: '28품관',
|
||||
},
|
||||
{
|
||||
id: 20,
|
||||
name: '조운',
|
||||
picture: '20.jpg',
|
||||
imageServer: 1,
|
||||
npcState: 2,
|
||||
ownerName: '',
|
||||
age: 35,
|
||||
level: 5,
|
||||
officerLevel: 0,
|
||||
killturn: 0,
|
||||
nationId: 0,
|
||||
nationName: '-',
|
||||
nationLevel: 0,
|
||||
personality: null,
|
||||
specialDomestic: null,
|
||||
specialWar: null,
|
||||
@@ -120,13 +187,53 @@ describe('public.getNpcList', () => {
|
||||
strength: 95,
|
||||
intelligence: 75,
|
||||
experience: 900,
|
||||
experienceText: '무명',
|
||||
dedication: 600,
|
||||
dedicationText: '28품관',
|
||||
},
|
||||
]);
|
||||
expect(result.tokenKeepCounts).toEqual({});
|
||||
expect(JSON.stringify(result)).not.toContain('노출 금지');
|
||||
expect(JSON.stringify(result)).not.toContain('userId');
|
||||
});
|
||||
|
||||
it('returns the full id-ordered list and every active reservation only to an authenticated caller', async () => {
|
||||
const auth: GameSessionTokenPayload = {
|
||||
version: 1,
|
||||
profile: 'che:default',
|
||||
issuedAt: '2026-07-31T00:00:00.000Z',
|
||||
expiresAt: '2026-08-31T00:00:00.000Z',
|
||||
sessionId: 'npc-list-owner',
|
||||
user: {
|
||||
id: 'owner-user',
|
||||
username: 'owner-user',
|
||||
displayName: '소유자',
|
||||
roles: ['user'],
|
||||
legacyMemberNo: 101,
|
||||
},
|
||||
sanctions: {},
|
||||
};
|
||||
|
||||
const result = await appRouter
|
||||
.createCaller(buildContext(auth))
|
||||
.public.getNpcList({ sort: 1, includeAllWithToken: true });
|
||||
|
||||
expect(result.tokenKeepCounts).toEqual({ 10: 2, 20: 0 });
|
||||
expect(result.generals.map((general) => general.id)).toEqual([10, 20, 30]);
|
||||
expect(result.generals[2]).toMatchObject({
|
||||
npcState: 0,
|
||||
level: 40,
|
||||
experienceText: '지역적',
|
||||
dedicationText: '21품관',
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects the token-aware full list without an authenticated session', async () => {
|
||||
await expect(
|
||||
appRouter.createCaller(buildContext()).public.getNpcList({ sort: 1, includeAllWithToken: true })
|
||||
).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
|
||||
});
|
||||
|
||||
it('keeps pool rows before possessed NPCs when the selected value is tied', async () => {
|
||||
const result = await appRouter.createCaller(buildContext()).public.getNpcList({ sort: 3 });
|
||||
|
||||
|
||||
Reference in New Issue
Block a user