Add analysis REST API
This commit is contained in:
1 parent
770c198ccd
commit
e1164e0b47
10 files changed
+867
-5
No files matched your search
@@ -137,7 +137,7 @@ describe('AnalysisQueueService', () => {
|
||||
$set: {
|
||||
status: 'failed',
|
||||
stage: 'enqueue',
|
||||
error: 'redis unavailable',
|
||||
error: 'Analysis could not be queued.',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
@@ -109,7 +109,7 @@ export class AnalysisQueueService {
|
||||
$set: {
|
||||
status: 'failed',
|
||||
stage: 'enqueue',
|
||||
error: this.errorMessage(error),
|
||||
error: this.publicErrorMessage(),
|
||||
},
|
||||
},
|
||||
)
|
||||
@@ -144,6 +144,10 @@ export class AnalysisQueueService {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
private publicErrorMessage(): string {
|
||||
return 'Analysis could not be queued.';
|
||||
}
|
||||
|
||||
private duplicateRequestKey(data: UserAnalysisJobData): string {
|
||||
return [
|
||||
data.platformRoute,
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import { FEATURE_SCHEMA_VERSION } from '@persona-lenz/shared';
|
||||
import type { ConnectionService } from '../global/database/connection.service';
|
||||
import { AnalysisReadService } from './analysis-read.service';
|
||||
|
||||
function createLeanExec<T>(value: T) {
|
||||
return {
|
||||
lean: jest.fn(() => ({
|
||||
exec: jest.fn().mockResolvedValue(value),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
describe('AnalysisReadService', () => {
|
||||
it('queries analysis jobs by jobId and serializes public failed errors', async () => {
|
||||
const findOne = jest.fn(() =>
|
||||
createLeanExec({
|
||||
error: 'internal host redis.local refused connection',
|
||||
jobId: 'analysis-job-1',
|
||||
progress: { fetchedMatches: 0, totalMatches: 20 },
|
||||
status: 'failed',
|
||||
}),
|
||||
);
|
||||
const service = new AnalysisReadService({
|
||||
getModel: jest.fn().mockResolvedValue({ findOne }),
|
||||
} as unknown as ConnectionService);
|
||||
|
||||
await expect(service.getJobStatus('analysis-job-1')).resolves.toEqual({
|
||||
error: 'Analysis failed during processing.',
|
||||
jobId: 'analysis-job-1',
|
||||
progress: { fetchedMatches: 0, totalMatches: 20 },
|
||||
status: 'failed',
|
||||
});
|
||||
expect(findOne).toHaveBeenCalledWith({ jobId: 'analysis-job-1' });
|
||||
});
|
||||
|
||||
it('distinguishes analyzed accounts with no ranked games from missing accounts', async () => {
|
||||
const accountFindOne = jest.fn(() =>
|
||||
createLeanExec({
|
||||
gameName: 'Hide on bush',
|
||||
profileIconId: 1,
|
||||
tagLine: 'KR1',
|
||||
tiers: [],
|
||||
}),
|
||||
);
|
||||
const profileFindOne = jest.fn(() => createLeanExec(null));
|
||||
const service = new AnalysisReadService({
|
||||
getModel: jest.fn((modelKey: string) =>
|
||||
Promise.resolve(
|
||||
modelKey === 'account'
|
||||
? { findOne: accountFindOne }
|
||||
: { findOne: profileFindOne },
|
||||
),
|
||||
),
|
||||
} as unknown as ConnectionService);
|
||||
|
||||
await expect(
|
||||
service.getLatestPlayerAnalysis('target-puuid', 420),
|
||||
).rejects.toThrow('분석할 랭크 게임이 없음');
|
||||
});
|
||||
|
||||
it('queries account and profile by puuid/queue and applies lower-is-better scoring', async () => {
|
||||
const accountFindOne = jest.fn(() =>
|
||||
createLeanExec({
|
||||
gameName: 'Hide on bush',
|
||||
profileIconId: 1,
|
||||
tagLine: 'KR1',
|
||||
tiers: [],
|
||||
}),
|
||||
);
|
||||
const profileFindOne = jest.fn(() =>
|
||||
createLeanExec({
|
||||
championPool: [{ championId: 103, games: 4, wins: 3 }],
|
||||
confidence: 0.9,
|
||||
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||
mainRole: 'MIDDLE',
|
||||
profile: {
|
||||
kda: 0.8,
|
||||
killParticipation: 0.7,
|
||||
damageShare: 0.6,
|
||||
damagePerMin: 0.5,
|
||||
goldPerMin: 0.4,
|
||||
csPerMin: 0.3,
|
||||
visionScorePerMin: 0.2,
|
||||
wardsKilledPerMin: 0.1,
|
||||
controlWardsPlaced: 0.2,
|
||||
deathsPerMin: 0.1,
|
||||
objectiveParticipation: 0.6,
|
||||
soloKills: 0.4,
|
||||
},
|
||||
queueId: 420,
|
||||
sampleGameCount: 12,
|
||||
updatedAt: new Date('2026-07-02T00:00:00.000Z'),
|
||||
}),
|
||||
);
|
||||
const service = new AnalysisReadService({
|
||||
getModel: jest.fn((modelKey: string) =>
|
||||
Promise.resolve(
|
||||
modelKey === 'account'
|
||||
? { findOne: accountFindOne }
|
||||
: { findOne: profileFindOne },
|
||||
),
|
||||
),
|
||||
} as unknown as ConnectionService);
|
||||
|
||||
const analysis = await service.getLatestPlayerAnalysis('target-puuid', 420);
|
||||
|
||||
expect(accountFindOne).toHaveBeenCalledWith({ puuid: 'target-puuid' });
|
||||
expect(profileFindOne).toHaveBeenCalledWith({
|
||||
puuid: 'target-puuid',
|
||||
queueId: 420,
|
||||
});
|
||||
expect(analysis.strengths).toEqual([
|
||||
{ metricId: 'deathsPerMin', value: 0.1 },
|
||||
{ metricId: 'kda', value: 0.8 },
|
||||
{ metricId: 'killParticipation', value: 0.7 },
|
||||
]);
|
||||
expect(analysis.weaknesses).toEqual([
|
||||
{ metricId: 'wardsKilledPerMin', value: 0.1 },
|
||||
{ metricId: 'visionScorePerMin', value: 0.2 },
|
||||
{ metricId: 'controlWardsPlaced', value: 0.2 },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,178 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import {
|
||||
METRICS,
|
||||
type AnalysisJobStatusDto,
|
||||
type MetricValueDto,
|
||||
type PlayerAnalysisDto,
|
||||
} from '@persona-lenz/shared';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import type {
|
||||
Account,
|
||||
AnalysisJob,
|
||||
PlayerProfile,
|
||||
TierInfo,
|
||||
} from '../global/database/schemas';
|
||||
|
||||
type JobStatusRecord = Pick<
|
||||
AnalysisJob,
|
||||
'error' | 'jobId' | 'progress' | 'puuid' | 'stage' | 'status'
|
||||
>;
|
||||
|
||||
type AccountSummaryRecord = Pick<
|
||||
Account,
|
||||
'gameName' | 'profileIconId' | 'tagLine' | 'tiers'
|
||||
>;
|
||||
|
||||
type PlayerProfileRecord = Pick<
|
||||
PlayerProfile,
|
||||
| 'championPool'
|
||||
| 'confidence'
|
||||
| 'featureSchemaVersion'
|
||||
| 'mainRole'
|
||||
| 'profile'
|
||||
| 'queueId'
|
||||
| 'sampleGameCount'
|
||||
| 'updatedAt'
|
||||
>;
|
||||
|
||||
@Injectable()
|
||||
export class AnalysisReadService {
|
||||
constructor(private readonly connectionService: ConnectionService) {}
|
||||
|
||||
public async getJobStatus(jobId: string): Promise<AnalysisJobStatusDto> {
|
||||
const analysisJobModel =
|
||||
await this.connectionService.getModel('analysisJob');
|
||||
const job = await analysisJobModel
|
||||
.findOne({ jobId })
|
||||
.lean<JobStatusRecord>()
|
||||
.exec();
|
||||
|
||||
if (!job) {
|
||||
throw new NotFoundException('Analysis job not found.');
|
||||
}
|
||||
|
||||
return {
|
||||
jobId: job.jobId,
|
||||
status: job.status,
|
||||
stage: job.stage,
|
||||
puuid: job.puuid,
|
||||
progress: job.progress,
|
||||
error: this.publicJobError(job.error),
|
||||
};
|
||||
}
|
||||
|
||||
public async getLatestPlayerAnalysis(
|
||||
puuid: string,
|
||||
queueId: number,
|
||||
): Promise<PlayerAnalysisDto> {
|
||||
const [account, profile] = await Promise.all([
|
||||
this.findAccount(puuid),
|
||||
this.findPlayerProfile(puuid, queueId),
|
||||
]);
|
||||
|
||||
if (!account) {
|
||||
throw new NotFoundException('Player account not found.');
|
||||
}
|
||||
if (!profile) {
|
||||
throw new NotFoundException('분석할 랭크 게임이 없음');
|
||||
}
|
||||
|
||||
return {
|
||||
account: {
|
||||
gameName: account.gameName,
|
||||
tagLine: account.tagLine,
|
||||
profileIconId: account.profileIconId,
|
||||
tiers: account.tiers.map((tier) => this.toTierDto(tier)),
|
||||
},
|
||||
profile: {
|
||||
mainRole: profile.mainRole,
|
||||
queueId: profile.queueId,
|
||||
sampleGameCount: profile.sampleGameCount,
|
||||
championPool: profile.championPool,
|
||||
playstyle: Object.fromEntries(
|
||||
METRICS.map((metric) => [
|
||||
metric.id,
|
||||
this.clampMetricValue(profile.profile[metric.id]),
|
||||
]),
|
||||
) as PlayerAnalysisDto['profile']['playstyle'],
|
||||
featureSchemaVersion: profile.featureSchemaVersion,
|
||||
confidence: profile.confidence,
|
||||
},
|
||||
strengths: this.resolveMetricHighlights(profile.profile, 'strength'),
|
||||
weaknesses: this.resolveMetricHighlights(profile.profile, 'weakness'),
|
||||
updatedAt: profile.updatedAt.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
private async findAccount(
|
||||
puuid: string,
|
||||
): Promise<AccountSummaryRecord | null> {
|
||||
const accountModel = await this.connectionService.getModel('account');
|
||||
return accountModel.findOne({ puuid }).lean<AccountSummaryRecord>().exec();
|
||||
}
|
||||
|
||||
private async findPlayerProfile(
|
||||
puuid: string,
|
||||
queueId: number,
|
||||
): Promise<PlayerProfileRecord | null> {
|
||||
const playerProfileModel =
|
||||
await this.connectionService.getModel('playerProfile');
|
||||
return playerProfileModel
|
||||
.findOne({ puuid, queueId })
|
||||
.lean<PlayerProfileRecord>()
|
||||
.exec();
|
||||
}
|
||||
|
||||
private resolveMetricHighlights(
|
||||
profile: Record<string, number>,
|
||||
direction: 'strength' | 'weakness',
|
||||
): MetricValueDto[] {
|
||||
return METRICS.map((metric) => {
|
||||
const value = this.clampMetricValue(profile[metric.id]);
|
||||
return {
|
||||
metricId: metric.id,
|
||||
score: metric.direction === 'lowerIsBetter' ? 1 - value : value,
|
||||
value,
|
||||
};
|
||||
})
|
||||
.sort((left, right) =>
|
||||
direction === 'strength'
|
||||
? right.score - left.score
|
||||
: left.score - right.score,
|
||||
)
|
||||
.slice(0, 3)
|
||||
.map(({ metricId, value }) => ({ metricId, value }));
|
||||
}
|
||||
|
||||
private clampMetricValue(value: unknown): number {
|
||||
return typeof value === 'number' && Number.isFinite(value)
|
||||
? Math.max(0, Math.min(1, value))
|
||||
: 0;
|
||||
}
|
||||
|
||||
private toTierDto(
|
||||
tier: TierInfo,
|
||||
): PlayerAnalysisDto['account']['tiers'][number] {
|
||||
return {
|
||||
queueType: tier.queueType,
|
||||
tier: tier.tier,
|
||||
rank: tier.rank,
|
||||
leaguePoints: tier.leaguePoints,
|
||||
wins: tier.wins,
|
||||
losses: tier.losses,
|
||||
fetchedAt: tier.fetchedAt?.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
private publicJobError(error: string | undefined): string | null {
|
||||
if (!error) return null;
|
||||
if (
|
||||
error === 'Analysis failed during processing.' ||
|
||||
error === 'Riot API key is invalid or expired.' ||
|
||||
error === 'Analysis could not be queued.'
|
||||
) {
|
||||
return error;
|
||||
}
|
||||
return 'Analysis failed during processing.';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
|
||||
|
||||
const REQUEST_WINDOW_MS = 60_000;
|
||||
const MAX_REQUESTS_PER_WINDOW = 10;
|
||||
|
||||
interface RequestWindow {
|
||||
count: number;
|
||||
resetAt: number;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AnalysisRequestThrottleService {
|
||||
private readonly requestWindows = new Map<string, RequestWindow>();
|
||||
|
||||
public assertAllowed(clientKey: string, now = Date.now()): void {
|
||||
const existingWindow = this.requestWindows.get(clientKey);
|
||||
if (!existingWindow || existingWindow.resetAt <= now) {
|
||||
this.requestWindows.set(clientKey, {
|
||||
count: 1,
|
||||
resetAt: now + REQUEST_WINDOW_MS,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (existingWindow.count >= MAX_REQUESTS_PER_WINDOW) {
|
||||
throw new HttpException(
|
||||
'Too many analysis requests.',
|
||||
HttpStatus.TOO_MANY_REQUESTS,
|
||||
);
|
||||
}
|
||||
|
||||
existingWindow.count += 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
HttpCode,
|
||||
Param,
|
||||
Post,
|
||||
Query,
|
||||
Req,
|
||||
} from '@nestjs/common';
|
||||
import type {
|
||||
AnalysisJobStatusDto,
|
||||
AnalysisRequestAcceptedDto,
|
||||
PlayerAnalysisDto,
|
||||
} from '@persona-lenz/shared';
|
||||
import {
|
||||
RIOT_PLATFORM_ROUTES,
|
||||
toRegionalRoute,
|
||||
type RiotPlatformRoute,
|
||||
} from '../riot/riot.types';
|
||||
import { AnalysisQueueService } from './analysis-queue.service';
|
||||
import {
|
||||
DEFAULT_ANALYSIS_MATCH_COUNT,
|
||||
MAX_ANALYSIS_MATCH_COUNT,
|
||||
normalizeRequestedMatchCount,
|
||||
} from './analysis.constants';
|
||||
import { AnalysisReadService } from './analysis-read.service';
|
||||
import { AnalysisRequestThrottleService } from './analysis-request-throttle.service';
|
||||
import type { UserAnalysisJobData } from './analysis.types';
|
||||
import type { Request } from 'express';
|
||||
|
||||
@Controller()
|
||||
export class AnalysisController {
|
||||
constructor(
|
||||
private readonly analysisQueueService: AnalysisQueueService,
|
||||
private readonly analysisReadService: AnalysisReadService,
|
||||
private readonly analysisRequestThrottleService: AnalysisRequestThrottleService,
|
||||
) {}
|
||||
|
||||
@Post('analysis/request')
|
||||
@HttpCode(202)
|
||||
public async requestAnalysis(
|
||||
@Body() body: unknown,
|
||||
@Req() request: Request,
|
||||
): Promise<AnalysisRequestAcceptedDto> {
|
||||
const data = this.parseAnalysisRequest(body);
|
||||
this.analysisRequestThrottleService.assertAllowed(
|
||||
this.resolveClientKey(request),
|
||||
);
|
||||
return this.analysisQueueService.enqueueUserAnalysis(data);
|
||||
}
|
||||
|
||||
@Get('analysis/jobs/:jobId')
|
||||
public async getJobStatus(
|
||||
@Param('jobId') jobId: string,
|
||||
): Promise<AnalysisJobStatusDto> {
|
||||
return this.analysisReadService.getJobStatus(jobId);
|
||||
}
|
||||
|
||||
@Get('players/:puuid/analysis/latest')
|
||||
public async getLatestPlayerAnalysis(
|
||||
@Param('puuid') puuid: string,
|
||||
@Query('queueId') rawQueueId?: string,
|
||||
): Promise<PlayerAnalysisDto> {
|
||||
return this.analysisReadService.getLatestPlayerAnalysis(
|
||||
this.parsePuuid(puuid),
|
||||
this.parseQueueId(rawQueueId),
|
||||
);
|
||||
}
|
||||
|
||||
private parseAnalysisRequest(body: unknown): UserAnalysisJobData {
|
||||
const record = this.requireRecord(body);
|
||||
const gameName = this.parseTrimmedString(
|
||||
record.gameName,
|
||||
'gameName',
|
||||
3,
|
||||
16,
|
||||
);
|
||||
const tagLine = this.parseTrimmedString(record.tagLine, 'tagLine', 3, 5);
|
||||
const platformRoute = this.parsePlatformRoute(record.platform ?? 'kr');
|
||||
const requestedMatchCount = this.parseMatchCount(record.matchCount);
|
||||
|
||||
return {
|
||||
gameName,
|
||||
tagLine,
|
||||
platformRoute,
|
||||
regionalRoute: toRegionalRoute(platformRoute),
|
||||
queueId: 420,
|
||||
requestedMatchCount,
|
||||
};
|
||||
}
|
||||
|
||||
private requireRecord(value: unknown): Record<string, unknown> {
|
||||
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
||||
throw new BadRequestException('Request body must be an object.');
|
||||
}
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
private parseTrimmedString(
|
||||
value: unknown,
|
||||
fieldName: string,
|
||||
minimumLength: number,
|
||||
maximumLength: number,
|
||||
): string {
|
||||
if (typeof value !== 'string') {
|
||||
throw new BadRequestException(`${fieldName} must be a string.`);
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length < minimumLength || trimmed.length > maximumLength) {
|
||||
throw new BadRequestException(`${fieldName} is out of range.`);
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
private parsePlatformRoute(value: unknown): RiotPlatformRoute {
|
||||
if (
|
||||
typeof value !== 'string' ||
|
||||
!RIOT_PLATFORM_ROUTES.includes(value as RiotPlatformRoute)
|
||||
) {
|
||||
throw new BadRequestException('platform is unsupported.');
|
||||
}
|
||||
return value as RiotPlatformRoute;
|
||||
}
|
||||
|
||||
private parseMatchCount(value: unknown): number {
|
||||
if (value === undefined) return DEFAULT_ANALYSIS_MATCH_COUNT;
|
||||
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
||||
throw new BadRequestException('matchCount must be a finite number.');
|
||||
}
|
||||
return normalizeRequestedMatchCount(
|
||||
Math.min(Math.max(value, 1), MAX_ANALYSIS_MATCH_COUNT),
|
||||
);
|
||||
}
|
||||
|
||||
private parsePuuid(value: string): string {
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length === 0 || trimmed.length > 128) {
|
||||
throw new BadRequestException('puuid is out of range.');
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
private parseQueueId(value?: string): number {
|
||||
if (value === undefined) return 420;
|
||||
const queueId = Number(value);
|
||||
if (!Number.isInteger(queueId) || queueId !== 420) {
|
||||
throw new BadRequestException('queueId is unsupported.');
|
||||
}
|
||||
return queueId;
|
||||
}
|
||||
|
||||
private resolveClientKey(request: Request): string {
|
||||
return request.ip || request.socket.remoteAddress || 'unknown-client';
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,9 @@ import { DatabaseModule } from '../global/database/database.module';
|
||||
import { SecretModule } from '../global/secret/secret.module';
|
||||
import { SecretService } from '../global/secret/secret.service';
|
||||
import { RiotModule } from '../riot/riot.module';
|
||||
import { AnalysisController } from './analysis.controller';
|
||||
import { AnalysisReadService } from './analysis-read.service';
|
||||
import { AnalysisRequestThrottleService } from './analysis-request-throttle.service';
|
||||
import { AnalysisQueueService } from './analysis-queue.service';
|
||||
import {
|
||||
ANALYSIS_JOB_ID_FACTORY,
|
||||
@@ -39,11 +42,14 @@ import { ProfileBuilderService } from './profile-builder.service';
|
||||
useValue: randomUUID,
|
||||
},
|
||||
AnalysisQueueService,
|
||||
AnalysisReadService,
|
||||
AnalysisRequestThrottleService,
|
||||
AnalysisPipelineService,
|
||||
AnalysisProcessor,
|
||||
FeatureExtractorService,
|
||||
ProfileBuilderService,
|
||||
],
|
||||
controllers: [AnalysisController],
|
||||
exports: [AnalysisQueueService, AnalysisPipelineService],
|
||||
})
|
||||
export class AnalysisModule {}
|
||||
@@ -68,7 +68,7 @@ describe('shared DTO contracts', () => {
|
||||
const request: AnalysisRequestDto = {
|
||||
gameName: 'Hide on bush',
|
||||
tagLine: 'KR1',
|
||||
platform: 'kr',
|
||||
platform: 'ph2',
|
||||
matchCount: 20,
|
||||
};
|
||||
const jobStatus: AnalysisJobStatusDto = {
|
||||
@@ -107,7 +107,7 @@ describe('shared DTO contracts', () => {
|
||||
updatedAt: '2026-07-02T00:00:00.000Z',
|
||||
};
|
||||
|
||||
expect(request.platform).toBe('kr');
|
||||
expect(request.platform).toBe('ph2');
|
||||
expect(accepted.status).toBe('queued');
|
||||
expect(jobStatus.progress.totalMatches).toBe(20);
|
||||
expect(analysis.profile.mainRole).toBe('MIDDLE');
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
import { getQueueToken } from '@nestjs/bullmq';
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { INestApplication } from '@nestjs/common';
|
||||
import {
|
||||
FEATURE_SCHEMA_VERSION,
|
||||
type PlayerAnalysisDto,
|
||||
} from '@persona-lenz/shared';
|
||||
import request from 'supertest';
|
||||
import { App } from 'supertest/types';
|
||||
import { configureApp } from './../src/app.setup';
|
||||
import { AppModule } from './../src/app.module';
|
||||
import { AnalysisQueueService } from './../src/modules/analysis/analysis-queue.service';
|
||||
import { ANALYSIS_QUEUE_NAME } from './../src/modules/analysis/analysis.constants';
|
||||
import { ConnectionService } from './../src/modules/global/database/connection.service';
|
||||
import { REDIS_CLIENT } from './../src/modules/global/redis/redis.constants';
|
||||
@@ -12,13 +17,35 @@ import { SecretService } from './../src/modules/global/secret/secret.service';
|
||||
|
||||
describe('AppController (e2e)', () => {
|
||||
let app: INestApplication<App>;
|
||||
let analysisQueueService: {
|
||||
enqueueUserAnalysis: jest.Mock;
|
||||
};
|
||||
let connectionService: {
|
||||
getModel: jest.Mock;
|
||||
};
|
||||
|
||||
function createLeanExec<T>(value: T) {
|
||||
return {
|
||||
lean: jest.fn(() => ({
|
||||
exec: jest.fn().mockResolvedValue(value),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
analysisQueueService = {
|
||||
enqueueUserAnalysis: jest.fn(),
|
||||
};
|
||||
connectionService = {
|
||||
getModel: jest.fn(),
|
||||
};
|
||||
const moduleFixture: TestingModule = await Test.createTestingModule({
|
||||
imports: [AppModule],
|
||||
})
|
||||
.overrideProvider(ConnectionService)
|
||||
.useValue({})
|
||||
.useValue(connectionService)
|
||||
.overrideProvider(AnalysisQueueService)
|
||||
.useValue(analysisQueueService)
|
||||
.overrideProvider(SecretService)
|
||||
.useValue({
|
||||
get: jest.fn((key: string) => {
|
||||
@@ -52,6 +79,337 @@ describe('AppController (e2e)', () => {
|
||||
.expect({ status: 'ok' });
|
||||
});
|
||||
|
||||
it('/api/analysis/request (POST) validates and enqueues analysis requests', async () => {
|
||||
analysisQueueService.enqueueUserAnalysis.mockResolvedValue({
|
||||
jobId: 'analysis-job-1',
|
||||
status: 'queued',
|
||||
});
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.post('/api/analysis/request')
|
||||
.send({
|
||||
gameName: ' Hide on bush ',
|
||||
ignored: 'field',
|
||||
matchCount: 999,
|
||||
tagLine: ' KR1 ',
|
||||
})
|
||||
.expect(202)
|
||||
.expect({
|
||||
jobId: 'analysis-job-1',
|
||||
status: 'queued',
|
||||
});
|
||||
|
||||
expect(analysisQueueService.enqueueUserAnalysis).toHaveBeenCalledWith({
|
||||
gameName: 'Hide on bush',
|
||||
tagLine: 'KR1',
|
||||
platformRoute: 'kr',
|
||||
regionalRoute: 'asia',
|
||||
queueId: 420,
|
||||
requestedMatchCount: 50,
|
||||
});
|
||||
});
|
||||
|
||||
it('/api/analysis/request (POST) maps non-default platforms to regional routes', async () => {
|
||||
analysisQueueService.enqueueUserAnalysis.mockResolvedValue({
|
||||
jobId: 'analysis-job-1',
|
||||
status: 'queued',
|
||||
});
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.post('/api/analysis/request')
|
||||
.send({
|
||||
gameName: 'Hide on bush',
|
||||
matchCount: 0,
|
||||
platform: 'ph2',
|
||||
tagLine: 'KR1',
|
||||
})
|
||||
.expect(202);
|
||||
|
||||
expect(analysisQueueService.enqueueUserAnalysis).toHaveBeenCalledWith({
|
||||
gameName: 'Hide on bush',
|
||||
tagLine: 'KR1',
|
||||
platformRoute: 'ph2',
|
||||
regionalRoute: 'sea',
|
||||
queueId: 420,
|
||||
requestedMatchCount: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
['short gameName', { gameName: 'x', tagLine: 'KR1' }],
|
||||
['missing tagLine', { gameName: 'Hide on bush' }],
|
||||
['long tagLine', { gameName: 'Hide on bush', tagLine: 'TOOLONG' }],
|
||||
[
|
||||
'unsupported platform',
|
||||
{ gameName: 'Hide on bush', platform: 'bad', tagLine: 'KR1' },
|
||||
],
|
||||
[
|
||||
'non-number matchCount',
|
||||
{ gameName: 'Hide on bush', matchCount: '20', tagLine: 'KR1' },
|
||||
],
|
||||
])('/api/analysis/request (POST) rejects %s', async (_label, body) => {
|
||||
await request(app.getHttpServer())
|
||||
.post('/api/analysis/request')
|
||||
.send(body)
|
||||
.expect(400);
|
||||
|
||||
expect(analysisQueueService.enqueueUserAnalysis).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('/api/analysis/request (POST) throttles repeated accepted requests', async () => {
|
||||
analysisQueueService.enqueueUserAnalysis.mockResolvedValue({
|
||||
jobId: 'analysis-job-1',
|
||||
status: 'queued',
|
||||
});
|
||||
|
||||
for (let index = 0; index < 10; index += 1) {
|
||||
await request(app.getHttpServer())
|
||||
.post('/api/analysis/request')
|
||||
.send({
|
||||
gameName: 'Hide on bush',
|
||||
tagLine: 'KR1',
|
||||
})
|
||||
.expect(202);
|
||||
}
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.post('/api/analysis/request')
|
||||
.send({
|
||||
gameName: 'Hide on bush',
|
||||
tagLine: 'KR1',
|
||||
})
|
||||
.expect(429);
|
||||
});
|
||||
|
||||
it('/api/analysis/jobs/:jobId (GET) returns job statuses', async () => {
|
||||
const records = new Map([
|
||||
[
|
||||
'queued-job',
|
||||
{
|
||||
error: undefined,
|
||||
jobId: 'queued-job',
|
||||
progress: { fetchedMatches: 0, totalMatches: 0 },
|
||||
status: 'queued',
|
||||
},
|
||||
],
|
||||
[
|
||||
'completed-job',
|
||||
{
|
||||
error: undefined,
|
||||
jobId: 'completed-job',
|
||||
progress: { fetchedMatches: 20, totalMatches: 20 },
|
||||
puuid: 'target-puuid',
|
||||
stage: 'completed',
|
||||
status: 'completed',
|
||||
},
|
||||
],
|
||||
[
|
||||
'failed-job',
|
||||
{
|
||||
error: 'internal redis hostname leaked',
|
||||
jobId: 'failed-job',
|
||||
progress: { fetchedMatches: 4, totalMatches: 20 },
|
||||
stage: 'fetch-match-details',
|
||||
status: 'failed',
|
||||
},
|
||||
],
|
||||
]);
|
||||
const findOne = jest.fn(({ jobId }: { jobId: string }) =>
|
||||
createLeanExec(records.get(jobId) ?? null),
|
||||
);
|
||||
connectionService.getModel.mockResolvedValue({
|
||||
findOne,
|
||||
});
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.get('/api/analysis/jobs/queued-job')
|
||||
.expect(200)
|
||||
.expect({
|
||||
error: null,
|
||||
jobId: 'queued-job',
|
||||
progress: { fetchedMatches: 0, totalMatches: 0 },
|
||||
status: 'queued',
|
||||
});
|
||||
await request(app.getHttpServer())
|
||||
.get('/api/analysis/jobs/completed-job')
|
||||
.expect(200)
|
||||
.expect({
|
||||
error: null,
|
||||
jobId: 'completed-job',
|
||||
progress: { fetchedMatches: 20, totalMatches: 20 },
|
||||
puuid: 'target-puuid',
|
||||
stage: 'completed',
|
||||
status: 'completed',
|
||||
});
|
||||
await request(app.getHttpServer())
|
||||
.get('/api/analysis/jobs/failed-job')
|
||||
.expect(200)
|
||||
.expect({
|
||||
error: 'Analysis failed during processing.',
|
||||
jobId: 'failed-job',
|
||||
progress: { fetchedMatches: 4, totalMatches: 20 },
|
||||
stage: 'fetch-match-details',
|
||||
status: 'failed',
|
||||
});
|
||||
|
||||
expect(findOne).toHaveBeenCalledWith({ jobId: 'queued-job' });
|
||||
expect(findOne).toHaveBeenCalledWith({ jobId: 'completed-job' });
|
||||
expect(findOne).toHaveBeenCalledWith({ jobId: 'failed-job' });
|
||||
});
|
||||
|
||||
it('/api/analysis/jobs/:jobId (GET) returns 404 for missing jobs', async () => {
|
||||
connectionService.getModel.mockResolvedValue({
|
||||
findOne: jest.fn(() => createLeanExec(null)),
|
||||
});
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.get('/api/analysis/jobs/missing-job')
|
||||
.expect(404);
|
||||
});
|
||||
|
||||
it('/api/players/:puuid/analysis/latest (GET) returns latest analysis', async () => {
|
||||
const accountFindOne = jest.fn(() =>
|
||||
createLeanExec({
|
||||
gameName: 'Hide on bush',
|
||||
profileIconId: 1,
|
||||
tagLine: 'KR1',
|
||||
tiers: [
|
||||
{
|
||||
fetchedAt: new Date('2026-07-01T00:00:00.000Z'),
|
||||
leaguePoints: 100,
|
||||
losses: 5,
|
||||
queueType: 'RANKED_SOLO_5x5',
|
||||
rank: 'I',
|
||||
tier: 'MASTER',
|
||||
wins: 10,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
const profileFindOne = jest.fn(() =>
|
||||
createLeanExec({
|
||||
championPool: [{ championId: 103, games: 4, wins: 3 }],
|
||||
confidence: 0.9,
|
||||
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||
mainRole: 'MIDDLE',
|
||||
profile: {
|
||||
kda: 0.8,
|
||||
killParticipation: 0.7,
|
||||
damageShare: 0.6,
|
||||
damagePerMin: 0.5,
|
||||
goldPerMin: 0.4,
|
||||
csPerMin: 0.3,
|
||||
visionScorePerMin: 0.2,
|
||||
wardsKilledPerMin: 0.1,
|
||||
controlWardsPlaced: 0.2,
|
||||
deathsPerMin: 0.1,
|
||||
objectiveParticipation: 0.6,
|
||||
soloKills: 0.4,
|
||||
},
|
||||
queueId: 420,
|
||||
sampleGameCount: 12,
|
||||
updatedAt: new Date('2026-07-02T00:00:00.000Z'),
|
||||
}),
|
||||
);
|
||||
connectionService.getModel.mockImplementation((modelKey: string) => {
|
||||
if (modelKey === 'account') {
|
||||
return Promise.resolve({
|
||||
findOne: accountFindOne,
|
||||
});
|
||||
}
|
||||
if (modelKey !== 'playerProfile') {
|
||||
throw new Error(`Unexpected model ${modelKey}`);
|
||||
}
|
||||
return Promise.resolve({
|
||||
findOne: profileFindOne,
|
||||
});
|
||||
});
|
||||
|
||||
const response = await request(app.getHttpServer())
|
||||
.get('/api/players/target-puuid/analysis/latest')
|
||||
.expect(200);
|
||||
const responseBody = response.body as PlayerAnalysisDto;
|
||||
|
||||
expect(accountFindOne).toHaveBeenCalledWith({ puuid: 'target-puuid' });
|
||||
expect(profileFindOne).toHaveBeenCalledWith({
|
||||
puuid: 'target-puuid',
|
||||
queueId: 420,
|
||||
});
|
||||
expect(responseBody).toEqual({
|
||||
account: {
|
||||
gameName: 'Hide on bush',
|
||||
profileIconId: 1,
|
||||
tagLine: 'KR1',
|
||||
tiers: [
|
||||
{
|
||||
fetchedAt: '2026-07-01T00:00:00.000Z',
|
||||
leaguePoints: 100,
|
||||
losses: 5,
|
||||
queueType: 'RANKED_SOLO_5x5',
|
||||
rank: 'I',
|
||||
tier: 'MASTER',
|
||||
wins: 10,
|
||||
},
|
||||
],
|
||||
},
|
||||
profile: {
|
||||
championPool: [{ championId: 103, games: 4, wins: 3 }],
|
||||
confidence: 0.9,
|
||||
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||
mainRole: 'MIDDLE',
|
||||
playstyle: {
|
||||
kda: 0.8,
|
||||
killParticipation: 0.7,
|
||||
damageShare: 0.6,
|
||||
damagePerMin: 0.5,
|
||||
goldPerMin: 0.4,
|
||||
csPerMin: 0.3,
|
||||
visionScorePerMin: 0.2,
|
||||
wardsKilledPerMin: 0.1,
|
||||
controlWardsPlaced: 0.2,
|
||||
deathsPerMin: 0.1,
|
||||
objectiveParticipation: 0.6,
|
||||
soloKills: 0.4,
|
||||
},
|
||||
queueId: 420,
|
||||
sampleGameCount: 12,
|
||||
},
|
||||
strengths: [
|
||||
{ metricId: 'deathsPerMin', value: 0.1 },
|
||||
{ metricId: 'kda', value: 0.8 },
|
||||
{ metricId: 'killParticipation', value: 0.7 },
|
||||
],
|
||||
weaknesses: [
|
||||
{ metricId: 'wardsKilledPerMin', value: 0.1 },
|
||||
{ metricId: 'visionScorePerMin', value: 0.2 },
|
||||
{ metricId: 'controlWardsPlaced', value: 0.2 },
|
||||
],
|
||||
updatedAt: '2026-07-02T00:00:00.000Z',
|
||||
});
|
||||
});
|
||||
|
||||
it('/api/players/:puuid/analysis/latest (GET) returns 404 without a profile', async () => {
|
||||
connectionService.getModel.mockImplementation((modelKey: string) => {
|
||||
if (modelKey === 'playerProfile') {
|
||||
return Promise.resolve({
|
||||
findOne: jest.fn(() => createLeanExec(null)),
|
||||
});
|
||||
}
|
||||
return Promise.resolve({
|
||||
findOne: jest.fn(() => createLeanExec({})),
|
||||
});
|
||||
});
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.get('/api/players/target-puuid/analysis/latest')
|
||||
.expect(404)
|
||||
.expect((response) => {
|
||||
expect(response.body).toMatchObject({
|
||||
message: '분석할 랭크 게임이 없음',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
@@ -13,7 +13,9 @@ export type AnalysisPlatformRoute =
|
||||
| 'ru'
|
||||
| 'me1'
|
||||
| 'oc1'
|
||||
| 'ph2'
|
||||
| 'sg2'
|
||||
| 'th2'
|
||||
| 'tw2'
|
||||
| 'vn2';
|
||||
|
||||
|
||||
Reference in new issue
Block a user