Add analysis REST API

This commit is contained in:
dahyeon committed 2026-07-02 21:01:26 -07:00
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 {}