feat(api): implement tournament support backend

This commit is contained in:
dahyeon committed 2026-05-01 17:44:48 +09:00
1 parent 6f4c03b006
commit 1fd0899756
139 files changed
+18348

No files matched your search

+22
View File
@@ -0,0 +1,22 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});
+14
View File
@@ -0,0 +1,14 @@
import { Controller, Get } from '@nestjs/common';
import { AllowPublicAccess } from './modules/auth/allow-public-access.decorator';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
@AllowPublicAccess()
getHello(): string {
return this.appService.getHello();
}
}
+42
View File
@@ -0,0 +1,42 @@
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AuctionModule } from './modules/auction/auction.module';
import { AuthModule } from './modules/auth/auth.module';
import { CommunityModule } from './modules/community/community.module';
import { CommunityStatsModule } from './modules/community-stats/community-stats.module';
import { DakaoModule } from './modules/dakao/dakao.module';
import { GlobalModule } from './modules/global/global.module';
import { LegacyImportModule } from './modules/legacy-import/legacy-import.module';
import { MatchHistoryModule } from './modules/match-history/match-history.module';
import { MatchModule } from './modules/match/match.module';
import { RiotModule } from './modules/riot/riot.module';
import { TournamentCodeModule } from './modules/tournament-code/tournament-code.module';
import { TournamentResultModule } from './modules/tournament-result/tournament-result.module';
import { UserModule } from './modules/user/user.module';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: ['../project.env', 'project.env'],
}),
GlobalModule,
AuthModule,
RiotModule,
CommunityModule,
CommunityStatsModule,
MatchModule,
MatchHistoryModule,
LegacyImportModule,
TournamentCodeModule,
TournamentResultModule,
AuctionModule,
UserModule,
DakaoModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
+8
View File
@@ -0,0 +1,8 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}
+34
View File
@@ -0,0 +1,34 @@
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule, {
rawBody: true,
});
const isDev = process.env.NODE_ENV === 'dev';
const webOrigins = process.env.WEB_ORIGIN?.split(',').map((origin) =>
origin.trim(),
) ?? [
'http://localhost:5173',
'http://126.dahyeon.us:5173',
'https://lolympus.dahyeon.us',
];
app.enableCors({
origin: isDev ? true : webOrigins,
credentials: true,
allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'],
});
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
transformOptions: { enableImplicitConversion: false },
}),
);
await app.listen(isDev ? 3000 : 10712);
}
bootstrap();
@@ -0,0 +1,140 @@
import {
BadRequestException,
Body,
Controller,
Delete,
Get,
HttpCode,
HttpStatus,
Param,
Post,
UseGuards,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
import { CurrentUser } from '../auth/current-user.decorator';
import { Roles } from '../auth/roles.decorator';
import { RolesGuard } from '../auth/roles.guard';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
import type { UserDocument } from '../global/database/schema';
import { AuctionService } from './auction.service';
import { PlaceBidDto, SoldDto, StartAuctionDto } from './dto/auction.dto';
@Controller('communities/:communityId/matches/:matchId/auction')
export class AuctionController {
constructor(private readonly auctionService: AuctionService) {}
@Post()
@Roles('admin', 'owner')
@UseGuards(RolesGuard)
public async startAuction(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: StartAuctionDto,
) {
this.assertSameCommunity(currentUser, communityId);
return this.auctionService.start({
matchId,
communityId,
captains: body.captains.map((c) => ({
side: c.side,
userId: new mongoose.Types.ObjectId(c.userId),
})),
initialPoints: body.initialPoints ?? 1000,
maxTimerSeconds: body.maxTimerSeconds ?? 30,
});
}
@Get()
@AllowPublicAccess()
public async getAuction(
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
) {
return this.auctionService.getByMatchId(matchId);
}
// 공개 — 팀장 2명만 쓸 엔드포인트(트러스트 기반, 10명 동시 관전).
@Post('open-bidding')
@AllowPublicAccess()
@HttpCode(HttpStatus.OK)
public async openBidding(
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
) {
return this.auctionService.openBidding(matchId);
}
@Post('bids')
@AllowPublicAccess()
@HttpCode(HttpStatus.OK)
public async placeBid(
@CurrentUser() currentUser: UserDocument | undefined,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: PlaceBidDto,
) {
return this.auctionService.placeBid({
matchId,
side: body.side,
amount: body.amount,
bidderUserId: this.resolveBidder(currentUser, body.bidderUserId),
});
}
@Post('sold')
@AllowPublicAccess()
@HttpCode(HttpStatus.OK)
public async markSold(
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: SoldDto,
) {
return this.auctionService.markSold({
matchId,
assignedPosition: body.assignedPosition,
});
}
@Post('next')
@AllowPublicAccess()
@HttpCode(HttpStatus.OK)
public async next(
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
) {
return this.auctionService.next(matchId);
}
@Delete()
@Roles('admin', 'owner')
@UseGuards(RolesGuard)
@HttpCode(HttpStatus.NO_CONTENT)
public async resetAuction(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
) {
this.assertSameCommunity(currentUser, communityId);
await this.auctionService.reset({ matchId, communityId });
}
private resolveBidder(
currentUser: UserDocument | undefined,
bodyBidder?: string,
): mongoose.Types.ObjectId | undefined {
if (currentUser) return currentUser._id;
if (!bodyBidder) return undefined;
if (!mongoose.isValidObjectId(bodyBidder)) {
throw new BadRequestException('Invalid bidderUserId.');
}
return new mongoose.Types.ObjectId(bodyBidder);
}
private assertSameCommunity(
user: UserDocument,
communityId: mongoose.Types.ObjectId,
): void {
if (!user.communityId.equals(communityId)) {
throw new BadRequestException('Different community.');
}
}
}
@@ -0,0 +1,354 @@
import { Logger } from '@nestjs/common';
import {
ConnectedSocket,
MessageBody,
OnGatewayConnection,
OnGatewayDisconnect,
SubscribeMessage,
WebSocketGateway,
WebSocketServer,
} from '@nestjs/websockets';
import mongoose from 'mongoose';
import type { JWTPayload } from 'jose';
import { Namespace, Socket } from 'socket.io';
import { AuthService } from '../auth/auth.service';
import { IdentityService } from '../auth/identity.service';
import { JwtService } from '../auth/jwt.service';
import { ConnectionService } from '../global/database/connection.service';
import type {
AuctionDocument,
IdentityDocument,
Position,
TeamSide,
UserDocument,
} from '../global/database/schema';
import { AuctionService } from './auction.service';
interface JoinAuctionPayload {
matchId: string;
}
interface BidPayload {
side: TeamSide;
amount: number;
bidderUserId?: string;
}
interface SoldPayload {
assignedPosition?: Position;
}
@WebSocketGateway({
namespace: '/auction',
cors: {
origin: true,
credentials: true,
allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'],
},
})
export class AuctionGateway
implements OnGatewayConnection, OnGatewayDisconnect
{
@WebSocketServer()
private server!: Namespace;
private readonly logger = new Logger(AuctionGateway.name);
private readonly roomTimers = new Map<string, NodeJS.Timeout>();
constructor(
private readonly auctionService: AuctionService,
private readonly authService: AuthService,
private readonly jwtService: JwtService,
private readonly identityService: IdentityService,
private readonly connectionService: ConnectionService,
) {}
public async handleConnection(socket: Socket) {
try {
await this.authenticateSocket(socket);
this.logger.debug(`Auction client connected: ${socket.id}`);
} catch (err) {
this.logger.warn(
`Auction client authentication failed: ${
err instanceof Error ? err.message : err
}`,
);
socket.disconnect(true);
}
}
public handleDisconnect(socket: Socket) {
const matchId = this.getSocketMatchId(socket);
if (!matchId) return;
this.maybeClearRoomTimer(matchId);
}
@SubscribeMessage('join')
public async handleJoin(
@ConnectedSocket() socket: Socket,
@MessageBody() payload: JoinAuctionPayload,
) {
if (!payload?.matchId || !mongoose.isValidObjectId(payload.matchId)) {
this.emitError(socket, 'Invalid matchId.');
return;
}
await socket.join(payload.matchId);
socket.data.matchId = payload.matchId;
try {
await this.resolveSocketUserForMatch(socket, payload.matchId);
const auction = await this.auctionService.getByMatchId(
new mongoose.Types.ObjectId(payload.matchId),
);
this.broadcastState(payload.matchId, auction);
} catch (error) {
this.emitKnownError(socket, error);
}
}
@SubscribeMessage('bid')
public async handleBid(
@ConnectedSocket() socket: Socket,
@MessageBody() payload: BidPayload,
) {
const matchId = this.requireJoinedMatchId(socket);
if (!matchId) return;
const bidderUserId = this.resolveBidderUserId(socket, payload?.bidderUserId);
if (payload?.bidderUserId && !bidderUserId) {
this.emitError(socket, 'Invalid bidderUserId.');
return;
}
try {
const auction = await this.auctionService.placeBid({
matchId: new mongoose.Types.ObjectId(matchId),
side: payload.side,
amount: payload.amount,
bidderUserId,
});
this.broadcastState(matchId, auction);
} catch (error) {
this.emitKnownError(socket, error);
}
}
@SubscribeMessage('open-bidding')
public async handleOpenBidding(@ConnectedSocket() socket: Socket) {
const matchId = this.requireJoinedMatchId(socket);
if (!matchId) return;
try {
const auction = await this.auctionService.openBidding(
new mongoose.Types.ObjectId(matchId),
);
this.broadcastState(matchId, auction);
} catch (error) {
this.emitKnownError(socket, error);
}
}
@SubscribeMessage('sold')
public async handleSold(
@ConnectedSocket() socket: Socket,
@MessageBody() payload: SoldPayload,
) {
const matchId = this.requireJoinedMatchId(socket);
if (!matchId) return;
try {
const auction = await this.auctionService.markSold({
matchId: new mongoose.Types.ObjectId(matchId),
assignedPosition: payload?.assignedPosition,
});
this.broadcastState(matchId, auction);
} catch (error) {
this.emitKnownError(socket, error);
}
}
@SubscribeMessage('next')
public async handleNext(@ConnectedSocket() socket: Socket) {
const matchId = this.requireJoinedMatchId(socket);
if (!matchId) return;
try {
const auction = await this.auctionService.next(
new mongoose.Types.ObjectId(matchId),
);
this.broadcastState(matchId, auction);
} catch (error) {
this.emitKnownError(socket, error);
}
}
private requireJoinedMatchId(socket: Socket): string | null {
const matchId = this.getSocketMatchId(socket);
if (!matchId) {
this.emitError(socket, 'Join a match room before sending events.');
return null;
}
return matchId;
}
private getSocketMatchId(socket: Socket): string | undefined {
return typeof socket.data.matchId === 'string'
? socket.data.matchId
: undefined;
}
private resolveBidderUserId(
socket: Socket,
payloadBidderUserId?: string,
): mongoose.Types.ObjectId | undefined {
const candidate =
payloadBidderUserId ??
(socket.data.user as UserDocument | undefined)?._id.toString() ??
this.readHandshakeUserId(socket);
if (!candidate || !mongoose.isValidObjectId(candidate)) {
return undefined;
}
return new mongoose.Types.ObjectId(candidate);
}
private readHandshakeUserId(socket: Socket): string | undefined {
const authUserId = socket.handshake.auth['x-auth-user-id'];
if (typeof authUserId === 'string') return authUserId;
const header = socket.handshake.headers['x-auth-user-id'];
return Array.isArray(header) ? header[0] : header;
}
private async authenticateSocket(socket: Socket): Promise<void> {
const fallback = await this.authService.resolveDevUserById(
this.readHandshakeUserId(socket),
);
if (fallback) {
socket.data.user = fallback.user;
socket.data.identity = fallback.identity;
return;
}
const token = this.readHandshakeToken(socket);
if (!token) {
// 임시 운영용: 경매 진행 중에는 로그인 없이도 관전/팀장 모드 선택/입찰을 허용한다.
return;
}
const { payload } = await this.jwtService.verify(
token,
'MICROSOFT_ENTRAID',
);
socket.data.identity = await this.identityService.findOrCreateByOid({
entraOid: this.requireStringClaim(payload, 'oid'),
tenantId: this.stringClaim(payload.tid),
email:
this.stringClaim(payload.preferred_username) ??
this.stringClaim(payload.email),
displayName: this.stringClaim(payload.name),
});
}
private readHandshakeToken(socket: Socket): string | undefined {
const authToken = socket.handshake.auth.token;
if (typeof authToken === 'string' && authToken.trim()) {
return authToken.trim().replace(/^Bearer\s+/i, '');
}
const header = socket.handshake.headers.authorization;
const authorization = Array.isArray(header) ? header[0] : header;
if (authorization?.startsWith('Bearer ')) {
return authorization.slice('Bearer '.length).trim();
}
return undefined;
}
private async resolveSocketUserForMatch(
socket: Socket,
matchId: string,
): Promise<void> {
if (socket.data.user || !socket.data.identity) return;
const MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findById(matchId).select({
communityId: 1,
});
if (!match) return;
const UserModel = await this.connectionService.getModel('user');
socket.data.user = await UserModel.findOne({
communityId: match.communityId,
identityId: (socket.data.identity as IdentityDocument)._id,
}).exec();
}
private requireStringClaim(payload: JWTPayload, key: string): string {
const value = payload[key];
if (typeof value !== 'string' || value.length === 0) {
throw new Error(`Token is missing ${key} claim.`);
}
return value;
}
private stringClaim(value: unknown): string | undefined {
return typeof value === 'string' && value.length > 0 ? value : undefined;
}
private broadcastState(matchId: string, auction: AuctionDocument) {
this.server.to(matchId).emit('state', this.serializeAuction(auction));
this.syncRoomTimer(matchId, auction);
}
private syncRoomTimer(matchId: string, auction: AuctionDocument) {
this.clearRoomTimer(matchId);
if (!auction.currentDeadline) return;
const deadline = auction.currentDeadline;
const deadlineIso = deadline.toISOString();
this.server.to(matchId).emit('tick', {
deadline: deadlineIso,
serverTime: new Date().toISOString(),
});
const timer = setInterval(() => {
this.server.to(matchId).emit('tick', {
deadline: deadlineIso,
serverTime: new Date().toISOString(),
});
if (Date.now() >= deadline.getTime()) {
this.clearRoomTimer(matchId);
}
}, 1000);
this.roomTimers.set(matchId, timer);
}
private maybeClearRoomTimer(matchId: string) {
const room = this.server.adapter.rooms.get(matchId);
if (room && room.size > 0) return;
this.clearRoomTimer(matchId);
}
private clearRoomTimer(matchId: string) {
const timer = this.roomTimers.get(matchId);
if (!timer) return;
clearInterval(timer);
this.roomTimers.delete(matchId);
}
private emitKnownError(socket: Socket, error: unknown) {
const message =
error instanceof Error ? error.message : 'Unexpected auction gateway error.';
this.emitError(socket, message);
}
private emitError(socket: Socket, message: string) {
socket.emit('error', { message });
}
private serializeAuction(auction: AuctionDocument) {
return JSON.parse(JSON.stringify(auction));
}
}
@@ -0,0 +1,15 @@
import { Module } from '@nestjs/common';
import { RiotModule } from '../riot/riot.module';
import { TournamentCodeModule } from '../tournament-code/tournament-code.module';
import { TournamentResultModule } from '../tournament-result/tournament-result.module';
import { AuctionGateway } from './auction.gateway';
import { AuctionController } from './auction.controller';
import { AuctionService } from './auction.service';
@Module({
imports: [RiotModule, TournamentCodeModule, TournamentResultModule],
controllers: [AuctionController],
providers: [AuctionService, AuctionGateway],
exports: [AuctionService],
})
export class AuctionModule {}
@@ -0,0 +1,262 @@
import mongoose from 'mongoose';
import { AuctionService } from './auction.service';
describe('AuctionService', () => {
function createService(models: Record<string, unknown>) {
const connectionService = {
getModel: jest.fn((name: string) => models[name]),
createSession: jest.fn(),
};
const enrichmentService = {
enrichRiotAccount: jest.fn(),
};
const tournamentCodeService = {
reserveForMatch: jest.fn().mockResolvedValue(undefined),
releaseFromMatch: jest.fn().mockResolvedValue(undefined),
};
const tournamentResultService = {
scheduleInitialPoll: jest.fn().mockResolvedValue(null),
};
return {
service: new AuctionService(
connectionService as never,
enrichmentService as never,
tournamentCodeService as never,
tournamentResultService as never,
),
connectionService,
tournamentCodeService,
tournamentResultService,
};
}
function createFullTeam(side: 'blue' | 'red') {
return {
side,
captainUserId: new mongoose.Types.ObjectId(),
points: 100,
members: Array.from({ length: 4 }, () => ({
userId: new mongoose.Types.ObjectId(),
assignedPosition: 'MID',
cost: 10,
})),
};
}
it('rejects bids when the team already has 5 members including captain', async () => {
const matchId = new mongoose.Types.ObjectId();
const auction = {
phase: 'bidding',
teams: [createFullTeam('blue'), createFullTeam('red')],
currentBid: 10,
save: jest.fn().mockResolvedValue(undefined),
};
const { service } = createService({
auction: {
findOne: jest.fn().mockResolvedValue(auction),
},
});
await expect(
service.placeBid({
matchId,
side: 'blue',
amount: 20,
}),
).rejects.toThrow('Team already has maximum members.');
expect(auction.save).not.toHaveBeenCalled();
});
it('rejects sold confirmation when the winning team is already full', async () => {
const matchId = new mongoose.Types.ObjectId();
const auction = {
phase: 'bidding',
currentBidder: 'blue',
currentBid: 20,
currentIndex: 0,
order: [
{
userId: new mongoose.Types.ObjectId(),
preferredPositions: [{ position: 'ADC', priority: 1 }],
},
],
teams: [createFullTeam('blue'), createFullTeam('red')],
save: jest.fn().mockResolvedValue(undefined),
};
const { service } = createService({
auction: {
findOne: jest.fn().mockResolvedValue(auction),
},
});
await expect(service.markSold({ matchId })).rejects.toThrow(
'Team already has maximum members.',
);
expect(auction.save).not.toHaveBeenCalled();
});
it('syncs completed auction teams into the match document', async () => {
const matchId = new mongoose.Types.ObjectId();
const blueCaptainId = new mongoose.Types.ObjectId();
const redCaptainId = new mongoose.Types.ObjectId();
const blueMemberId = new mongoose.Types.ObjectId();
const redMemberId = new mongoose.Types.ObjectId();
const auction = {
matchId,
phase: 'sold',
currentIndex: 1,
order: [{ userId: blueMemberId }, { userId: redMemberId }],
teams: [
{
side: 'blue',
captainUserId: blueCaptainId,
points: 970,
members: [
{
userId: blueMemberId,
assignedPosition: 'ADC',
cost: 30,
},
],
},
{
side: 'red',
captainUserId: redCaptainId,
points: 940,
members: [
{
userId: redMemberId,
assignedPosition: 'JGL',
cost: 60,
},
],
},
],
save: jest.fn().mockResolvedValue(undefined),
};
const match = {
participants: [
{
userId: blueCaptainId,
preferredPositions: [{ position: 'TOP', priority: 1 }],
},
{
userId: redCaptainId,
preferredPositions: [{ position: 'MID', priority: 1 }],
},
{
userId: blueMemberId,
preferredPositions: [{ position: 'ADC', priority: 1 }],
},
{
userId: redMemberId,
preferredPositions: [{ position: 'JGL', priority: 1 }],
},
],
status: 'team-built',
teams: [],
save: jest.fn().mockResolvedValue(undefined),
};
const { service } = createService({
auction: {
findOne: jest.fn().mockResolvedValue(auction),
},
match: {
findById: jest.fn().mockResolvedValue(match),
},
});
await service.next(matchId);
expect(auction.phase).toBe('complete');
expect(auction.completedAt).toBeInstanceOf(Date);
expect(auction.save).toHaveBeenCalledTimes(1);
expect(match.save).toHaveBeenCalledTimes(1);
expect(match.teams).toEqual([
{
side: 'blue',
name: '블루팀',
captainUserId: blueCaptainId,
members: [
{
userId: blueCaptainId,
assignedPosition: 'TOP',
cost: 0,
},
{
userId: blueMemberId,
assignedPosition: 'ADC',
cost: 30,
},
],
},
{
side: 'red',
name: '레드팀',
captainUserId: redCaptainId,
members: [
{
userId: redCaptainId,
assignedPosition: 'MID',
cost: 0,
},
{
userId: redMemberId,
assignedPosition: 'JGL',
cost: 60,
},
],
},
]);
});
it('clears match teams when resetting an auction', async () => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
const session = {
startTransaction: jest.fn(),
commitTransaction: jest.fn().mockResolvedValue(undefined),
abortTransaction: jest.fn().mockResolvedValue(undefined),
endSession: jest.fn().mockResolvedValue(undefined),
};
const auction = {
deleteOne: jest.fn().mockResolvedValue(undefined),
};
const match = {
communityId,
status: 'team-built',
teams: [
{
side: 'blue',
name: '블루팀',
members: [],
},
],
save: jest.fn().mockResolvedValue(undefined),
};
const auctionFindOneQuery = {
session: jest.fn().mockResolvedValue(auction),
};
const matchFindByIdQuery = {
session: jest.fn().mockResolvedValue(match),
};
const { service, connectionService } = createService({
auction: {
findOne: jest.fn().mockReturnValue(auctionFindOneQuery),
},
match: {
findById: jest.fn().mockReturnValue(matchFindByIdQuery),
},
});
connectionService.createSession.mockResolvedValue(session);
await service.reset({ matchId, communityId });
expect(match.status).toBe('recruiting');
expect(match.teams).toEqual([]);
expect(match.save).toHaveBeenCalledWith({ session });
expect(session.commitTransaction).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,436 @@
import {
BadRequestException,
Injectable,
InternalServerErrorException,
NotFoundException,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import {
AuctionDocument,
AuctionPlayerSnapshot,
AuctionTeam,
MatchTeamMember,
Position,
TeamSide,
} from '../global/database/schema';
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
import { TournamentCodeService } from '../tournament-code/tournament-code.service';
import { TournamentResultService } from '../tournament-result/tournament-result.service';
const AUCTION_MAX_TEAM_SIZE = 5;
interface StartAuctionParams {
matchId: mongoose.Types.ObjectId;
communityId: mongoose.Types.ObjectId;
captains: { side: TeamSide; userId: mongoose.Types.ObjectId }[];
initialPoints: number;
maxTimerSeconds: number;
}
interface PlaceBidParams {
matchId: mongoose.Types.ObjectId;
side: TeamSide;
amount: number;
bidderUserId?: mongoose.Types.ObjectId;
}
interface MarkSoldParams {
matchId: mongoose.Types.ObjectId;
assignedPosition?: Position;
}
@Injectable()
export class AuctionService {
constructor(
private readonly connectionService: ConnectionService,
private readonly enrichmentService: RiotAccountEnrichmentService,
private readonly tournamentCodeService: TournamentCodeService,
private readonly tournamentResultService: TournamentResultService,
) {}
public async start(params: StartAuctionParams): Promise<AuctionDocument> {
const MatchModel = await this.connectionService.getModel('match');
const UserModel = await this.connectionService.getModel('user');
const AuctionModel = await this.connectionService.getModel('auction');
const CommunityModel = await this.connectionService.getModel('community');
const match = await MatchModel.findById(params.matchId);
if (!match) throw new NotFoundException('Match not found.');
if (!match.communityId.equals(params.communityId)) {
throw new BadRequestException('Match does not belong to this community.');
}
const existing = await AuctionModel.findOne({ matchId: params.matchId });
if (existing) {
throw new BadRequestException('Auction already exists for this match.');
}
const captainUserIds = params.captains.map((c) => c.userId);
if (captainUserIds[0].equals(captainUserIds[1])) {
throw new BadRequestException('Captains must be different users.');
}
const captainParticipants = match.participants.filter((p) =>
captainUserIds.some((cid) => cid.equals(p.userId)),
);
if (captainParticipants.length !== 2) {
throw new BadRequestException(
'Both captains must be participants of the match.',
);
}
if (
match.participants.length >
params.captains.length * AUCTION_MAX_TEAM_SIZE
) {
throw new BadRequestException(
'Auction supports up to 5 members per team including captains.',
);
}
const basePlayerUsers = await UserModel.find({
_id: {
$in: match.participants
.filter((p) => !captainUserIds.some((cid) => cid.equals(p.userId)))
.map((p) => p.userId),
},
});
const community = await CommunityModel.findById(match.communityId)
.select({ riotPlatform: 1, riotRegion: 1 })
.lean()
.exec();
const platform = community?.riotPlatform ?? 'kr';
const region = community?.riotRegion ?? 'asia';
const enrichTargets = basePlayerUsers
.map((user) => ({
userId: user._id,
puuid: (user.riotAccounts.find((account) => account.isPrimary) ?? user.riotAccounts[0])
?.puuid,
}))
.filter((target): target is { userId: mongoose.Types.ObjectId; puuid: string } =>
typeof target.puuid === 'string' && target.puuid.length > 0,
);
await runWithConcurrency(enrichTargets, 3, async (target) => {
await this.enrichmentService.enrichRiotAccount({
userId: target.userId,
puuid: target.puuid,
options: {
force: false,
platform,
region,
},
});
});
const playerUsers = await UserModel.find({
_id: { $in: basePlayerUsers.map((user) => user._id) },
});
const userById = new Map(playerUsers.map((u) => [u._id.toString(), u]));
const nonCaptainPuuids = new Set<string>();
const order: AuctionPlayerSnapshot[] = [];
for (const participant of match.participants) {
if (captainUserIds.some((cid) => cid.equals(participant.userId))) {
continue;
}
const user = userById.get(participant.userId.toString());
if (!user) continue;
const primary =
user.riotAccounts.find((a) => a.isPrimary) ?? user.riotAccounts[0];
if (!primary) {
throw new BadRequestException(
`Participant ${user._id.toString()} has no Riot account.`,
);
}
if (nonCaptainPuuids.has(primary.puuid)) continue;
nonCaptainPuuids.add(primary.puuid);
order.push({
userId: user._id,
puuid: primary.puuid,
gameName: primary.gameName,
tagLine: primary.tagLine,
profileIconId: primary.profileIconId,
preferredPositions: participant.preferredPositions,
tiers: primary.tiers,
masteries: primary.championMasteries,
recentStatsSummary: primary.recentStatsSummary,
});
}
const auction = await AuctionModel.create({
matchId: params.matchId,
phase: 'presenting',
teams: params.captains.map((c) => ({
side: c.side,
captainUserId: c.userId,
points: params.initialPoints,
members: [],
})),
order,
currentIndex: 0,
bids: [],
currentBid: 0,
maxTimerSeconds: params.maxTimerSeconds,
initialPoints: params.initialPoints,
startedAt: new Date(),
});
match.status = 'team-built';
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
await match.save();
await this.tournamentCodeService.reserveForMatch(match);
await this.tournamentResultService.scheduleInitialPoll(match);
return auction;
}
public async getByMatchId(
matchId: mongoose.Types.ObjectId,
): Promise<AuctionDocument> {
const AuctionModel = await this.connectionService.getModel('auction');
const auction = await AuctionModel.findOne({ matchId });
if (!auction) throw new NotFoundException('Auction not found.');
return auction;
}
public async openBidding(
matchId: mongoose.Types.ObjectId,
): Promise<AuctionDocument> {
const auction = await this.getByMatchId(matchId);
if (auction.phase !== 'presenting') {
throw new BadRequestException('Auction is not in presenting phase.');
}
auction.phase = 'bidding';
auction.currentBid = 0;
auction.currentBidder = undefined;
auction.currentDeadline = this.createDeadline(auction.maxTimerSeconds);
await auction.save();
return auction;
}
public async placeBid(params: PlaceBidParams): Promise<AuctionDocument> {
const auction = await this.getByMatchId(params.matchId);
if (auction.phase !== 'bidding') {
throw new BadRequestException('Auction is not in bidding phase.');
}
const team = auction.teams.find((t) => t.side === params.side);
if (!team) throw new BadRequestException('Unknown team side.');
if (params.amount <= auction.currentBid) {
throw new BadRequestException('Bid must exceed current bid.');
}
if (params.amount > team.points) {
throw new BadRequestException('Bid exceeds team points.');
}
this.assertTeamHasSlot(team);
// 임시 운영용: 클라이언트에서 선택한 팀장 모드를 신뢰하고 실제 로그인 사용자 검증은 건너뛴다.
auction.currentBid = params.amount;
auction.currentBidder = params.side;
auction.currentDeadline = this.createDeadline(
this.resolveBidExtensionSeconds(auction),
);
auction.bids.push({
side: params.side,
amount: params.amount,
bidderUserId: team.captainUserId,
timestamp: new Date(),
});
await auction.save();
return auction;
}
public async markSold(params: MarkSoldParams): Promise<AuctionDocument> {
const auction = await this.getByMatchId(params.matchId);
if (auction.phase !== 'bidding') {
throw new BadRequestException('Auction is not in bidding phase.');
}
if (!auction.currentBidder || auction.currentBid <= 0) {
throw new BadRequestException('No bid to mark sold.');
}
const team = auction.teams.find((t) => t.side === auction.currentBidder);
if (!team) throw new BadRequestException('Winning team not found.');
this.assertTeamHasSlot(team);
const current = auction.order[auction.currentIndex];
if (!current) throw new BadRequestException('No current player.');
const preferredPrimary = current.preferredPositions[0]?.position;
team.members.push({
userId: current.userId,
assignedPosition: params.assignedPosition ?? preferredPrimary ?? 'MID',
cost: auction.currentBid,
});
team.points -= auction.currentBid;
auction.phase = 'sold';
auction.currentDeadline = undefined;
await auction.save();
return auction;
}
public async next(
matchId: mongoose.Types.ObjectId,
): Promise<AuctionDocument> {
const auction = await this.getByMatchId(matchId);
if (auction.phase !== 'sold' && auction.phase !== 'presenting') {
throw new BadRequestException('Cannot advance from current phase.');
}
const nextIndex = auction.currentIndex + 1;
if (nextIndex >= auction.order.length) {
auction.phase = 'complete';
auction.completedAt = new Date();
} else {
auction.currentIndex = nextIndex;
auction.phase = 'presenting';
auction.currentBid = 0;
auction.currentBidder = undefined;
}
auction.currentDeadline = undefined;
await auction.save();
if (auction.phase === 'complete') {
await this.syncMatchTeamsFromAuction(auction);
}
return auction;
}
public async reset(params: {
matchId: mongoose.Types.ObjectId;
communityId: mongoose.Types.ObjectId;
}): Promise<void> {
const AuctionModel = await this.connectionService.getModel('auction');
const MatchModel = await this.connectionService.getModel('match');
const session = await this.connectionService.createSession();
if (!session) {
throw new InternalServerErrorException('Failed to start DB session.');
}
try {
session.startTransaction();
const auction = await AuctionModel.findOne({
matchId: params.matchId,
}).session(session);
if (!auction) throw new NotFoundException('Auction not found.');
const match = await MatchModel.findById(params.matchId).session(session);
if (!match) throw new NotFoundException('Match not found.');
if (!match.communityId.equals(params.communityId)) {
throw new BadRequestException('Community mismatch.');
}
await auction.deleteOne({ session });
if (match.status === 'team-built') {
await this.tournamentCodeService.releaseFromMatch(match);
match.status = 'recruiting';
match.teams = [];
match.tournamentCodeIds = [];
match.teamBuiltAt = undefined;
match.result = undefined;
match.resultPollState = undefined;
await match.save({ session });
}
await session.commitTransaction();
} catch (err) {
await session.abortTransaction();
throw err;
} finally {
await session.endSession();
}
}
private createDeadline(secondsFromNow: number): Date {
return new Date(Date.now() + secondsFromNow * 1000);
}
private resolveBidExtensionSeconds(auction: AuctionDocument): number {
if (!auction.currentDeadline) {
return auction.maxTimerSeconds;
}
const remainingSeconds = Math.ceil(
(auction.currentDeadline.getTime() - Date.now()) / 1000,
);
return Math.max(5, remainingSeconds);
}
private assertTeamHasSlot(team: AuctionTeam): void {
if (this.countTeamMembersIncludingCaptain(team) >= AUCTION_MAX_TEAM_SIZE) {
throw new BadRequestException('Team already has maximum members.');
}
}
private countTeamMembersIncludingCaptain(team: AuctionTeam): number {
const userIds = new Set<string>([team.captainUserId.toString()]);
for (const member of team.members) {
userIds.add(member.userId.toString());
}
return userIds.size;
}
private async syncMatchTeamsFromAuction(
auction: AuctionDocument,
): Promise<void> {
const MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findById(auction.matchId);
if (!match) throw new NotFoundException('Match not found.');
const participantByUserId = new Map(
match.participants.map((participant) => [
participant.userId.toString(),
participant,
]),
);
match.teams = auction.teams.map((team) => {
const captain = participantByUserId.get(team.captainUserId.toString());
const members: MatchTeamMember[] = [
{
userId: team.captainUserId,
assignedPosition: captain?.preferredPositions[0]?.position ?? 'MID',
cost: 0,
},
...team.members
.filter((member) => !member.userId.equals(team.captainUserId))
.map((member) => ({
userId: member.userId,
assignedPosition: member.assignedPosition,
cost: member.cost,
})),
];
return {
side: team.side,
name: this.resolveTeamName(team.side),
captainUserId: team.captainUserId,
members,
};
});
match.status = 'team-built';
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
await match.save();
await this.tournamentCodeService.reserveForMatch(match);
await this.tournamentResultService.scheduleInitialPoll(match);
}
private resolveTeamName(side: TeamSide): string {
return side === 'blue' ? '블루팀' : '레드팀';
}
}
async function runWithConcurrency<T>(
items: T[],
concurrency: number,
worker: (item: T) => Promise<void>,
): Promise<void> {
if (items.length === 0) return;
const queue = [...items];
const runners = Array.from({ length: Math.min(concurrency, queue.length) }, async () => {
while (queue.length > 0) {
const item = queue.shift();
if (item === undefined) return;
await worker(item);
}
});
await Promise.allSettled(runners);
}
@@ -0,0 +1,60 @@
import { Type } from 'class-transformer';
import {
ArrayMaxSize,
ArrayMinSize,
IsArray,
IsEnum,
IsInt,
IsMongoId,
IsOptional,
Min,
ValidateNested,
} from 'class-validator';
import { TEAM_SIDES } from '../../global/database/schema';
import type { TeamSide } from '../../global/database/schema';
class CaptainAssignmentDto {
@IsEnum(TEAM_SIDES)
side!: TeamSide;
@IsMongoId()
userId!: string;
}
export class StartAuctionDto {
@IsArray()
@ArrayMinSize(2)
@ArrayMaxSize(2)
@ValidateNested({ each: true })
@Type(() => CaptainAssignmentDto)
captains!: CaptainAssignmentDto[];
@IsOptional()
@IsInt()
@Min(1)
initialPoints?: number;
@IsOptional()
@IsInt()
@Min(5)
maxTimerSeconds?: number;
}
export class PlaceBidDto {
@IsEnum(TEAM_SIDES)
side!: TeamSide;
@IsInt()
@Min(1)
amount!: number;
@IsOptional()
@IsMongoId()
bidderUserId?: string;
}
export class SoldDto {
@IsOptional()
@IsEnum(['TOP', 'JGL', 'MID', 'ADC', 'SUP'])
assignedPosition?: 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP';
}
@@ -0,0 +1,7 @@
import { SetMetadata } from '@nestjs/common';
export const METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED =
'lolympus:allow_public_access';
export const AllowPublicAccess = () =>
SetMetadata(METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED, true);
+16
View File
@@ -0,0 +1,16 @@
import type { JWTHeaderParameters, JWTPayload } from 'jose';
import type {
IdentityDocument,
UserDocument,
} from '../global/database/schema';
import type { IdentityProviderName } from './jwt.service';
declare module 'express' {
interface Request {
tokenPayload?: JWTPayload;
tokenHeader?: JWTHeaderParameters;
identityProvider?: IdentityProviderName;
identity?: IdentityDocument;
user?: UserDocument;
}
}
@@ -0,0 +1,18 @@
import { Injectable, NestMiddleware } from '@nestjs/common';
import type { NextFunction, Request, Response } from 'express';
import { AuthService } from './auth.service';
import './auth-request';
@Injectable()
export class AuthMiddleware implements NestMiddleware {
constructor(private readonly authService: AuthService) {}
public async use(req: Request, _res: Response, next: NextFunction) {
const fallback = await this.authService.resolveDevFallbackFromRequest(req);
if (fallback) {
req.user = fallback.user;
req.identity = fallback.identity;
}
next();
}
}
+33
View File
@@ -0,0 +1,33 @@
import { Global, Module } from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
import { AuthService } from './auth.service';
import { IdentityResolverGuard } from './identity-resolver.guard';
import { IdentityService } from './identity.service';
import { JwtAuthGuard } from './jwt.guard';
import { JwtService } from './jwt.service';
import { RolesGuard } from './roles.guard';
import { UserResolverGuard } from './user-resolver.guard';
@Global()
@Module({
providers: [
AuthService,
JwtService,
IdentityService,
JwtAuthGuard,
IdentityResolverGuard,
UserResolverGuard,
RolesGuard,
{ provide: APP_GUARD, useClass: JwtAuthGuard },
{ provide: APP_GUARD, useClass: IdentityResolverGuard },
{ provide: APP_GUARD, useClass: UserResolverGuard },
],
exports: [
AuthService,
JwtService,
IdentityService,
UserResolverGuard,
RolesGuard,
],
})
export class AuthModule {}
+62
View File
@@ -0,0 +1,62 @@
import { Injectable } from '@nestjs/common';
import type { Request } from 'express';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import {
IdentityDocument,
UserDocument,
} from '../global/database/schema';
import { SecretService } from '../global/secret/secret.service';
import './auth-request';
interface DevFallbackResult {
user: UserDocument;
identity?: IdentityDocument;
}
@Injectable()
export class AuthService {
constructor(
private readonly connectionService: ConnectionService,
private readonly secretService: SecretService,
) {}
public async resolveDevFallbackFromRequest(
req: Request,
): Promise<DevFallbackResult | null> {
if (!(await this.isDevHeaderEnabled())) return null;
const header = req.headers['x-auth-user-id'];
const userId = Array.isArray(header) ? header[0] : header;
return this.resolveDevUserById(userId);
}
public async resolveDevUserById(
userId: unknown,
): Promise<DevFallbackResult | null> {
if (!(await this.isDevHeaderEnabled())) return null;
if (typeof userId !== 'string' || !mongoose.isValidObjectId(userId)) {
return null;
}
const UserModel = await this.connectionService.getModel('user');
const user = await UserModel.findById(userId).exec();
if (!user) return null;
const result: DevFallbackResult = { user };
if (user.identityId) {
const IdentityModel = await this.connectionService.getModel('identity');
const identity = await IdentityModel.findById(user.identityId).exec();
if (identity) result.identity = identity;
}
return result;
}
private async isDevHeaderEnabled(): Promise<boolean> {
if (process.env.NODE_ENV === 'prod') return false;
const value = await this.secretService.get<string>(
'AUTH_DEV_HEADER_ENABLED',
process.env.AUTH_DEV_HEADER_ENABLED ?? 'false',
);
return value === 'true';
}
}
@@ -0,0 +1,11 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import type { Request } from 'express';
import { IdentityDocument } from '../global/database/schema';
import './auth-request';
export const CurrentIdentity = createParamDecorator(
(_data: unknown, ctx: ExecutionContext): IdentityDocument | undefined => {
const req = ctx.switchToHttp().getRequest<Request>();
return req.identity;
},
);
@@ -0,0 +1,11 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import type { Request } from 'express';
import { UserDocument } from '../global/database/schema';
import './auth-request';
export const CurrentUser = createParamDecorator(
(_data: unknown, ctx: ExecutionContext): UserDocument | undefined => {
const req = ctx.switchToHttp().getRequest<Request>();
return req.user;
},
);
@@ -0,0 +1,38 @@
import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import type { Request } from 'express';
import { IdentityService } from './identity.service';
import './auth-request';
@Injectable()
export class IdentityResolverGuard implements CanActivate {
constructor(private readonly identityService: IdentityService) {}
public async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<Request>();
if (request.identity || !request.tokenPayload) return true;
const entraOid = stringClaim(request.tokenPayload.oid);
if (!entraOid) {
throw new UnauthorizedException('Token is missing oid claim.');
}
request.identity = await this.identityService.findOrCreateByOid({
entraOid,
tenantId: stringClaim(request.tokenPayload.tid),
email:
stringClaim(request.tokenPayload.preferred_username) ??
stringClaim(request.tokenPayload.email),
displayName: stringClaim(request.tokenPayload.name),
});
return true;
}
}
function stringClaim(value: unknown): string | undefined {
return typeof value === 'string' && value.length > 0 ? value : undefined;
}
@@ -0,0 +1,39 @@
import { Injectable, InternalServerErrorException } from '@nestjs/common';
import { ConnectionService } from '../global/database/connection.service';
import { IdentityDocument } from '../global/database/schema';
interface IdentityInput {
entraOid: string;
tenantId?: string;
email?: string;
displayName?: string;
}
@Injectable()
export class IdentityService {
constructor(private readonly connectionService: ConnectionService) {}
public async findOrCreateByOid(
input: IdentityInput,
): Promise<IdentityDocument> {
const IdentityModel = await this.connectionService.getModel('identity');
const identity = await IdentityModel.findOneAndUpdate(
{ entraOid: input.entraOid },
{
$set: {
tenantId: input.tenantId,
email: input.email,
displayName: input.displayName,
lastSignInAt: new Date(),
},
$setOnInsert: { entraOid: input.entraOid },
},
{ upsert: true, returnDocument: 'after', setDefaultsOnInsert: true },
).exec();
if (!identity) {
throw new InternalServerErrorException('Failed to resolve identity.');
}
return identity;
}
}
+91
View File
@@ -0,0 +1,91 @@
import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { decodeJwt } from 'jose';
import type { Request } from 'express';
import { METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED } from './allow-public-access.decorator';
import { AuthService } from './auth.service';
import { IdentityProviderName, JwtService } from './jwt.service';
import './auth-request';
@Injectable()
export class JwtAuthGuard implements CanActivate {
constructor(
private readonly reflector: Reflector,
private readonly jwtService: JwtService,
private readonly authService: AuthService,
) {}
public async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<Request>();
const isPublicAccessAllowed = this.reflector.getAllAndOverride<boolean>(
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
[context.getHandler(), context.getClass()],
);
const authz = request.headers?.authorization;
const authzHeader = Array.isArray(authz) ? authz[0] : authz;
if (!authzHeader) {
const fallback =
await this.authService.resolveDevFallbackFromRequest(request);
if (fallback) {
request.user = fallback.user;
request.identity = fallback.identity;
return true;
}
if (isPublicAccessAllowed) return true;
throw new UnauthorizedException(
'Missing or invalid Authorization header',
);
}
if (!authzHeader.startsWith('Bearer ')) {
throw new UnauthorizedException(
'Missing or invalid Authorization header',
);
}
const token = authzHeader.slice('Bearer '.length).trim();
if (!token) {
throw new UnauthorizedException('Empty bearer token');
}
const identityProvider = this.pickIdPFromToken(token);
try {
const verifyResult = await this.jwtService.verify(
token,
identityProvider,
);
request.tokenPayload = verifyResult.payload;
request.tokenHeader = verifyResult.protectedHeader;
request.identityProvider = identityProvider;
return true;
} catch (err) {
const message =
err instanceof Error ? err.message : 'JWT verification failed';
throw new UnauthorizedException(message);
}
}
private pickIdPFromToken(token: string): IdentityProviderName {
try {
const { iss } = decodeJwt(token) as { iss?: string };
if (!iss) {
throw new Error('Token has no issuer (iss) claim');
}
const lower = iss.toLowerCase();
if (lower.includes('login.microsoftonline.com')) {
return 'MICROSOFT_ENTRAID';
}
throw new Error(`Unknown issuer: ${iss}`);
} catch (err) {
const message = err instanceof Error ? err.message : 'Unable to decode token';
throw new UnauthorizedException(message);
}
}
}
+100
View File
@@ -0,0 +1,100 @@
import { Injectable } from '@nestjs/common';
import {
createRemoteJWKSet,
jwtVerify,
JWTPayload,
JWTVerifyGetKey,
JWTVerifyResult,
} from 'jose';
import { SecretService } from '../global/secret/secret.service';
export type IdentityProviderName = 'MICROSOFT_ENTRAID';
interface EntraConfig {
tenantId: string;
audience: string;
issuer: string;
allowedAlgs: string[];
jwks: JWTVerifyGetKey;
}
@Injectable()
export class JwtService {
private entraConfig?: EntraConfig;
private readonly clockTolerance = Number(
process.env.JWT_CLOCK_TOLERANCE || 5,
);
constructor(private readonly secretService: SecretService) {}
public async verify(
token: string,
identityProvider: IdentityProviderName,
): Promise<JWTVerifyResult<JWTPayload>> {
if (!token) {
throw new Error('Empty token');
}
if (identityProvider !== 'MICROSOFT_ENTRAID') {
throw new Error(`Identity provider not configured: ${identityProvider}`);
}
const provider = await this.getEntraConfig();
const result = await jwtVerify(token, provider.jwks, {
issuer: provider.issuer,
audience: provider.audience,
algorithms: provider.allowedAlgs,
clockTolerance: this.clockTolerance,
});
const { payload, protectedHeader } = result;
if (!provider.allowedAlgs.includes(protectedHeader.alg as string)) {
throw new Error(`Unexpected alg: ${protectedHeader.alg}`);
}
if (payload.ver && payload.ver !== '2.0') {
throw new Error(`Unsupported Entra token version: ${payload.ver}`);
}
if (payload.tid && payload.tid !== provider.tenantId) {
throw new Error(`Unexpected tenant: ${payload.tid}`);
}
return result;
}
private async getEntraConfig(): Promise<EntraConfig> {
if (this.entraConfig) return this.entraConfig;
await this.secretService.ready();
const [audience, tenantId, allowedAlgsRaw] = await Promise.all([
this.secretService.get<string>('JWT_CLAIM_AUDIENCE'),
this.secretService.get<string>('MICROSOFT_ENTRAID_TENANT_ID'),
this.secretService.get<string>('MICROSOFT_ENTRAID_ALLOWED_ALGS', 'RS256'),
]);
const allowedAlgs = allowedAlgsRaw
.split(',')
.map((alg) => alg.trim())
.filter(Boolean);
if (allowedAlgs.length === 0) {
allowedAlgs.push('RS256');
}
const issuer = `https://login.microsoftonline.com/${tenantId}/v2.0`;
const jwks = createRemoteJWKSet(
new URL('https://login.microsoftonline.com/common/discovery/v2.0/keys'),
{
cooldownDuration: 30_000,
timeoutDuration: 10_000,
},
);
this.entraConfig = {
tenantId,
audience,
issuer,
allowedAlgs,
jwks,
};
return this.entraConfig;
}
}
+35
View File
@@ -0,0 +1,35 @@
import { CommunityRole } from '../global/database/schema';
export type Permission =
| 'community:edit'
| 'community:delete'
| 'community:transfer'
| 'user:role:manage'
| 'match:create'
| 'match:edit'
| 'match:delete'
| 'auction:manage';
type PermissionSet = readonly Permission[] | readonly ['*'];
export const ROLE_PERMISSIONS: Record<CommunityRole, PermissionSet> = {
owner: ['*'] as const,
admin: [
'community:edit',
'user:role:manage',
'match:create',
'match:edit',
'match:delete',
'auction:manage',
] as const,
member: [] as const,
};
export function roleHasPermission(
role: CommunityRole,
permission: Permission,
): boolean {
const perms = ROLE_PERMISSIONS[role];
if (perms.length === 1 && perms[0] === '*') return true;
return (perms as readonly Permission[]).includes(permission);
}
@@ -0,0 +1,7 @@
import { SetMetadata } from '@nestjs/common';
import { CommunityRole } from '../global/database/schema';
export const ROLES_KEY = 'lolympus:roles';
export const Roles = (...roles: CommunityRole[]) =>
SetMetadata(ROLES_KEY, roles);
+36
View File
@@ -0,0 +1,36 @@
import {
CanActivate,
ExecutionContext,
ForbiddenException,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import type { Request } from 'express';
import { CommunityRole, UserDocument } from '../global/database/schema';
import { ROLES_KEY } from './roles.decorator';
import './auth-request';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private readonly reflector: Reflector) {}
public canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.getAllAndOverride<CommunityRole[]>(
ROLES_KEY,
[context.getHandler(), context.getClass()],
);
if (!requiredRoles || requiredRoles.length === 0) return true;
const req = context.switchToHttp().getRequest<Request>();
const user = req.user as UserDocument | undefined;
if (!user && req.identity) {
throw new ForbiddenException('No membership in this community.');
}
if (!user) throw new UnauthorizedException('Authentication required.');
if (!requiredRoles.includes(user.role)) {
throw new ForbiddenException('Insufficient role.');
}
return true;
}
}
@@ -0,0 +1,55 @@
import { ExecutionContext } from '@nestjs/common';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import { IdentityDocument, UserDocument } from '../global/database/schema';
import { UserResolverGuard } from './user-resolver.guard';
import './auth-request';
function createContext(request: Record<string, unknown>): ExecutionContext {
return {
switchToHttp: () => ({
getRequest: () => request,
}),
} as ExecutionContext;
}
describe('UserResolverGuard', () => {
it('resolves the community membership before role guards run', async () => {
const communityId = new mongoose.Types.ObjectId();
const identityId = new mongoose.Types.ObjectId();
const user = { _id: new mongoose.Types.ObjectId() } as UserDocument;
const findOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue(user),
});
const connectionService = {
getModel: jest.fn().mockResolvedValue({ findOne }),
} as unknown as ConnectionService;
const request = {
params: { communityId: communityId.toString() },
identity: { _id: identityId } as IdentityDocument,
};
const guard = new UserResolverGuard(connectionService);
await expect(guard.canActivate(createContext(request))).resolves.toBe(true);
expect(findOne).toHaveBeenCalledWith({
communityId,
identityId,
});
expect(request.user).toBe(user);
});
it('skips lookup when there is no resolved identity', async () => {
const connectionService = {
getModel: jest.fn(),
} as unknown as ConnectionService;
const request = {
params: { communityId: new mongoose.Types.ObjectId().toString() },
};
const guard = new UserResolverGuard(connectionService);
await expect(guard.canActivate(createContext(request))).resolves.toBe(true);
expect(connectionService.getModel).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,33 @@
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import type { Request } from 'express';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import './auth-request';
@Injectable()
export class UserResolverGuard implements CanActivate {
constructor(private readonly connectionService: ConnectionService) {}
public async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<Request>();
const communityId = request.params?.communityId;
if (
request.user ||
!request.identity ||
typeof communityId !== 'string' ||
!mongoose.isValidObjectId(communityId)
) {
return true;
}
const UserModel = await this.connectionService.getModel('user');
const user = await UserModel.findOne({
communityId: new mongoose.Types.ObjectId(communityId),
identityId: request.identity._id,
}).exec();
if (user) request.user = user;
return true;
}
}
@@ -0,0 +1,24 @@
import {
ArgumentMetadata,
BadRequestException,
Injectable,
PipeTransform,
} from '@nestjs/common';
import mongoose from 'mongoose';
@Injectable()
export class ParseObjectIdPipe
implements PipeTransform<string, mongoose.Types.ObjectId>
{
public transform(
value: string,
metadata: ArgumentMetadata,
): mongoose.Types.ObjectId {
if (!mongoose.isValidObjectId(value)) {
throw new BadRequestException(
`Invalid ObjectId for ${metadata.data ?? 'param'}.`,
);
}
return new mongoose.Types.ObjectId(value);
}
}
@@ -0,0 +1,59 @@
import { Injectable, Logger } from '@nestjs/common';
import { GarnetService } from '../global/garnet/garnet.service';
const COMMUNITY_STATS_TTL_SECONDS = 60 * 60;
const COMMUNITY_STATS_DETAIL_TTL_SECONDS = 24 * 60 * 60;
@Injectable()
export class CommunityStatsCacheService {
private readonly logger = new Logger(CommunityStatsCacheService.name);
constructor(private readonly garnetService: GarnetService) {}
public get<T>(key: string): Promise<T | null> {
return this.garnetService.getJson<T>(key);
}
public set(
key: string,
value: unknown,
ttlSeconds = COMMUNITY_STATS_TTL_SECONDS,
): Promise<void> {
return this.garnetService.setJson(key, value, ttlSeconds);
}
public setDetail(key: string, value: unknown): Promise<void> {
return this.set(key, value, COMMUNITY_STATS_DETAIL_TTL_SECONDS);
}
public async invalidateCommunity(communityId: string): Promise<number> {
const prefix = `riot:communitystats:`;
const match = `${prefix}*${communityId}*`;
const client = this.garnetService.raw();
let cursor = '0';
let deleted = 0;
do {
const reply = (await client.sendCommand([
'SCAN',
cursor,
'MATCH',
match,
'COUNT',
'100',
])) as [string, string[]];
cursor = reply[0];
const keys = reply[1] ?? [];
if (keys.length > 0) {
deleted += await client.del(keys);
}
} while (cursor !== '0');
if (deleted > 0) {
this.logger.debug(
`Invalidated ${deleted} community stats cache keys for ${communityId}.`,
);
}
return deleted;
}
}
@@ -0,0 +1,115 @@
import { Controller, Get, Param, Query } from '@nestjs/common';
import mongoose from 'mongoose';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
import { CommunityStatsService } from './community-stats.service';
import type { CommunityStatsFilters } from './community-stats.types';
@Controller('communities/:communityId')
export class CommunityStatsController {
constructor(private readonly communityStatsService: CommunityStatsService) {}
@Get('internal-stats/matches')
@AllowPublicAccess()
public getMatches(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Query('seasonId') seasonId?: string,
@Query('from') from?: string,
@Query('to') to?: string,
@Query('championId') championId?: string,
@Query('cursor') cursor?: string,
@Query('limit') limit?: string,
) {
return this.communityStatsService.getMatches({
communityId,
filters: this.toFilters({ seasonId, from, to, championId, cursor, limit }),
});
}
@Get('internal-stats/leaderboard')
@AllowPublicAccess()
public getLeaderboard(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Query('seasonId') seasonId?: string,
@Query('from') from?: string,
@Query('to') to?: string,
@Query('championId') championId?: string,
) {
return this.communityStatsService.getLeaderboard({
communityId,
filters: this.toFilters({ seasonId, from, to, championId }),
});
}
@Get('internal-stats/team-insights')
@AllowPublicAccess()
public getTeamInsights(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Query('seasonId') seasonId?: string,
@Query('from') from?: string,
@Query('to') to?: string,
@Query('championId') championId?: string,
) {
return this.communityStatsService.getTeamInsights({
communityId,
filters: this.toFilters({ seasonId, from, to, championId }),
});
}
@Get('internal-stats/match/:matchId')
@AllowPublicAccess()
public getMatchDetail(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
) {
return this.communityStatsService.getMatchDetail({ communityId, matchId });
}
@Get('users/:userId/internal-history')
@AllowPublicAccess()
public getUserInternalHistory(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId,
@Query('seasonId') seasonId?: string,
@Query('from') from?: string,
@Query('to') to?: string,
@Query('championId') championId?: string,
@Query('cursor') cursor?: string,
@Query('limit') limit?: string,
) {
return this.communityStatsService.getUserInternalHistory({
communityId,
userId,
filters: this.toFilters({ seasonId, from, to, championId, cursor, limit }),
});
}
private toFilters(params: {
seasonId?: string;
from?: string;
to?: string;
championId?: string;
cursor?: string;
limit?: string;
}): CommunityStatsFilters {
return {
seasonId: params.seasonId,
from: params.from,
to: params.to,
championId: this.toNumber(params.championId),
cursor: this.toNumber(params.cursor),
limit: this.toNumber(params.limit),
};
}
private toNumber(value: string | undefined): number | undefined {
if (!value) return undefined;
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : undefined;
}
}
@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { CommunityStatsCacheService } from './community-stats-cache.service';
import { CommunityStatsController } from './community-stats.controller';
import { CommunityStatsService } from './community-stats.service';
@Module({
controllers: [CommunityStatsController],
providers: [CommunityStatsService, CommunityStatsCacheService],
exports: [CommunityStatsService],
})
export class CommunityStatsModule {}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,196 @@
import type { RiotLane, TeamSide } from '../global/database/schema';
import type { RecentMatchView, HistorySeasonDto } from '../match-history/match-history.types';
export interface CommunityStatsFilters {
seasonId?: string;
from?: string;
to?: string;
championId?: number;
cursor?: number;
limit?: number;
}
export interface InternalMatchListResponse {
matches: InternalMatchCardView[];
nextCursor: number | null;
season: HistorySeasonDto;
}
export interface InternalMatchCardView {
matchId: string;
title: string;
scheduledAt: string;
status: 'finished' | 'in-progress';
gameCount: number;
blueScore: number;
redScore: number;
winnerSide?: TeamSide;
games: Array<{
gameNumber: number;
riotMatchId: string | null;
winnerSide: TeamSide | null;
gameDuration: number;
}>;
teams: Array<{
side: TeamSide;
name: string;
members: Array<{
userId: string;
summonerName: string;
profileIconId: number;
}>;
}>;
}
export interface LeaderboardResponse {
rows: LeaderboardRow[];
season: HistorySeasonDto;
}
export interface LeaderboardRow {
userId: string;
summonerName: string;
profileIconId: number;
games: number;
wins: number;
losses: number;
winRate: number;
totalKills: number;
totalDeaths: number;
totalAssists: number;
kda: number;
avgGoldPerMin: number;
avgKillParticipation: number;
avgCsPerMin: number;
avgDamageShare: number;
avgVisionScore: number;
byLane: Partial<Record<RiotLane, { games: number; wins: number; kda: number }>>;
topChampions: Array<{ championId: number; games: number; winRate: number }>;
}
export interface LeaderHighlight {
metric: number;
userId: string;
summonerName: string;
championId?: number;
matchId?: string;
isSingleGame: boolean;
}
export interface TeamInsightsResponse {
season: HistorySeasonDto;
sideWinRate: {
blue: number;
red: number;
bluePicks: number;
redPicks: number;
};
topKda: LeaderHighlight | null;
mostKills: LeaderHighlight | null;
topTeamGpm: LeaderHighlight | null;
topKillParticipation: LeaderHighlight | null;
bestFarm: LeaderHighlight | null;
minGamesThreshold: number;
}
export interface InternalMatchDetailResponse {
match: InternalMatchCardView;
games: Array<{
gameNumber: number;
riotMatchId: string;
gameCreation: number;
gameDuration: number;
teams: Array<{
side: TeamSide;
win: boolean;
objectives: { baron: number; dragon: number; tower: number };
participants: Array<{
userId: string | null;
summonerName: string;
side: TeamSide;
teamPosition: string;
championId: number;
kills: number;
deaths: number;
assists: number;
cs: number;
csPerMin: number;
gold: number;
gpm: number;
damageDealtToChampions: number;
damageShare: number;
killParticipation: number;
visionScore: number;
items: number[];
trinket: number;
summonerSpells: [number, number];
perks: { primaryStyle?: number; subStyle?: number; keystone?: number };
win: boolean;
}>;
}>;
}>;
}
export interface UserInternalHistoryResponse {
season: HistorySeasonDto;
championStats: LeaderboardChampionStats;
summary: {
windowSize: number;
winRate: number;
wins: number;
losses: number;
streak: { type: 'win' | 'loss'; count: number } | null;
kda: number;
avgKills: number;
avgDeaths: number;
avgAssists: number;
bestRating: {
rating: number | 'Perfect';
kills: number;
deaths: number;
assists: number;
matchId: string;
} | null;
positionRates: Partial<Record<RiotLane, number>>;
topChampions: Array<{
championId: number;
games: number;
winRate: number;
pickRate: number;
avgRating: number;
}>;
lastFetchedAt: string | null;
};
matches: RecentMatchView[];
nextCursor: number | null;
lastFetchedAt: string | null;
}
export interface LeaderboardChampionStats {
queueGroup: 'internal';
rank: 'all';
queueIds: number[];
season: HistorySeasonDto;
lastFetchedAt: string | null;
champions: Array<{
championId: number;
games: number;
wins: number;
losses: number;
winRate: number;
avgKills: number;
avgDeaths: number;
avgAssists: number;
kda: number;
totalKills: number;
totalDeaths: number;
totalAssists: number;
doubleKills: number;
tripleKills: number;
quadraKills: number;
pentaKills: number;
avgCs: number;
avgCsPerMin: number;
}>;
totals: LeaderboardChampionStats['champions'][number];
}
@@ -0,0 +1,107 @@
import {
Body,
Controller,
BadRequestException,
ForbiddenException,
Get,
Param,
Patch,
Post,
Req,
UseGuards,
} from '@nestjs/common';
import type { Request } from 'express';
import mongoose from 'mongoose';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
import { CurrentUser } from '../auth/current-user.decorator';
import { Roles } from '../auth/roles.decorator';
import { RolesGuard } from '../auth/roles.guard';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
import type { UserDocument } from '../global/database/schema';
import '../auth/auth-request';
import { CommunityService } from './community.service';
import { CreateCommunityDto } from './dto/create-community.dto';
import { TransferOwnershipDto } from './dto/transfer-ownership.dto';
@Controller('communities')
export class CommunityController {
constructor(private readonly communityService: CommunityService) {}
@Post()
@AllowPublicAccess()
public async createCommunity(
@Body() body: CreateCommunityDto,
@Req() req: Request,
) {
if (!req.identity && !body.owner) {
throw new BadRequestException(
'owner is required when not authenticated.',
);
}
return this.communityService.createCommunityWithOwner({
...body,
identityId: req.identity?._id,
});
}
@Get(':communityId')
@AllowPublicAccess()
public async getCommunity(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
) {
return this.communityService.getById(communityId);
}
@Patch(':communityId/members/:userId/promote')
@Roles('owner')
@UseGuards(RolesGuard)
public async promoteToAdmin(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('userId', ParseObjectIdPipe) targetUserId: mongoose.Types.ObjectId,
) {
this.assertOwnerOfCommunity(currentUser, communityId);
return this.communityService.promoteToAdmin({ communityId, targetUserId });
}
@Patch(':communityId/members/:userId/demote')
@Roles('owner')
@UseGuards(RolesGuard)
public async demoteToMember(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('userId', ParseObjectIdPipe) targetUserId: mongoose.Types.ObjectId,
) {
this.assertOwnerOfCommunity(currentUser, communityId);
return this.communityService.demoteToMember({ communityId, targetUserId });
}
@Patch(':communityId/transfer-ownership')
@Roles('owner')
@UseGuards(RolesGuard)
public async transferOwnership(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Body() body: TransferOwnershipDto,
) {
this.assertOwnerOfCommunity(currentUser, communityId);
return this.communityService.transferOwnership({
communityId,
currentOwnerUserId: currentUser._id,
newOwnerUserId: new mongoose.Types.ObjectId(body.newOwnerUserId),
});
}
private assertOwnerOfCommunity(
user: UserDocument,
communityId: mongoose.Types.ObjectId,
): void {
if (!user.communityId.equals(communityId)) {
throw new ForbiddenException('You do not belong to this community.');
}
}
}
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { CommunityController } from './community.controller';
import { CommunityService } from './community.service';
@Module({
controllers: [CommunityController],
providers: [CommunityService],
exports: [CommunityService],
})
export class CommunityModule {}
@@ -0,0 +1,196 @@
import {
BadRequestException,
Injectable,
InternalServerErrorException,
NotFoundException,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import {
CommunityDocument,
UserDocument,
} from '../global/database/schema';
export interface CreateCommunityInput {
name: string;
description?: string;
identityId?: mongoose.Types.ObjectId;
owner?: {
kakaoTalkId?: string;
kakaoTalkNickname?: string;
discordId?: string;
discordNickname?: string;
};
}
@Injectable()
export class CommunityService {
constructor(private readonly connectionService: ConnectionService) {}
public async getById(
communityId: mongoose.Types.ObjectId,
): Promise<CommunityDocument> {
const CommunityModel = await this.connectionService.getModel('community');
const community = await CommunityModel.findById(communityId).exec();
if (!community) throw new NotFoundException('Community not found.');
return community;
}
public async createCommunityWithOwner(input: CreateCommunityInput): Promise<{
community: CommunityDocument;
owner: UserDocument;
}> {
const CommunityModel = await this.connectionService.getModel('community');
const UserModel = await this.connectionService.getModel('user');
const communityId = new mongoose.Types.ObjectId();
const ownerUserId = new mongoose.Types.ObjectId();
const session = await this.connectionService.createSession();
if (!session) {
throw new InternalServerErrorException('Failed to start DB session.');
}
try {
session.startTransaction();
const [community] = await CommunityModel.create(
[
{
_id: communityId,
name: input.name,
description: input.description ?? '',
ownerUserId,
},
],
{ session },
);
const [owner] = await UserModel.create(
[
{
_id: ownerUserId,
communityId,
identityId: input.identityId,
role: 'owner',
kakaoTalkId: input.owner?.kakaoTalkId,
kakaoTalkNickname: input.owner?.kakaoTalkNickname,
discordId: input.owner?.discordId,
discordNickname: input.owner?.discordNickname,
},
],
{ session },
);
await session.commitTransaction();
return { community, owner };
} catch (err) {
await session.abortTransaction();
throw err;
} finally {
await session.endSession();
}
}
public async promoteToAdmin(params: {
communityId: mongoose.Types.ObjectId;
targetUserId: mongoose.Types.ObjectId;
}): Promise<UserDocument> {
return this.changeNonOwnerRole({ ...params, nextRole: 'admin' });
}
public async demoteToMember(params: {
communityId: mongoose.Types.ObjectId;
targetUserId: mongoose.Types.ObjectId;
}): Promise<UserDocument> {
return this.changeNonOwnerRole({ ...params, nextRole: 'member' });
}
public async transferOwnership(params: {
communityId: mongoose.Types.ObjectId;
currentOwnerUserId: mongoose.Types.ObjectId;
newOwnerUserId: mongoose.Types.ObjectId;
}): Promise<{
community: CommunityDocument;
previousOwner: UserDocument;
newOwner: UserDocument;
}> {
if (params.currentOwnerUserId.equals(params.newOwnerUserId)) {
throw new BadRequestException('New owner is already the current owner.');
}
const CommunityModel = await this.connectionService.getModel('community');
const UserModel = await this.connectionService.getModel('user');
const session = await this.connectionService.createSession();
if (!session) {
throw new InternalServerErrorException('Failed to start DB session.');
}
try {
session.startTransaction();
const community = await CommunityModel.findById(
params.communityId,
).session(session);
if (!community) throw new NotFoundException('Community not found.');
if (!community.ownerUserId.equals(params.currentOwnerUserId)) {
throw new BadRequestException('Acting user is not the current owner.');
}
const [previousOwner, newOwner] = await Promise.all([
UserModel.findById(params.currentOwnerUserId).session(session),
UserModel.findById(params.newOwnerUserId).session(session),
]);
if (!previousOwner)
throw new NotFoundException('Previous owner user not found.');
if (!newOwner) throw new NotFoundException('New owner user not found.');
if (!newOwner.communityId.equals(params.communityId)) {
throw new BadRequestException(
'New owner does not belong to this community.',
);
}
community.ownerUserId = newOwner._id;
previousOwner.role = 'admin';
newOwner.role = 'owner';
await Promise.all([
community.save({ session }),
previousOwner.save({ session }),
newOwner.save({ session }),
]);
await session.commitTransaction();
return { community, previousOwner, newOwner };
} catch (err) {
await session.abortTransaction();
throw err;
} finally {
await session.endSession();
}
}
private async changeNonOwnerRole(params: {
communityId: mongoose.Types.ObjectId;
targetUserId: mongoose.Types.ObjectId;
nextRole: 'admin' | 'member';
}): Promise<UserDocument> {
const UserModel = await this.connectionService.getModel('user');
const user = await UserModel.findById(params.targetUserId);
if (!user) throw new NotFoundException('Target user not found.');
if (!user.communityId.equals(params.communityId)) {
throw new BadRequestException(
'Target user does not belong to this community.',
);
}
if (user.role === 'owner') {
throw new BadRequestException(
'Owner role must be changed via transferOwnership.',
);
}
user.role = params.nextRole;
await user.save();
return user;
}
}
@@ -0,0 +1,47 @@
import { Type } from 'class-transformer';
import {
IsOptional,
IsString,
MaxLength,
MinLength,
ValidateNested,
} from 'class-validator';
class CreateCommunityOwnerDto {
@IsOptional()
@IsString()
@MaxLength(64)
kakaoTalkId?: string;
@IsOptional()
@IsString()
@MaxLength(64)
kakaoTalkNickname?: string;
@IsOptional()
@IsString()
@MaxLength(64)
discordId?: string;
@IsOptional()
@IsString()
@MaxLength(64)
discordNickname?: string;
}
export class CreateCommunityDto {
@IsString()
@MinLength(1)
@MaxLength(64)
name!: string;
@IsOptional()
@IsString()
@MaxLength(1024)
description?: string;
@IsOptional()
@ValidateNested()
@Type(() => CreateCommunityOwnerDto)
owner?: CreateCommunityOwnerDto;
}
@@ -0,0 +1,6 @@
import { IsMongoId } from 'class-validator';
export class TransferOwnershipDto {
@IsMongoId()
newOwnerUserId!: string;
}
@@ -0,0 +1,90 @@
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import { RiotAccount, UserDocument } from '../global/database/schema';
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
import { RiotAccountService } from '../riot/riot-account.service';
import { DakaoUserError, DakaoUserService } from './dakao-user.service';
const objectId = (hex: string) => new mongoose.Types.ObjectId(hex);
function makeQuery<T>(value: T) {
return {
exec: jest.fn().mockResolvedValue(value),
};
}
function makeService(params: {
user: Partial<UserDocument>;
riotAccountService?: Partial<RiotAccountService>;
enrichmentService?: Partial<RiotAccountEnrichmentService>;
}) {
const findOneAndUpdate = jest
.fn()
.mockReturnValue(makeQuery(params.user as UserDocument));
const connectionService = {
getModel: jest.fn().mockResolvedValue({ findOneAndUpdate }),
} as unknown as ConnectionService;
const riotAccountService = {
getByRiotId: jest.fn(),
...params.riotAccountService,
} as unknown as RiotAccountService;
const enrichmentService = {
enrichRiotAccount: jest.fn(),
...params.enrichmentService,
} as unknown as RiotAccountEnrichmentService;
return {
service: new DakaoUserService(
connectionService,
riotAccountService,
enrichmentService,
),
connectionService,
findOneAndUpdate,
riotAccountService,
enrichmentService,
};
}
describe('DakaoUserService', () => {
it('rejects account registration when the user already has a Riot account', async () => {
const save = jest.fn().mockResolvedValue(undefined);
const existingAccount = {
puuid: 'puuid-1',
gameName: '기존소환사',
tagLine: 'KR1',
isPrimary: true,
} as RiotAccount;
const {
service,
connectionService,
riotAccountService,
enrichmentService,
} = makeService({
user: {
_id: objectId('222222222222222222222222'),
riotAccounts: [existingAccount],
save,
} as Partial<UserDocument>,
});
await expect(
service.registerPrimaryRiotAccount({
communityId: objectId('111111111111111111111111'),
kakaoTalkId: 'kakao-user-1',
kakaoTalkNickname: '프리리',
gameName: '새소환사',
tagLine: 'KR2',
}),
).rejects.toMatchObject({
code: 'riot_account_already_registered',
detail: '기존소환사#KR1',
} satisfies Partial<DakaoUserError>);
expect(connectionService.getModel).toHaveBeenCalledTimes(1);
expect(connectionService.getModel).toHaveBeenCalledWith('user');
expect(riotAccountService.getByRiotId).not.toHaveBeenCalled();
expect(enrichmentService.enrichRiotAccount).not.toHaveBeenCalled();
expect(save).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,393 @@
import { Injectable, Logger } from '@nestjs/common';
import mongoose, { isValidObjectId } from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import { RiotAccount, UserDocument } from '../global/database/schema';
import { RiotApiError } from '../riot/riot.client.service';
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
import { RiotAccountService } from '../riot/riot-account.service';
import {
RIOT_PLATFORM_ROUTES,
RIOT_REGIONAL_ROUTES,
RiotPlatformRoute,
RiotRegionalRoute,
} from '../riot/riot.types';
import { formatCodePoints, normalizeRiotIdPart } from './riot-id.util';
export class DakaoUserError extends Error {
constructor(
public readonly code:
| 'invalid_project_id'
| 'community_not_found'
| 'riot_account_not_found'
| 'riot_account_already_registered'
| 'riot_account_conflict'
| 'riot_account_lookup_failed',
public readonly detail?: string,
) {
super(`Dakao user error: ${code}${detail ? ` (${detail})` : ''}`);
}
}
interface ResolveContext {
communityId: mongoose.Types.ObjectId;
kakaoTalkId: string;
kakaoTalkNickname: string;
gameName: string;
tagLine: string;
}
interface ResolveResult {
user: UserDocument;
riotAccount: RiotAccount;
}
interface RiotRouting {
platform: RiotPlatformRoute;
region: RiotRegionalRoute;
}
interface ResolvedRiotIdentity {
requestedGameName: string;
requestedTagLine: string;
dto: { puuid: string; gameName: string | null; tagLine: string | null };
}
const DEFAULT_RIOT_PLATFORM: RiotPlatformRoute = 'kr';
const DEFAULT_RIOT_REGION: RiotRegionalRoute = 'asia';
@Injectable()
export class DakaoUserService {
private readonly logger = new Logger(DakaoUserService.name);
constructor(
private readonly connectionService: ConnectionService,
private readonly riotAccountService: RiotAccountService,
private readonly enrichmentService: RiotAccountEnrichmentService,
) {}
public async resolveCommunityIdByDakaoProjectId(
dakaoProjectId: string,
): Promise<mongoose.Types.ObjectId> {
if (!isValidObjectId(dakaoProjectId)) {
throw new DakaoUserError('invalid_project_id', dakaoProjectId);
}
const CommunityModel = await this.connectionService.getModel('community');
const community = await CommunityModel.findOne({
dakaoProjectId: dakaoProjectId,
})
.select({ _id: 1 })
.lean()
.exec();
if (!community) {
throw new DakaoUserError('community_not_found', dakaoProjectId);
}
return community._id as mongoose.Types.ObjectId;
}
public async upsertUser(params: {
communityId: mongoose.Types.ObjectId;
kakaoTalkId: string;
kakaoTalkNickname: string;
}): Promise<UserDocument> {
const UserModel = await this.connectionService.getModel('user');
const user = await UserModel.findOneAndUpdate(
{ communityId: params.communityId, kakaoTalkId: params.kakaoTalkId },
{
$set: { kakaoTalkNickname: params.kakaoTalkNickname },
$setOnInsert: {
communityId: params.communityId,
kakaoTalkId: params.kakaoTalkId,
role: 'member',
isActivated: true,
},
},
{ upsert: true, returnDocument: 'after', setDefaultsOnInsert: true },
).exec();
if (!user) {
// upsert + returnDocument='after' 이면 항상 반환되지만 타입 안전을 위해 가드.
throw new DakaoUserError('community_not_found');
}
return user;
}
public async resolveRiotAccount(
context: ResolveContext,
): Promise<ResolveResult> {
const user = await this.upsertUser(context);
const routing = await this.resolveRiotRouting(context.communityId);
const { requestedGameName, requestedTagLine, dto } =
await this.lookupRiotIdentity(context, routing);
const existing = user.riotAccounts.find(
(a) =>
a.gameName.toLowerCase() === requestedGameName.toLowerCase() &&
a.tagLine.toLowerCase() === requestedTagLine.toLowerCase(),
);
if (existing) {
this.logger.log(
`Found existing Riot account ${requestedGameName}#${requestedTagLine}: puuid=${existing.puuid}`,
);
}
if (existing) {
const nextGameName = dto.gameName ?? requestedGameName;
const nextTagLine = dto.tagLine ?? requestedTagLine;
if (existing.puuid !== dto.puuid) {
this.logger.warn(
`Riot account puuid mismatch for ${requestedGameName}#${requestedTagLine}: stored=${existing.puuid} resolved=${dto.puuid}. Updating stored account.`,
);
existing.puuid = dto.puuid;
existing.gameName = nextGameName;
existing.tagLine = nextTagLine;
this.clearRiotCache(existing);
await this.saveUserHandlingDuplicate(user, nextGameName, nextTagLine);
return this.enrichAttachedAccount({
user,
riotAccount: existing,
platform: routing.platform,
region: routing.region,
});
}
if (
existing.gameName !== nextGameName ||
existing.tagLine !== nextTagLine
) {
existing.gameName = nextGameName;
existing.tagLine = nextTagLine;
await user.save();
}
return { user, riotAccount: existing };
}
return this.attachRiotAccount({
user,
puuid: dto.puuid,
gameName: dto.gameName ?? requestedGameName,
tagLine: dto.tagLine ?? requestedTagLine,
platform: routing.platform,
region: routing.region,
});
}
public async registerPrimaryRiotAccount(
context: ResolveContext,
): Promise<ResolveResult> {
const user = await this.upsertUser(context);
const existingPrimary = user.riotAccounts.find(
(account) => account.isPrimary,
);
const existingAccount = existingPrimary ?? user.riotAccounts[0];
if (existingAccount) {
throw new DakaoUserError(
'riot_account_already_registered',
`${existingAccount.gameName}#${existingAccount.tagLine}`,
);
}
const routing = await this.resolveRiotRouting(context.communityId);
const { requestedGameName, requestedTagLine, dto } =
await this.lookupRiotIdentity(context, routing);
const nextGameName = dto.gameName ?? requestedGameName;
const nextTagLine = dto.tagLine ?? requestedTagLine;
return this.attachRiotAccount({
user,
puuid: dto.puuid,
gameName: nextGameName,
tagLine: nextTagLine,
platform: routing.platform,
region: routing.region,
});
}
private async lookupRiotIdentity(
context: ResolveContext,
routing: RiotRouting,
): Promise<ResolvedRiotIdentity> {
const requestedGameName = normalizeRiotIdPart(context.gameName);
const requestedTagLine = normalizeRiotIdPart(context.tagLine);
this.logRiotIdNormalization(context, requestedGameName, requestedTagLine);
try {
const dto = await this.riotAccountService.getByRiotId(
requestedGameName,
requestedTagLine,
{ region: routing.region },
);
this.logger.log(
`Resolved Riot ID ${requestedGameName}#${requestedTagLine} via ${routing.region}: puuid=${dto.puuid} canonical=${dto.gameName ?? '-'}#${dto.tagLine ?? '-'}`,
);
return { requestedGameName, requestedTagLine, dto };
} catch (err) {
if (err instanceof RiotApiError && err.status === 404) {
throw new DakaoUserError(
'riot_account_not_found',
`${requestedGameName}#${requestedTagLine}`,
);
}
this.logger.error(
`Riot account lookup failed for ${requestedGameName}#${requestedTagLine}: ${
(err as Error)?.message ?? err
}`,
);
throw new DakaoUserError(
'riot_account_lookup_failed',
(err as Error)?.message,
);
}
}
private logRiotIdNormalization(
context: ResolveContext,
normalizedGameName: string,
normalizedTagLine: string,
): void {
if (
context.gameName === normalizedGameName &&
context.tagLine === normalizedTagLine
) {
return;
}
this.logger.warn(
`Normalized Riot ID input ${context.gameName}#${context.tagLine} -> ${normalizedGameName}#${normalizedTagLine} ` +
`(gameNameCodePoints=${formatCodePoints(context.gameName)}, tagLineCodePoints=${formatCodePoints(context.tagLine)})`,
);
}
private async resolveRiotRouting(
communityId: mongoose.Types.ObjectId,
): Promise<RiotRouting> {
const CommunityModel = await this.connectionService.getModel('community');
const community = await CommunityModel.findById(communityId)
.select({ riotPlatform: 1, riotRegion: 1 })
.lean()
.exec();
return {
platform: this.toRiotPlatform(community?.riotPlatform),
region: this.toRiotRegion(community?.riotRegion),
};
}
private async attachRiotAccount(params: {
user: UserDocument;
puuid: string;
gameName: string;
tagLine: string;
platform: RiotPlatformRoute;
region: RiotRegionalRoute;
}): Promise<ResolveResult> {
const { user } = params;
const isFirst = user.riotAccounts.length === 0;
user.riotAccounts.push({
puuid: params.puuid,
gameName: params.gameName,
tagLine: params.tagLine,
profileIconId: 0,
revisionDate: 0,
summonerLevel: 0,
isPrimary: isFirst,
tiers: [],
tierHistory: [],
matchIds: [],
championMasteries: [],
championRecords: {},
} as unknown as RiotAccount);
await this.saveUserHandlingDuplicate(user, params.gameName, params.tagLine);
const attached = user.riotAccounts.find((a) => a.puuid === params.puuid);
if (!attached) {
throw new DakaoUserError('riot_account_lookup_failed', 'attach failed');
}
return this.enrichAttachedAccount({
user,
riotAccount: attached,
platform: params.platform,
region: params.region,
});
}
private async enrichAttachedAccount(params: {
user: UserDocument;
riotAccount: RiotAccount;
platform: RiotPlatformRoute;
region: RiotRegionalRoute;
}): Promise<ResolveResult> {
// 외부 API 실패는 등록 자체를 막지 않음.
try {
const enrichResult = await this.enrichmentService.enrichRiotAccount({
userId: params.user._id,
puuid: params.riotAccount.puuid,
options: {
force: true,
platform: params.platform,
region: params.region,
},
});
if (enrichResult.account) {
return { user: params.user, riotAccount: enrichResult.account };
}
} catch (err) {
this.logger.warn(
`Riot enrichment failed (continuing with empty data): ${
(err as Error)?.message ?? err
}`,
);
}
return { user: params.user, riotAccount: params.riotAccount };
}
private async saveUserHandlingDuplicate(
user: UserDocument,
gameName: string,
tagLine: string,
): Promise<void> {
try {
await user.save();
} catch (err) {
// 같은 communityId + puuid 중복은 다른 유저가 이미 등록한 케이스.
if ((err as { code?: number })?.code === 11000) {
throw new DakaoUserError(
'riot_account_conflict',
`${gameName}#${tagLine}`,
);
}
throw err;
}
}
private clearRiotCache(account: RiotAccount): void {
account.profileIconId = 0;
account.revisionDate = 0;
account.summonerLevel = 0;
account.tiers = [];
account.tierHistory = [];
account.matchIds = [];
account.matchIdsFetchedAt = undefined;
account.recentStatsSummary = undefined;
account.recentStatsFetchedAt = undefined;
account.championMasteries = [];
account.championMasteriesFetchedAt = undefined;
account.championRecords = {};
account.championRecordsFetchedAt = undefined;
}
private toRiotPlatform(value: unknown): RiotPlatformRoute {
return typeof value === 'string' &&
RIOT_PLATFORM_ROUTES.includes(value as RiotPlatformRoute)
? (value as RiotPlatformRoute)
: DEFAULT_RIOT_PLATFORM;
}
private toRiotRegion(value: unknown): RiotRegionalRoute {
return typeof value === 'string' &&
RIOT_REGIONAL_ROUTES.includes(value as RiotRegionalRoute)
? (value as RiotRegionalRoute)
: DEFAULT_RIOT_REGION;
}
}
@@ -0,0 +1,33 @@
import { Module } from '@nestjs/common';
import { MatchModule } from '../match/match.module';
import { RiotModule } from '../riot/riot.module';
import {
DAKAO_OPTIONS,
createDefaultDakaoOptions,
} from './dakao.options';
import { DakaoPublisher } from './dakao.publisher';
import { DakaoSubscriber } from './dakao.subscriber';
import { DakaoUserService } from './dakao-user.service';
import { IdempotencyCache } from './idempotency.cache';
import { AccountRegisterHandler } from './handlers/account-register.handler';
import { MatchJoinHandler } from './handlers/match-join.handler';
import { MatchListHandler } from './handlers/match-list.handler';
@Module({
imports: [RiotModule, MatchModule],
providers: [
{
provide: DAKAO_OPTIONS,
useFactory: createDefaultDakaoOptions,
},
DakaoPublisher,
DakaoSubscriber,
DakaoUserService,
IdempotencyCache,
AccountRegisterHandler,
MatchListHandler,
MatchJoinHandler,
],
exports: [DakaoPublisher],
})
export class DakaoModule {}
@@ -0,0 +1,13 @@
import { randomUUID } from 'crypto';
export const DAKAO_OPTIONS = Symbol('DAKAO_OPTIONS');
export interface DakaoOptions {
instanceId: string;
}
export function createDefaultDakaoOptions(): DakaoOptions {
return {
instanceId: process.env.DAKAO_INSTANCE_ID || randomUUID(),
};
}
@@ -0,0 +1,73 @@
import { SecretService } from '../global/secret/secret.service';
import { NatsService } from '../global/nats/nats.service';
import { DakaoCommandEnvelope, DakaoSendMessagePayload } from './dakao.types';
import { DakaoPublisher } from './dakao.publisher';
function makePublisher() {
const natsService = {
publish: jest.fn().mockResolvedValue(undefined),
subscribe: jest.fn(),
} as unknown as NatsService;
const secretService = {} as SecretService;
const publisher = new DakaoPublisher(natsService, secretService, {
instanceId: 'test',
});
return { publisher, natsService };
}
function getPublishedPayload(natsService: NatsService): DakaoSendMessagePayload {
const publish = natsService.publish as jest.Mock;
const envelope = publish.mock.calls[0][1] as DakaoCommandEnvelope<
DakaoSendMessagePayload
>;
return envelope.payload;
}
describe('DakaoPublisher', () => {
it('keeps valid mention segments intact', async () => {
const { publisher, natsService } = makePublisher();
await publisher.sendMessage({
chatroomId: '18474390111480678',
segments: [
{
kind: 'mention',
userId: '6215844374579825921',
displayText: '날으는꼴뚜기/95/여/D',
},
{ kind: 'text', text: ' 신청 완료' },
],
});
expect(getPublishedPayload(natsService).segments).toEqual([
{
kind: 'mention',
userId: '6215844374579825921',
displayText: '날으는꼴뚜기/95/여/D',
},
{ kind: 'text', text: ' 신청 완료' },
]);
});
it('downgrades invalid mention segments to text before publishing', async () => {
const { publisher, natsService } = makePublisher();
await publisher.sendMessage({
chatroomId: '18474390111480678',
segments: [
{
kind: 'mention',
userId: '-123',
displayText: '소쿠리',
},
{ kind: 'text', text: ' 신청 완료' },
],
});
expect(getPublishedPayload(natsService).segments).toEqual([
{ kind: 'text', text: '@소쿠리' },
{ kind: 'text', text: ' 신청 완료' },
]);
});
});
@@ -0,0 +1,154 @@
import {
Inject,
Injectable,
Logger,
OnModuleDestroy,
OnModuleInit,
} from '@nestjs/common';
import { randomUUID } from 'crypto';
import { SecretService } from '../global/secret/secret.service';
import { NatsService } from '../global/nats/nats.service';
import {
DakaoCommandEnvelope,
DakaoResultEnvelope,
DakaoSegment,
DakaoSendMessagePayload,
} from './dakao.types';
import type { DakaoOptions } from './dakao.options';
import { DAKAO_OPTIONS } from './dakao.options';
const SEND_MESSAGE_SUBJECT_DEFAULT = 'dakao.command.chat.send-message.v1';
const COMMAND_SOURCE_DEFAULT = 'lolympus-tournament-support';
@Injectable()
export class DakaoPublisher implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(DakaoPublisher.name);
private replySubject = '';
private sendMessageSubject = SEND_MESSAGE_SUBJECT_DEFAULT;
private source = COMMAND_SOURCE_DEFAULT;
constructor(
private readonly natsService: NatsService,
private readonly secretService: SecretService,
@Inject(DAKAO_OPTIONS) private readonly options: DakaoOptions,
) {}
async onModuleInit() {
const replyOverride = await this.secretService
.get<string>('DAKAO_REPLY_SUBJECT_PREFIX')
.catch(() => undefined);
const sendOverride = await this.secretService
.get<string>('DAKAO_NATS_COMMAND_CHAT_SEND_MESSAGE_SUBJECT')
.catch(() => undefined);
const sourceOverride = await this.secretService
.get<string>('DAKAO_COMMAND_SOURCE')
.catch(() => undefined);
const replyPrefix = replyOverride || `dakao.result.${COMMAND_SOURCE_DEFAULT}`;
this.replySubject = `${replyPrefix}.${this.options.instanceId}`;
this.sendMessageSubject = sendOverride || SEND_MESSAGE_SUBJECT_DEFAULT;
this.source = sourceOverride || COMMAND_SOURCE_DEFAULT;
this.natsService.subscribe<DakaoResultEnvelope>(
this.replySubject,
(data) => this.handleReply(data),
);
this.logger.log(
`Dakao reply subscriber ready on subject="${this.replySubject}"`,
);
}
async onModuleDestroy() {
// NatsService 가 subscription 정리한다.
}
public async sendMessage(params: {
chatroomId: string;
segments: DakaoSegment[];
correlationId?: string;
}): Promise<void> {
const payload: DakaoSendMessagePayload = {
chatroomId: params.chatroomId,
segments: this.normalizeSegments(params.segments),
};
const envelope: DakaoCommandEnvelope<DakaoSendMessagePayload> = {
schema: 'dakao.command.v1',
id: randomUUID(),
type: 'chat.send-message',
source: this.source,
correlationId: params.correlationId,
replySubject: this.replySubject,
payload,
};
await this.natsService.publish(this.sendMessageSubject, envelope);
}
private normalizeSegments(segments: DakaoSegment[]): DakaoSegment[] {
const normalized: DakaoSegment[] = [];
for (const segment of segments) {
if (segment.kind === 'text') {
if (segment.text.length > 0) normalized.push(segment);
continue;
}
if (segment.kind === 'mention') {
const userId = segment.userId.trim();
const displayText = segment.displayText.trim();
if (this.isPositiveIntegerString(userId) && displayText.length > 0) {
normalized.push({ kind: 'mention', userId, displayText });
continue;
}
const fallbackText = this.renderMentionFallback(displayText, userId);
this.logger.warn(
`Dakao mention downgraded to text because userId/displayText is invalid: userId="${userId || '-'}" displayText="${displayText || '-'}"`,
);
normalized.push({ kind: 'text', text: fallbackText });
continue;
}
const id = segment.id.trim();
const altText = segment.altText.trim();
if (
id.length > 0 &&
altText.length > 0 &&
!/[()@]/.test(altText)
) {
normalized.push({ kind: 'emoticon', id, altText });
continue;
}
this.logger.warn(
`Dakao emoticon downgraded to text because id/altText is invalid: id="${id || '-'}" altText="${altText || '-'}"`,
);
normalized.push({ kind: 'text', text: `(${altText || '이모티콘'})` });
}
return normalized.length > 0
? normalized
: [{ kind: 'text', text: '명령 처리 결과를 보낼 수 없습니다.' }];
}
private isPositiveIntegerString(value: string): boolean {
return /^[1-9]\d*$/.test(value);
}
private renderMentionFallback(displayText: string, userId: string): string {
const label = displayText || userId || '사용자';
return label.startsWith('@') ? label : `@${label}`;
}
private handleReply(reply: DakaoResultEnvelope): void {
if (reply.status === 'succeeded') {
this.logger.log(
`Dakao reply succeeded id=${reply.id} type=${reply.type} correlationId=${reply.correlationId ?? '-'}`,
);
return;
}
this.logger.warn(
`Dakao reply failed id=${reply.id} type=${reply.type} code=${reply.error?.code ?? '-'} retryable=${reply.error?.retryable ?? false} message=${reply.error?.message ?? '-'}`,
);
}
}
@@ -0,0 +1,212 @@
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import mongoose from 'mongoose';
import { NatsService } from '../global/nats/nats.service';
import { SecretService } from '../global/secret/secret.service';
import { CommandParseError, parseCommand } from './parsers/command.parser';
import { DakaoInboundEvent, DakaoLong, DakaoSegment } from './dakao.types';
import { DakaoPublisher } from './dakao.publisher';
import { DakaoUserError, DakaoUserService } from './dakao-user.service';
import { IdempotencyCache } from './idempotency.cache';
import { AccountRegisterHandler } from './handlers/account-register.handler';
import { MatchJoinHandler } from './handlers/match-join.handler';
import { MatchListHandler } from './handlers/match-list.handler';
const INBOUND_SUBJECT_DEFAULT = 'lolympus-tournament-support.kakaotalk.command';
@Injectable()
export class DakaoSubscriber implements OnModuleInit {
private readonly logger = new Logger(DakaoSubscriber.name);
private inboundSubject = INBOUND_SUBJECT_DEFAULT;
private botUserId: string | undefined;
constructor(
private readonly natsService: NatsService,
private readonly secretService: SecretService,
private readonly dakaoUserService: DakaoUserService,
private readonly publisher: DakaoPublisher,
private readonly idempotency: IdempotencyCache,
private readonly accountRegisterHandler: AccountRegisterHandler,
private readonly matchListHandler: MatchListHandler,
private readonly matchJoinHandler: MatchJoinHandler,
) {}
async onModuleInit() {
const subjectOverride = await this.secretService
.get<string>('DAKAO_INBOUND_SUBJECT')
.catch(() => undefined);
this.inboundSubject = subjectOverride || INBOUND_SUBJECT_DEFAULT;
this.botUserId = await this.secretService
.get<string>('DAKAO_BOT_USER_ID')
.catch(() => undefined);
this.natsService.subscribe<DakaoInboundEvent>(
this.inboundSubject,
(event) => this.handleEvent(event),
);
this.logger.log(
`Dakao inbound subscriber ready on subject="${this.inboundSubject}"`,
);
}
private async handleEvent(event: DakaoInboundEvent): Promise<void> {
if (!this.validate(event)) return;
if (this.botUserId && event.userId === this.botUserId) {
return;
}
const logIdKey = this.deriveLogIdKey(event);
if (logIdKey && this.idempotency.has(logIdKey)) {
return;
}
if (logIdKey) this.idempotency.remember(logIdKey);
let communityId: mongoose.Types.ObjectId;
try {
communityId = await this.dakaoUserService.resolveCommunityIdByDakaoProjectId(
event.projectId,
);
} catch (err) {
if (err instanceof DakaoUserError) {
if (err.code === 'invalid_project_id') {
this.logger.warn(`Invalid dakao projectId format: ${event.projectId}`);
return;
}
if (err.code === 'community_not_found') {
// 우리 쪽이 모르는 projectId. 메시지를 보내봤자 컨텍스트가 없으므로 로그만.
this.logger.warn(`Unknown dakao projectId: ${event.projectId}`);
return;
}
}
throw err;
}
let segments: DakaoSegment[];
const senderNickname = this.resolveSenderNickname(event);
const correlationId = this.serializeDakaoLong(event.origin.chatLog.logId);
try {
const command = parseCommand(event.origin.chatLog.message);
switch (command.kind) {
case 'match-list':
segments = await this.matchListHandler.handle({
communityId,
senderUserId: event.userId,
senderNickname,
});
break;
case 'account-register':
segments = await this.accountRegisterHandler.handle({
communityId,
senderUserId: event.userId,
senderNickname,
gameName: command.gameName,
tagLine: command.tagLine,
});
break;
case 'match-join':
segments = await this.matchJoinHandler.handle({
communityId,
matchId: command.matchId,
senderUserId: event.userId,
senderNickname,
gameName: command.gameName,
tagLine: command.tagLine,
positions: command.positions.positions,
});
break;
}
await this.publisher.sendMessage({
chatroomId: event.chatroomId,
segments,
correlationId,
});
} catch (err) {
if (err instanceof CommandParseError) {
// not_a_command 는 명령이 아닌 일반 메시지 → 무시.
if (err.code === 'not_a_command') return;
await this.publisher.sendMessage({
chatroomId: event.chatroomId,
segments: this.parseErrorReply(event, senderNickname, err),
correlationId,
});
return;
}
this.logger.error(
`Unhandled dakao event error: ${(err as Error)?.stack ?? err}`,
);
}
}
private validate(event: unknown): event is DakaoInboundEvent {
if (!event || typeof event !== 'object') return false;
const e = event as Partial<DakaoInboundEvent>;
if (typeof e.projectId !== 'string' || e.projectId.length === 0) return false;
if (typeof e.chatroomId !== 'string' || e.chatroomId.length === 0)
return false;
if (typeof e.nickname !== 'string') return false;
if (typeof e.userId !== 'string' || e.userId.length === 0) return false;
if (!e.origin || typeof e.origin !== 'object') return false;
const chatLog = (e.origin as { chatLog?: unknown }).chatLog;
if (!chatLog || typeof chatLog !== 'object') return false;
if (typeof (chatLog as { message?: unknown }).message !== 'string')
return false;
return true;
}
private deriveLogIdKey(event: DakaoInboundEvent): string | null {
const serialized = this.serializeDakaoLong(event.origin.chatLog.logId);
return serialized ? `${event.projectId}:${serialized}` : null;
}
private serializeDakaoLong(value: DakaoLong | string | undefined): string {
if (typeof value === 'string') return value;
if (!value || typeof value !== 'object') return '';
const high = BigInt(value.high ?? 0);
const low = BigInt.asUintN(32, BigInt(value.low ?? 0));
const combined = (high << 32n) | low;
return value.unsigned
? BigInt.asUintN(64, combined).toString()
: BigInt.asIntN(64, combined).toString();
}
private resolveSenderNickname(event: DakaoInboundEvent): string {
const primary = event.nickname?.trim();
if (primary) return primary;
const fallback = event.origin.authorNickname?.trim();
return fallback ?? '';
}
private parseErrorReply(
event: DakaoInboundEvent,
senderNickname: string,
err: CommandParseError,
): DakaoSegment[] {
const head: DakaoSegment[] = [
{
kind: 'mention',
userId: event.userId,
displayText: senderNickname,
},
];
const text = ((): string => {
switch (err.code) {
case 'unknown_command':
return ` 알 수 없는 명령어입니다. 사용법: !내전 목록, !내전 계정등록 <게임명>#<태그>, !내전 신청 <ID> <게임명>#<태그> <포지션1>,<포지션2>`;
case 'usage':
return ` 사용법: !내전 목록, !내전 계정등록 <게임명>#<태그>, !내전 신청 <ID> <게임명>#<태그> <포지션1>,<포지션2>`;
case 'invalid_match_id':
return ` 매치 ID 형식이 올바르지 않습니다 (${err.detail ?? ''}).`;
case 'invalid_riot_id':
return ` 라이엇 ID 형식이 올바르지 않습니다 (예: 프리리#KR1).`;
case 'invalid_position':
return ` 포지션 입력이 올바르지 않습니다. 최소 2개, 중복 없이, 인식되는 별칭(탑/정글/미드/원딜/서폿) 사용.`;
default:
return ` 명령을 처리할 수 없습니다.`;
}
})();
return [...head, { kind: 'text', text }];
}
}
+102
View File
@@ -0,0 +1,102 @@
// dakao NATS contracts
// inbound: dakao 가 lolympus-tournament-support.kakaotalk.command 로 발행하는 이벤트
// outbound: 우리가 dakao.command.chat.send-message.v1 로 발행하는 명령
// reply: dakao 가 우리 envelope 의 replySubject 로 publish 하는 결과
// ===== Inbound =====
export interface DakaoLong {
high?: number;
low?: number;
unsigned?: boolean;
}
export interface DakaoOriginChatLog {
logId: DakaoLong | string;
chatId: DakaoLong | string;
authorId: DakaoLong | string;
type: number;
sendAt: number;
message: string;
prevId?: DakaoLong | string;
msgId?: number;
revision?: number;
scope?: number;
}
export interface DakaoOrigin {
chatId: DakaoLong | string;
logId: DakaoLong | string;
authorNickname?: string;
chatLog: DakaoOriginChatLog;
noSeen?: boolean;
notiRead?: boolean;
li?: number;
status?: number;
}
export interface DakaoInboundEvent {
projectId: string;
chatroomId: string;
nickname: string;
userId: string;
origin: DakaoOrigin;
}
// ===== Outbound: chat.send-message =====
export interface DakaoTextSegment {
kind: 'text';
text: string;
}
export interface DakaoMentionSegment {
kind: 'mention';
userId: string;
displayText: string;
}
export interface DakaoEmoticonSegment {
kind: 'emoticon';
id: string;
altText: string;
}
export type DakaoSegment =
| DakaoTextSegment
| DakaoMentionSegment
| DakaoEmoticonSegment;
export interface DakaoSendMessagePayload {
chatroomId: string;
segments: DakaoSegment[];
attachment?: string | Record<string, unknown>;
type?: number;
noSeen?: boolean;
scope?: number;
silence?: boolean;
}
export interface DakaoCommandEnvelope<TPayload> {
schema: 'dakao.command.v1';
id: string;
type: string;
source: string;
correlationId?: string;
replySubject?: string;
payload: TPayload;
}
// ===== Reply =====
export interface DakaoResultEnvelope {
schema: 'dakao.result.v1';
id: string;
type: string;
status: 'succeeded' | 'failed';
handledAt: string;
correlationId?: string;
result?: Record<string, unknown>;
error?: {
code: string;
message: string;
retryable: boolean;
};
}
@@ -0,0 +1,49 @@
import mongoose from 'mongoose';
import { DakaoUserError, DakaoUserService } from '../dakao-user.service';
import { AccountRegisterHandler } from './account-register.handler';
const objectId = (hex: string) => new mongoose.Types.ObjectId(hex);
function makeHandler(dakaoUserService?: Partial<DakaoUserService>) {
return new AccountRegisterHandler({
registerPrimaryRiotAccount: jest.fn(),
...dakaoUserService,
} as unknown as DakaoUserService);
}
const baseParams = {
communityId: objectId('111111111111111111111111'),
senderUserId: 'kakao-user-1',
senderNickname: '프리리',
gameName: '프리리',
tagLine: 'KR1',
};
describe('AccountRegisterHandler', () => {
it('translates already-registered Riot account errors', async () => {
const handler = makeHandler({
registerPrimaryRiotAccount: jest
.fn()
.mockRejectedValue(
new DakaoUserError(
'riot_account_already_registered',
'기존소환사#KR1',
),
),
});
const segments = await handler.handle(baseParams);
expect(segments).toEqual([
expect.objectContaining({ kind: 'mention', userId: 'kakao-user-1' }),
expect.objectContaining({
kind: 'text',
text: expect.stringContaining('이미 등록된 라이엇 계정'),
}),
]);
expect(segments[1]).toMatchObject({
kind: 'text',
text: expect.stringContaining('기존소환사#KR1'),
});
});
});
@@ -0,0 +1,81 @@
import { Injectable } from '@nestjs/common';
import mongoose from 'mongoose';
import { DakaoSegment } from '../dakao.types';
import { DakaoUserError, DakaoUserService } from '../dakao-user.service';
interface AccountRegisterHandlerParams {
communityId: mongoose.Types.ObjectId;
senderUserId: string;
senderNickname: string;
gameName: string;
tagLine: string;
}
@Injectable()
export class AccountRegisterHandler {
constructor(private readonly dakaoUserService: DakaoUserService) {}
public async handle(
params: AccountRegisterHandlerParams,
): Promise<DakaoSegment[]> {
try {
const resolved = await this.dakaoUserService.registerPrimaryRiotAccount({
communityId: params.communityId,
kakaoTalkId: params.senderUserId,
kakaoTalkNickname: params.senderNickname,
gameName: params.gameName,
tagLine: params.tagLine,
});
return [
{
kind: 'mention',
userId: params.senderUserId,
displayText: params.senderNickname,
},
{
kind: 'text',
text:
` 계정 등록 완료` +
`\n대표 계정: ${resolved.riotAccount.gameName}#${resolved.riotAccount.tagLine}`,
},
];
} catch (err) {
if (err instanceof DakaoUserError) {
return this.errorReply(params, this.translateUserError(err));
}
throw err;
}
}
private errorReply(
params: AccountRegisterHandlerParams,
message: string,
): DakaoSegment[] {
return [
{
kind: 'mention',
userId: params.senderUserId,
displayText: params.senderNickname,
},
{ kind: 'text', text: ` ${message}` },
];
}
private translateUserError(err: DakaoUserError): string {
switch (err.code) {
case 'invalid_project_id':
return '커뮤니티 식별자가 올바르지 않습니다.';
case 'community_not_found':
return '연결된 커뮤니티를 찾을 수 없습니다.';
case 'riot_account_not_found':
return `라이엇 계정을 찾을 수 없습니다 (${err.detail ?? ''}).`;
case 'riot_account_already_registered':
return `이미 등록된 라이엇 계정이 있습니다 (${err.detail ?? ''}). 변경이 필요하면 운영자에게 문의해주세요.`;
case 'riot_account_conflict':
return `이미 다른 사용자가 등록한 라이엇 계정입니다 (${err.detail ?? ''}).`;
case 'riot_account_lookup_failed':
return '라이엇 계정 조회 중 오류가 발생했습니다. 잠시 후 다시 시도해주세요.';
}
}
}
@@ -0,0 +1,138 @@
import { BadRequestException } from '@nestjs/common';
import mongoose from 'mongoose';
import { MatchService } from '../../match/match.service';
import { DakaoUserError, DakaoUserService } from '../dakao-user.service';
import { MatchJoinHandler } from './match-join.handler';
const objectId = (hex: string) => new mongoose.Types.ObjectId(hex);
function makeHandler(overrides?: {
matchService?: Partial<MatchService>;
dakaoUserService?: Partial<DakaoUserService>;
}): MatchJoinHandler {
const matchService = {
join: jest.fn(),
...overrides?.matchService,
} as unknown as MatchService;
const dakaoUserService = {
resolveRiotAccount: jest.fn(),
...overrides?.dakaoUserService,
} as unknown as DakaoUserService;
return new MatchJoinHandler(matchService, dakaoUserService);
}
const baseParams = {
communityId: objectId('111111111111111111111111'),
matchId: '69b63bc96da18dfdb218ee8c',
senderUserId: 'kakao-user-1',
senderNickname: '프리리',
gameName: '프리리',
tagLine: 'KR1',
positions: ['MID', 'TOP'] as const,
};
describe('MatchJoinHandler', () => {
it('rejects invalid match id without touching services', async () => {
const handler = makeHandler();
const segments = await handler.handle({
...baseParams,
matchId: 'not-an-id',
positions: [...baseParams.positions],
});
expect(segments).toEqual([
expect.objectContaining({ kind: 'mention', userId: 'kakao-user-1' }),
expect.objectContaining({
kind: 'text',
text: expect.stringContaining('유효하지 않은 내전 ID'),
}),
]);
});
it('replies with success and uses input position priority', async () => {
const join = jest.fn().mockResolvedValue({
title: '저녁 내전',
participants: [{}, {}, {}],
maxParticipants: 10,
});
const resolveRiotAccount = jest.fn().mockResolvedValue({
user: { _id: objectId('222222222222222222222222') },
riotAccount: { puuid: 'puuid-1', gameName: '프리리', tagLine: 'KR1' },
});
const handler = makeHandler({
matchService: { join } as Partial<MatchService>,
dakaoUserService: {
resolveRiotAccount,
} as Partial<DakaoUserService>,
});
const segments = await handler.handle({
...baseParams,
positions: [...baseParams.positions],
});
expect(resolveRiotAccount).toHaveBeenCalledWith({
communityId: baseParams.communityId,
kakaoTalkId: 'kakao-user-1',
kakaoTalkNickname: '프리리',
gameName: '프리리',
tagLine: 'KR1',
});
expect(join).toHaveBeenCalledWith({
matchId: expect.any(mongoose.Types.ObjectId),
userId: expect.any(mongoose.Types.ObjectId),
preferredPositions: [
{ position: 'MID', priority: 1 },
{ position: 'TOP', priority: 2 },
],
riotPuuid: 'puuid-1',
});
expect(segments[1]).toMatchObject({
kind: 'text',
text: expect.stringContaining('신청 완료 (3/10)'),
});
});
it('translates riot_account_not_found errors', async () => {
const handler = makeHandler({
dakaoUserService: {
resolveRiotAccount: jest
.fn()
.mockRejectedValue(
new DakaoUserError('riot_account_not_found', '프리리#KR1'),
),
} as Partial<DakaoUserService>,
});
const segments = await handler.handle({
...baseParams,
positions: [...baseParams.positions],
});
expect(segments[1]).toMatchObject({
kind: 'text',
text: expect.stringContaining('라이엇 계정을 찾을 수 없습니다'),
});
});
it('translates match BadRequest into korean', async () => {
const handler = makeHandler({
matchService: {
join: jest
.fn()
.mockRejectedValue(new BadRequestException('Match is full.')),
} as Partial<MatchService>,
dakaoUserService: {
resolveRiotAccount: jest.fn().mockResolvedValue({
user: { _id: objectId('222222222222222222222222') },
riotAccount: { puuid: 'p', gameName: 'g', tagLine: 't' },
}),
} as Partial<DakaoUserService>,
});
const segments = await handler.handle({
...baseParams,
positions: [...baseParams.positions],
});
expect(segments[1]).toMatchObject({
kind: 'text',
text: expect.stringContaining('정원이 가득'),
});
});
});
@@ -0,0 +1,128 @@
import {
BadRequestException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { MatchService } from '../../match/match.service';
import { Position, PositionPreference } from '../../global/database/schema';
import { DakaoSegment } from '../dakao.types';
import { DakaoUserError, DakaoUserService } from '../dakao-user.service';
interface JoinHandlerParams {
communityId: mongoose.Types.ObjectId;
matchId: string;
senderUserId: string; // kakaoTalkId
senderNickname: string; // kakaoTalkNickname
gameName: string;
tagLine: string;
positions: Position[];
}
@Injectable()
export class MatchJoinHandler {
constructor(
private readonly matchService: MatchService,
private readonly dakaoUserService: DakaoUserService,
) {}
public async handle(params: JoinHandlerParams): Promise<DakaoSegment[]> {
if (!mongoose.isValidObjectId(params.matchId)) {
return this.errorReply(params, '유효하지 않은 내전 ID 입니다.');
}
const matchObjectId = new mongoose.Types.ObjectId(params.matchId);
let resolved;
try {
resolved = await this.dakaoUserService.resolveRiotAccount({
communityId: params.communityId,
kakaoTalkId: params.senderUserId,
kakaoTalkNickname: params.senderNickname,
gameName: params.gameName,
tagLine: params.tagLine,
});
} catch (err) {
if (err instanceof DakaoUserError) {
return this.errorReply(params, this.translateUserError(err));
}
throw err;
}
const preferredPositions: PositionPreference[] = params.positions.map(
(position, index) => ({ position, priority: index + 1 }),
);
try {
const match = await this.matchService.join({
matchId: matchObjectId,
userId: resolved.user._id,
preferredPositions,
riotPuuid: resolved.riotAccount.puuid,
});
return [
{
kind: 'mention',
userId: params.senderUserId,
displayText: params.senderNickname,
},
{
kind: 'text',
text:
` 신청 완료 (${match.participants.length}/${match.maxParticipants})` +
`\n내전: ${match.title}` +
`\n계정: ${resolved.riotAccount.gameName}#${resolved.riotAccount.tagLine}` +
`\n포지션: ${params.positions.join(', ')}`,
},
];
} catch (err) {
if (err instanceof NotFoundException) {
return this.errorReply(params, '내전을 찾을 수 없습니다.');
}
if (err instanceof BadRequestException) {
return this.errorReply(params, this.translateBadRequest(err.message));
}
throw err;
}
}
private errorReply(
params: JoinHandlerParams,
message: string,
): DakaoSegment[] {
return [
{
kind: 'mention',
userId: params.senderUserId,
displayText: params.senderNickname,
},
{ kind: 'text', text: ` ${message}` },
];
}
private translateUserError(err: DakaoUserError): string {
switch (err.code) {
case 'invalid_project_id':
return '커뮤니티 식별자가 올바르지 않습니다.';
case 'community_not_found':
return '연결된 커뮤니티를 찾을 수 없습니다.';
case 'riot_account_not_found':
return `라이엇 계정을 찾을 수 없습니다 (${err.detail ?? ''}).`;
case 'riot_account_already_registered':
return `이미 등록된 라이엇 계정이 있습니다 (${err.detail ?? ''}).`;
case 'riot_account_conflict':
return `이미 다른 사용자가 등록한 라이엇 계정입니다 (${err.detail ?? ''}).`;
case 'riot_account_lookup_failed':
return '라이엇 계정 조회 중 오류가 발생했습니다. 잠시 후 다시 시도해주세요.';
}
}
private translateBadRequest(raw: string): string {
if (raw.includes('different communities'))
return '이 내전은 현재 채팅방의 커뮤니티 소속이 아닙니다.';
if (raw.includes('not recruiting')) return '모집 중인 내전이 아닙니다.';
if (raw.includes('full')) return '정원이 가득 찼습니다.';
if (raw.includes('already joined')) return '이미 신청한 내전입니다.';
return raw;
}
}
@@ -0,0 +1,63 @@
import { Injectable } from '@nestjs/common';
import mongoose from 'mongoose';
import { MatchService } from '../../match/match.service';
import { DakaoSegment } from '../dakao.types';
@Injectable()
export class MatchListHandler {
constructor(private readonly matchService: MatchService) {}
public async handle(params: {
communityId: mongoose.Types.ObjectId;
senderUserId: string;
senderNickname: string;
}): Promise<DakaoSegment[]> {
const matches = await this.matchService.list({
communityId: params.communityId,
status: 'recruiting',
limit: 10,
});
if (matches.length === 0) {
return [
{
kind: 'mention',
userId: params.senderUserId,
displayText: params.senderNickname,
},
{ kind: 'text', text: ' 모집 중인 내전이 없습니다.' },
];
}
const lines = matches.map((m, i) => {
const id = (m._id as mongoose.Types.ObjectId).toString();
const filled = m.participants.length;
const cap = m.maxParticipants;
const time = formatScheduledAt(m.scheduledAt);
return `\n${i + 1}. ${m.title} (${filled}/${cap}) ${time}\n ID: ${id}`;
});
return [
{
kind: 'mention',
userId: params.senderUserId,
displayText: params.senderNickname,
},
{
kind: 'text',
text: ` 모집 중인 내전 ${matches.length}건${lines.join('')}\n계정등록: !내전 계정등록 <닉네임>#<태그>\n신청: !내전 신청 <ID> <닉네임>#<태그> <포지션1>,<포지션2>`,
},
];
}
}
function formatScheduledAt(date: Date): string {
// YYYY-MM-DD HH:mm (KST 표기)
const kst = new Date(date.getTime() + 9 * 60 * 60 * 1000);
const yyyy = kst.getUTCFullYear();
const mm = String(kst.getUTCMonth() + 1).padStart(2, '0');
const dd = String(kst.getUTCDate()).padStart(2, '0');
const hh = String(kst.getUTCHours()).padStart(2, '0');
const mi = String(kst.getUTCMinutes()).padStart(2, '0');
return `${yyyy}-${mm}-${dd} ${hh}:${mi}`;
}
@@ -0,0 +1,35 @@
import { Injectable } from '@nestjs/common';
const TTL_MS = 5 * 60 * 1000;
const MAX_ENTRIES = 5000;
@Injectable()
export class IdempotencyCache {
private readonly entries = new Map<string, number>();
public has(key: string): boolean {
const expiresAt = this.entries.get(key);
if (expiresAt === undefined) return false;
if (expiresAt < Date.now()) {
this.entries.delete(key);
return false;
}
return true;
}
public remember(key: string): void {
this.evictExpired();
if (this.entries.size >= MAX_ENTRIES) {
const oldestKey = this.entries.keys().next().value;
if (oldestKey !== undefined) this.entries.delete(oldestKey);
}
this.entries.set(key, Date.now() + TTL_MS);
}
private evictExpired(): void {
const now = Date.now();
for (const [key, expiresAt] of this.entries) {
if (expiresAt < now) this.entries.delete(key);
}
}
}
@@ -0,0 +1,95 @@
import { CommandParseError, parseCommand } from './command.parser';
describe('parseCommand', () => {
it('parses match-list command (목록)', () => {
expect(parseCommand('!내전 목록')).toEqual({ kind: 'match-list' });
});
it('parses match-list command (리스트)', () => {
expect(parseCommand('!내전 리스트')).toEqual({ kind: 'match-list' });
});
it('parses match-join command with simple riot id', () => {
const result = parseCommand(
'!내전 신청 69b63bc96da18dfdb218ee8c 프리리#KR1 미드,탑',
);
expect(result).toMatchObject({
kind: 'match-join',
matchId: '69b63bc96da18dfdb218ee8c',
gameName: '프리리',
tagLine: 'KR1',
});
if (result.kind === 'match-join') {
expect(result.positions.positions).toEqual(['MID', 'TOP']);
}
});
it('handles riot game name with spaces', () => {
const result = parseCommand(
'!내전 신청 69b63bc96da18dfdb218ee8c hello world#KR1 미드,서폿',
);
expect(result).toMatchObject({
kind: 'match-join',
gameName: 'hello world',
tagLine: 'KR1',
});
});
it('normalizes hidden unicode differences in riot id', () => {
const decomposedGameName = '프리리'.normalize('NFD');
const result = parseCommand(
`!내전 신청 69b63bc96da18dfdb218ee8c ${decomposedGameName}\u200B#KR1\uFEFF 미드,탑`,
);
expect(result).toMatchObject({
kind: 'match-join',
gameName: '프리리',
tagLine: 'KR1',
});
});
it('parses account register command', () => {
expect(parseCommand('!내전 계정등록 hello world#KR1')).toEqual({
kind: 'account-register',
gameName: 'hello world',
tagLine: 'KR1',
});
});
it('normalizes account register riot id', () => {
const decomposedGameName = '프리리'.normalize('NFD');
expect(
parseCommand(`!내전 계정등록 ${decomposedGameName}\u200B#KR1\uFEFF`),
).toEqual({
kind: 'account-register',
gameName: '프리리',
tagLine: 'KR1',
});
});
it('throws not_a_command for non-prefix messages', () => {
expect(() => parseCommand('안녕하세요')).toThrow(/not_a_command/);
});
it('throws unknown_command for unrecognized subcommands', () => {
expect(() => parseCommand('!내전 폭파')).toThrow(/unknown_command/);
});
it('throws invalid_match_id for non-objectid match', () => {
expect(() =>
parseCommand('!내전 신청 not-an-id 프리리#KR1 미드,탑'),
).toThrow(/invalid_match_id/);
});
it('throws invalid_riot_id when # missing', () => {
expect(() =>
parseCommand('!내전 신청 69b63bc96da18dfdb218ee8c 프리리 미드,탑'),
).toThrow(/invalid_riot_id/);
});
it('throws invalid_position for too few positions', () => {
expect(() => {
parseCommand('!내전 신청 69b63bc96da18dfdb218ee8c 프리리#KR1 미드');
}).toThrow(CommandParseError);
});
});
@@ -0,0 +1,147 @@
import { ParsedPositions, parsePositionList } from './position.parser';
import { normalizeRiotIdPart } from '../riot-id.util';
export type DakaoCommand =
| { kind: 'match-list' }
| {
kind: 'account-register';
gameName: string;
tagLine: string;
}
| {
kind: 'match-join';
matchId: string;
gameName: string;
tagLine: string;
positions: ParsedPositions;
};
export class CommandParseError extends Error {
constructor(
public readonly code:
| 'not_a_command'
| 'unknown_command'
| 'usage'
| 'invalid_riot_id'
| 'invalid_position'
| 'invalid_match_id',
public readonly detail?: string,
) {
super(`Command parse error: ${code}${detail ? ` (${detail})` : ''}`);
}
}
const COMMAND_PREFIX = '!내전';
export function parseCommand(rawMessage: string): DakaoCommand {
const message = rawMessage.trim();
if (!message.startsWith(COMMAND_PREFIX)) {
throw new CommandParseError('not_a_command');
}
const rest = message.slice(COMMAND_PREFIX.length).trim();
if (rest.length === 0) {
throw new CommandParseError('usage');
}
const firstSpace = rest.search(/\s/);
const subCommand = firstSpace === -1 ? rest : rest.slice(0, firstSpace);
const args = firstSpace === -1 ? '' : rest.slice(firstSpace + 1).trim();
switch (subCommand) {
case '목록':
case '리스트':
return { kind: 'match-list' };
case '신청':
return parseJoinArgs(args);
case '계정등록':
return parseAccountRegisterArgs(args);
default:
throw new CommandParseError('unknown_command', subCommand);
}
}
function parseAccountRegisterArgs(args: string): DakaoCommand {
if (args.length === 0) {
throw new CommandParseError('usage');
}
const hashIndex = args.lastIndexOf('#');
if (hashIndex <= 0 || hashIndex === args.length - 1) {
throw new CommandParseError('invalid_riot_id', args);
}
const gameName = normalizeRiotIdPart(args.slice(0, hashIndex));
const tagLine = normalizeRiotIdPart(args.slice(hashIndex + 1));
if (gameName.length === 0 || tagLine.length === 0) {
throw new CommandParseError('invalid_riot_id', args);
}
return {
kind: 'account-register',
gameName,
tagLine,
};
}
function parseJoinArgs(args: string): DakaoCommand {
if (args.length === 0) {
throw new CommandParseError('usage');
}
// 마지막 토큰이 포지션 리스트(쉼표 포함). 그 앞이 라이엇 ID(공백 포함 가능). 그 앞이 matchId.
// 형식: <matchId> <gameName...>#<tagLine> <pos1>,<pos2>...
// 끝에서부터 토큰을 분리해 안정적으로 파싱한다.
const lastSpace = args.lastIndexOf(' ');
if (lastSpace === -1) {
throw new CommandParseError('usage');
}
const positionPart = args.slice(lastSpace + 1).trim();
const head = args.slice(0, lastSpace).trim();
if (positionPart.length === 0 || head.length === 0) {
throw new CommandParseError('usage');
}
const headSpace = head.indexOf(' ');
if (headSpace === -1) {
throw new CommandParseError('usage');
}
const matchId = head.slice(0, headSpace).trim();
const riotId = head.slice(headSpace + 1).trim();
if (!isObjectIdHex(matchId)) {
throw new CommandParseError('invalid_match_id', matchId);
}
const hashIndex = riotId.lastIndexOf('#');
if (hashIndex <= 0 || hashIndex === riotId.length - 1) {
throw new CommandParseError('invalid_riot_id', riotId);
}
const gameName = normalizeRiotIdPart(riotId.slice(0, hashIndex));
const tagLine = normalizeRiotIdPart(riotId.slice(hashIndex + 1));
if (gameName.length === 0 || tagLine.length === 0) {
throw new CommandParseError('invalid_riot_id', riotId);
}
let positions: ParsedPositions;
try {
positions = parsePositionList(positionPart);
} catch (err) {
throw new CommandParseError(
'invalid_position',
(err as Error)?.message ?? positionPart,
);
}
return {
kind: 'match-join',
matchId,
gameName,
tagLine,
positions,
};
}
function isObjectIdHex(value: string): boolean {
return /^[a-f0-9]{24}$/i.test(value);
}
@@ -0,0 +1,41 @@
import { parsePositionList, PositionParseError } from './position.parser';
describe('parsePositionList', () => {
it('parses two korean positions in priority order', () => {
const result = parsePositionList('미드,탑');
expect(result.positions).toEqual(['MID', 'TOP']);
});
it('parses english aliases case-insensitively', () => {
const result = parsePositionList('JGL, sup');
expect(result.positions).toEqual(['JGL', 'SUP']);
});
it('accepts up to 5 distinct positions', () => {
const result = parsePositionList('탑,정글,미드,원딜,서폿');
expect(result.positions).toEqual(['TOP', 'JGL', 'MID', 'ADC', 'SUP']);
});
it('rejects when fewer than 2 positions', () => {
expect(() => parsePositionList('미드')).toThrow(PositionParseError);
expect(() => parsePositionList('미드')).toThrow(/too_few/);
});
it('rejects when more than 5 positions', () => {
expect(() => parsePositionList('탑,정글,미드,원딜,서폿,바텀')).toThrow(
/too_many/,
);
});
it('rejects duplicates after alias normalization', () => {
expect(() => parsePositionList('미드,mid')).toThrow(/duplicate/);
});
it('rejects unknown tokens', () => {
expect(() => parsePositionList('미드,캐리')).toThrow(/unknown/);
});
it('rejects empty input', () => {
expect(() => parsePositionList('')).toThrow(/empty/);
});
});
@@ -0,0 +1,87 @@
import { Position } from '../../global/database/schema';
const POSITION_ALIASES: Record<string, Position> = {
// TOP
top: 'TOP',
탑: 'TOP',
top레인: 'TOP',
// JUNGLE
jgl: 'JGL',
jungle: 'JGL',
jng: 'JGL',
jg: 'JGL',
정글: 'JGL',
정글러: 'JGL',
// MID
mid: 'MID',
middle: 'MID',
미드: 'MID',
// ADC (BOTTOM)
adc: 'ADC',
ad: 'ADC',
bot: 'ADC',
bottom: 'ADC',
원딜: 'ADC',
바텀: 'ADC',
// SUP
sup: 'SUP',
supp: 'SUP',
support: 'SUP',
서폿: 'SUP',
서포터: 'SUP',
};
export interface ParsedPositions {
positions: Position[];
}
export class PositionParseError extends Error {
constructor(
public readonly reason:
| 'too_few'
| 'too_many'
| 'duplicate'
| 'unknown'
| 'empty',
public readonly token?: string,
) {
super(`Position parse error: ${reason}${token ? ` (${token})` : ''}`);
}
}
export function parsePositionList(input: string): ParsedPositions {
const trimmed = input.trim();
if (trimmed.length === 0) {
throw new PositionParseError('empty');
}
const tokens = trimmed
.split(',')
.map((t) => t.trim())
.filter((t) => t.length > 0);
if (tokens.length < 2) {
throw new PositionParseError('too_few');
}
if (tokens.length > 5) {
throw new PositionParseError('too_many');
}
const positions: Position[] = [];
const seen = new Set<Position>();
for (const token of tokens) {
const key = token.toLowerCase().replace(/\s+/g, '');
const mapped = POSITION_ALIASES[key];
if (!mapped) {
throw new PositionParseError('unknown', token);
}
if (seen.has(mapped)) {
throw new PositionParseError('duplicate', token);
}
seen.add(mapped);
positions.push(mapped);
}
return { positions };
}
@@ -0,0 +1,14 @@
const ZERO_WIDTH_CHARACTERS = /[\u200B-\u200D\uFEFF]/g;
export function normalizeRiotIdPart(value: string): string {
return value.replace(ZERO_WIDTH_CHARACTERS, '').trim().normalize('NFC');
}
export function formatCodePoints(value: string): string {
return Array.from(value)
.map((char) => {
const codePoint = char.codePointAt(0);
return `U+${codePoint?.toString(16).toUpperCase().padStart(4, '0')}`;
})
.join(' ');
}
@@ -0,0 +1,14 @@
import { resolveMongoDbName } from './connection.service';
describe('resolveMongoDbName', () => {
it('uses production database only for prod', () => {
expect(resolveMongoDbName('prod')).toBe('lolympus');
});
it('uses isolated databases for non-production environments', () => {
expect(resolveMongoDbName('dev')).toBe('lolympus-dev');
expect(resolveMongoDbName('test')).toBe('lolympus-test');
expect(resolveMongoDbName('')).toBe('lolympus-dev');
expect(resolveMongoDbName('local')).toBe('lolympus-dev');
});
});
@@ -0,0 +1,100 @@
import { Injectable, Scope, OnModuleInit } from '@nestjs/common';
import mongoose from 'mongoose';
import { SecretService } from '../secret/secret.service';
import { tournamentModelDefinitions, TournamentModelTypes } from './schema';
export function resolveMongoDbName(nodeEnv = process.env.NODE_ENV): string {
if (nodeEnv === 'prod') return 'lolympus';
if (nodeEnv === 'test') return 'lolympus-test';
return 'lolympus-dev';
}
@Injectable({ scope: Scope.DEFAULT })
export class ConnectionService implements OnModuleInit {
private connection: mongoose.Connection | null = null;
constructor(private readonly secretService: SecretService) {}
private tournamentModels: Map<string, mongoose.Model<any>> | null = null;
public async getConnection(): Promise<mongoose.Connection> {
if (this.connection !== null && this.connection.readyState === 1) {
return this.connection;
}
const connectionString = await this.secretService.get(
'MONGODB_CONNECTION_STRING',
);
const dbName = resolveMongoDbName();
const defaultConnection = await mongoose
.createConnection(connectionString, {
dbName,
minPoolSize: 10,
maxPoolSize: 20,
})
.asPromise();
this.connection = defaultConnection;
console.log(`Default Connection이 새로 생성됨. dbName=${dbName}`);
return this.connection;
}
public async getModel<K extends keyof TournamentModelTypes>(
modelKey: K,
): Promise<mongoose.Model<TournamentModelTypes[K]>> {
if (this.tournamentModels)
return this.tournamentModels.get(modelKey) as mongoose.Model<
TournamentModelTypes[K]
>;
const models = new Map<K, mongoose.Model<TournamentModelTypes[K]>>();
const connection = await this.getConnection();
tournamentModelDefinitions.forEach((modelDefinition) => {
// 이미 생성된 경우 컴파일 스킵.
if (
Object.prototype.hasOwnProperty.call(
connection.models,
modelDefinition.name,
)
) {
models.set(
modelDefinition.name as K,
connection.models[modelDefinition.name],
);
return;
} else {
models.set(
modelDefinition.name as K,
connection.model<TournamentModelTypes[K]>(
modelDefinition.name,
modelDefinition.schema,
modelDefinition.schemaName,
),
);
}
});
this.tournamentModels = models;
return models.get(modelKey) as mongoose.Model<TournamentModelTypes[K]>;
}
public async createSession(
options?: mongoose.ClientSessionOptions,
): Promise<mongoose.ClientSession | undefined> {
try {
const connection = await this.getConnection();
const session = await connection.startSession(options);
return session as unknown as mongoose.ClientSession;
} catch (error) {
console.log(error);
}
}
public async onModuleInit() {
await this.getConnection().catch(console.error);
}
public async onModuleDestroy() {
this.connection?.close();
}
}
@@ -0,0 +1,9 @@
import { DynamicModule, Module } from '@nestjs/common';
import { ConnectionService } from './connection.service';
@Module({
imports: [],
providers: [ConnectionService],
exports: [ConnectionService],
})
export class DatabaseModule {}
File diff suppressed because it is too large. Load diff
+5
View File
@@ -0,0 +1,5 @@
export interface ModelDefinition {
name: string;
schema: mongoose.Schema<any>;
schemaName?: string;
}
@@ -0,0 +1 @@
export const GARNET_CLIENT = Symbol('GARNET_CLIENT');
@@ -0,0 +1,57 @@
import { Logger, Module } from '@nestjs/common';
import { createClient } from 'redis';
import { SecretModule } from '../secret/secret.module';
import { SecretService } from '../secret/secret.service';
import { GARNET_CLIENT } from './garnet.constants';
import { GarnetService, type GarnetRedisClient } from './garnet.service';
function normalizeGarnetUrl(endpoint: string): string {
const trimmed = endpoint.trim();
if (!trimmed) {
throw new Error('GARNET_ENDPOINT cannot be empty');
}
if (/^redis(s)?:\/\//iu.test(trimmed)) {
return trimmed;
}
return `redis://${trimmed}`;
}
@Module({
imports: [SecretModule],
providers: [
{
provide: GARNET_CLIENT,
inject: [SecretService],
useFactory: async (
secretService: SecretService,
): Promise<GarnetRedisClient> => {
await secretService.ready();
const [endpoint, username, password] = await Promise.all([
secretService.get<string>('GARNET_ENDPOINT'),
secretService.get<string>('GARNET_USERID'),
secretService.get<string>('GARNET_PASSWORD'),
]);
const logger = new Logger('GarnetClient');
const client = createClient({
url: normalizeGarnetUrl(endpoint),
username,
password,
});
client.on('error', (error) => {
logger.error(`Garnet client error: ${error?.message ?? error}`);
});
await client.connect();
logger.log('Garnet connected');
return client;
},
},
GarnetService,
],
exports: [GarnetService, GARNET_CLIENT],
})
export class GarnetModule {}
@@ -0,0 +1,213 @@
import {
Inject,
Injectable,
Logger,
OnModuleDestroy,
} from '@nestjs/common';
import type { createClient } from 'redis';
import { GARNET_CLIENT } from './garnet.constants';
export type GarnetRedisClient = ReturnType<typeof createClient>;
export interface StreamEntry {
deliveriesCounter?: number;
id: string;
message: Record<string, string>;
millisElapsedFromDelivery?: number;
}
export interface StreamReadResult {
messages: StreamEntry[];
name: string;
}
interface RawStreamMessage {
deliveriesCounter?: number;
id: string;
message: unknown;
millisElapsedFromDelivery?: number;
}
interface RawStreamReadResult {
messages: RawStreamMessage[];
name: string;
}
function normalizeStreamFields(fields: unknown): Record<string, string> {
if (fields instanceof Map) {
return Object.fromEntries(
[...fields.entries()].map(([key, value]) => [String(key), String(value)]),
);
}
if (typeof fields === 'object' && fields !== null) {
return Object.fromEntries(
Object.entries(fields as Record<string, unknown>).map(([key, value]) => [
key,
String(value),
]),
);
}
return {};
}
@Injectable()
export class GarnetService implements OnModuleDestroy {
private readonly logger = new Logger(GarnetService.name);
constructor(
@Inject(GARNET_CLIENT) private readonly client: GarnetRedisClient,
) {}
async onModuleDestroy() {
try {
await this.client.quit();
} catch {
this.client.destroy();
}
}
public raw(): GarnetRedisClient {
return this.client;
}
public async getJson<T>(key: string): Promise<T | null> {
const raw = await this.client.get(key);
if (!raw) return null;
try {
return JSON.parse(raw) as T;
} catch (err) {
this.logger.warn(
`Failed to JSON.parse cached value for key="${key}": ${
(err as Error)?.message ?? err
}`,
);
return null;
}
}
public async setJson(
key: string,
value: unknown,
ttlSeconds?: number,
): Promise<void> {
const serialized = JSON.stringify(value);
if (ttlSeconds && ttlSeconds > 0) {
await this.client.set(key, serialized, { EX: ttlSeconds });
return;
}
await this.client.set(key, serialized);
}
public async getString(key: string): Promise<string | null> {
return this.client.get(key);
}
public async setString(
key: string,
value: string,
ttlSeconds?: number,
): Promise<void> {
if (ttlSeconds && ttlSeconds > 0) {
await this.client.set(key, value, { EX: ttlSeconds });
return;
}
await this.client.set(key, value);
}
public async setStringIfAbsent(
key: string,
value: string,
ttlSeconds?: number,
): Promise<boolean> {
const options: { EX?: number; NX: true } = { NX: true };
if (ttlSeconds && ttlSeconds > 0) options.EX = ttlSeconds;
const result = await this.client.set(key, value, options);
return result === 'OK';
}
public async delete(key: string): Promise<number> {
return this.client.del(key);
}
public async appendStream(
key: string,
fields: Record<string, string>,
options?: { maxLen?: number },
): Promise<string> {
const trimOptions =
options?.maxLen && options.maxLen > 0
? {
TRIM: {
strategy: 'MAXLEN' as const,
strategyModifier: '~' as const,
threshold: options.maxLen,
},
}
: undefined;
return this.client.xAdd(key, '*', fields, trimOptions);
}
public async createConsumerGroup(
key: string,
group: string,
startId = '$',
): Promise<void> {
await this.client.xGroupCreate(key, group, startId, { MKSTREAM: true });
}
public async readGroup(
key: string,
group: string,
consumer: string,
startId: string,
options?: { blockMs?: number; count?: number },
): Promise<StreamReadResult[] | null> {
const readOptions: { BLOCK?: number; COUNT?: number } = {};
if (options?.blockMs !== undefined) readOptions.BLOCK = options.blockMs;
if (options?.count !== undefined) readOptions.COUNT = options.count;
const reply = await this.client.xReadGroup(
group,
consumer,
{ key, id: startId },
readOptions,
);
if (!reply) return null;
return (reply as RawStreamReadResult[]).map((stream) => ({
name: String(stream.name),
messages: stream.messages.map((message) => ({
deliveriesCounter:
typeof message.deliveriesCounter === 'number'
? message.deliveriesCounter
: undefined,
id: String(message.id),
message: normalizeStreamFields(message.message),
millisElapsedFromDelivery:
typeof message.millisElapsedFromDelivery === 'number'
? message.millisElapsedFromDelivery
: undefined,
})),
}));
}
public async acknowledgeStream(
key: string,
group: string,
ids: string | string[],
): Promise<number> {
return this.client.xAck(key, group, ids);
}
public async streamLength(key: string): Promise<number> {
return this.client.xLen(key);
}
public async publish(channel: string, message: string): Promise<number> {
return this.client.publish(channel, message);
}
}
@@ -0,0 +1,13 @@
import { Module, Global } from '@nestjs/common';
import { SecretModule } from './secret/secret.module';
import { NatsModule } from './nats/nats.module';
import { DatabaseModule } from './database/database.module';
import { GarnetModule } from './garnet/garnet.module';
@Global()
@Module({
imports: [SecretModule, NatsModule, DatabaseModule, GarnetModule],
providers: [],
exports: [SecretModule, NatsModule, DatabaseModule, GarnetModule],
})
export class GlobalModule {}
@@ -0,0 +1 @@
export const NATS_CLIENT = Symbol('NATS_CLIENT');
@@ -0,0 +1,45 @@
import { Module } from '@nestjs/common';
import fs from 'fs/promises';
import { connect } from 'nats';
import type { NatsConnection } from 'nats';
import { SecretModule } from '../secret/secret.module';
import { SecretService } from '../secret/secret.service';
import { NATS_CLIENT } from './nats.constants';
import { NatsService } from './nats.service';
@Module({
imports: [SecretModule],
providers: [
{
provide: NATS_CLIENT,
inject: [SecretService],
useFactory: async (
secretService: SecretService,
): Promise<NatsConnection> => {
await secretService.ready();
const [endpoint, user, password, serviceName] = await Promise.all([
secretService.get<string>('NATS_ENDPOINT'),
secretService.get<string>('NATS_USER'),
secretService.get<string>('NATS_PASS'),
secretService.get<string>('SERVICE_NAME'),
]);
return connect({
name: serviceName,
servers: [endpoint],
maxReconnectAttempts: -1,
reconnectTimeWait: 500,
reconnect: true,
pingInterval: 20000,
timeout: 5000,
user,
pass: password,
});
},
},
NatsService,
],
exports: [NatsService, NATS_CLIENT],
})
export class NatsModule {}
@@ -0,0 +1,117 @@
import {
Inject,
Injectable,
Logger,
OnModuleDestroy,
} from '@nestjs/common';
import { StringCodec } from 'nats';
import type { Msg, NatsConnection, Subscription } from 'nats';
import { NATS_CLIENT } from './nats.constants';
export type NatsMessageHandler<T = unknown> = (
data: T,
msg: Msg,
) => Promise<void> | void;
@Injectable()
export class NatsService implements OnModuleDestroy {
private readonly logger = new Logger(NatsService.name);
private readonly stringCodec = StringCodec();
private readonly subscriptions = new Set<Subscription>();
constructor(
@Inject(NATS_CLIENT) private readonly natsClient: NatsConnection,
) {}
async onModuleDestroy() {
for (const sub of this.subscriptions) {
try {
sub.unsubscribe();
} catch {
// ignore
}
}
this.subscriptions.clear();
try {
const closed = this.natsClient.closed();
await this.natsClient.drain();
const err = await closed;
if (err) this.logger.error(`NATS closed with error: ${err}`);
} catch {
try {
await this.natsClient.close();
} catch {
// ignore
}
}
}
public async publish<T = unknown>(subject: string, data: T): Promise<void> {
this.natsClient.publish(
subject,
this.stringCodec.encode(JSON.stringify(data)),
);
await this.natsClient.flush();
}
public subscribe<T = unknown>(
subject: string,
handler: NatsMessageHandler<T>,
options?: { queue?: string },
): Subscription {
const sub = this.natsClient.subscribe(subject, {
queue: options?.queue,
});
this.subscriptions.add(sub);
void this.consumeSubscription(sub, handler);
return sub;
}
private async consumeSubscription<T>(
sub: Subscription,
handler: NatsMessageHandler<T>,
): Promise<void> {
try {
for await (const msg of sub) {
await this.dispatch(msg, handler);
}
} catch (err) {
this.logger.error(
`NATS subscription on subject="${sub.getSubject()}" terminated: ${
(err as Error)?.message ?? err
}`,
);
} finally {
this.subscriptions.delete(sub);
}
}
private async dispatch<T>(
msg: Msg,
handler: NatsMessageHandler<T>,
): Promise<void> {
let data: T;
try {
const decoded = this.stringCodec.decode(msg.data);
data = JSON.parse(decoded) as T;
} catch (err) {
this.logger.warn(
`Failed to decode NATS message on subject="${msg.subject}": ${
(err as Error)?.message ?? err
}`,
);
return;
}
try {
await handler(data, msg);
} catch (err) {
this.logger.error(
`Handler error on subject="${msg.subject}": ${
(err as Error)?.stack ?? err
}`,
);
}
}
}
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { SecretService } from './secret.service';
@Module({
imports: [],
providers: [SecretService],
exports: [SecretService],
})
export class SecretModule {}
@@ -0,0 +1,152 @@
import { Injectable, Logger } from '@nestjs/common';
import { InfisicalSDK } from '@infisical/sdk';
import { ConfigService } from '@nestjs/config';
type SecretMap = Record<string, string | boolean | undefined>;
@Injectable()
export class SecretService {
private logger = new Logger(SecretService.name);
private secrets: SecretMap | null = null; // null = 아직 로드 전
private loading?: Promise<void>; // 진행 중인 로드(중복 호출 방지)
private infisicalClient: InfisicalSDK;
private readonly siteUrl: string;
private readonly clientSecret: string;
private readonly clientId: string;
private readonly projectId: string;
private readonly PROCESS_ENVS = [
'COSMOSDB_ENDPOINT',
'COSMOSDB_KEY',
'NATS_ENDPOINT',
'NATS_TOKEN',
'NATS_URL',
'DAKAO_INBOUND_SUBJECT',
'DAKAO_NATS_COMMAND_CHAT_SEND_MESSAGE_SUBJECT',
'DAKAO_REPLY_SUBJECT_PREFIX',
'DAKAO_COMMAND_SOURCE',
'DAKAO_BOT_USER_ID',
'DAKAO_INSTANCE_ID',
'JWT_CLAIM_AUDIENCE',
'MICROSOFT_ENTRAID_TENANT_ID',
'MICROSOFT_ENTRAID_ALLOWED_ALGS',
'AUTH_DEV_HEADER_ENABLED',
// 필요시 추가
] as const;
constructor(private readonly config: ConfigService) {
this.siteUrl =
this.config.get<string>('INFISICAL_SITE_URL') ??
'https://secret-manager.dahyeon.us/';
this.clientSecret = this.config.get<string>(
'INFISICAL_CLIENT_SECRET',
) as string;
this.clientId = this.config.get<string>('INFISICAL_CLIENT_ID') as string;
this.projectId = this.config.get<string>('INFISICAL_PROJECT_ID') as string;
// console.log(this.siteUrl, this.clientSecret, this.clientId, this.projectId)
const missing = [
!this.siteUrl && 'INFISICAL_SITE_URL',
!this.clientId && 'INFISICAL_CLIENT_ID',
!this.clientSecret && 'INFISICAL_CLIENT_SECRET',
!this.projectId && 'INFISICAL_PROJECT_ID',
].filter(Boolean);
if (missing.length > 0) {
throw new Error(
`Missing required Infisical configuration: ${missing.join(', ')}`,
);
}
this.infisicalClient = new InfisicalSDK({ siteUrl: this.siteUrl });
}
/** 한 번만 로그인/페치. 동시에 여러 번 호출돼도 같은 Promise를 공유 */
private async fetchSecrets(): Promise<void> {
if (this.secrets) return; // 이미 로드됨
if (this.loading) return this.loading; // 로드 중이면 그거 기다리기
this.loading = (async () => {
await this.infisicalClient.auth().universalAuth.login({
clientId: this.clientId,
clientSecret: this.clientSecret,
});
// console.log(this.infisicalClient)
const res = await this.infisicalClient.secrets().listSecrets({
environment:
process.env.NODE_ENV === 'prod'
? 'prod'
: process.env.NODE_ENV === 'test'
? 'staging'
: 'dev',
projectId: this.projectId,
});
// 임시 객체에 채운 뒤 한 번에 교체(일관성 보장)
const map: SecretMap = {};
for (const s of res.secrets) {
map[s.secretKey] = s.secretValue;
}
// 필요한 값은 process.env에 반영
for (const k of this.PROCESS_ENVS) {
const v = map[k as string];
if (typeof v === 'string' && v.length > 0) {
process.env[k as string] = v;
}
}
this.secrets = map;
this.logger.log(
`Fetched ${Object.keys(map).length} secrets from Infisical`,
);
})();
try {
await this.loading;
} finally {
this.loading = undefined; // 실패/성공 모두 끝나면 해제(실패 시 재시도 가능)
}
}
/** lazy get: 필요할 때 처음 한번만 로드 */
public async get<T = string>(key: string, fallback?: T): Promise<T> {
if (!this.secrets) {
await this.fetchSecrets();
}
// console.log('Secrets loaded:', this.secrets);
const val = this.secrets![key];
if (val === undefined) {
const cfg = this.config.get<T>(key);
if (cfg !== undefined) return cfg;
if (fallback !== undefined) return fallback;
throw new Error(`Secret not found for key="${key}"`);
}
return val as T;
}
/** 필요 시: 동기 접근(초기화 안됐으면 에러). constructor 등에서 강제 사용 금지 */
public getSync<T = string>(key: string, fallback?: T): T {
if (!this.secrets) {
const cfg = this.config.get<T>(key);
if (cfg !== undefined) return cfg;
if (fallback !== undefined) return fallback;
throw new Error(`SecretService not initialized yet (key="${key}")`);
}
const val = this.secrets[key];
if (val === undefined) {
const cfg = this.config.get<T>(key);
if (cfg !== undefined) return cfg;
if (fallback !== undefined) return fallback;
throw new Error(`Secret not found for key="${key}"`);
}
return val as T;
}
/** 선택: 사전에 강제로 로드하고 싶을 때 호출 */
public async ready(): Promise<void> {
await this.fetchSecrets();
}
}
@@ -0,0 +1,150 @@
import {
BadRequestException,
Body,
Controller,
Get,
Param,
Post,
Query,
UseGuards,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { CurrentUser } from '../auth/current-user.decorator';
import { Roles } from '../auth/roles.decorator';
import { RolesGuard } from '../auth/roles.guard';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
import type { UserDocument } from '../global/database/schema';
import type {
BulkDeleteLegacyMatchesRequest,
StartLegacyImportRequest,
} from './legacy-import.types';
import { LegacyImportService } from './legacy-import.service';
@Controller('communities/:communityId')
@Roles('owner', 'admin')
@UseGuards(RolesGuard)
export class LegacyImportController {
constructor(private readonly legacyImportService: LegacyImportService) {}
@Get('legacy-import/members')
public previewMembers(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Query('windowStart') windowStart?: string,
@Query('windowEnd') windowEnd?: string,
) {
this.assertSameCommunity(currentUser, communityId);
return this.legacyImportService.previewMembers({
communityId,
windowStart,
windowEnd,
});
}
@Post('legacy-import')
public start(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Body() body: StartLegacyImportRequest,
) {
this.assertSameCommunity(currentUser, communityId);
return this.legacyImportService.start({
communityId,
triggeredBy: currentUser._id,
body,
});
}
@Get('legacy-import-jobs')
public listJobs(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Query('limit') limit?: string,
) {
this.assertSameCommunity(currentUser, communityId);
return this.legacyImportService.listJobs({
communityId,
limit: this.toNumber(limit),
});
}
@Get('legacy-import-jobs/:jobId')
public getJob(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('jobId') jobId: string,
) {
this.assertSameCommunity(currentUser, communityId);
return this.legacyImportService.getJob({ communityId, jobId });
}
@Post('legacy-import-jobs/:jobId/cancel')
public cancel(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('jobId') jobId: string,
) {
this.assertSameCommunity(currentUser, communityId);
return this.legacyImportService.cancel({ communityId, jobId });
}
@Get('legacy-matches')
public listLegacyMatches(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Query('cursor') cursor?: string,
@Query('limit') limit?: string,
) {
this.assertSameCommunity(currentUser, communityId);
return this.legacyImportService.listLegacyMatches({
communityId,
cursor: this.toNumber(cursor),
limit: this.toNumber(limit),
});
}
@Post('legacy-matches/bulk-delete')
public bulkDeleteLegacyMatches(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Body() body: BulkDeleteLegacyMatchesRequest,
) {
this.assertSameCommunity(currentUser, communityId);
return this.legacyImportService.bulkDeleteLegacyMatches({
communityId,
body,
});
}
@Post('legacy-matches/rebuild')
public rebuildLegacyMatches(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
) {
this.assertSameCommunity(currentUser, communityId);
return this.legacyImportService.rebuildLegacyMatches({ communityId });
}
private assertSameCommunity(
user: UserDocument,
communityId: mongoose.Types.ObjectId,
): void {
if (!user.communityId.equals(communityId)) {
throw new BadRequestException('Different community.');
}
}
private toNumber(value: string | undefined): number | undefined {
if (!value) return undefined;
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : undefined;
}
}
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { CommunityStatsModule } from '../community-stats/community-stats.module';
import { RiotModule } from '../riot/riot.module';
import { LegacyImportController } from './legacy-import.controller';
import { LegacyImportService } from './legacy-import.service';
@Module({
imports: [RiotModule, CommunityStatsModule],
controllers: [LegacyImportController],
providers: [LegacyImportService],
exports: [LegacyImportService],
})
export class LegacyImportModule {}
@@ -0,0 +1,775 @@
import {
BadRequestException,
ConflictException,
Injectable,
Logger,
NotFoundException,
} from '@nestjs/common';
import { randomUUID } from 'crypto';
import mongoose from 'mongoose';
import { CommunityStatsService } from '../community-stats/community-stats.service';
import { ConnectionService } from '../global/database/connection.service';
import type {
LegacyImportJobDocument,
Match,
RiotMatch as StoredRiotMatch,
UserDocument,
} from '../global/database/schema';
import { GarnetService } from '../global/garnet/garnet.service';
import { RIOT_JOB_LOW_STREAM } from '../riot-job-queue/riot-job-queue.types';
import { RiotMatchService } from '../riot/riot-match.service';
import type { RiotMatchDto, RiotRegionalRoute } from '../riot/riot.types';
import {
buildGameResult,
buildParticipantsSnapshot,
buildTeams,
buildUserByPuuidMap,
countKnownParticipants,
resolveExternalCount,
resolveTeam100IsBlue,
type UserByPuuidMap,
} from './match-builder.util';
import {
LEGACY_IMPORT_DEFAULT_START_ISO,
LEGACY_IMPORT_LOCK_TTL_SECONDS,
LEGACY_IMPORT_MEMBER_AVG_SECONDS,
type BulkDeleteLegacyMatchesRequest,
type LegacyImportMemberJob,
type LegacyImportMemberWindowView,
type LegacyMatchListResponse,
type RebuildLegacyMatchesResponse,
type StartLegacyImportRequest,
type StartLegacyImportResponse,
} from './legacy-import.types';
const MATCH_IMPORT_LOCK_TTL_SECONDS = 60;
const MATCH_ID_PAGE_SIZE = 100;
type ImportOutcome = 'imported' | 'duplicate' | 'skipped' | 'error';
@Injectable()
export class LegacyImportService {
private readonly logger = new Logger(LegacyImportService.name);
constructor(
private readonly connectionService: ConnectionService,
private readonly garnetService: GarnetService,
private readonly riotMatchService: RiotMatchService,
private readonly communityStatsService: CommunityStatsService,
) {}
public async previewMembers(params: {
communityId: mongoose.Types.ObjectId;
windowStart?: string;
windowEnd?: string;
}): Promise<{ members: LegacyImportMemberWindowView[] }> {
const { windowStart, windowEnd } = this.resolveWindow(params);
const users = await this.findImportableUsers(params.communityId);
return {
members: users.map((user) =>
this.toMemberWindowView(user, windowStart, windowEnd),
),
};
}
public async start(params: {
communityId: mongoose.Types.ObjectId;
triggeredBy: mongoose.Types.ObjectId;
body: StartLegacyImportRequest;
}): Promise<StartLegacyImportResponse> {
const lockKey = this.communityLockKey(params.communityId);
const jobId = randomUUID();
const acquired = await this.garnetService.setStringIfAbsent(
lockKey,
jobId,
LEGACY_IMPORT_LOCK_TTL_SECONDS,
);
if (!acquired) {
throw new ConflictException('Legacy import is already running.');
}
try {
const CommunityModel = await this.connectionService.getModel('community');
const community = await CommunityModel.findById(params.communityId)
.select({ riotRegion: 1 })
.lean()
.exec();
if (!community) throw new NotFoundException('Community not found.');
const { windowStart, windowEnd } = this.resolveWindow({
windowStart: params.body.windowStart,
windowEnd: params.body.windowEnd,
});
const users = await this.findImportableUsers(params.communityId);
const overrides = new Map(
(params.body.memberOverrides ?? []).map((override) => [
override.userId,
override,
]),
);
const windows = users
.map((user) => this.resolveMemberWindow(user, windowStart, windowEnd, overrides))
.filter((window) => window.startTime.getTime() <= window.endTime.getTime());
const LegacyImportJobModel =
await this.connectionService.getModel('legacyImportJob');
await LegacyImportJobModel.create({
jobId,
communityId: params.communityId,
triggeredBy: params.triggeredBy,
startedAt: new Date(),
state: 'running',
windowStart,
windowEnd,
memberOverrides: windows,
totalMembers: windows.length,
processedMembers: 0,
totalDiscoveredMatchIds: 0,
totalImportedMatches: 0,
totalSkippedDuplicate: 0,
totalErrors: 0,
averageMemberSeconds: LEGACY_IMPORT_MEMBER_AVG_SECONDS,
});
for (const window of windows) {
const job: LegacyImportMemberJob = {
kind: 'legacy-import-member',
jobId: randomUUID(),
parentJobId: jobId,
communityId: params.communityId.toString(),
userId: window.userId.toString(),
puuid: window.puuid,
startTime: Math.floor(window.startTime.getTime() / 1000),
endTime: Math.floor(window.endTime.getTime() / 1000),
triggeredBy: params.triggeredBy.toString(),
region: (community.riotRegion ?? 'asia') as RiotRegionalRoute,
};
await this.garnetService.appendStream(
RIOT_JOB_LOW_STREAM,
{ job: JSON.stringify(job) },
{ maxLen: 10_000 },
);
}
if (windows.length === 0) {
await LegacyImportJobModel.updateOne(
{ jobId },
{ $set: { state: 'completed', completedAt: new Date() } },
).exec();
await this.garnetService.delete(lockKey);
}
return {
jobId,
totalMembers: windows.length,
etaSeconds: windows.length * LEGACY_IMPORT_MEMBER_AVG_SECONDS,
};
} catch (error) {
await this.garnetService.delete(lockKey);
throw error;
}
}
public async listJobs(params: {
communityId: mongoose.Types.ObjectId;
limit?: number;
}): Promise<{ jobs: LegacyImportJobDocument[] }> {
const LegacyImportJobModel =
await this.connectionService.getModel('legacyImportJob');
const jobs = await LegacyImportJobModel.find({ communityId: params.communityId })
.sort({ startedAt: -1 })
.limit(Math.min(params.limit ?? 10, 50))
.exec();
return { jobs };
}
public async getJob(params: {
communityId: mongoose.Types.ObjectId;
jobId: string;
}): Promise<LegacyImportJobDocument> {
const LegacyImportJobModel =
await this.connectionService.getModel('legacyImportJob');
const job = await LegacyImportJobModel.findOne({
communityId: params.communityId,
jobId: params.jobId,
}).exec();
if (!job) throw new NotFoundException('Legacy import job not found.');
return job;
}
public async cancel(params: {
communityId: mongoose.Types.ObjectId;
jobId: string;
}): Promise<LegacyImportJobDocument> {
const LegacyImportJobModel =
await this.connectionService.getModel('legacyImportJob');
const job = await LegacyImportJobModel.findOneAndUpdate(
{
communityId: params.communityId,
jobId: params.jobId,
state: { $in: ['pending', 'running'] },
},
{ $set: { state: 'cancelled', completedAt: new Date() } },
{ returnDocument: 'after' },
).exec();
if (!job) throw new NotFoundException('Running legacy import job not found.');
await this.garnetService.delete(this.communityLockKey(params.communityId));
return job;
}
public async processMemberJob(job: LegacyImportMemberJob): Promise<void> {
const started = Date.now();
const legacyJob = await this.getRunnableJob(job);
if (!legacyJob) return;
let discovered = 0;
let imported = 0;
let duplicates = 0;
let errors = 0;
try {
const userByPuuid = await this.buildUserByPuuidMap(
new mongoose.Types.ObjectId(job.communityId),
);
const matchIds = await this.collectMatchIds(job);
discovered = matchIds.size;
for (const matchId of matchIds) {
if (await this.isCancelled(job.parentJobId)) break;
const outcome = await this.importSingleMatch(matchId, job, userByPuuid);
if (outcome === 'imported') imported += 1;
if (outcome === 'duplicate') duplicates += 1;
if (outcome === 'error') errors += 1;
}
} catch (error) {
errors += 1;
await this.recordError(job.parentJobId, {
puuid: job.puuid,
reason: error instanceof Error ? error.message : String(error),
});
this.logger.warn(
`Legacy import member job failed ${job.jobId}: ${
error instanceof Error ? error.message : error
}`,
);
} finally {
await this.finishMemberJob(job, {
discovered,
imported,
duplicates,
errors,
elapsedSeconds: Math.max(1, Math.round((Date.now() - started) / 1000)),
});
}
}
public async listLegacyMatches(params: {
communityId: mongoose.Types.ObjectId;
cursor?: number;
limit?: number;
}): Promise<LegacyMatchListResponse> {
const MatchModel = await this.connectionService.getModel('match');
const limit = Math.max(1, Math.min(params.limit ?? 30, 100));
const filter: Record<string, unknown> = {
communityId: params.communityId,
legacyImported: true,
};
if (params.cursor) {
filter.scheduledAt = { $lt: new Date(params.cursor) };
}
const matches = await MatchModel.find(filter)
.sort({ scheduledAt: -1 })
.limit(limit + 1)
.exec();
const visible = matches.slice(0, limit);
const riotMatchIds = visible
.map((match) => match.result?.games[0]?.riotMatchId)
.filter((matchId): matchId is string => Boolean(matchId));
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
const rawDocs = await RiotMatchModel.find({ matchId: { $in: riotMatchIds } })
.lean()
.exec();
const rawById = new Map(
rawDocs.map((doc) => [doc.matchId, doc.raw as unknown as RiotMatchDto]),
);
const userByPuuid = await this.buildUserByPuuidMap(params.communityId);
return {
matches: visible.map((match) => {
const riotMatchId = match.result?.games[0]?.riotMatchId ?? null;
const raw = riotMatchId ? rawById.get(riotMatchId) : undefined;
const memberCount = match.result?.games[0]?.participants.length ?? 0;
return {
matchId: match._id.toString(),
title: match.title,
scheduledAt: match.scheduledAt.toISOString(),
riotMatchId,
memberCount,
externalCount: raw
? resolveExternalCount(raw, userByPuuid)
: Math.max(0, 10 - memberCount),
blueScore: match.result?.blueScore ?? 0,
redScore: match.result?.redScore ?? 0,
winnerSide: match.result?.winnerSide,
};
}),
nextCursor:
matches.length > limit
? visible[visible.length - 1]?.scheduledAt.getTime() ?? null
: null,
};
}
public async bulkDeleteLegacyMatches(params: {
communityId: mongoose.Types.ObjectId;
body: BulkDeleteLegacyMatchesRequest;
}): Promise<{ deleted: number }> {
const ids = (params.body.matchIds ?? [])
.filter((id) => mongoose.isValidObjectId(id))
.map((id) => new mongoose.Types.ObjectId(id));
if (ids.length === 0) return { deleted: 0 };
const MatchModel = await this.connectionService.getModel('match');
const result = await MatchModel.deleteMany({
_id: { $in: ids },
communityId: params.communityId,
legacyImported: true,
}).exec();
await this.communityStatsService.invalidateCommunity(params.communityId);
return { deleted: result.deletedCount ?? 0 };
}
public async rebuildLegacyMatches(params: {
communityId: mongoose.Types.ObjectId;
}): Promise<RebuildLegacyMatchesResponse> {
const MatchModel = await this.connectionService.getModel('match');
const matches = await MatchModel.find({
communityId: params.communityId,
legacyImported: true,
}).exec();
const riotMatchIds = matches
.map(
(match) =>
match.result?.games[0]?.riotMatchId ?? match.result?.riotMatchIds?.[0],
)
.filter((matchId): matchId is string => Boolean(matchId));
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
const rawDocs = await RiotMatchModel.find({ matchId: { $in: riotMatchIds } })
.lean()
.exec();
const rawById = new Map<string, RiotMatchDto>();
for (const doc of rawDocs) {
if (isRiotMatchDto(doc.raw)) rawById.set(doc.matchId, doc.raw);
}
const userByPuuid = await this.buildUserByPuuidMap(params.communityId);
const result: RebuildLegacyMatchesResponse = {
scanned: matches.length,
rebuilt: 0,
normalizedTitles: 0,
skippedMissingRaw: 0,
skippedNoKnownParticipants: 0,
};
for (const match of matches) {
const riotMatchId =
match.result?.games[0]?.riotMatchId ?? match.result?.riotMatchIds?.[0];
const raw = riotMatchId ? rawById.get(riotMatchId) : undefined;
const title = this.normalizeLegacyTitle(
match.title,
raw?.info.gameCreation ?? match.scheduledAt.getTime(),
);
const update: Partial<Match> = {};
if (title !== match.title) {
update.title = title;
result.normalizedTitles += 1;
}
if (!raw || !riotMatchId) {
result.skippedMissingRaw += 1;
if (Object.keys(update).length > 0) {
await MatchModel.updateOne({ _id: match._id }, { $set: update }).exec();
}
continue;
}
const team100IsBlue = resolveTeam100IsBlue(raw, userByPuuid);
const participants = buildParticipantsSnapshot(raw, userByPuuid);
const gameResult = buildGameResult(raw, userByPuuid, team100IsBlue, 1);
if (!gameResult || participants.length === 0) {
result.skippedNoKnownParticipants += 1;
if (Object.keys(update).length > 0) {
await MatchModel.updateOne({ _id: match._id }, { $set: update }).exec();
}
continue;
}
const winnerSide = gameResult.winnerSide;
update.mapId = raw.info.mapId ?? match.mapId;
update.participants = participants;
update.teams = buildTeams(raw, userByPuuid, team100IsBlue);
update.result = {
winnerSide,
blueScore: winnerSide === 'blue' ? 1 : 0,
redScore: winnerSide === 'red' ? 1 : 0,
riotMatchIds: [riotMatchId],
games: [gameResult],
};
await MatchModel.updateOne(
{
_id: match._id,
communityId: params.communityId,
legacyImported: true,
},
{ $set: update },
).exec();
result.rebuilt += 1;
}
if (result.rebuilt > 0 || result.normalizedTitles > 0) {
await this.communityStatsService.invalidateCommunity(params.communityId);
}
return result;
}
private async collectMatchIds(job: LegacyImportMemberJob): Promise<Set<string>> {
const matchIds = new Set<string>();
let start = 0;
while (true) {
const ids = await this.riotMatchService.getMatchIdsByPuuid(job.puuid, {
region: job.region,
type: 'tourney',
startTime: job.startTime,
endTime: job.endTime,
start,
count: MATCH_ID_PAGE_SIZE,
});
ids.forEach((matchId) => matchIds.add(matchId));
if (ids.length < MATCH_ID_PAGE_SIZE) break;
start += MATCH_ID_PAGE_SIZE;
}
return matchIds;
}
private async importSingleMatch(
riotMatchId: string,
job: LegacyImportMemberJob,
userByPuuid: UserByPuuidMap,
): Promise<ImportOutcome> {
const lockKey = `legacy-import:match:${riotMatchId}`;
const acquired = await this.garnetService.setStringIfAbsent(
lockKey,
job.parentJobId,
MATCH_IMPORT_LOCK_TTL_SECONDS,
);
if (!acquired) return 'duplicate';
try {
const MatchModel = await this.connectionService.getModel('match');
const existing = await MatchModel.exists({
'result.games.riotMatchId': riotMatchId,
});
if (existing) return 'duplicate';
const detail = await this.ensureRiotMatchPersisted(riotMatchId, job.region);
if (!detail.info.tournamentCode) return 'skipped';
const counts = countKnownParticipants(detail, userByPuuid);
if (counts.total === 0) return 'skipped';
const team100IsBlue = resolveTeam100IsBlue(detail, userByPuuid);
const gameResult = buildGameResult(detail, userByPuuid, team100IsBlue, 1);
if (!gameResult || gameResult.participants.length === 0) return 'skipped';
const winnerSide = gameResult.winnerSide;
const matchPayload: Partial<Match> = {
communityId: new mongoose.Types.ObjectId(job.communityId),
title: this.formatLegacyDate(detail.info.gameCreation),
description: 'Legacy import (자동 생성)',
mapId: detail.info.mapId ?? 11,
status: 'finished',
scheduledAt: new Date(detail.info.gameCreation),
maxParticipants: 10,
gameCount: 1,
tournamentCodeIds: [],
teamBuiltAt: new Date(detail.info.gameCreation),
hostUserId: new mongoose.Types.ObjectId(job.triggeredBy),
participants: buildParticipantsSnapshot(detail, userByPuuid),
teams: buildTeams(detail, userByPuuid, team100IsBlue),
result: {
winnerSide,
blueScore: winnerSide === 'blue' ? 1 : 0,
redScore: winnerSide === 'red' ? 1 : 0,
riotMatchIds: [riotMatchId],
games: [gameResult],
},
legacyImported: true,
legacyImportSource: {
importedAt: new Date(),
importedBy: new mongoose.Types.ObjectId(job.triggeredBy),
triggeringPuuid: job.puuid,
jobId: job.parentJobId,
},
prizes: [],
notices: [],
schedule: [],
};
await MatchModel.create(matchPayload);
return 'imported';
} catch (error) {
await this.recordError(job.parentJobId, {
puuid: job.puuid,
matchId: riotMatchId,
reason: error instanceof Error ? error.message : String(error),
});
return 'error';
} finally {
await this.garnetService.delete(lockKey);
}
}
private async ensureRiotMatchPersisted(
riotMatchId: string,
region: RiotRegionalRoute,
): Promise<RiotMatchDto> {
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
const stored = await RiotMatchModel.findOne({ matchId: riotMatchId }).exec();
if (isRiotMatchDto(stored?.raw)) return stored.raw;
const dto = await this.riotMatchService.getMatch(riotMatchId, { region });
const payload: Partial<StoredRiotMatch> = {
matchId: dto.metadata.matchId,
gameCreation: dto.info.gameCreation,
gameDuration: dto.info.gameDuration,
gameVersion: dto.info.gameVersion,
queueId: dto.info.queueId,
participantPuuids: dto.metadata.participants,
raw: dto as unknown as Record<string, unknown>,
fetchedAt: new Date(),
};
await RiotMatchModel.updateOne(
{ matchId: dto.metadata.matchId },
{ $set: payload },
{ upsert: true },
).exec();
return dto;
}
private async finishMemberJob(
job: LegacyImportMemberJob,
stats: {
discovered: number;
imported: number;
duplicates: number;
errors: number;
elapsedSeconds: number;
},
): Promise<void> {
const LegacyImportJobModel =
await this.connectionService.getModel('legacyImportJob');
const current = await LegacyImportJobModel.findOne({
jobId: job.parentJobId,
}).exec();
if (!current || current.state === 'cancelled') return;
const average =
current.averageMemberSeconds === undefined
? stats.elapsedSeconds
: Math.round(current.averageMemberSeconds * 0.7 + stats.elapsedSeconds * 0.3);
const nextProcessed = current.processedMembers + 1;
const completed = nextProcessed >= current.totalMembers;
await LegacyImportJobModel.updateOne(
{ jobId: job.parentJobId },
{
$set: {
state: completed ? 'completed' : current.state,
completedAt: completed ? new Date() : current.completedAt,
averageMemberSeconds: average,
},
$inc: {
processedMembers: 1,
totalDiscoveredMatchIds: stats.discovered,
totalImportedMatches: stats.imported,
totalSkippedDuplicate: stats.duplicates,
totalErrors: stats.errors,
},
},
).exec();
if (completed) {
await Promise.all([
this.garnetService.delete(
this.communityLockKey(new mongoose.Types.ObjectId(job.communityId)),
),
this.communityStatsService.invalidateCommunity(
new mongoose.Types.ObjectId(job.communityId),
),
]);
}
}
private async getRunnableJob(
job: LegacyImportMemberJob,
): Promise<LegacyImportJobDocument | null> {
const LegacyImportJobModel =
await this.connectionService.getModel('legacyImportJob');
const legacyJob = await LegacyImportJobModel.findOne({
jobId: job.parentJobId,
}).exec();
if (!legacyJob || legacyJob.state === 'cancelled') return null;
if (legacyJob.state === 'completed' || legacyJob.state === 'failed') return null;
return legacyJob;
}
private async isCancelled(parentJobId: string): Promise<boolean> {
const LegacyImportJobModel =
await this.connectionService.getModel('legacyImportJob');
const job = await LegacyImportJobModel.findOne({ jobId: parentJobId })
.select({ state: 1 })
.lean()
.exec();
return job?.state === 'cancelled';
}
private async recordError(
jobId: string,
error: { puuid?: string; matchId?: string; reason: string },
): Promise<void> {
const LegacyImportJobModel =
await this.connectionService.getModel('legacyImportJob');
await LegacyImportJobModel.updateOne(
{ jobId },
{
$push: {
errors: {
...error,
at: new Date(),
},
},
},
).exec();
}
private async buildUserByPuuidMap(
communityId: mongoose.Types.ObjectId,
): Promise<UserByPuuidMap> {
const users = await this.findImportableUsers(communityId);
return buildUserByPuuidMap(users);
}
private async findImportableUsers(
communityId: mongoose.Types.ObjectId,
): Promise<UserDocument[]> {
const UserModel = await this.connectionService.getModel('user');
return UserModel.find({
communityId,
'riotAccounts.0': { $exists: true },
}).exec();
}
private toMemberWindowView(
user: UserDocument,
windowStart: Date,
windowEnd: Date,
): LegacyImportMemberWindowView {
const resolved = this.resolveMemberWindow(user, windowStart, windowEnd, new Map());
const account =
user.riotAccounts.find((riotAccount) => riotAccount.isPrimary) ??
user.riotAccounts[0];
return {
userId: user._id.toString(),
puuid: account.puuid,
displayName:
user.kakaoTalkNickname ??
user.discordNickname ??
account.gameName ??
user._id.toString(),
gameName: account.gameName,
tagLine: account.tagLine,
profileIconId: account.profileIconId,
isActivated: user.isActivated,
startTime: resolved.startTime.toISOString(),
endTime: resolved.endTime.toISOString(),
};
}
private resolveMemberWindow(
user: UserDocument,
windowStart: Date,
windowEnd: Date,
overrides: Map<string, { startTime?: string; endTime?: string }>,
) {
const account =
user.riotAccounts.find((riotAccount) => riotAccount.isPrimary) ??
user.riotAccounts[0];
if (!account) throw new BadRequestException('Riot account not found.');
const override = overrides.get(user._id.toString());
const overrideStart = this.parseOptionalDate(override?.startTime);
const overrideEnd = this.parseOptionalDate(override?.endTime);
const activeEnd = user.isActivated ? windowEnd : user.updatedAt;
const startTime = overrideStart ?? windowStart;
const endTime = this.minDate(windowEnd, activeEnd, overrideEnd);
return {
userId: user._id,
puuid: account.puuid,
startTime,
endTime,
};
}
private resolveWindow(params: {
windowStart?: string;
windowEnd?: string;
}) {
const windowStart =
this.parseOptionalDate(params.windowStart) ??
new Date(LEGACY_IMPORT_DEFAULT_START_ISO);
const windowEnd = this.parseOptionalDate(params.windowEnd) ?? new Date();
if (windowStart.getTime() > windowEnd.getTime()) {
throw new BadRequestException('windowStart must be before windowEnd.');
}
return { windowStart, windowEnd };
}
private parseOptionalDate(value: string | undefined): Date | undefined {
if (!value) return undefined;
const parsed = new Date(value);
if (Number.isNaN(parsed.getTime())) {
throw new BadRequestException('Invalid date.');
}
return parsed;
}
private minDate(...values: Array<Date | undefined>): Date {
return new Date(Math.min(...values.filter(Boolean).map((date) => date!.getTime())));
}
private normalizeLegacyTitle(title: string, gameCreation: number): string {
const stripped = title.replace(/^\[(?:legacy|lagacy)\]\s*/i, '').trim();
return stripped || this.formatLegacyDate(gameCreation);
}
private formatLegacyDate(gameCreation: number): string {
return new Intl.DateTimeFormat('ko-KR', {
timeZone: 'Asia/Seoul',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
}).format(new Date(gameCreation));
}
private communityLockKey(communityId: mongoose.Types.ObjectId): string {
return `legacy-import:lock:${communityId.toString()}`;
}
}
function isRiotMatchDto(value: unknown): value is RiotMatchDto {
return Boolean(
value &&
typeof value === 'object' &&
'metadata' in value &&
'info' in value,
);
}
@@ -0,0 +1,75 @@
import type { RiotRegionalRoute } from '../riot/riot.types';
export const LEGACY_IMPORT_DEFAULT_START_ISO = '2024-05-01T00:00:00.000Z';
export const LEGACY_IMPORT_LOCK_TTL_SECONDS = 6 * 60 * 60;
export const LEGACY_IMPORT_MEMBER_AVG_SECONDS = 60;
export interface LegacyImportMemberJob {
kind: 'legacy-import-member';
jobId: string;
parentJobId: string;
communityId: string;
userId: string;
puuid: string;
startTime: number;
endTime: number;
triggeredBy: string;
region: RiotRegionalRoute;
}
export interface LegacyImportMemberOverrideRequest {
userId: string;
startTime?: string;
endTime?: string;
}
export interface StartLegacyImportRequest {
windowStart?: string;
windowEnd?: string;
memberOverrides?: LegacyImportMemberOverrideRequest[];
}
export interface LegacyImportMemberWindowView {
userId: string;
puuid: string;
displayName: string;
gameName: string;
tagLine: string;
profileIconId: number;
isActivated: boolean;
startTime: string;
endTime: string;
}
export interface StartLegacyImportResponse {
jobId: string;
totalMembers: number;
etaSeconds: number;
}
export interface LegacyMatchListResponse {
matches: Array<{
matchId: string;
title: string;
scheduledAt: string;
riotMatchId: string | null;
memberCount: number;
externalCount: number;
blueScore: number;
redScore: number;
winnerSide?: 'blue' | 'red';
}>;
nextCursor: number | null;
}
export interface BulkDeleteLegacyMatchesRequest {
matchIds?: string[];
}
export interface RebuildLegacyMatchesResponse {
scanned: number;
rebuilt: number;
normalizedTitles: number;
skippedMissingRaw: number;
skippedNoKnownParticipants: number;
}
@@ -0,0 +1,189 @@
import mongoose from 'mongoose';
import type {
MatchGameResult,
MatchParticipant,
MatchTeam,
Position,
RiotAccount,
TeamSide,
UserDocument,
} from '../global/database/schema';
import type { RiotMatchDto, RiotMatchParticipantDto } from '../riot/riot.types';
const RIOT_BLUE_TEAM_ID = 100;
const RIOT_RED_TEAM_ID = 200;
export interface LegacyUserSnapshot {
userId: mongoose.Types.ObjectId;
account: RiotAccount;
displayName: string;
preferredPositions: UserDocument['preferredPositions'];
}
export type UserByPuuidMap = Map<string, LegacyUserSnapshot>;
export function buildUserByPuuidMap(users: UserDocument[]): UserByPuuidMap {
const entries = new Map<string, LegacyUserSnapshot>();
for (const user of users) {
for (const account of user.riotAccounts) {
entries.set(account.puuid, {
userId: user._id,
account,
displayName:
user.kakaoTalkNickname ??
user.discordNickname ??
account.gameName ??
user._id.toString(),
preferredPositions: user.preferredPositions ?? [],
});
}
}
return entries;
}
export function countKnownParticipants(
detail: RiotMatchDto,
userByPuuid: UserByPuuidMap,
): { team100: number; team200: number; total: number } {
const team100 = detail.info.participants.filter(
(participant) =>
participant.teamId === RIOT_BLUE_TEAM_ID && userByPuuid.has(participant.puuid),
).length;
const team200 = detail.info.participants.filter(
(participant) =>
participant.teamId === RIOT_RED_TEAM_ID && userByPuuid.has(participant.puuid),
).length;
return { team100, team200, total: team100 + team200 };
}
export function resolveTeam100IsBlue(
detail: RiotMatchDto,
userByPuuid: UserByPuuidMap,
): boolean {
const counts = countKnownParticipants(detail, userByPuuid);
return counts.team100 >= counts.team200;
}
export function buildParticipantsSnapshot(
detail: RiotMatchDto,
userByPuuid: UserByPuuidMap,
): MatchParticipant[] {
return detail.info.participants
.map((participant): MatchParticipant | null => {
const user = userByPuuid.get(participant.puuid);
if (!user) return null;
return {
userId: user.userId,
puuid: user.account.puuid,
gameName: user.account.gameName || participant.riotIdGameName,
tagLine: user.account.tagLine || participant.riotIdTagLine,
profileIconId: user.account.profileIconId,
tier:
user.account.tiers.find((tier) => tier.queueType === 'RANKED_SOLO_5x5') ??
user.account.tiers[0],
preferredPositions: user.preferredPositions,
joinedAt: new Date(detail.info.gameCreation),
};
})
.filter((participant): participant is MatchParticipant => Boolean(participant));
}
export function buildTeams(
detail: RiotMatchDto,
userByPuuid: UserByPuuidMap,
team100IsBlue: boolean,
): MatchTeam[] {
return (['blue', 'red'] as TeamSide[]).map((side) => {
const teamId = resolveRiotTeamId(side, team100IsBlue);
const members = detail.info.participants
.filter((participant) => participant.teamId === teamId)
.map((participant) => {
const user = userByPuuid.get(participant.puuid);
if (!user) return null;
return {
userId: user.userId,
assignedPosition: resolveAssignedPosition(participant, user),
};
})
.filter((member): member is NonNullable<typeof member> => Boolean(member));
return {
side,
name: side === 'blue' ? '블루팀' : '레드팀',
members,
};
});
}
export function buildGameResult(
detail: RiotMatchDto,
userByPuuid: UserByPuuidMap,
team100IsBlue: boolean,
gameNumber = 1,
): MatchGameResult | null {
const winningTeam = detail.info.teams.find((team) => team.win);
if (!winningTeam) return null;
const winnerSide = resolveSide(winningTeam.teamId, team100IsBlue);
if (!winnerSide) return null;
const participants = detail.info.participants
.map((participant) => {
const user = userByPuuid.get(participant.puuid);
const side = resolveSide(participant.teamId, team100IsBlue);
if (!user || !side) return null;
return {
userId: user.userId,
side,
championId: participant.championId,
kills: participant.kills,
deaths: participant.deaths,
assists: participant.assists,
win: participant.win,
};
})
.filter((participant): participant is NonNullable<typeof participant> =>
Boolean(participant),
);
return {
gameNumber,
riotMatchId: detail.metadata.matchId,
winnerSide,
gameCreation: detail.info.gameCreation,
gameDuration: detail.info.gameDuration,
participants,
};
}
export function resolveExternalCount(
detail: RiotMatchDto,
userByPuuid: UserByPuuidMap,
): number {
return detail.info.participants.filter(
(participant) => !userByPuuid.has(participant.puuid),
).length;
}
function resolveRiotTeamId(side: TeamSide, team100IsBlue: boolean): number {
if (side === 'blue') {
return team100IsBlue ? RIOT_BLUE_TEAM_ID : RIOT_RED_TEAM_ID;
}
return team100IsBlue ? RIOT_RED_TEAM_ID : RIOT_BLUE_TEAM_ID;
}
function resolveSide(teamId: number, team100IsBlue: boolean): TeamSide | null {
if (teamId === RIOT_BLUE_TEAM_ID) return team100IsBlue ? 'blue' : 'red';
if (teamId === RIOT_RED_TEAM_ID) return team100IsBlue ? 'red' : 'blue';
return null;
}
function resolveAssignedPosition(
participant: RiotMatchParticipantDto,
user: LegacyUserSnapshot,
): Position {
const lane = participant.teamPosition || participant.individualPosition;
if (lane === 'TOP') return 'TOP';
if (lane === 'JUNGLE') return 'JGL';
if (lane === 'MIDDLE') return 'MID';
if (lane === 'BOTTOM') return 'ADC';
if (lane === 'UTILITY') return 'SUP';
return user.preferredPositions[0]?.position ?? 'TOP';
}
@@ -0,0 +1,123 @@
import { Body, Controller, Get, Param, Post, Query } from '@nestjs/common';
import mongoose from 'mongoose';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
import { RiotJobQueueService } from '../riot-job-queue/riot-job-queue.service';
import type {
RiotJobPriority,
} from '../riot-job-queue/riot-job-queue.types';
import { MatchHistoryService } from './match-history.service';
interface RefreshBody {
queueGroups?: string[];
priority?: RiotJobPriority;
}
@Controller('communities/:communityId/users/:userId')
export class MatchHistoryController {
constructor(
private readonly matchHistoryService: MatchHistoryService,
private readonly riotJobQueueService: RiotJobQueueService,
) {}
@Get('history-profile')
@AllowPublicAccess()
public getProfile(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId,
) {
return this.matchHistoryService.getProfile({ communityId, userId });
}
@Get('champion-stats')
@AllowPublicAccess()
public getChampionStats(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId,
@Query('queueGroup') queueGroup?: string,
@Query('rank') rank?: string,
@Query('seasonId') seasonId?: string,
) {
return this.matchHistoryService.getChampionStats({
communityId,
userId,
filters: { queueGroup, rank, seasonId },
});
}
@Get('recent-summary')
@AllowPublicAccess()
public getRecentSummary(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId,
@Query('queueGroup') queueGroup?: string,
@Query('rank') rank?: string,
@Query('seasonId') seasonId?: string,
@Query('championId') championId?: string,
@Query('limit') limit?: string,
) {
return this.matchHistoryService.getRecentSummary({
communityId,
userId,
filters: {
queueGroup,
rank,
seasonId,
championId: this.toNumber(championId),
limit: this.toNumber(limit),
},
});
}
@Get('recent-matches')
@AllowPublicAccess()
public getRecentMatches(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId,
@Query('queueGroup') queueGroup?: string,
@Query('rank') rank?: string,
@Query('seasonId') seasonId?: string,
@Query('championId') championId?: string,
@Query('limit') limit?: string,
@Query('cursor') cursor?: string,
) {
return this.matchHistoryService.getRecentMatches({
communityId,
userId,
filters: {
queueGroup,
rank,
seasonId,
championId: this.toNumber(championId),
limit: this.toNumber(limit),
cursor: this.toNumber(cursor),
},
});
}
@Post('refresh')
@AllowPublicAccess()
public refresh(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId,
@Body() body: RefreshBody,
) {
return this.riotJobQueueService.enqueueRefresh({
communityId,
userId,
queueGroups: body.queueGroups ?? ['summoners-rift'],
priority: body.priority ?? 'high',
});
}
private toNumber(value: string | undefined): number | undefined {
if (!value) return undefined;
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : undefined;
}
}
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { RiotJobQueueModule } from '../riot-job-queue/riot-job-queue.module';
import { MatchHistoryController } from './match-history.controller';
import { MatchHistoryService } from './match-history.service';
@Module({
imports: [RiotJobQueueModule],
controllers: [MatchHistoryController],
providers: [MatchHistoryService],
exports: [MatchHistoryService],
})
export class MatchHistoryModule {}
@@ -0,0 +1,753 @@
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import type {
CommunityDocument,
RiotAccount,
RiotLane,
RiotMatchDocument,
UserDocument,
} from '../global/database/schema';
import {
isRiotQueueGroup,
isRiotRankFilter,
RIOT_QUEUE_LABELS,
resolveRiotQueueIds,
type RiotQueueGroup,
type RiotRankFilter,
} from '../riot/riot-queue.constants';
import type {
RiotMatchDto,
RiotMatchParticipantDto,
} from '../riot/riot.types';
import type {
ChampionStatsResponse,
ChampionStatsRow,
HistorySeasonDto,
RecentMatchesResponse,
RecentMatchView,
RecentSummaryResponse,
UserHistoryProfileResponse,
} from './match-history.types';
const DEFAULT_QUEUE_GROUP: RiotQueueGroup = 'summoners-rift';
const DEFAULT_RANK: RiotRankFilter = 'all';
const DEFAULT_RECENT_LIMIT = 10;
const DEFAULT_SUMMARY_LIMIT = 20;
const MAX_AGGREGATE_MATCHES = 500;
const MAX_RECENT_SCAN = 120;
interface HistoryContext {
community: CommunityDocument;
user: UserDocument;
account: RiotAccount;
season: HistorySeasonDto;
seasonStartedAt: Date | null;
}
interface MatchFilters {
queueGroup?: string;
rank?: string;
seasonId?: string;
championId?: number;
limit?: number;
cursor?: number;
}
interface AggregatedChampion {
championId: number;
games: number;
wins: number;
totalKills: number;
totalDeaths: number;
totalAssists: number;
totalCs: number;
totalGameMinutes: number;
doubleKills: number;
tripleKills: number;
quadraKills: number;
pentaKills: number;
}
@Injectable()
export class MatchHistoryService {
constructor(private readonly connectionService: ConnectionService) {}
public async getProfile(params: {
communityId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
}): Promise<UserHistoryProfileResponse> {
const context = await this.resolveContext(params);
const lastFetchedAt =
context.account.recentStatsFetchedAt ??
context.account.matchIdsFetchedAt ??
null;
return {
userId: context.user._id.toString(),
puuid: context.account.puuid,
gameName: context.account.gameName,
tagLine: context.account.tagLine,
profileIconId: context.account.profileIconId,
summonerLevel: context.account.summonerLevel,
tiers: context.account.tiers.map((tier) => ({
queueType: tier.queueType,
tier: tier.tier,
rank: tier.rank,
leaguePoints: tier.leaguePoints,
wins: tier.wins,
losses: tier.losses,
fetchedAt: tier.fetchedAt.toISOString(),
})),
season: context.season,
seasons: this.resolveSeasons(context.community),
lastFetchedAt: lastFetchedAt?.toISOString() ?? null,
};
}
public async getChampionStats(params: {
communityId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
filters: MatchFilters;
}): Promise<ChampionStatsResponse> {
const context = await this.resolveContext({
...params,
seasonId: params.filters.seasonId,
});
const { queueGroup, rank, queueIds } = this.resolveQueueFilters(
params.filters,
);
const docs = await this.findStoredMatches({
context,
queueIds,
limit: MAX_AGGREGATE_MATCHES,
});
const aggregates = new Map<number, AggregatedChampion>();
for (const doc of docs) {
const dto = doc.raw as unknown as RiotMatchDto;
const participant = this.findParticipant(dto, context.account.puuid);
if (!participant) continue;
const aggregate =
aggregates.get(participant.championId) ??
this.createChampionAggregate(participant.championId);
this.addParticipantToChampionAggregate(aggregate, participant, dto);
aggregates.set(participant.championId, aggregate);
}
const champions = [...aggregates.values()]
.map((aggregate) => this.toChampionStatsRow(aggregate))
.sort((a, b) => b.games - a.games || b.winRate - a.winRate);
const totals = this.toChampionStatsRow(
[...aggregates.values()].reduce(
(acc, aggregate) => this.mergeChampionAggregate(acc, aggregate),
this.createChampionAggregate(0),
),
);
return {
queueGroup,
rank,
queueIds,
season: context.season,
lastFetchedAt: this.resolveLastFetchedAt(docs, context),
champions,
totals,
};
}
public async getRecentSummary(params: {
communityId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
filters: MatchFilters;
}): Promise<RecentSummaryResponse> {
const context = await this.resolveContext({
...params,
seasonId: params.filters.seasonId,
});
const { queueIds } = this.resolveQueueFilters(params.filters);
const limit = this.clampLimit(params.filters.limit, DEFAULT_SUMMARY_LIMIT, 50);
const docs = await this.findStoredMatches({
context,
queueIds,
championId: params.filters.championId,
limit,
scanLimit: params.filters.championId ? MAX_RECENT_SCAN : undefined,
});
const views = docs
.map((doc) => this.toRecentMatchView(doc, context.account.puuid))
.filter((view): view is RecentMatchView => Boolean(view))
.slice(0, limit);
return this.createRecentSummary(views, docs, context, limit);
}
public async getRecentMatches(params: {
communityId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
filters: MatchFilters;
}): Promise<RecentMatchesResponse> {
const context = await this.resolveContext({
...params,
seasonId: params.filters.seasonId,
});
const { queueIds } = this.resolveQueueFilters(params.filters);
const limit = this.clampLimit(params.filters.limit, DEFAULT_RECENT_LIMIT, 30);
const docs = await this.findStoredMatches({
context,
queueIds,
championId: params.filters.championId,
limit: limit + 1,
cursor: params.filters.cursor,
scanLimit: params.filters.championId ? MAX_RECENT_SCAN : undefined,
});
const views = docs
.map((doc) => this.toRecentMatchView(doc, context.account.puuid))
.filter((view): view is RecentMatchView => Boolean(view));
const page = views.slice(0, limit);
return {
matches: page,
nextCursor: views.length > limit ? page[page.length - 1]?.gameCreation ?? null : null,
lastFetchedAt: this.resolveLastFetchedAt(docs, context),
season: context.season,
};
}
private async resolveContext(params: {
communityId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
seasonId?: string;
}): Promise<HistoryContext> {
const UserModel = await this.connectionService.getModel('user');
const CommunityModel = await this.connectionService.getModel('community');
const [user, community] = await Promise.all([
UserModel.findById(params.userId).exec(),
CommunityModel.findById(params.communityId).exec(),
]);
if (!community) throw new NotFoundException('Community not found.');
if (!user || !user.communityId.equals(params.communityId)) {
throw new NotFoundException('User not found.');
}
const account =
user.riotAccounts.find((riotAccount) => riotAccount.isPrimary) ??
user.riotAccounts[0];
if (!account) {
throw new NotFoundException('Riot account not found.');
}
const season = this.resolveSeason(community, params.seasonId);
const seasonStartedAt = season.startedAt
? new Date(season.startedAt)
: (community.seasonStartedAt ?? null);
return { community, user, account, season, seasonStartedAt };
}
private resolveSeason(
community: CommunityDocument,
seasonId?: string,
): HistorySeasonDto {
const seasons = this.resolveSeasons(community);
if (seasonId && seasonId !== 'current') {
const selected = seasons.find((season) => season.id === seasonId);
if (!selected) throw new BadRequestException('Invalid seasonId.');
return selected;
}
const configured =
seasons.find((season) => !season.endedAt) ??
[...seasons].sort((left, right) =>
(right.startedAt ?? '').localeCompare(left.startedAt ?? ''),
)[0];
if (configured) return configured;
return {
id: 'current',
label: '현재 시즌',
startedAt: community.seasonStartedAt?.toISOString() ?? null,
endedAt: null,
};
}
private resolveSeasons(community: CommunityDocument): HistorySeasonDto[] {
const configured = community.seasons?.map((season) => ({
id: season.id,
label: season.label,
startedAt: season.startedAt.toISOString(),
endedAt: season.endedAt?.toISOString() ?? null,
}));
if (configured?.length) return configured;
return [
{
id: 'current',
label: '현재 시즌',
startedAt: community.seasonStartedAt?.toISOString() ?? null,
endedAt: null,
},
];
}
private resolveQueueFilters(filters: MatchFilters): {
queueGroup: RiotQueueGroup;
rank: RiotRankFilter;
queueIds: number[];
} {
const queueGroup = filters.queueGroup ?? DEFAULT_QUEUE_GROUP;
const rank = filters.rank ?? DEFAULT_RANK;
if (!isRiotQueueGroup(queueGroup)) {
throw new BadRequestException('Invalid queueGroup.');
}
if (!isRiotRankFilter(rank)) {
throw new BadRequestException('Invalid rank filter.');
}
return {
queueGroup,
rank,
queueIds: resolveRiotQueueIds(queueGroup, rank),
};
}
private async findStoredMatches(params: {
context: HistoryContext;
queueIds: number[];
limit: number;
cursor?: number;
championId?: number;
scanLimit?: number;
}): Promise<RiotMatchDocument[]> {
if (params.queueIds.length === 0) return [];
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
const gameCreation: Record<string, number> = {};
if (params.context.seasonStartedAt) {
gameCreation.$gte = params.context.seasonStartedAt.getTime();
}
if (params.cursor) gameCreation.$lt = params.cursor;
const query: Record<string, unknown> = {
participantPuuids: params.context.account.puuid,
queueId: { $in: params.queueIds },
};
if (Object.keys(gameCreation).length > 0) query.gameCreation = gameCreation;
const docs = await RiotMatchModel.find(query)
.sort({ gameCreation: -1 })
.limit(params.scanLimit ?? params.limit)
.exec();
if (!params.championId) return docs.slice(0, params.limit);
return docs
.filter((doc) => {
const participant = this.findParticipant(
doc.raw as unknown as RiotMatchDto,
params.context.account.puuid,
);
return participant?.championId === params.championId;
})
.slice(0, params.limit);
}
private findParticipant(
match: RiotMatchDto,
puuid: string,
): RiotMatchParticipantDto | null {
return (
match.info.participants.find((participant) => participant.puuid === puuid) ??
null
);
}
private createChampionAggregate(championId: number): AggregatedChampion {
return {
championId,
games: 0,
wins: 0,
totalKills: 0,
totalDeaths: 0,
totalAssists: 0,
totalCs: 0,
totalGameMinutes: 0,
doubleKills: 0,
tripleKills: 0,
quadraKills: 0,
pentaKills: 0,
};
}
private addParticipantToChampionAggregate(
aggregate: AggregatedChampion,
participant: RiotMatchParticipantDto,
match: RiotMatchDto,
): void {
const minutes = this.resolveGameMinutes(match, participant);
aggregate.games += 1;
aggregate.wins += participant.win ? 1 : 0;
aggregate.totalKills += participant.kills;
aggregate.totalDeaths += participant.deaths;
aggregate.totalAssists += participant.assists;
aggregate.totalCs += this.resolveTotalCs(participant);
aggregate.totalGameMinutes += minutes;
aggregate.doubleKills += this.numberField(participant, 'doubleKills');
aggregate.tripleKills += this.numberField(participant, 'tripleKills');
aggregate.quadraKills += this.numberField(participant, 'quadraKills');
aggregate.pentaKills += this.numberField(participant, 'pentaKills');
}
private mergeChampionAggregate(
acc: AggregatedChampion,
aggregate: AggregatedChampion,
): AggregatedChampion {
acc.games += aggregate.games;
acc.wins += aggregate.wins;
acc.totalKills += aggregate.totalKills;
acc.totalDeaths += aggregate.totalDeaths;
acc.totalAssists += aggregate.totalAssists;
acc.totalCs += aggregate.totalCs;
acc.totalGameMinutes += aggregate.totalGameMinutes;
acc.doubleKills += aggregate.doubleKills;
acc.tripleKills += aggregate.tripleKills;
acc.quadraKills += aggregate.quadraKills;
acc.pentaKills += aggregate.pentaKills;
return acc;
}
private toChampionStatsRow(aggregate: AggregatedChampion): ChampionStatsRow {
const losses = aggregate.games - aggregate.wins;
return {
championId: aggregate.championId,
games: aggregate.games,
wins: aggregate.wins,
losses,
winRate: this.percent(aggregate.wins, aggregate.games),
avgKills: this.average(aggregate.totalKills, aggregate.games),
avgDeaths: this.average(aggregate.totalDeaths, aggregate.games),
avgAssists: this.average(aggregate.totalAssists, aggregate.games),
kda: this.resolveKda(
aggregate.totalKills,
aggregate.totalDeaths,
aggregate.totalAssists,
),
totalKills: aggregate.totalKills,
totalDeaths: aggregate.totalDeaths,
totalAssists: aggregate.totalAssists,
doubleKills: aggregate.doubleKills,
tripleKills: aggregate.tripleKills,
quadraKills: aggregate.quadraKills,
pentaKills: aggregate.pentaKills,
avgCs: this.average(aggregate.totalCs, aggregate.games),
avgCsPerMin: this.average(aggregate.totalCs, aggregate.totalGameMinutes),
};
}
private toRecentMatchView(
doc: RiotMatchDocument,
puuid: string,
): RecentMatchView | null {
const dto = doc.raw as unknown as RiotMatchDto;
const participant = this.findParticipant(dto, puuid);
if (!participant) return null;
const teamParticipants = dto.info.participants.filter(
(candidate) => candidate.teamId === participant.teamId,
);
const teamKills = teamParticipants.reduce(
(sum, candidate) => sum + candidate.kills,
0,
);
const minutes = this.resolveGameMinutes(dto, participant);
const totalCs = this.resolveTotalCs(participant);
const damageShare = this.resolveDamageShare(dto, participant);
const rating = this.resolveRating({
participant,
teamKills,
minutes,
damageShare,
});
return {
matchId: dto.metadata.matchId,
queueId: dto.info.queueId,
queueLabel: RIOT_QUEUE_LABELS[dto.info.queueId] ?? `큐 ${dto.info.queueId}`,
gameCreation: dto.info.gameCreation,
gameDuration: dto.info.gameDuration,
win: participant.win,
remake:
this.booleanField(participant, 'gameEndedInEarlySurrender') ||
dto.info.gameDuration < 240,
championId: participant.championId,
championLevel: participant.champLevel,
teamPosition: participant.teamPosition || participant.individualPosition,
kills: participant.kills,
deaths: participant.deaths,
assists: participant.assists,
kda: this.resolveKda(
participant.kills,
participant.deaths,
participant.assists,
),
rating,
totalCs,
csPerMin: this.average(totalCs, minutes),
killParticipation: this.percent(
participant.kills + participant.assists,
teamKills,
),
visionScore: participant.visionScore,
controlWardsBought: this.numberField(
participant,
'visionWardsBoughtInGame',
),
wardsPlaced: participant.wardsPlaced,
wardsKilled: participant.wardsKilled,
damageDealtToChampions: participant.totalDamageDealtToChampions,
damageTaken: participant.totalDamageTaken,
goldEarned: participant.goldEarned,
items: [
participant.item0,
participant.item1,
participant.item2,
participant.item3,
participant.item4,
participant.item5,
],
trinket: participant.item6,
summonerSpells: [participant.summoner1Id, participant.summoner2Id],
perks: this.resolvePerks(participant),
teams: this.resolveTeams(dto),
};
}
private createRecentSummary(
views: RecentMatchView[],
docs: RiotMatchDocument[],
context: HistoryContext,
requestedLimit: number,
): RecentSummaryResponse {
const totals = views.reduce(
(acc, view) => {
acc.wins += view.win ? 1 : 0;
acc.kills += view.kills;
acc.deaths += view.deaths;
acc.assists += view.assists;
return acc;
},
{ wins: 0, kills: 0, deaths: 0, assists: 0 },
);
const losses = views.length - totals.wins;
const best = views.reduce<RecentMatchView | null>((acc, view) => {
if (!acc) return view;
return view.deaths === 0 || view.rating > acc.rating ? view : acc;
}, null);
return {
windowSize: Math.min(views.length, requestedLimit),
winRate: this.percent(totals.wins, views.length),
wins: totals.wins,
losses,
streak: this.resolveStreak(views),
kda: this.resolveKda(totals.kills, totals.deaths, totals.assists),
avgKills: this.average(totals.kills, views.length),
avgDeaths: this.average(totals.deaths, views.length),
avgAssists: this.average(totals.assists, views.length),
bestRating: best
? {
rating: best.deaths === 0 ? 'Perfect' : best.rating,
kills: best.kills,
deaths: best.deaths,
assists: best.assists,
matchId: best.matchId,
}
: null,
positionRates: this.resolvePositionRates(views),
topChampions: this.resolveTopChampions(views),
lastFetchedAt: this.resolveLastFetchedAt(docs, context),
};
}
private resolveTeams(match: RiotMatchDto): RecentMatchView['teams'] {
return match.info.teams.map((team) => ({
side: team.teamId as 100 | 200,
win: team.win,
objectives: {
baron: team.objectives?.baron?.kills,
dragon: team.objectives?.dragon?.kills,
tower: team.objectives?.tower?.kills,
},
participants: match.info.participants
.filter((participant) => participant.teamId === team.teamId)
.map((participant) => ({
puuid: participant.puuid,
gameName: participant.riotIdGameName || participant.summonerName || 'Unknown',
tagLine: participant.riotIdTagLine || '',
championId: participant.championId,
teamPosition: participant.teamPosition || participant.individualPosition,
kills: participant.kills,
deaths: participant.deaths,
assists: participant.assists,
})),
}));
}
private resolvePerks(participant: RiotMatchParticipantDto): RecentMatchView['perks'] {
const primary = participant.perks.styles.find(
(style) => style.description === 'primaryStyle',
);
const sub = participant.perks.styles.find(
(style) => style.description === 'subStyle',
);
return {
primaryStyle: primary?.style,
subStyle: sub?.style,
keystone: primary?.selections[0]?.perk,
};
}
private resolvePositionRates(
views: RecentMatchView[],
): Partial<Record<RiotLane, number>> {
const counts = new Map<string, number>();
for (const view of views) {
if (!view.teamPosition) continue;
counts.set(view.teamPosition, (counts.get(view.teamPosition) ?? 0) + 1);
}
return Object.fromEntries(
[...counts.entries()].map(([lane, count]) => [
lane,
this.percent(count, views.length),
]),
) as Partial<Record<RiotLane, number>>;
}
private resolveTopChampions(views: RecentMatchView[]): RecentSummaryResponse['topChampions'] {
const byChampion = new Map<number, { games: number; wins: number; rating: number }>();
for (const view of views) {
const stat =
byChampion.get(view.championId) ?? { games: 0, wins: 0, rating: 0 };
stat.games += 1;
stat.wins += view.win ? 1 : 0;
stat.rating += view.rating;
byChampion.set(view.championId, stat);
}
return [...byChampion.entries()]
.map(([championId, stat]) => ({
championId,
games: stat.games,
winRate: this.percent(stat.wins, stat.games),
pickRate: this.percent(stat.games, views.length),
avgRating: this.average(stat.rating, stat.games),
}))
.sort((a, b) => b.games - a.games || b.winRate - a.winRate)
.slice(0, 3);
}
private resolveStreak(
views: RecentMatchView[],
): RecentSummaryResponse['streak'] {
if (views.length === 0) return null;
const firstWin = views[0].win;
let count = 0;
for (const view of views) {
if (view.win !== firstWin) break;
count += 1;
}
return { type: firstWin ? 'win' : 'loss', count };
}
private resolveRating(params: {
participant: RiotMatchParticipantDto;
teamKills: number;
minutes: number;
damageShare: number;
}): number {
const { participant, teamKills, minutes, damageShare } = params;
const kda = this.resolveKda(
participant.kills,
participant.deaths,
participant.assists,
);
const kp = teamKills > 0 ? (participant.kills + participant.assists) / teamKills : 0;
const csPerMin = this.resolveTotalCs(participant) / Math.max(minutes, 1);
const visionPerMin = participant.visionScore / Math.max(minutes, 1);
const score =
Math.min(kda / 6, 1) * 4 +
Math.min(kp, 1) * 2 +
Math.min(csPerMin / 9, 1) * 2 +
Math.min(damageShare / 0.35, 1) +
Math.min(visionPerMin / 2, 1);
return this.round(score);
}
private resolveDamageShare(
match: RiotMatchDto,
participant: RiotMatchParticipantDto,
): number {
const teamDamage = match.info.participants
.filter((candidate) => candidate.teamId === participant.teamId)
.reduce((sum, candidate) => sum + candidate.totalDamageDealtToChampions, 0);
return teamDamage > 0 ? participant.totalDamageDealtToChampions / teamDamage : 0;
}
private resolveTotalCs(participant: RiotMatchParticipantDto): number {
return participant.totalMinionsKilled + participant.neutralMinionsKilled;
}
private resolveGameMinutes(
match: RiotMatchDto,
participant: RiotMatchParticipantDto,
): number {
return Math.max((participant.timePlayed || match.info.gameDuration) / 60, 1);
}
private resolveKda(kills: number, deaths: number, assists: number): number {
return deaths === 0 ? kills + assists : this.round((kills + assists) / deaths);
}
private resolveLastFetchedAt(
docs: RiotMatchDocument[],
context: HistoryContext,
): string | null {
if (docs.length === 0) {
return context.account.recentStatsFetchedAt?.toISOString() ?? null;
}
const oldest = docs.reduce((acc, doc) =>
doc.fetchedAt.getTime() < acc.getTime() ? doc.fetchedAt : acc,
docs[0].fetchedAt);
return oldest.toISOString();
}
private clampLimit(value: number | undefined, fallback: number, max: number): number {
if (!value || !Number.isFinite(value)) return fallback;
return Math.max(1, Math.min(Math.floor(value), max));
}
private percent(value: number, total: number): number {
return total > 0 ? Math.round((value / total) * 100) : 0;
}
private average(value: number, total: number): number {
return total > 0 ? this.round(value / total) : 0;
}
private round(value: number): number {
return Math.round(value * 10) / 10;
}
private numberField(
value: RiotMatchParticipantDto,
key: string,
): number {
const field = value[key];
return typeof field === 'number' && Number.isFinite(field) ? field : 0;
}
private booleanField(
value: RiotMatchParticipantDto,
key: string,
): boolean {
return value[key] === true;
}
}
@@ -0,0 +1,146 @@
import type { RiotLane } from '../global/database/schema';
import type {
RiotQueueGroup,
RiotRankFilter,
} from '../riot/riot-queue.constants';
export interface HistorySeasonDto {
id: string;
label: string;
startedAt: string | null;
endedAt: string | null;
}
export interface UserHistoryProfileResponse {
userId: string;
puuid: string;
gameName: string;
tagLine: string;
profileIconId: number;
summonerLevel: number;
tiers: Array<{
queueType: string;
tier: string;
rank: string;
leaguePoints: number;
wins: number;
losses: number;
fetchedAt: string;
}>;
season: HistorySeasonDto;
seasons: HistorySeasonDto[];
lastFetchedAt: string | null;
}
export interface ChampionStatsRow {
championId: number;
games: number;
wins: number;
losses: number;
winRate: number;
avgKills: number;
avgDeaths: number;
avgAssists: number;
kda: number;
totalKills: number;
totalDeaths: number;
totalAssists: number;
doubleKills: number;
tripleKills: number;
quadraKills: number;
pentaKills: number;
avgCs: number;
avgCsPerMin: number;
}
export interface ChampionStatsResponse {
queueGroup: RiotQueueGroup;
rank: RiotRankFilter;
queueIds: number[];
season: HistorySeasonDto;
lastFetchedAt: string | null;
champions: ChampionStatsRow[];
totals: ChampionStatsRow;
}
export interface RecentSummaryResponse {
windowSize: number;
winRate: number;
wins: number;
losses: number;
streak: { type: 'win' | 'loss'; count: number } | null;
kda: number;
avgKills: number;
avgDeaths: number;
avgAssists: number;
bestRating: {
rating: number | 'Perfect';
kills: number;
deaths: number;
assists: number;
matchId: string;
} | null;
positionRates: Partial<Record<RiotLane, number>>;
topChampions: Array<{
championId: number;
games: number;
winRate: number;
pickRate: number;
avgRating: number;
}>;
lastFetchedAt: string | null;
}
export interface RecentMatchesResponse {
matches: RecentMatchView[];
nextCursor: number | null;
lastFetchedAt: string | null;
season: HistorySeasonDto;
}
export interface RecentMatchView {
matchId: string;
queueId: number;
queueLabel: string;
gameCreation: number;
gameDuration: number;
win: boolean;
remake: boolean;
championId: number;
championLevel: number;
teamPosition: string;
kills: number;
deaths: number;
assists: number;
kda: number;
rating: number;
totalCs: number;
csPerMin: number;
killParticipation: number;
visionScore: number;
controlWardsBought: number;
wardsPlaced: number;
wardsKilled: number;
damageDealtToChampions: number;
damageTaken: number;
goldEarned: number;
items: number[];
trinket: number;
summonerSpells: [number, number];
perks: { primaryStyle?: number; subStyle?: number; keystone?: number };
teams: Array<{
side: 100 | 200;
win: boolean;
objectives?: { baron?: number; dragon?: number; tower?: number };
participants: Array<{
puuid: string;
gameName: string;
tagLine: string;
championId: number;
teamPosition: string;
kills: number;
deaths: number;
assists: number;
}>;
}>;
}
@@ -0,0 +1,145 @@
import { Type } from 'class-transformer';
import {
ArrayMaxSize,
ArrayMinSize,
IsArray,
IsDate,
IsEnum,
IsInt,
IsOptional,
IsString,
MaxLength,
Min,
MinLength,
ValidateNested,
} from 'class-validator';
import { POSITIONS } from '../../global/database/schema';
import type { Position } from '../../global/database/schema';
export class PositionPreferenceDto {
@IsEnum(POSITIONS)
position!: Position;
@IsInt()
@Min(1)
priority!: number;
}
class MatchScheduleItemDto {
@IsString()
@MaxLength(32)
time!: string;
@IsString()
@MaxLength(128)
label!: string;
}
export class CreateMatchDto {
@IsString()
@MinLength(1)
@MaxLength(128)
title!: string;
@IsOptional()
@IsString()
@MaxLength(2048)
description?: string;
@IsOptional()
@IsInt()
mapId?: number;
@IsDate()
@Type(() => Date)
scheduledAt!: Date;
@IsOptional()
@IsInt()
@Min(2)
maxParticipants?: number;
@IsOptional()
@IsInt()
@Min(1)
gameCount?: number;
@IsOptional()
@IsArray()
@IsString({ each: true })
@ArrayMaxSize(32)
prizes?: string[];
@IsOptional()
@IsArray()
@IsString({ each: true })
@ArrayMaxSize(32)
notices?: string[];
@IsOptional()
@IsArray()
@ValidateNested({ each: true })
@Type(() => MatchScheduleItemDto)
@ArrayMaxSize(32)
schedule?: MatchScheduleItemDto[];
}
export class UpdateMatchDto {
@IsOptional()
@IsString()
@MaxLength(128)
title?: string;
@IsOptional()
@IsString()
@MaxLength(2048)
description?: string;
@IsOptional()
@IsInt()
mapId?: number;
@IsOptional()
@IsDate()
@Type(() => Date)
scheduledAt?: Date;
@IsOptional()
@IsInt()
@Min(2)
maxParticipants?: number;
@IsOptional()
@IsInt()
@Min(1)
gameCount?: number;
@IsOptional()
@IsArray()
@IsString({ each: true })
prizes?: string[];
@IsOptional()
@IsArray()
@IsString({ each: true })
notices?: string[];
@IsOptional()
@IsArray()
@ValidateNested({ each: true })
@Type(() => MatchScheduleItemDto)
schedule?: MatchScheduleItemDto[];
}
export class JoinMatchDto {
@IsArray()
@ArrayMinSize(1)
@ArrayMaxSize(5)
@ValidateNested({ each: true })
@Type(() => PositionPreferenceDto)
preferredPositions!: PositionPreferenceDto[];
@IsOptional()
@IsString()
userId?: string;
}
@@ -0,0 +1,169 @@
import {
BadRequestException,
Body,
Controller,
Delete,
Get,
HttpCode,
HttpStatus,
Param,
Patch,
Post,
Query,
UseGuards,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
import { CurrentUser } from '../auth/current-user.decorator';
import { Roles } from '../auth/roles.decorator';
import { RolesGuard } from '../auth/roles.guard';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
import type {
MatchDocument,
MatchStatus,
UserDocument,
} from '../global/database/schema';
import {
CreateMatchDto,
JoinMatchDto,
UpdateMatchDto,
} from './dto/create-match.dto';
import { MatchService } from './match.service';
@Controller('communities/:communityId/matches')
export class MatchController {
constructor(private readonly matchService: MatchService) {}
@Post()
@Roles('admin', 'owner')
@UseGuards(RolesGuard)
public async createMatch(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Body() body: CreateMatchDto,
) {
this.assertSameCommunity(currentUser, communityId);
return this.matchService.create({
communityId,
hostUserId: currentUser._id,
data: {
title: body.title,
description: body.description ?? '',
mapId: body.mapId ?? 11,
scheduledAt: body.scheduledAt,
maxParticipants: body.maxParticipants ?? 10,
gameCount: body.gameCount,
prizes: body.prizes ?? [],
notices: body.notices ?? [],
schedule: body.schedule ?? [],
},
});
}
// 공개 — 커뮤니티 내 매치 리스트. 로그인 시 본인 참여 여부를 함께 반환.
@Get()
@AllowPublicAccess()
public async listMatches(
@CurrentUser() currentUser: UserDocument | undefined,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Query('status') status?: MatchStatus,
@Query('limit') limit?: string,
) {
const matches = await this.matchService.list({
communityId,
status,
limit: limit ? Number(limit) : undefined,
});
if (!currentUser) return { matches };
const myId = currentUser._id;
return {
matches: matches.map((m) => this.annotateJoined(m, myId)),
};
}
@Get(':matchId')
@AllowPublicAccess()
public async getMatch(
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
) {
const match = await this.matchService.getById(matchId);
return this.matchService.serialize(match);
}
@Patch(':matchId')
@Roles('admin', 'owner')
@UseGuards(RolesGuard)
public async updateMatch(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: UpdateMatchDto,
) {
this.assertSameCommunity(currentUser, communityId);
return this.matchService.update({ matchId, communityId, patch: body });
}
@Delete(':matchId')
@Roles('admin', 'owner')
@UseGuards(RolesGuard)
@HttpCode(HttpStatus.NO_CONTENT)
public async deleteMatch(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
) {
this.assertSameCommunity(currentUser, communityId);
await this.matchService.remove({ matchId, communityId });
}
// 공개 — 참여 (로그인된 유저는 자기 자신, 비로그인은 body.userId 사용).
@Post(':matchId/participants')
@AllowPublicAccess()
public async joinMatch(
@CurrentUser() currentUser: UserDocument | undefined,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: JoinMatchDto,
) {
const userId = this.resolveJoinerUserId(currentUser, body.userId);
return this.matchService.join({
matchId,
userId,
preferredPositions: body.preferredPositions,
});
}
private resolveJoinerUserId(
currentUser: UserDocument | undefined,
bodyUserId?: string,
): mongoose.Types.ObjectId {
if (currentUser) return currentUser._id;
if (!bodyUserId || !mongoose.isValidObjectId(bodyUserId)) {
throw new BadRequestException(
'userId is required when not authenticated.',
);
}
return new mongoose.Types.ObjectId(bodyUserId);
}
private annotateJoined(
match: MatchDocument,
userId: mongoose.Types.ObjectId,
) {
const obj = match.toObject();
const joined = match.participants.some((p) => p.userId.equals(userId));
return { ...obj, joined };
}
private assertSameCommunity(
user: UserDocument,
communityId: mongoose.Types.ObjectId,
): void {
if (!user.communityId.equals(communityId)) {
throw new BadRequestException('Different community.');
}
}
}
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { CommunityStatsModule } from '../community-stats/community-stats.module';
import { TournamentCodeModule } from '../tournament-code/tournament-code.module';
import { MatchController } from './match.controller';
import { MatchService } from './match.service';
@Module({
imports: [TournamentCodeModule, CommunityStatsModule],
controllers: [MatchController],
providers: [MatchService],
exports: [MatchService],
})
export class MatchModule {}
+213
View File
@@ -0,0 +1,213 @@
import {
BadRequestException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { CommunityStatsService } from '../community-stats/community-stats.service';
import { ConnectionService } from '../global/database/connection.service';
import {
Match,
MatchDocument,
MatchStatus,
PositionPreference,
TierInfo,
} from '../global/database/schema';
import { DEFAULT_TOURNAMENT_GAME_COUNT } from '../tournament-code/tournament-code.constants';
import { TournamentCodeService } from '../tournament-code/tournament-code.service';
interface CreateMatchParams {
communityId: mongoose.Types.ObjectId;
hostUserId?: mongoose.Types.ObjectId;
data: Partial<Match> & Pick<Match, 'title' | 'scheduledAt'>;
}
interface UpdateMatchParams {
matchId: mongoose.Types.ObjectId;
communityId: mongoose.Types.ObjectId;
patch: Partial<Match>;
}
interface ListMatchesQuery {
communityId: mongoose.Types.ObjectId;
status?: MatchStatus;
limit?: number;
}
interface JoinMatchParams {
matchId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
preferredPositions: PositionPreference[];
// 특정 RiotAccount(puuid)로 참가하고 싶을 때 지정. 없으면 primary 사용.
riotPuuid?: string;
}
@Injectable()
export class MatchService {
constructor(
private readonly connectionService: ConnectionService,
private readonly tournamentCodeService: TournamentCodeService,
private readonly communityStatsService: CommunityStatsService,
) {}
public async create(params: CreateMatchParams): Promise<MatchDocument> {
const MatchModel = await this.connectionService.getModel('match');
const CommunityModel = await this.connectionService.getModel('community');
const community = await CommunityModel.findById(params.communityId)
.select({ matchGameCount: 1 })
.lean()
.exec();
return MatchModel.create({
...params.data,
gameCount:
params.data.gameCount ??
community?.matchGameCount ??
DEFAULT_TOURNAMENT_GAME_COUNT,
communityId: params.communityId,
hostUserId: params.hostUserId,
});
}
public async list(query: ListMatchesQuery): Promise<MatchDocument[]> {
const MatchModel = await this.connectionService.getModel('match');
const filter: {
communityId: mongoose.Types.ObjectId;
status?: MatchStatus;
} = {
communityId: query.communityId,
};
if (query.status) filter.status = query.status;
return MatchModel.find(filter)
.sort({ scheduledAt: -1 })
.limit(Math.min(query.limit ?? 50, 200))
.exec();
}
public async getById(
matchId: mongoose.Types.ObjectId,
): Promise<MatchDocument> {
const MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findById(matchId);
if (!match) throw new NotFoundException('Match not found.');
return match;
}
public async serialize(match: MatchDocument) {
const obj = match.toObject();
if (obj.result?.games) {
obj.result.games = [...obj.result.games].sort(
(left, right) => left.gameNumber - right.gameNumber,
);
}
return {
...obj,
gameCount: match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT,
tournamentCodes: await this.tournamentCodeService.buildSlots(match),
};
}
public async update(params: UpdateMatchParams): Promise<MatchDocument> {
const MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findById(params.matchId);
if (!match) throw new NotFoundException('Match not found.');
if (!match.communityId.equals(params.communityId)) {
throw new BadRequestException('Match does not belong to this community.');
}
const previousStatus = match.status;
match.set(params.patch);
if (
previousStatus !== 'recruiting' &&
match.status === 'recruiting' &&
match.tournamentCodeIds.length > 0
) {
await this.tournamentCodeService.releaseFromMatch(match);
match.tournamentCodeIds = [];
match.teamBuiltAt = undefined;
match.result = undefined;
match.resultPollState = undefined;
}
await match.save();
return match;
}
public async remove(params: {
matchId: mongoose.Types.ObjectId;
communityId: mongoose.Types.ObjectId;
}): Promise<void> {
const MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findById(params.matchId);
if (!match) throw new NotFoundException('Match not found.');
if (!match.communityId.equals(params.communityId)) {
throw new BadRequestException('Match does not belong to this community.');
}
await this.tournamentCodeService.releaseFromMatch(match);
await match.deleteOne();
await this.communityStatsService.invalidateCommunity(params.communityId);
}
public async join(params: JoinMatchParams): Promise<MatchDocument> {
const MatchModel = await this.connectionService.getModel('match');
const UserModel = await this.connectionService.getModel('user');
const user = await UserModel.findById(params.userId);
if (!user) throw new NotFoundException('User not found.');
const match = await MatchModel.findById(params.matchId);
if (!match) throw new NotFoundException('Match not found.');
if (!match.communityId.equals(user.communityId)) {
throw new BadRequestException(
'User and match belong to different communities.',
);
}
if (match.status !== 'recruiting') {
throw new BadRequestException('Match is not recruiting.');
}
if (match.participants.length >= match.maxParticipants) {
throw new BadRequestException('Match is full.');
}
const alreadyIn = match.participants.some((p) => p.userId.equals(user._id));
if (alreadyIn) {
throw new BadRequestException('User already joined this match.');
}
const selectedRiot = params.riotPuuid
? user.riotAccounts.find((a) => a.puuid === params.riotPuuid)
: user.riotAccounts.find((a) => a.isPrimary);
const selectedTier = this.selectParticipantTier(selectedRiot?.tiers ?? []);
match.participants.push({
userId: user._id,
puuid: selectedRiot?.puuid,
gameName: selectedRiot?.gameName,
tagLine: selectedRiot?.tagLine,
profileIconId: selectedRiot?.profileIconId,
tier: selectedTier,
preferredPositions: params.preferredPositions,
joinedAt: new Date(),
});
await match.save();
return match;
}
private selectParticipantTier(tiers: TierInfo[]): TierInfo | undefined {
const tier =
tiers.find((entry) => entry.queueType === 'RANKED_SOLO_5x5') ?? tiers[0];
if (!tier) return undefined;
return {
leagueId: tier.leagueId,
queueType: tier.queueType,
tier: tier.tier,
rank: tier.rank,
puuid: tier.puuid,
leaguePoints: tier.leaguePoints,
wins: tier.wins,
losses: tier.losses,
veteran: tier.veteran,
inactive: tier.inactive,
freshBlood: tier.freshBlood,
hotStreak: tier.hotStreak,
miniSeries: tier.miniSeries,
fetchedAt: tier.fetchedAt,
};
}
}
@@ -0,0 +1,24 @@
import { Controller, Get, NotFoundException, Param } from '@nestjs/common';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
import { RiotJobQueueService } from './riot-job-queue.service';
@Controller('riot/jobs')
export class RiotJobQueueController {
constructor(private readonly jobQueueService: RiotJobQueueService) {}
@Get('parents/:parentJobId')
@AllowPublicAccess()
public async getParent(@Param('parentJobId') parentJobId: string) {
const status = await this.jobQueueService.getParentStatus(parentJobId);
if (!status) throw new NotFoundException('Riot parent job not found.');
return status;
}
@Get(':jobId')
@AllowPublicAccess()
public async getJob(@Param('jobId') jobId: string) {
const status = await this.jobQueueService.getStatus(jobId);
if (!status) throw new NotFoundException('Riot job not found.');
return status;
}
}
@@ -0,0 +1,16 @@
import { forwardRef, Module } from '@nestjs/common';
import { LegacyImportModule } from '../legacy-import/legacy-import.module';
import { RiotModule } from '../riot/riot.module';
import { TournamentResultModule } from '../tournament-result/tournament-result.module';
import { RiotJobQueueController } from './riot-job-queue.controller';
import { RiotJobQueueService } from './riot-job-queue.service';
import { RiotJobWorkerService } from './riot-job-worker.service';
import { RiotRefreshGateway } from './riot-refresh.gateway';
@Module({
imports: [RiotModule, LegacyImportModule, forwardRef(() => TournamentResultModule)],
controllers: [RiotJobQueueController],
providers: [RiotJobQueueService, RiotJobWorkerService, RiotRefreshGateway],
exports: [RiotJobQueueService],
})
export class RiotJobQueueModule {}
@@ -0,0 +1,482 @@
import {
BadRequestException,
HttpException,
HttpStatus,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { randomUUID } from 'crypto';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import type {
CommunityDocument,
RiotAccount,
UserDocument,
} from '../global/database/schema';
import { GarnetService } from '../global/garnet/garnet.service';
import {
isRiotQueueGroup,
resolveRiotQueueIds,
type RiotQueueGroup,
} from '../riot/riot-queue.constants';
import {
EnqueueRefreshResult,
RIOT_JOB_AVG_SECONDS,
RIOT_JOB_DEDUP_TTL_SECONDS,
RIOT_JOB_HIGH_COOLDOWN_SECONDS,
RIOT_JOB_HIGH_STREAM,
RIOT_JOB_LOW_COOLDOWN_SECONDS,
RIOT_JOB_LOW_STREAM,
RIOT_JOB_SCHEDULED_ZSET,
RIOT_JOB_STATUS_TTL_SECONDS,
RiotJobPriority,
RiotJobState,
RiotJobStatus,
RiotParentJobStatus,
RiotRefreshEvent,
RiotRefreshSubJob,
} from './riot-job-queue.types';
import type {
EnqueueTournamentResultPollResult,
PollTournamentResultJob,
} from '../tournament-result/tournament-result.types';
interface RefreshContext {
community: CommunityDocument;
user: UserDocument;
account: RiotAccount;
}
@Injectable()
export class RiotJobQueueService {
constructor(
private readonly connectionService: ConnectionService,
private readonly garnetService: GarnetService,
) {}
public async enqueueRefresh(params: {
communityId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
queueGroups: string[];
priority: RiotJobPriority;
requestedBy?: string;
}): Promise<EnqueueRefreshResult> {
const context = await this.resolveContext(params);
const queueGroups = this.normalizeQueueGroups(params.queueGroups);
const stream = this.resolveStream(params.priority);
const streamLength = await this.garnetService.streamLength(stream);
const dedupKeys = queueGroups.map((queueGroup) =>
this.dedupKey(context.account.puuid, queueGroup),
);
const existingJobIds = await Promise.all(
dedupKeys.map((key) => this.garnetService.getString(key)),
);
const needsNewJob = existingJobIds.some((jobId) => !jobId);
if (params.priority === 'high' && needsNewJob) {
this.assertHighQueueAccepting(streamLength);
this.assertRefreshBudget(context.account.lastRefreshRequestedAt, 'high');
}
if (params.priority === 'low' && needsNewJob) {
this.assertRefreshBudget(context.account.lastRefreshRequestedAt, 'low');
}
const parentJobId = randomUUID();
const subJobs: EnqueueRefreshResult['subJobs'] = [];
for (let index = 0; index < queueGroups.length; index += 1) {
const queueGroup = queueGroups[index];
const existingJobId = existingJobIds[index];
const queuePosition = streamLength + subJobs.length + 1;
if (existingJobId) {
const existingStatus = await this.getStatus(existingJobId);
subJobs.push({
jobId: existingJobId,
queueGroup,
alreadyQueued: true,
etaSeconds: existingStatus?.etaSeconds ?? queuePosition * RIOT_JOB_AVG_SECONDS,
queuePosition: existingStatus?.queuePosition ?? queuePosition,
});
continue;
}
const job: RiotRefreshSubJob = {
jobId: randomUUID(),
parentJobId,
userId: context.user._id.toString(),
puuid: context.account.puuid,
region: context.community.riotRegion ?? 'asia',
platform: context.community.riotPlatform ?? 'kr',
queueGroup,
queueIds: resolveRiotQueueIds(queueGroup, 'all'),
requestedAt: Date.now(),
requestedBy: params.requestedBy,
priority: params.priority,
};
const acquired = await this.garnetService.setStringIfAbsent(
dedupKeys[index],
job.jobId,
RIOT_JOB_DEDUP_TTL_SECONDS,
);
if (!acquired) {
const jobId = await this.garnetService.getString(dedupKeys[index]);
if (!jobId) continue;
const status = await this.getStatus(jobId);
subJobs.push({
jobId,
queueGroup,
alreadyQueued: true,
etaSeconds: status?.etaSeconds ?? queuePosition * RIOT_JOB_AVG_SECONDS,
queuePosition: status?.queuePosition ?? queuePosition,
});
continue;
}
const status: RiotJobStatus = {
jobId: job.jobId,
parentJobId,
state: 'queued',
priority: params.priority,
queueGroup,
queueIds: job.queueIds,
puuid: job.puuid,
userId: job.userId,
enqueuedAt: new Date(job.requestedAt).toISOString(),
etaSeconds: queuePosition * RIOT_JOB_AVG_SECONDS,
queuePosition,
};
await Promise.all([
this.setStatus(status),
this.garnetService.appendStream(
stream,
{ job: JSON.stringify(job) },
{ maxLen: 10_000 },
),
]);
subJobs.push({
jobId: job.jobId,
queueGroup,
alreadyQueued: false,
etaSeconds: status.etaSeconds,
queuePosition,
});
}
await this.setParent(parentJobId, subJobs.map((job) => job.jobId));
if (params.priority === 'high' && needsNewJob) {
await this.markRefreshRequested(context.user._id, context.account.puuid);
}
return {
parentJobId,
subJobs,
totalEtaSeconds: subJobs.reduce((sum, job) => sum + job.etaSeconds, 0),
};
}
public async enqueueTournamentResultPoll(params: {
matchId: string;
attempt: number;
expandedToAllPuuids: boolean;
priority: RiotJobPriority;
deferUntilMs?: number;
}): Promise<EnqueueTournamentResultPollResult> {
const job: PollTournamentResultJob = {
kind: 'poll-tournament-result',
jobId: randomUUID(),
matchId: params.matchId,
attempt: params.attempt,
expandedToAllPuuids: params.expandedToAllPuuids,
enqueuedAt: Date.now(),
priority: params.priority,
};
if (params.deferUntilMs && params.deferUntilMs > Date.now()) {
await this.scheduleJob(job, params.deferUntilMs);
} else {
await this.appendJob(job);
}
return {
jobId: job.jobId,
matchId: job.matchId,
priority: job.priority,
attempt: job.attempt,
expandedToAllPuuids: job.expandedToAllPuuids,
};
}
public async promoteDueScheduledJobs(limit = 100): Promise<number> {
const client = this.garnetService.raw();
const raw = (await client.sendCommand([
'ZRANGEBYSCORE',
RIOT_JOB_SCHEDULED_ZSET,
'-inf',
String(Date.now()),
'LIMIT',
'0',
String(limit),
])) as string[] | null;
const entries = raw ?? [];
let promoted = 0;
for (const entry of entries) {
const removed = (await client.sendCommand([
'ZREM',
RIOT_JOB_SCHEDULED_ZSET,
entry,
])) as number;
if (removed !== 1) continue;
const job = this.parseScheduledJob(entry);
if (!job) continue;
await this.appendJob(job);
promoted += 1;
}
return promoted;
}
public async getStatus(jobId: string): Promise<RiotJobStatus | null> {
return this.garnetService.getJson<RiotJobStatus>(this.statusKey(jobId));
}
public async getParentStatus(
parentJobId: string,
): Promise<RiotParentJobStatus | null> {
const jobIds = await this.garnetService.getJson<string[]>(
this.parentKey(parentJobId),
);
if (!jobIds) return null;
const subJobs = (
await Promise.all(jobIds.map((jobId) => this.getStatus(jobId)))
).filter((status): status is RiotJobStatus => Boolean(status));
const done = subJobs.filter((job) =>
job.state === 'completed' || job.state === 'failed',
).length;
const state = this.resolveParentState(subJobs);
return {
parentJobId,
state,
done,
total: subJobs.length,
etaSeconds: subJobs
.filter((job) => job.state === 'queued' || job.state === 'processing')
.reduce((sum, job) => sum + job.etaSeconds, 0),
subJobs,
};
}
public async markProcessing(job: RiotRefreshSubJob): Promise<RiotJobStatus> {
const status = await this.requireStatus(job.jobId);
const next: RiotJobStatus = {
...status,
state: 'processing',
startedAt: new Date().toISOString(),
etaSeconds: RIOT_JOB_AVG_SECONDS,
queuePosition: 0,
};
await this.setStatus(next);
return next;
}
public async markCompleted(
job: RiotRefreshSubJob,
): Promise<RiotRefreshEvent> {
const status = await this.requireStatus(job.jobId);
const next: RiotJobStatus = {
...status,
state: 'completed',
finishedAt: new Date().toISOString(),
etaSeconds: 0,
queuePosition: 0,
};
await Promise.all([
this.setStatus(next),
this.garnetService.delete(this.dedupKey(job.puuid, job.queueGroup)),
]);
return this.toEvent(next);
}
public async markFailed(
job: RiotRefreshSubJob,
error: unknown,
): Promise<RiotRefreshEvent> {
const message = error instanceof Error ? error.message : String(error);
const status = await this.requireStatus(job.jobId);
const next: RiotJobStatus = {
...status,
state: 'failed',
finishedAt: new Date().toISOString(),
error: message,
etaSeconds: 0,
queuePosition: 0,
};
await Promise.all([
this.setStatus(next),
this.garnetService.delete(this.dedupKey(job.puuid, job.queueGroup)),
]);
return this.toEvent(next);
}
private async resolveContext(params: {
communityId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
}): Promise<RefreshContext> {
const UserModel = await this.connectionService.getModel('user');
const CommunityModel = await this.connectionService.getModel('community');
const [user, community] = await Promise.all([
UserModel.findById(params.userId).exec(),
CommunityModel.findById(params.communityId).exec(),
]);
if (!community) throw new NotFoundException('Community not found.');
if (!user || !user.communityId.equals(params.communityId)) {
throw new NotFoundException('User not found.');
}
const account =
user.riotAccounts.find((riotAccount) => riotAccount.isPrimary) ??
user.riotAccounts[0];
if (!account) throw new NotFoundException('Riot account not found.');
return { community, user, account };
}
private normalizeQueueGroups(queueGroups: string[]): RiotQueueGroup[] {
const values = queueGroups.length > 0 ? queueGroups : ['summoners-rift'];
const unique = [...new Set(values)];
if (!unique.every(isRiotQueueGroup)) {
throw new BadRequestException('Invalid queueGroups.');
}
return unique;
}
private assertHighQueueAccepting(streamLength: number): void {
if (streamLength <= 50) return;
throw new HttpException(
{
reason: 'queue-full',
retryAfterSeconds: RIOT_JOB_AVG_SECONDS * streamLength,
},
HttpStatus.TOO_MANY_REQUESTS,
);
}
private assertRefreshBudget(
lastRequestedAt: Date | undefined,
priority: RiotJobPriority,
): void {
if (!lastRequestedAt) return;
const cooldownSeconds =
priority === 'high'
? RIOT_JOB_HIGH_COOLDOWN_SECONDS
: RIOT_JOB_LOW_COOLDOWN_SECONDS;
const elapsedSeconds = (Date.now() - lastRequestedAt.getTime()) / 1000;
if (elapsedSeconds >= cooldownSeconds) return;
throw new HttpException(
{
reason: 'cooldown',
retryAfterSeconds: Math.ceil(cooldownSeconds - elapsedSeconds),
},
HttpStatus.TOO_MANY_REQUESTS,
);
}
private async markRefreshRequested(
userId: mongoose.Types.ObjectId,
puuid: string,
): Promise<void> {
const UserModel = await this.connectionService.getModel('user');
await UserModel.updateOne(
{ _id: userId, 'riotAccounts.puuid': puuid },
{ $set: { 'riotAccounts.$.lastRefreshRequestedAt': new Date() } },
).exec();
}
private resolveStream(priority: RiotJobPriority): string {
return priority === 'high' ? RIOT_JOB_HIGH_STREAM : RIOT_JOB_LOW_STREAM;
}
private async appendJob(job: RiotRefreshSubJob | PollTournamentResultJob) {
await this.garnetService.appendStream(
this.resolveStream(job.priority),
{ job: JSON.stringify(job) },
{ maxLen: 10_000 },
);
}
private async scheduleJob(
job: PollTournamentResultJob,
deferUntilMs: number,
): Promise<void> {
await this.garnetService.raw().sendCommand([
'ZADD',
RIOT_JOB_SCHEDULED_ZSET,
String(deferUntilMs),
JSON.stringify(job),
]);
}
private parseScheduledJob(value: string): PollTournamentResultJob | null {
try {
const parsed = JSON.parse(value) as PollTournamentResultJob;
return parsed.kind === 'poll-tournament-result' ? parsed : null;
} catch {
return null;
}
}
private resolveParentState(subJobs: RiotJobStatus[]): RiotJobState {
if (subJobs.some((job) => job.state === 'processing')) return 'processing';
if (subJobs.some((job) => job.state === 'queued')) return 'queued';
if (subJobs.some((job) => job.state === 'failed')) return 'failed';
return 'completed';
}
private async requireStatus(jobId: string): Promise<RiotJobStatus> {
const status = await this.getStatus(jobId);
if (!status) throw new Error(`Missing riot job status: ${jobId}`);
return status;
}
private async setStatus(status: RiotJobStatus): Promise<void> {
await this.garnetService.setJson(
this.statusKey(status.jobId),
status,
RIOT_JOB_STATUS_TTL_SECONDS,
);
}
private async setParent(parentJobId: string, jobIds: string[]): Promise<void> {
await this.garnetService.setJson(
this.parentKey(parentJobId),
jobIds,
RIOT_JOB_STATUS_TTL_SECONDS,
);
}
private toEvent(status: RiotJobStatus): RiotRefreshEvent {
return {
parentJobId: status.parentJobId,
jobId: status.jobId,
queueGroup: status.queueGroup,
puuid: status.puuid,
state: status.state,
error: status.error,
};
}
private statusKey(jobId: string): string {
return `riot:job:status:${jobId}`;
}
private parentKey(parentJobId: string): string {
return `riot:job:parent:${parentJobId}`;
}
private dedupKey(puuid: string, queueGroup: RiotQueueGroup): string {
return `riot:job:dedup:${puuid}:${queueGroup}`;
}
}
@@ -0,0 +1,88 @@
import type {
RiotPlatformRoute,
RiotRegionalRoute,
} from '../riot/riot.types';
import type { RiotQueueGroup } from '../riot/riot-queue.constants';
import type { PollTournamentResultJob } from '../tournament-result/tournament-result.types';
import type { LegacyImportMemberJob } from '../legacy-import/legacy-import.types';
export const RIOT_JOB_HIGH_STREAM = 'riot:queue:high';
export const RIOT_JOB_LOW_STREAM = 'riot:queue:low';
export const RIOT_JOB_SCHEDULED_ZSET = 'riot:queue:scheduled';
export const RIOT_JOB_GROUP = 'riot-refresh-worker';
export const RIOT_JOB_STATUS_TTL_SECONDS = 24 * 60 * 60;
export const RIOT_JOB_DEDUP_TTL_SECONDS = 5 * 60;
export const RIOT_JOB_HIGH_COOLDOWN_SECONDS = 5 * 60;
export const RIOT_JOB_LOW_COOLDOWN_SECONDS = 60 * 60;
export const RIOT_JOB_AVG_SECONDS = 20;
export type RiotJobPriority = 'high' | 'low';
export type RiotJobState = 'queued' | 'processing' | 'completed' | 'failed';
export interface RiotRefreshSubJob {
kind?: 'refresh-account';
jobId: string;
parentJobId: string;
userId: string;
puuid: string;
region: RiotRegionalRoute;
platform: RiotPlatformRoute;
queueGroup: RiotQueueGroup;
queueIds: number[];
requestedAt: number;
requestedBy?: string;
priority: RiotJobPriority;
}
export type RiotJobPayload =
| RiotRefreshSubJob
| PollTournamentResultJob
| LegacyImportMemberJob;
export interface RiotJobStatus {
jobId: string;
parentJobId: string;
state: RiotJobState;
priority: RiotJobPriority;
queueGroup: RiotQueueGroup;
queueIds: number[];
puuid: string;
userId: string;
enqueuedAt: string;
startedAt?: string;
finishedAt?: string;
error?: string;
etaSeconds: number;
queuePosition: number;
alreadyQueued?: boolean;
}
export interface RiotParentJobStatus {
parentJobId: string;
state: RiotJobState;
done: number;
total: number;
etaSeconds: number;
subJobs: RiotJobStatus[];
}
export interface RiotRefreshEvent {
parentJobId: string;
jobId: string;
queueGroup: RiotQueueGroup;
puuid: string;
state: RiotJobState;
error?: string;
}
export interface EnqueueRefreshResult {
parentJobId: string;
subJobs: Array<{
jobId: string;
queueGroup: RiotQueueGroup;
alreadyQueued: boolean;
etaSeconds: number;
queuePosition: number;
}>;
totalEtaSeconds: number;
}
@@ -0,0 +1,227 @@
import {
Injectable,
Logger,
OnModuleDestroy,
OnModuleInit,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import { GarnetService, StreamEntry } from '../global/garnet/garnet.service';
import { LegacyImportService } from '../legacy-import/legacy-import.service';
import type { LegacyImportMemberJob } from '../legacy-import/legacy-import.types';
import { RiotRecentMatchesService } from '../riot/riot-recent-matches.service';
import {
RIOT_JOB_GROUP,
RIOT_JOB_HIGH_STREAM,
RIOT_JOB_LOW_STREAM,
RiotJobPayload,
RiotRefreshSubJob,
} from './riot-job-queue.types';
import { RiotJobQueueService } from './riot-job-queue.service';
import { RiotRefreshGateway } from './riot-refresh.gateway';
import { TournamentResultService } from '../tournament-result/tournament-result.service';
import type { PollTournamentResultJob } from '../tournament-result/tournament-result.types';
const LEADER_KEY = 'riot:worker:leader';
const LEADER_TTL_SECONDS = 60;
@Injectable()
export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(RiotJobWorkerService.name);
private readonly consumer = `${process.pid}:${Math.random().toString(36).slice(2)}`;
private stopped = false;
constructor(
private readonly garnetService: GarnetService,
private readonly jobQueueService: RiotJobQueueService,
private readonly recentMatchesService: RiotRecentMatchesService,
private readonly connectionService: ConnectionService,
private readonly refreshGateway: RiotRefreshGateway,
private readonly tournamentResultService: TournamentResultService,
private readonly legacyImportService: LegacyImportService,
) {}
public async onModuleInit() {
await this.ensureConsumerGroups();
void this.loop();
}
public onModuleDestroy() {
this.stopped = true;
}
private async loop(): Promise<void> {
while (!this.stopped) {
try {
const isLeader = await this.tryBecomeLeader();
if (!isLeader) {
await this.sleep(1_000);
continue;
}
await this.jobQueueService.promoteDueScheduledJobs();
const entry =
(await this.readOne(RIOT_JOB_HIGH_STREAM, 100)) ??
(await this.readOne(RIOT_JOB_LOW_STREAM, 1_000));
if (!entry) continue;
await this.processEntry(entry.stream, entry.message);
} catch (error) {
this.logger.warn(
`Riot job worker loop failed: ${
error instanceof Error ? error.message : error
}`,
);
await this.sleep(1_000);
}
}
}
private async processEntry(stream: string, entry: StreamEntry): Promise<void> {
const job = this.parseJob(entry);
if (!job) {
await this.garnetService.acknowledgeStream(stream, RIOT_JOB_GROUP, entry.id);
return;
}
try {
if (this.isTournamentResultJob(job)) {
await this.tournamentResultService.processPollJob(job);
return;
}
if (this.isLegacyImportJob(job)) {
await this.legacyImportService.processMemberJob(job);
return;
}
await this.jobQueueService.markProcessing(job);
for (const queueId of job.queueIds) {
await this.recentMatchesService.ensureFreshForQueue({
puuid: job.puuid,
region: job.region,
queueId,
});
}
await this.markUserFetchedAt(job);
const event = await this.jobQueueService.markCompleted(job);
this.refreshGateway.broadcastRefreshEvent(event);
} catch (error) {
if (this.isTournamentResultJob(job)) {
this.logger.warn(
`Tournament result poll job failed ${job.jobId}: ${
error instanceof Error ? error.message : error
}`,
);
return;
}
if (this.isLegacyImportJob(job)) {
this.logger.warn(
`Legacy import member job failed ${job.jobId}: ${
error instanceof Error ? error.message : error
}`,
);
return;
}
const event = await this.jobQueueService.markFailed(job, error);
this.refreshGateway.broadcastRefreshEvent(event);
this.logger.warn(
`Riot refresh job failed ${job.jobId}: ${
error instanceof Error ? error.message : error
}`,
);
} finally {
await this.garnetService.acknowledgeStream(stream, RIOT_JOB_GROUP, entry.id);
}
}
private async markUserFetchedAt(job: RiotRefreshSubJob): Promise<void> {
const UserModel = await this.connectionService.getModel('user');
const now = new Date();
const $set: Record<string, Date> = {
'riotAccounts.$.matchIdsFetchedAt': now,
};
for (const queueId of job.queueIds) {
$set[`riotAccounts.$.matchIdsByQueueFetchedAt.${queueId}`] = now;
}
await UserModel.updateOne(
{
_id: new mongoose.Types.ObjectId(job.userId),
'riotAccounts.puuid': job.puuid,
},
{ $set },
).exec();
}
private parseJob(entry: StreamEntry): RiotJobPayload | null {
const raw = entry.message.job;
if (!raw) return null;
try {
return JSON.parse(raw) as RiotJobPayload;
} catch {
return null;
}
}
private isTournamentResultJob(
job: RiotJobPayload,
): job is PollTournamentResultJob {
return job.kind === 'poll-tournament-result';
}
private isLegacyImportJob(
job: RiotJobPayload,
): job is LegacyImportMemberJob {
return job.kind === 'legacy-import-member';
}
private async readOne(
stream: string,
blockMs: number,
): Promise<{ stream: string; message: StreamEntry } | null> {
const result = await this.garnetService.readGroup(
stream,
RIOT_JOB_GROUP,
this.consumer,
'>',
{ count: 1, blockMs },
);
const message = result?.[0]?.messages[0];
return message ? { stream, message } : null;
}
private async ensureConsumerGroups(): Promise<void> {
await Promise.all(
[RIOT_JOB_HIGH_STREAM, RIOT_JOB_LOW_STREAM].map(async (stream) => {
try {
await this.garnetService.createConsumerGroup(stream, RIOT_JOB_GROUP);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
if (!message.includes('BUSYGROUP')) throw error;
}
}),
);
}
private async tryBecomeLeader(): Promise<boolean> {
const current = await this.garnetService.getString(LEADER_KEY);
if (current === this.consumer) {
await this.garnetService.setString(
LEADER_KEY,
this.consumer,
LEADER_TTL_SECONDS,
);
return true;
}
if (current) return false;
return this.garnetService.setStringIfAbsent(
LEADER_KEY,
this.consumer,
LEADER_TTL_SECONDS,
);
}
private sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
}
@@ -0,0 +1,78 @@
import { Logger } from '@nestjs/common';
import {
ConnectedSocket,
MessageBody,
SubscribeMessage,
WebSocketGateway,
WebSocketServer,
} from '@nestjs/websockets';
import type { Namespace, Socket } from 'socket.io';
import type { RiotRefreshEvent } from './riot-job-queue.types';
interface SubscribePayload {
puuid?: string;
parentJobId?: string;
}
const MAX_ROOMS_PER_SOCKET = 5;
@WebSocketGateway({
namespace: '/riot-refresh',
cors: {
origin: true,
credentials: true,
allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'],
},
})
export class RiotRefreshGateway {
@WebSocketServer()
private server!: Namespace;
private readonly logger = new Logger(RiotRefreshGateway.name);
@SubscribeMessage('subscribe')
public async handleSubscribe(
@ConnectedSocket() socket: Socket,
@MessageBody() payload: SubscribePayload,
) {
const rooms = this.resolveRooms(payload);
if (rooms.length === 0) {
socket.emit('error', { message: 'Invalid riot refresh subscription.' });
return;
}
const currentRooms = [...socket.rooms].filter((room) => room !== socket.id);
if (currentRooms.length + rooms.length > MAX_ROOMS_PER_SOCKET) {
socket.emit('error', { message: 'Too many riot refresh subscriptions.' });
return;
}
await Promise.all(rooms.map((room) => socket.join(room)));
socket.emit('subscribed', { rooms });
}
public broadcastRefreshEvent(event: RiotRefreshEvent): void {
const rooms = [
`puuid:${event.puuid}`,
`parent:${event.parentJobId}`,
`job:${event.jobId}`,
];
this.logger.debug(
`Broadcast riot refresh ${event.state}: ${event.jobId} (${event.queueGroup})`,
);
for (const room of rooms) {
this.server.to(room).emit('riot-refresh', event);
}
}
private resolveRooms(payload: SubscribePayload): string[] {
const rooms: string[] = [];
if (typeof payload?.puuid === 'string' && payload.puuid.trim()) {
rooms.push(`puuid:${payload.puuid.trim()}`);
}
if (typeof payload?.parentJobId === 'string' && payload.parentJobId.trim()) {
rooms.push(`parent:${payload.parentJobId.trim()}`);
}
return rooms;
}
}
@@ -0,0 +1,494 @@
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import {
createEmptyRiotRecentStatsSummary,
type RiotRecentStatsSummary,
} from '../global/database/schema';
import { RiotAccountEnrichmentService } from './riot-account-enrichment.service';
import { RiotAccountService } from './riot-account.service';
import { RiotChampionMasteryService } from './riot-champion-mastery.service';
import { RiotApiError } from './riot.client.service';
import { RiotLeagueService } from './riot-league.service';
import { RiotRecentMatchesService } from './riot-recent-matches.service';
import { RiotRecentStatsService } from './riot-recent-stats.service';
import { RiotSummonerService } from './riot-summoner.service';
interface FakeAccount {
puuid: string;
profileIconId: number;
revisionDate: number;
summonerLevel: number;
matchIds: string[];
matchIdsFetchedAt?: Date;
recentStatsSummary?: RiotRecentStatsSummary;
recentStatsFetchedAt?: Date;
tiers: Array<{
leagueId: string;
queueType: string;
tier: string;
rank: string;
puuid: string;
leaguePoints: number;
wins: number;
losses: number;
fetchedAt: Date;
}>;
tierHistory: Array<{
queueType: string;
tier: string;
rank?: string;
leaguePoints?: number;
wins?: number;
losses?: number;
recordedAt: Date;
}>;
championMasteries: Array<{
puuid: string;
championId: number;
championLevel: number;
championPoints: number;
}>;
championMasteriesFetchedAt?: Date;
championRecords: Record<string, unknown>;
championRecordsFetchedAt?: Date;
}
function makeAccount(overrides: Partial<FakeAccount> = {}): FakeAccount {
return {
puuid: 'puuid-1',
profileIconId: 0,
revisionDate: 0,
summonerLevel: 0,
matchIds: [],
tiers: [],
tierHistory: [],
championMasteries: [],
championRecords: {},
...overrides,
};
}
function makeUser(account: FakeAccount) {
const _id = new mongoose.Types.ObjectId();
const save = jest.fn().mockResolvedValue(undefined);
return {
_id,
riotAccounts: [account],
save,
};
}
function makeService(overrides?: {
user?: any;
account?: Partial<RiotAccountService>;
summoner?: Partial<RiotSummonerService>;
league?: Partial<RiotLeagueService>;
mastery?: Partial<RiotChampionMasteryService>;
recentMatches?: Partial<RiotRecentMatchesService>;
recentStats?: Partial<RiotRecentStatsService>;
}) {
const user = overrides?.user;
const userFindById = jest.fn().mockReturnValue({
exec: () => Promise.resolve(user ?? null),
});
const communityFindById = jest.fn().mockReturnValue({
select: () => ({
lean: () => ({
exec: () =>
Promise.resolve({
riotPlatform: 'kr',
riotRegion: 'asia',
}),
}),
}),
});
const connectionService = {
getModel: jest.fn().mockImplementation(async (modelName: string) => {
if (modelName === 'user') {
return { findById: userFindById };
}
if (modelName === 'community') {
return { findById: communityFindById };
}
throw new Error(`Unexpected model: ${modelName}`);
}),
} as unknown as ConnectionService;
const summonerService = {
getByPuuid: jest.fn(),
...overrides?.summoner,
} as unknown as RiotSummonerService;
const accountService = {
getRegionByPuuid: jest.fn(),
...overrides?.account,
} as unknown as RiotAccountService;
const leagueService = {
getEntriesByPuuid: jest.fn(),
...overrides?.league,
} as unknown as RiotLeagueService;
const masteryService = {
getTopByPuuid: jest.fn(),
...overrides?.mastery,
} as unknown as RiotChampionMasteryService;
const recentMatchesService = {
syncRecentMatches: jest.fn().mockResolvedValue([]),
loadFromDb: jest.fn().mockResolvedValue([]),
...overrides?.recentMatches,
} as unknown as RiotRecentMatchesService;
const recentStatsService = {
computeSummary: jest
.fn()
.mockReturnValue(createEmptyRiotRecentStatsSummary()),
...overrides?.recentStats,
} as unknown as RiotRecentStatsService;
const service = new RiotAccountEnrichmentService(
connectionService,
accountService,
summonerService,
leagueService,
masteryService,
recentMatchesService,
recentStatsService,
);
return {
service,
user,
accountService,
summonerService,
leagueService,
masteryService,
recentMatchesService,
recentStatsService,
};
}
describe('RiotAccountEnrichmentService', () => {
it('returns failed for unknown user', async () => {
const { service } = makeService();
const result = await service.enrichRiotAccount({
userId: new mongoose.Types.ObjectId(),
puuid: 'puuid-1',
});
expect(result.summoner).toBe('failed');
expect(result.recentMatches).toBe('failed');
expect(result.account).toBeNull();
});
it('fills summoner / league / mastery on first attach (force)', async () => {
const account = makeAccount();
const user = makeUser(account);
const {
service,
summonerService,
leagueService,
masteryService,
recentMatchesService,
recentStatsService,
} =
makeService({
user,
summoner: {
getByPuuid: jest.fn().mockResolvedValue({
puuid: 'puuid-1',
profileIconId: 588,
revisionDate: 1776977597000,
summonerLevel: 529,
}),
} as Partial<RiotSummonerService>,
league: {
getEntriesByPuuid: jest.fn().mockResolvedValue([
{
leagueId: 'L1',
queueType: 'RANKED_SOLO_5x5',
tier: 'EMERALD',
rank: 'I',
puuid: 'puuid-1',
leaguePoints: 75,
wins: 160,
losses: 148,
},
]),
} as Partial<RiotLeagueService>,
mastery: {
getTopByPuuid: jest.fn().mockResolvedValue([
{
puuid: 'puuid-1',
championId: 7,
championLevel: 70,
championPoints: 742560,
},
]),
} as Partial<RiotChampionMasteryService>,
recentMatches: {
syncRecentMatches: jest.fn().mockResolvedValue([]),
loadFromDb: jest.fn().mockResolvedValue([
{ matchId: 'KR_1', raw: {} },
{ matchId: 'KR_2', raw: {} },
]),
} as Partial<RiotRecentMatchesService>,
recentStats: {
computeSummary: jest.fn().mockReturnValue({
overall: {
games: 2,
wins: 1,
losses: 1,
avgKills: 5.5,
avgDeaths: 2.5,
avgAssists: 7,
avgCs: 175,
avgCsPerMin: 6.4,
mostPlayedChampionIds: [7, 103],
},
byLane: {},
}),
} as Partial<RiotRecentStatsService>,
});
const result = await service.enrichRiotAccount({
userId: user._id,
puuid: 'puuid-1',
options: { force: true },
});
expect(result.summoner).toBe('updated');
expect(result.league).toBe('updated');
expect(result.masteries).toBe('updated');
expect(result.recentMatches).toBe('updated');
expect(account.profileIconId).toBe(588);
expect(account.summonerLevel).toBe(529);
expect(account.matchIds).toEqual(['KR_1', 'KR_2']);
expect(account.recentStatsSummary).toMatchObject({
overall: {
games: 2,
wins: 1,
losses: 1,
avgKills: 5.5,
avgDeaths: 2.5,
avgAssists: 7,
avgCs: 175,
avgCsPerMin: 6.4,
mostPlayedChampionIds: [7, 103],
},
});
expect(account.tiers).toHaveLength(1);
expect(account.tiers[0]).toMatchObject({
leagueId: 'L1',
queueType: 'RANKED_SOLO_5x5',
tier: 'EMERALD',
rank: 'I',
puuid: 'puuid-1',
leaguePoints: 75,
});
expect(account.tierHistory).toHaveLength(1);
expect(account.tierHistory[0]).toMatchObject({
queueType: 'RANKED_SOLO_5x5',
tier: 'EMERALD',
rank: 'I',
leaguePoints: 75,
wins: 160,
losses: 148,
});
expect(account.championMasteries).toEqual([
{
puuid: 'puuid-1',
championId: 7,
championLevel: 70,
championPoints: 742560,
},
]);
expect(account.championRecords).toEqual({});
expect(user.save).toHaveBeenCalledTimes(1);
expect(summonerService.getByPuuid).toHaveBeenCalledWith('puuid-1', {
platform: 'kr',
});
expect(leagueService.getEntriesByPuuid).toHaveBeenCalledWith('puuid-1', {
platform: 'kr',
});
expect(masteryService.getTopByPuuid).toHaveBeenCalledWith('puuid-1', {
platform: 'kr',
count: 10,
});
expect(recentMatchesService.syncRecentMatches).toHaveBeenCalledWith({
puuid: 'puuid-1',
region: 'asia',
limit: 20,
});
expect(recentStatsService.computeSummary).toHaveBeenCalled();
});
it('skips fresh data when within TTL and not forced', async () => {
const recent = new Date(Date.now() - 60_000);
const account = makeAccount({
profileIconId: 1,
revisionDate: Date.now() - 60_000,
summonerLevel: 100,
tiers: [
{
leagueId: 'L1',
queueType: 'RANKED_SOLO_5x5',
tier: 'GOLD',
rank: 'II',
puuid: 'puuid-1',
leaguePoints: 1,
wins: 1,
losses: 1,
fetchedAt: recent,
},
],
championMasteriesFetchedAt: recent,
recentStatsFetchedAt: recent,
recentStatsSummary: createEmptyRiotRecentStatsSummary(),
});
const user = makeUser(account);
const summoner = jest.fn();
const league = jest.fn();
const mastery = jest.fn();
const { service } = makeService({
user,
summoner: { getByPuuid: summoner } as Partial<RiotSummonerService>,
league: {
getEntriesByPuuid: league,
} as Partial<RiotLeagueService>,
mastery: {
getTopByPuuid: mastery,
} as Partial<RiotChampionMasteryService>,
});
const result = await service.enrichRiotAccount({
userId: user._id,
puuid: 'puuid-1',
});
expect(result.summoner).toBe('fresh');
expect(result.league).toBe('fresh');
expect(result.masteries).toBe('fresh');
expect(result.recentMatches).toBe('fresh');
expect(summoner).not.toHaveBeenCalled();
expect(league).not.toHaveBeenCalled();
expect(mastery).not.toHaveBeenCalled();
expect(user.save).not.toHaveBeenCalled();
});
it('records failed for individual failing fetches but updates the rest', async () => {
const account = makeAccount();
const user = makeUser(account);
const { service } = makeService({
user,
summoner: {
getByPuuid: jest.fn().mockRejectedValue(new Error('boom')),
} as Partial<RiotSummonerService>,
league: {
getEntriesByPuuid: jest.fn().mockResolvedValue([]),
} as Partial<RiotLeagueService>,
mastery: {
getTopByPuuid: jest.fn().mockResolvedValue([]),
} as Partial<RiotChampionMasteryService>,
});
const result = await service.enrichRiotAccount({
userId: user._id,
puuid: 'puuid-1',
options: { force: true },
});
expect(result.summoner).toBe('failed');
expect(result.league).toBe('updated');
expect(result.masteries).toBe('updated');
expect(result.recentMatches).toBe('updated');
expect(user.save).toHaveBeenCalled();
});
it('retries summoner lookup with region/by-puuid platform on 404', async () => {
const account = makeAccount();
const user = makeUser(account);
const summoner = jest
.fn()
.mockRejectedValueOnce(new RiotApiError('not found', 404, 'url'))
.mockResolvedValueOnce({
puuid: 'puuid-1',
profileIconId: 100,
revisionDate: 1776977597000,
summonerLevel: 30,
});
const region = jest.fn().mockResolvedValue({
puuid: 'puuid-1',
game: 'lol',
region: 'jp1',
});
const league = jest.fn().mockResolvedValue([]);
const mastery = jest.fn().mockResolvedValue([]);
const { service } = makeService({
user,
account: { getRegionByPuuid: region } as Partial<RiotAccountService>,
summoner: { getByPuuid: summoner } as Partial<RiotSummonerService>,
league: {
getEntriesByPuuid: league,
} as Partial<RiotLeagueService>,
mastery: {
getTopByPuuid: mastery,
} as Partial<RiotChampionMasteryService>,
});
const result = await service.enrichRiotAccount({
userId: user._id,
puuid: 'puuid-1',
options: { force: true, platform: 'kr' },
});
expect(result.summoner).toBe('updated');
expect(region).toHaveBeenCalledWith('puuid-1', { region: 'asia' });
expect(summoner).toHaveBeenNthCalledWith(1, 'puuid-1', {
platform: 'kr',
});
expect(summoner).toHaveBeenNthCalledWith(2, 'puuid-1', {
platform: 'jp1',
});
expect(league).toHaveBeenCalledWith('puuid-1', { platform: 'jp1' });
expect(mastery).toHaveBeenCalledWith('puuid-1', {
platform: 'jp1',
count: 10,
});
});
it('deduplicates concurrent enrichment for the same user and puuid', async () => {
const account = makeAccount();
const user = makeUser(account);
let resolveSummoner: (value: unknown) => void;
const summonerPromise = new Promise((resolve) => {
resolveSummoner = resolve;
});
const summoner = jest.fn().mockReturnValue(summonerPromise);
const { service } = makeService({
user,
summoner: { getByPuuid: summoner } as Partial<RiotSummonerService>,
league: {
getEntriesByPuuid: jest.fn().mockResolvedValue([]),
} as Partial<RiotLeagueService>,
mastery: {
getTopByPuuid: jest.fn().mockResolvedValue([]),
} as Partial<RiotChampionMasteryService>,
});
const first = service.enrichRiotAccount({
userId: user._id,
puuid: 'puuid-1',
options: { force: true },
});
const second = service.enrichRiotAccount({
userId: user._id,
puuid: 'puuid-1',
options: { force: true },
});
resolveSummoner!({
puuid: 'puuid-1',
profileIconId: 100,
revisionDate: 1776977597000,
summonerLevel: 30,
});
await Promise.all([first, second]);
expect(summoner).toHaveBeenCalledTimes(1);
expect(user.save).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,437 @@
import { Injectable, Logger } from '@nestjs/common';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import {
ChampionMasteryEntry,
RiotAccount,
TierInfo,
} from '../global/database/schema';
import { RiotAccountService } from './riot-account.service';
import { RiotChampionMasteryService } from './riot-champion-mastery.service';
import { RiotApiError } from './riot.client.service';
import { RiotLeagueService } from './riot-league.service';
import {
RIOT_RECENT_MATCH_LIMIT,
RiotRecentMatchesService,
} from './riot-recent-matches.service';
import { RiotRecentStatsService } from './riot-recent-stats.service';
import { RiotSummonerService } from './riot-summoner.service';
import {
RiotChampionMasteryDto,
RiotLeagueEntryDto,
RiotMatchDto,
RiotPlatformRoute,
RiotRegionalRoute,
RiotSummonerDto,
} from './riot.types';
const DEFAULT_PLATFORM: RiotPlatformRoute = 'kr';
const DEFAULT_REGION: RiotRegionalRoute = 'asia';
const MASTERY_LIMIT = 10;
const DEFAULT_SUMMONER_TTL_MS = 24 * 60 * 60 * 1000; // 24h
const DEFAULT_LEAGUE_TTL_MS = 60 * 60 * 1000; // 1h
const DEFAULT_MASTERY_TTL_MS = 6 * 60 * 60 * 1000; // 6h
const DEFAULT_RECENT_MATCHES_TTL_MS = 6 * 60 * 60 * 1000; // 6h
export interface EnrichOptions {
platform?: RiotPlatformRoute;
region?: RiotRegionalRoute;
force?: boolean;
summonerTtlMs?: number;
leagueTtlMs?: number;
masteryTtlMs?: number;
recentMatchesTtlMs?: number;
}
export interface EnrichResult {
summoner: 'updated' | 'fresh' | 'failed';
league: 'updated' | 'fresh' | 'failed';
masteries: 'updated' | 'fresh' | 'failed';
recentMatches: 'updated' | 'fresh' | 'failed';
account: RiotAccount | null;
}
@Injectable()
export class RiotAccountEnrichmentService {
private readonly logger = new Logger(RiotAccountEnrichmentService.name);
private readonly inFlight = new Map<string, Promise<EnrichResult>>();
constructor(
private readonly connectionService: ConnectionService,
private readonly accountService: RiotAccountService,
private readonly summonerService: RiotSummonerService,
private readonly leagueService: RiotLeagueService,
private readonly masteryService: RiotChampionMasteryService,
private readonly recentMatchesService: RiotRecentMatchesService,
private readonly recentStatsService: RiotRecentStatsService,
) {}
public async enrichRiotAccount(params: {
userId: mongoose.Types.ObjectId;
puuid: string;
options?: EnrichOptions;
}): Promise<EnrichResult> {
const key = `${params.userId.toString()}:${params.puuid}`;
const existing = this.inFlight.get(key);
if (existing) return existing;
const promise = this.doEnrichRiotAccount(params).finally(() => {
this.inFlight.delete(key);
});
this.inFlight.set(key, promise);
return promise;
}
private async doEnrichRiotAccount(params: {
userId: mongoose.Types.ObjectId;
puuid: string;
options?: EnrichOptions;
}): Promise<EnrichResult> {
const UserModel = await this.connectionService.getModel('user');
const user = await UserModel.findById(params.userId).exec();
if (!user) {
return {
summoner: 'failed',
league: 'failed',
masteries: 'failed',
recentMatches: 'failed',
account: null,
};
}
const account = user.riotAccounts.find((a) => a.puuid === params.puuid);
if (!account) {
return {
summoner: 'failed',
league: 'failed',
masteries: 'failed',
recentMatches: 'failed',
account: null,
};
}
const CommunityModel = await this.connectionService.getModel('community');
const community = await CommunityModel.findById(user.communityId)
.select({ riotPlatform: 1, riotRegion: 1, seasonStartedAt: 1 })
.lean()
.exec();
const opts = params.options ?? {};
const platform = opts.platform ?? community?.riotPlatform ?? DEFAULT_PLATFORM;
const region = opts.region ?? community?.riotRegion ?? DEFAULT_REGION;
const now = Date.now();
const summonerTtl = opts.summonerTtlMs ?? DEFAULT_SUMMONER_TTL_MS;
const leagueTtl = opts.leagueTtlMs ?? DEFAULT_LEAGUE_TTL_MS;
const masteryTtl = opts.masteryTtlMs ?? DEFAULT_MASTERY_TTL_MS;
const recentMatchesTtl =
opts.recentMatchesTtlMs ?? DEFAULT_RECENT_MATCHES_TTL_MS;
const force = opts.force === true;
const seasonStartedAt = community?.seasonStartedAt
? new Date(community.seasonStartedAt)
: undefined;
const seasonInvalidatesRecentStats =
seasonStartedAt !== undefined &&
(!account.recentStatsFetchedAt ||
account.recentStatsFetchedAt.getTime() < seasonStartedAt.getTime());
const summonerStale =
force ||
account.revisionDate === 0 ||
now - account.revisionDate > summonerTtl;
const leagueStale =
force ||
account.tiers.length === 0 ||
this.tiersOldestAt(account.tiers) < now - leagueTtl;
const masteryStale =
force ||
!account.championMasteriesFetchedAt ||
now - account.championMasteriesFetchedAt.getTime() > masteryTtl;
const recentMatchesStale =
force ||
seasonInvalidatesRecentStats ||
!account.recentStatsFetchedAt ||
!account.recentStatsSummary ||
now - account.recentStatsFetchedAt.getTime() > recentMatchesTtl;
const summonerOutcome = summonerStale
? await this.fetchSummonerSafe(params.puuid, platform, region)
: { status: 'fresh' as const, dto: null, platform };
const effectivePlatform = summonerOutcome.platform ?? platform;
const [leagueOutcome, masteryOutcome, recentMatchesOutcome] =
await Promise.all([
leagueStale
? this.fetchLeagueSafe(params.puuid, effectivePlatform)
: Promise.resolve({ status: 'fresh' as const, dto: null }),
masteryStale
? this.fetchMasteriesSafe(params.puuid, effectivePlatform)
: Promise.resolve({ status: 'fresh' as const, dto: null }),
recentMatchesStale
? this.fetchRecentMatchesSafe(params.puuid, region, seasonStartedAt)
: Promise.resolve({
status: 'fresh' as const,
summary: null,
matchIds: null,
}),
]);
if (summonerOutcome.status === 'updated' && summonerOutcome.dto) {
this.applySummoner(account, summonerOutcome.dto);
}
if (leagueOutcome.status === 'updated' && leagueOutcome.dto) {
this.applyLeagueEntries(account, leagueOutcome.dto);
}
if (masteryOutcome.status === 'updated' && masteryOutcome.dto) {
this.applyMasteries(account, masteryOutcome.dto);
}
if (
recentMatchesOutcome.status === 'updated' &&
recentMatchesOutcome.summary &&
recentMatchesOutcome.matchIds
) {
this.applyRecentMatches(
account,
recentMatchesOutcome.summary,
recentMatchesOutcome.matchIds,
);
}
if (
summonerOutcome.status === 'updated' ||
leagueOutcome.status === 'updated' ||
masteryOutcome.status === 'updated' ||
recentMatchesOutcome.status === 'updated'
) {
await user.save();
}
return {
summoner: summonerOutcome.status,
league: leagueOutcome.status,
masteries: masteryOutcome.status,
recentMatches: recentMatchesOutcome.status,
account,
};
}
private async fetchSummonerSafe(
puuid: string,
platform: RiotPlatformRoute,
region: RiotRegionalRoute,
): Promise<
| { status: 'updated'; dto: RiotSummonerDto; platform: RiotPlatformRoute }
| { status: 'failed'; dto: null; platform: RiotPlatformRoute }
> {
try {
const dto = await this.summonerService.getByPuuid(puuid, { platform });
return { status: 'updated', dto, platform };
} catch (err) {
if (err instanceof RiotApiError && err.status === 404) {
try {
const regionDto = await this.accountService.getRegionByPuuid(puuid, {
region,
});
if (regionDto.region !== platform) {
this.logger.warn(
`Summoner platform corrected for ${puuid}: ${platform} -> ${regionDto.region}`,
);
}
const dto = await this.summonerService.getByPuuid(puuid, {
platform: regionDto.region,
});
return { status: 'updated', dto, platform: regionDto.region };
} catch (fallbackErr) {
this.logger.warn(
`Summoner fallback fetch failed for ${puuid}: ${
(fallbackErr as Error)?.message ?? fallbackErr
}`,
);
return { status: 'failed', dto: null, platform };
}
}
this.logger.warn(
`Summoner fetch failed for ${puuid}: ${(err as Error)?.message ?? err}`,
);
return { status: 'failed', dto: null, platform };
}
}
private async fetchLeagueSafe(
puuid: string,
platform: RiotPlatformRoute,
): Promise<
| { status: 'updated'; dto: RiotLeagueEntryDto[] }
| { status: 'failed'; dto: null }
> {
try {
const dto = await this.leagueService.getEntriesByPuuid(puuid, {
platform,
});
return { status: 'updated', dto };
} catch (err) {
this.logger.warn(
`League entries fetch failed for ${puuid}: ${
(err as Error)?.message ?? err
}`,
);
return { status: 'failed', dto: null };
}
}
private async fetchMasteriesSafe(
puuid: string,
platform: RiotPlatformRoute,
): Promise<
| { status: 'updated'; dto: RiotChampionMasteryDto[] }
| { status: 'failed'; dto: null }
> {
try {
const dto = await this.masteryService.getTopByPuuid(puuid, {
platform,
count: MASTERY_LIMIT,
});
return { status: 'updated', dto };
} catch (err) {
this.logger.warn(
`Champion masteries fetch failed for ${puuid}: ${
(err as Error)?.message ?? err
}`,
);
return { status: 'failed', dto: null };
}
}
private async fetchRecentMatchesSafe(
puuid: string,
region: RiotRegionalRoute,
seasonStartedAt?: Date,
): Promise<
| {
status: 'updated';
summary: RiotAccount['recentStatsSummary'];
matchIds: string[];
}
| { status: 'failed'; summary: null; matchIds: null }
> {
try {
await this.recentMatchesService.syncRecentMatches({
puuid,
region,
limit: RIOT_RECENT_MATCH_LIMIT,
});
const matches = await this.recentMatchesService.loadFromDb({
puuid,
limit: RIOT_RECENT_MATCH_LIMIT,
});
const summary = this.recentStatsService.computeSummary(
matches.map((match) => match.raw as unknown as RiotMatchDto),
puuid,
{ seasonStartedAt },
);
return {
status: 'updated',
summary,
matchIds: matches.map((match) => match.matchId),
};
} catch (err) {
this.logger.warn(
`Recent matches fetch failed for ${puuid}: ${
(err as Error)?.message ?? err
}`,
);
return { status: 'failed', summary: null, matchIds: null };
}
}
private applySummoner(account: RiotAccount, dto: RiotSummonerDto): void {
account.profileIconId = dto.profileIconId;
account.revisionDate = dto.revisionDate;
account.summonerLevel = dto.summonerLevel;
}
private applyLeagueEntries(
account: RiotAccount,
entries: RiotLeagueEntryDto[],
): void {
const fetchedAt = new Date();
this.appendTierHistoryIfChanged(account, entries, fetchedAt);
const next: TierInfo[] = entries.map((e) => ({
leagueId: e.leagueId,
queueType: e.queueType,
tier: e.tier,
rank: e.rank,
puuid: e.puuid,
leaguePoints: e.leaguePoints,
wins: e.wins,
losses: e.losses,
veteran: e.veteran,
inactive: e.inactive,
freshBlood: e.freshBlood,
hotStreak: e.hotStreak,
miniSeries: e.miniSeries,
fetchedAt,
}));
account.tiers = next;
}
private appendTierHistoryIfChanged(
account: RiotAccount,
entries: RiotLeagueEntryDto[],
recordedAt: Date,
): void {
for (const entry of entries) {
const last = [...account.tierHistory]
.reverse()
.find((history) => history.queueType === entry.queueType);
const changed =
!last ||
last.tier !== entry.tier ||
(last.rank ?? '') !== (entry.rank ?? '');
if (!changed) continue;
account.tierHistory.push({
queueType: entry.queueType,
tier: entry.tier,
rank: entry.rank,
leaguePoints: entry.leaguePoints,
wins: entry.wins,
losses: entry.losses,
recordedAt,
});
}
}
private applyMasteries(
account: RiotAccount,
masteries: RiotChampionMasteryDto[],
): void {
const summary: ChampionMasteryEntry[] = masteries
.slice(0, MASTERY_LIMIT)
.map((m) => ({ ...m }));
account.championMasteries = summary;
account.championMasteriesFetchedAt = new Date();
}
private applyRecentMatches(
account: RiotAccount,
summary: NonNullable<RiotAccount['recentStatsSummary']>,
matchIds: string[],
): void {
const fetchedAt = new Date();
account.recentStatsSummary = summary;
account.recentStatsFetchedAt = fetchedAt;
account.matchIds = matchIds;
account.matchIdsFetchedAt = fetchedAt;
}
private tiersOldestAt(tiers: TierInfo[]): number {
if (tiers.length === 0) return 0;
let oldest = Infinity;
for (const t of tiers) {
const at = t.fetchedAt instanceof Date ? t.fetchedAt.getTime() : 0;
if (at < oldest) oldest = at;
}
return oldest === Infinity ? 0 : oldest;
}
}
@@ -0,0 +1,128 @@
import { Injectable } from '@nestjs/common';
import { RiotClientService } from './riot.client.service';
import {
RIOT_PLATFORM_ROUTES,
RiotAccountDto,
RiotAccountLookupOptions,
RiotAccountRegionDto,
} from './riot.types';
@Injectable()
export class RiotAccountService {
constructor(private readonly riotClientService: RiotClientService) {}
public async getByRiotId(
gameName: string,
tagLine: string,
options: RiotAccountLookupOptions = {},
): Promise<RiotAccountDto> {
return this.riotClientService.get<RiotAccountDto>(
`/riot/account/v1/accounts/by-riot-id/${encodeURIComponent(gameName)}/${encodeURIComponent(tagLine)}`,
{
region: options.region,
signal: options.signal,
},
parseRiotAccountDto,
);
}
public async getByPuuid(
puuid: string,
options: RiotAccountLookupOptions = {},
): Promise<RiotAccountDto> {
return this.riotClientService.get<RiotAccountDto>(
`/riot/account/v1/accounts/by-puuid/${encodeURIComponent(puuid)}`,
{
region: options.region,
signal: options.signal,
},
parseRiotAccountDto,
);
}
public async getRegionByPuuid(
puuid: string,
options: RiotAccountLookupOptions = {},
): Promise<RiotAccountRegionDto> {
return this.riotClientService.get<RiotAccountRegionDto>(
`/riot/account/v1/region/by-game/lol/by-puuid/${encodeURIComponent(puuid)}`,
{
region: options.region ?? 'asia',
signal: options.signal,
},
parseRiotAccountRegionDto,
);
}
}
function parseRiotAccountDto(value: unknown): RiotAccountDto {
if (!isRecord(value)) {
throw new TypeError('Riot account response must be an object.');
}
const puuid = value.puuid;
const gameName = value.gameName;
const tagLine = value.tagLine;
if (!isNonEmptyString(puuid)) {
throw new TypeError('Riot account response is missing a valid puuid.');
}
if (!isOptionalString(gameName)) {
throw new TypeError('Riot account response has an invalid gameName.');
}
if (!isOptionalString(tagLine)) {
throw new TypeError('Riot account response has an invalid tagLine.');
}
return {
puuid,
gameName: gameName ?? null,
tagLine: tagLine ?? null,
};
}
function parseRiotAccountRegionDto(value: unknown): RiotAccountRegionDto {
if (!isRecord(value)) {
throw new TypeError('Riot account region response must be an object.');
}
const puuid = value.puuid;
const game = value.game;
const region = value.region;
if (!isNonEmptyString(puuid)) {
throw new TypeError(
'Riot account region response is missing a valid puuid.',
);
}
if (!isNonEmptyString(game)) {
throw new TypeError(
'Riot account region response is missing a valid game.',
);
}
const platformRegion = region as (typeof RIOT_PLATFORM_ROUTES)[number];
if (
!isNonEmptyString(region) ||
!RIOT_PLATFORM_ROUTES.includes(platformRegion)
) {
throw new TypeError(
'Riot account region response is missing a valid region.',
);
}
return { puuid, game, region: platformRegion };
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
function isNonEmptyString(value: unknown): value is string {
return typeof value === 'string' && value.length > 0;
}
function isOptionalString(value: unknown): value is string | undefined {
return value === undefined || typeof value === 'string';
}
@@ -0,0 +1,129 @@
import { Injectable } from '@nestjs/common';
import { RiotClientService } from './riot.client.service';
import {
RiotChampionMasteryDto,
RiotPlatformLookupOptions,
} from './riot.types';
interface MasteriesByPuuidOptions extends RiotPlatformLookupOptions {
count?: number;
}
const DEFAULT_TOP_MASTERY_COUNT = 10;
const MAX_TOP_MASTERY_COUNT = 10;
@Injectable()
export class RiotChampionMasteryService {
constructor(private readonly riotClientService: RiotClientService) {}
public async getByPuuid(
puuid: string,
options: RiotPlatformLookupOptions = {},
): Promise<RiotChampionMasteryDto[]> {
return this.riotClientService.get<RiotChampionMasteryDto[]>(
`/lol/champion-mastery/v4/champion-masteries/by-puuid/${encodeURIComponent(puuid)}`,
{
platform: options.platform ?? 'kr',
signal: options.signal,
},
parseMasteries,
);
}
public async getTopByPuuid(
puuid: string,
options: MasteriesByPuuidOptions = {},
): Promise<RiotChampionMasteryDto[]> {
const count = options.count ?? DEFAULT_TOP_MASTERY_COUNT;
if (
!Number.isInteger(count) ||
count <= 0 ||
count > MAX_TOP_MASTERY_COUNT
) {
throw new RangeError('count must be an integer between 1 and 10.');
}
return this.riotClientService.get<RiotChampionMasteryDto[]>(
`/lol/champion-mastery/v4/champion-masteries/by-puuid/${encodeURIComponent(puuid)}/top`,
{
platform: options.platform ?? 'kr',
signal: options.signal,
query: { count },
},
parseMasteries,
);
}
}
function parseMasteries(value: unknown): RiotChampionMasteryDto[] {
if (!Array.isArray(value)) {
throw new TypeError('Champion masteries response must be an array.');
}
return value.map((entry, index) => parseEntry(entry, index));
}
function parseEntry(value: unknown, index: number): RiotChampionMasteryDto {
if (!isRecord(value)) {
throw new TypeError(`championMasteries[${index}] must be an object.`);
}
const puuid = value.puuid;
const championId = value.championId;
const championLevel = value.championLevel;
const championPoints = value.championPoints;
if (typeof puuid !== 'string') {
throw new TypeError(`championMasteries[${index}].puuid must be a string.`);
}
if (typeof championId !== 'number' || !Number.isFinite(championId)) {
throw new TypeError(
`championMasteries[${index}].championId must be a number.`,
);
}
if (typeof championLevel !== 'number' || !Number.isFinite(championLevel)) {
throw new TypeError(
`championMasteries[${index}].championLevel must be a number.`,
);
}
if (typeof championPoints !== 'number' || !Number.isFinite(championPoints)) {
throw new TypeError(
`championMasteries[${index}].championPoints must be a number.`,
);
}
return {
...value,
puuid,
championId,
championLevel,
championPoints,
lastPlayTime:
typeof value.lastPlayTime === 'number' ? value.lastPlayTime : undefined,
championPointsSinceLastLevel:
typeof value.championPointsSinceLastLevel === 'number'
? value.championPointsSinceLastLevel
: undefined,
championPointsUntilNextLevel:
typeof value.championPointsUntilNextLevel === 'number'
? value.championPointsUntilNextLevel
: undefined,
markRequiredForNextLevel:
typeof value.markRequiredForNextLevel === 'number'
? value.markRequiredForNextLevel
: undefined,
tokensEarned:
typeof value.tokensEarned === 'number' ? value.tokensEarned : undefined,
championSeasonMilestone:
typeof value.championSeasonMilestone === 'number'
? value.championSeasonMilestone
: undefined,
milestoneGrades: Array.isArray(value.milestoneGrades)
? (value.milestoneGrades as unknown[]).filter(
(v): v is string => typeof v === 'string',
)
: undefined,
nextSeasonMilestone: isRecord(value.nextSeasonMilestone)
? value.nextSeasonMilestone
: undefined,
};
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
@@ -0,0 +1,19 @@
import { Controller, Get, Query } from '@nestjs/common';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
import {
RiotDdragonService,
type DdragonManifest,
} from './riot-ddragon.service';
@Controller('riot/ddragon')
export class RiotDdragonController {
constructor(private readonly ddragonService: RiotDdragonService) {}
@Get('manifest')
@AllowPublicAccess()
public async getManifest(
@Query('locale') locale?: string,
): Promise<DdragonManifest> {
return this.ddragonService.getManifest(locale ?? 'ko_KR');
}
}
@@ -0,0 +1,142 @@
import { Injectable, Logger } from '@nestjs/common';
import { GarnetService } from '../global/garnet/garnet.service';
const DDRAGON_BASE = 'https://ddragon.leagueoflegends.com';
const DDRAGON_CDN = `${DDRAGON_BASE}/cdn`;
const DEFAULT_LOCALE = 'ko_KR';
const CACHE_TTL_SECONDS = 24 * 60 * 60;
const CACHE_VERSION = 'v2';
const FETCH_TIMEOUT_MS = 10_000;
export interface DdragonChampionEntry {
key: string;
name: string;
}
export interface DdragonManifest {
version: string;
cdn: string;
locale: string;
champions: Record<string, DdragonChampionEntry>;
fetchedAt: string;
}
interface ChampionDataEntry {
key: string;
id: string;
name: string;
}
interface ChampionDataResponse {
data: Record<string, ChampionDataEntry>;
}
@Injectable()
export class RiotDdragonService {
private readonly logger = new Logger(RiotDdragonService.name);
private inflight = new Map<string, Promise<DdragonManifest>>();
constructor(private readonly garnetService: GarnetService) {}
public async getManifest(locale: string = DEFAULT_LOCALE): Promise<DdragonManifest> {
const normalizedLocale = normalizeLocale(locale);
const cacheKey = manifestCacheKey(normalizedLocale);
const cached = await this.garnetService.getJson<DdragonManifest>(cacheKey);
if (cached) return cached;
const pending = this.inflight.get(cacheKey);
if (pending) return pending;
const promise = this.buildManifest(normalizedLocale)
.then(async (manifest) => {
await this.garnetService.setJson(cacheKey, manifest, CACHE_TTL_SECONDS);
return manifest;
})
.finally(() => {
this.inflight.delete(cacheKey);
});
this.inflight.set(cacheKey, promise);
return promise;
}
private async buildManifest(locale: string): Promise<DdragonManifest> {
const version = await this.fetchLatestVersion();
const champions = await this.fetchChampionMap(version, locale);
return {
version,
cdn: DDRAGON_CDN,
locale,
champions,
fetchedAt: new Date().toISOString(),
};
}
private async fetchLatestVersion(): Promise<string> {
const versions = await this.fetchJson<unknown>(`${DDRAGON_BASE}/api/versions.json`);
if (!Array.isArray(versions) || typeof versions[0] !== 'string') {
throw new Error('ddragon versions.json response is malformed.');
}
return versions[0];
}
private async fetchChampionMap(
version: string,
locale: string,
): Promise<Record<string, DdragonChampionEntry>> {
const url = `${DDRAGON_CDN}/${version}/data/${locale}/champion.json`;
const payload = await this.fetchJson<ChampionDataResponse>(url);
if (!payload || typeof payload !== 'object' || !payload.data) {
throw new Error(`ddragon champion.json response is malformed (${url}).`);
}
const map: Record<string, DdragonChampionEntry> = {};
for (const entry of Object.values(payload.data)) {
if (entry?.key && entry.id) {
map[entry.key] = {
key: entry.id,
name: typeof entry.name === 'string' ? entry.name : entry.id,
};
}
}
return map;
}
private async fetchJson<T>(url: string): Promise<T> {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
try {
const response = await fetch(url, {
method: 'GET',
headers: { Accept: 'application/json' },
signal: controller.signal,
});
if (!response.ok) {
throw new Error(
`ddragon request failed (${response.status}): ${url}`,
);
}
return (await response.json()) as T;
} catch (err) {
this.logger.error(
`ddragon fetch error for ${url}: ${(err as Error)?.message ?? err}`,
);
throw err;
} finally {
clearTimeout(timeout);
}
}
}
function normalizeLocale(locale: string): string {
const trimmed = locale.trim();
if (!/^[a-zA-Z]{2}_[a-zA-Z]{2}$/.test(trimmed)) {
return DEFAULT_LOCALE;
}
return `${trimmed.slice(0, 2).toLowerCase()}_${trimmed.slice(3).toUpperCase()}`;
}
function manifestCacheKey(locale: string): string {
return `ddragon:manifest:${CACHE_VERSION}:${locale}`;
}
@@ -0,0 +1,79 @@
import { Injectable } from '@nestjs/common';
import { RiotClientService } from './riot.client.service';
import {
RiotLeagueEntryDto,
RiotPlatformLookupOptions,
} from './riot.types';
@Injectable()
export class RiotLeagueService {
constructor(private readonly riotClientService: RiotClientService) {}
public async getEntriesByPuuid(
puuid: string,
options: RiotPlatformLookupOptions = {},
): Promise<RiotLeagueEntryDto[]> {
return this.riotClientService.get<RiotLeagueEntryDto[]>(
`/lol/league/v4/entries/by-puuid/${encodeURIComponent(puuid)}`,
{
platform: options.platform ?? 'kr',
signal: options.signal,
},
parseLeagueEntries,
);
}
}
function parseLeagueEntries(value: unknown): RiotLeagueEntryDto[] {
if (!Array.isArray(value)) {
throw new TypeError('League entries response must be an array.');
}
return value.map((entry, index) => parseEntry(entry, index));
}
function parseEntry(value: unknown, index: number): RiotLeagueEntryDto {
if (!isRecord(value)) {
throw new TypeError(`leagueEntries[${index}] must be an object.`);
}
return {
leagueId: requireString(value.leagueId, `leagueEntries[${index}].leagueId`),
queueType: requireString(
value.queueType,
`leagueEntries[${index}].queueType`,
),
tier: requireString(value.tier, `leagueEntries[${index}].tier`),
rank: requireString(value.rank, `leagueEntries[${index}].rank`),
puuid: requireString(value.puuid, `leagueEntries[${index}].puuid`),
leaguePoints: requireNumber(
value.leaguePoints,
`leagueEntries[${index}].leaguePoints`,
),
wins: requireNumber(value.wins, `leagueEntries[${index}].wins`),
losses: requireNumber(value.losses, `leagueEntries[${index}].losses`),
veteran: typeof value.veteran === 'boolean' ? value.veteran : undefined,
inactive: typeof value.inactive === 'boolean' ? value.inactive : undefined,
freshBlood:
typeof value.freshBlood === 'boolean' ? value.freshBlood : undefined,
hotStreak:
typeof value.hotStreak === 'boolean' ? value.hotStreak : undefined,
miniSeries: isRecord(value.miniSeries) ? value.miniSeries : undefined,
};
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
function requireString(value: unknown, path: string): string {
if (typeof value !== 'string' || value.length === 0) {
throw new TypeError(`${path} must be a non-empty string.`);
}
return value;
}
function requireNumber(value: unknown, path: string): number {
if (typeof value !== 'number' || !Number.isFinite(value)) {
throw new TypeError(`${path} must be a finite number.`);
}
return value;
}
@@ -0,0 +1,109 @@
import { RiotClientService } from './riot.client.service';
import { RiotMatchService } from './riot-match.service';
import type { RiotResponseParser } from './riot.types';
function createMatchPayload() {
const participant = {
assists: 7,
champExperience: 12000,
champLevel: 16,
championId: 103,
championName: 'Ahri',
deaths: 2,
goldEarned: 12000,
goldSpent: 11000,
individualPosition: '',
item0: 0,
item1: 0,
item2: 0,
item3: 0,
item4: 0,
item5: 0,
item6: 0,
kills: 8,
neutralMinionsKilled: 12,
participantId: 1,
perks: {
statPerks: { defense: 0, flex: 0, offense: 0 },
styles: [],
},
puuid: 'puuid-1',
riotIdGameName: '테스터',
riotIdTagLine: 'KR1',
summoner1Id: 4,
summoner2Id: 14,
summonerId: 'summoner-id-1',
summonerLevel: 100,
summonerName: '',
teamId: 100,
teamPosition: '',
timePlayed: 1800,
totalDamageDealtToChampions: 22000,
totalDamageTaken: 11000,
totalMinionsKilled: 180,
visionScore: 20,
wardsKilled: 2,
wardsPlaced: 10,
win: true,
};
return {
metadata: {
dataVersion: '2',
matchId: 'KR_8188913502',
participants: ['puuid-1'],
},
info: {
gameCreation: 1777000000000,
gameDuration: 1800,
gameEndTimestamp: 1777001800000,
gameId: 8188913502,
gameMode: 'CLASSIC',
gameName: 'teambuilder-match-8188913502',
gameStartTimestamp: 1777000000000,
gameType: 'MATCHED_GAME',
gameVersion: '15.8.1',
mapId: 11,
participants: [participant],
platformId: 'KR',
queueId: 420,
teams: [
{
bans: [],
objectives: {
baron: { first: false, kills: 0 },
champion: { first: true, kills: 25 },
dragon: { first: true, kills: 3 },
inhibitor: { first: false, kills: 1 },
riftHerald: { first: true, kills: 1 },
tower: { first: true, kills: 8 },
},
teamId: 100,
win: true,
},
],
},
};
}
describe('RiotMatchService', () => {
it('accepts empty Riot display fields in match participants', async () => {
const payload = createMatchPayload();
const riotClientService = {
get: jest.fn(
async <T>(
_path: string,
_options: unknown,
parser?: RiotResponseParser<T>,
) => (parser ? parser(payload) : (payload as T)),
),
} as unknown as RiotClientService;
const service = new RiotMatchService(riotClientService);
const match = await service.getMatch('KR_8188913502', { region: 'asia' });
expect(match.info.participants[0].summonerName).toBe('');
expect(match.info.participants[0].teamPosition).toBe('');
expect(match.info.participants[0].individualPosition).toBe('');
});
});
@@ -0,0 +1,630 @@
import { Injectable } from '@nestjs/common';
import { RiotClientService } from './riot.client.service';
import {
RiotMatchBanDto,
RiotMatchDto,
RiotMatchIdsLookupOptions,
RiotMatchInfoDto,
RiotMatchLookupOptions,
RiotMatchMetadataDto,
RiotMatchObjectiveDto,
RiotMatchObjectivesDto,
RiotMatchParticipantDto,
RiotMatchPerksDto,
RiotMatchPerkStyleDto,
RiotMatchPerkStyleSelectionDto,
RiotMatchStatPerksDto,
RiotMatchTeamDto,
RiotMatchType,
} from './riot.types';
const RIOT_MATCH_TYPES: RiotMatchType[] = [
'ranked',
'normal',
'tourney',
'tutorial',
];
@Injectable()
export class RiotMatchService {
constructor(private readonly riotClientService: RiotClientService) {}
public async getMatchIdsByPuuid(
puuid: string,
options: RiotMatchIdsLookupOptions = {},
): Promise<string[]> {
validateMatchIdsLookupOptions(options);
return this.riotClientService.get<string[]>(
`/lol/match/v5/matches/by-puuid/${encodeURIComponent(puuid)}/ids`,
{
region: options.region,
signal: options.signal,
query: {
start: options.start,
count: options.count,
queue: options.queue,
type: options.type,
startTime: options.startTime,
endTime: options.endTime,
},
},
parseMatchIdsResponse,
);
}
public async getMatch(
matchId: string,
options: RiotMatchLookupOptions = {},
): Promise<RiotMatchDto> {
return this.riotClientService.get<RiotMatchDto>(
`/lol/match/v5/matches/${encodeURIComponent(matchId)}`,
{
region: options.region,
signal: options.signal,
},
parseMatchResponse,
);
}
}
function validateMatchIdsLookupOptions(
options: RiotMatchIdsLookupOptions,
): void {
assertOptionalNonNegativeInteger(options.start, 'start');
assertOptionalRange(options.count, 'count', 0, 100);
assertOptionalNonNegativeInteger(options.queue, 'queue');
assertOptionalNonNegativeInteger(options.startTime, 'startTime');
assertOptionalNonNegativeInteger(options.endTime, 'endTime');
if (options.type !== undefined && !RIOT_MATCH_TYPES.includes(options.type)) {
throw new RangeError(
`type must be one of: ${RIOT_MATCH_TYPES.join(', ')}`,
);
}
if (
options.startTime !== undefined &&
options.endTime !== undefined &&
options.startTime > options.endTime
) {
throw new RangeError('startTime must be less than or equal to endTime.');
}
}
function parseMatchIdsResponse(value: unknown): string[] {
if (!Array.isArray(value)) {
throw new TypeError('Riot match ids response must be an array.');
}
if (!value.every(isNonEmptyString)) {
throw new TypeError('Riot match ids response must contain only strings.');
}
return value;
}
function parseMatchResponse(value: unknown): RiotMatchDto {
if (!isRecord(value)) {
throw new TypeError('Riot match response must be an object.');
}
return {
metadata: parseMatchMetadata(value.metadata),
info: parseMatchInfo(value.info),
};
}
function parseMatchMetadata(value: unknown): RiotMatchMetadataDto {
if (!isRecord(value)) {
throw new TypeError('Riot match metadata must be an object.');
}
const dataVersion = value.dataVersion;
const matchId = value.matchId;
const participants = value.participants;
if (!isNonEmptyString(dataVersion)) {
throw new TypeError('Riot match metadata.dataVersion must be a string.');
}
if (!isNonEmptyString(matchId)) {
throw new TypeError('Riot match metadata.matchId must be a string.');
}
if (!Array.isArray(participants) || !participants.every(isNonEmptyString)) {
throw new TypeError(
'Riot match metadata.participants must be an array of strings.',
);
}
return {
dataVersion,
matchId,
participants,
};
}
function parseMatchInfo(value: unknown): RiotMatchInfoDto {
if (!isRecord(value)) {
throw new TypeError('Riot match info must be an object.');
}
const participants = value.participants;
const teams = value.teams;
if (!Array.isArray(participants)) {
throw new TypeError('Riot match info.participants must be an array.');
}
if (!Array.isArray(teams)) {
throw new TypeError('Riot match info.teams must be an array.');
}
const gameCreation = requireNumber(value.gameCreation, 'info.gameCreation');
const gameDuration = requireNumber(value.gameDuration, 'info.gameDuration');
const gameId = requireNumber(value.gameId, 'info.gameId');
const gameMode = requireString(value.gameMode, 'info.gameMode');
const gameName = requireString(value.gameName, 'info.gameName');
const gameStartTimestamp = requireNumber(
value.gameStartTimestamp,
'info.gameStartTimestamp',
);
const gameType = requireString(value.gameType, 'info.gameType');
const gameVersion = requireString(value.gameVersion, 'info.gameVersion');
const mapId = requireNumber(value.mapId, 'info.mapId');
const platformId = requireString(value.platformId, 'info.platformId');
const queueId = requireNumber(value.queueId, 'info.queueId');
const gameEndTimestamp = optionalNumber(
value.gameEndTimestamp,
'info.gameEndTimestamp',
);
const tournamentCode = optionalString(
value.tournamentCode,
'info.tournamentCode',
);
const endOfGameResult = optionalString(
value.endOfGameResult,
'info.endOfGameResult',
);
return {
...value,
endOfGameResult,
gameCreation,
gameDuration,
gameEndTimestamp,
gameId,
gameMode,
gameName,
gameStartTimestamp,
gameType,
gameVersion,
mapId,
participants: participants.map((participant, index) =>
parseParticipant(participant, index),
),
platformId,
queueId,
teams: teams.map((team, index) => parseTeam(team, index)),
tournamentCode,
};
}
function parseParticipant(
value: unknown,
index: number,
): RiotMatchParticipantDto {
if (!isRecord(value)) {
throw new TypeError(`participants[${index}] must be an object.`);
}
return {
...value,
assists: requireNumber(value.assists, `participants[${index}].assists`),
champExperience: requireNumber(
value.champExperience,
`participants[${index}].champExperience`,
),
champLevel: requireNumber(
value.champLevel,
`participants[${index}].champLevel`,
),
championId: requireNumber(
value.championId,
`participants[${index}].championId`,
),
championName: requireString(
value.championName,
`participants[${index}].championName`,
),
deaths: requireNumber(value.deaths, `participants[${index}].deaths`),
goldEarned: requireNumber(
value.goldEarned,
`participants[${index}].goldEarned`,
),
goldSpent: requireNumber(
value.goldSpent,
`participants[${index}].goldSpent`,
),
individualPosition: requireStringAllowEmpty(
value.individualPosition,
`participants[${index}].individualPosition`,
),
item0: requireNumber(value.item0, `participants[${index}].item0`),
item1: requireNumber(value.item1, `participants[${index}].item1`),
item2: requireNumber(value.item2, `participants[${index}].item2`),
item3: requireNumber(value.item3, `participants[${index}].item3`),
item4: requireNumber(value.item4, `participants[${index}].item4`),
item5: requireNumber(value.item5, `participants[${index}].item5`),
item6: requireNumber(value.item6, `participants[${index}].item6`),
kills: requireNumber(value.kills, `participants[${index}].kills`),
neutralMinionsKilled: requireNumber(
value.neutralMinionsKilled,
`participants[${index}].neutralMinionsKilled`,
),
participantId: requireNumber(
value.participantId,
`participants[${index}].participantId`,
),
perks: parsePerks(value.perks, index),
puuid: requireString(value.puuid, `participants[${index}].puuid`),
riotIdGameName: optionalString(
value.riotIdGameName,
`participants[${index}].riotIdGameName`,
),
riotIdTagLine: optionalString(
value.riotIdTagLine,
`participants[${index}].riotIdTagLine`,
),
summoner1Id: requireNumber(
value.summoner1Id,
`participants[${index}].summoner1Id`,
),
summoner2Id: requireNumber(
value.summoner2Id,
`participants[${index}].summoner2Id`,
),
summonerId: requireString(
value.summonerId,
`participants[${index}].summonerId`,
),
summonerLevel: requireNumber(
value.summonerLevel,
`participants[${index}].summonerLevel`,
),
summonerName: requireStringAllowEmpty(
value.summonerName,
`participants[${index}].summonerName`,
),
teamId: requireNumber(value.teamId, `participants[${index}].teamId`),
teamPosition: requireStringAllowEmpty(
value.teamPosition,
`participants[${index}].teamPosition`,
),
timePlayed: requireNumber(
value.timePlayed,
`participants[${index}].timePlayed`,
),
totalDamageDealtToChampions: requireNumber(
value.totalDamageDealtToChampions,
`participants[${index}].totalDamageDealtToChampions`,
),
totalDamageTaken: requireNumber(
value.totalDamageTaken,
`participants[${index}].totalDamageTaken`,
),
totalMinionsKilled: requireNumber(
value.totalMinionsKilled,
`participants[${index}].totalMinionsKilled`,
),
visionScore: requireNumber(
value.visionScore,
`participants[${index}].visionScore`,
),
wardsKilled: requireNumber(
value.wardsKilled,
`participants[${index}].wardsKilled`,
),
wardsPlaced: requireNumber(
value.wardsPlaced,
`participants[${index}].wardsPlaced`,
),
win: requireBoolean(value.win, `participants[${index}].win`),
};
}
function parsePerks(value: unknown, participantIndex: number): RiotMatchPerksDto {
if (!isRecord(value)) {
throw new TypeError(
`participants[${participantIndex}].perks must be an object.`,
);
}
const styles = value.styles;
if (!Array.isArray(styles)) {
throw new TypeError(
`participants[${participantIndex}].perks.styles must be an array.`,
);
}
return {
statPerks: parseStatPerks(value.statPerks, participantIndex),
styles: styles.map((style, styleIndex) =>
parsePerkStyle(style, participantIndex, styleIndex),
),
};
}
function parseStatPerks(
value: unknown,
participantIndex: number,
): RiotMatchStatPerksDto {
if (!isRecord(value)) {
throw new TypeError(
`participants[${participantIndex}].perks.statPerks must be an object.`,
);
}
return {
defense: requireNumber(
value.defense,
`participants[${participantIndex}].perks.statPerks.defense`,
),
flex: requireNumber(
value.flex,
`participants[${participantIndex}].perks.statPerks.flex`,
),
offense: requireNumber(
value.offense,
`participants[${participantIndex}].perks.statPerks.offense`,
),
};
}
function parsePerkStyle(
value: unknown,
participantIndex: number,
styleIndex: number,
): RiotMatchPerkStyleDto {
if (!isRecord(value)) {
throw new TypeError(
`participants[${participantIndex}].perks.styles[${styleIndex}] must be an object.`,
);
}
const selections = value.selections;
if (!Array.isArray(selections)) {
throw new TypeError(
`participants[${participantIndex}].perks.styles[${styleIndex}].selections must be an array.`,
);
}
return {
description: requireString(
value.description,
`participants[${participantIndex}].perks.styles[${styleIndex}].description`,
),
selections: selections.map((selection, selectionIndex) =>
parsePerkSelection(
selection,
participantIndex,
styleIndex,
selectionIndex,
),
),
style: requireNumber(
value.style,
`participants[${participantIndex}].perks.styles[${styleIndex}].style`,
),
};
}
function parsePerkSelection(
value: unknown,
participantIndex: number,
styleIndex: number,
selectionIndex: number,
): RiotMatchPerkStyleSelectionDto {
if (!isRecord(value)) {
throw new TypeError(
`participants[${participantIndex}].perks.styles[${styleIndex}].selections[${selectionIndex}] must be an object.`,
);
}
return {
perk: requireNumber(
value.perk,
`participants[${participantIndex}].perks.styles[${styleIndex}].selections[${selectionIndex}].perk`,
),
var1: requireNumber(
value.var1,
`participants[${participantIndex}].perks.styles[${styleIndex}].selections[${selectionIndex}].var1`,
),
var2: requireNumber(
value.var2,
`participants[${participantIndex}].perks.styles[${styleIndex}].selections[${selectionIndex}].var2`,
),
var3: requireNumber(
value.var3,
`participants[${participantIndex}].perks.styles[${styleIndex}].selections[${selectionIndex}].var3`,
),
};
}
function parseTeam(value: unknown, index: number): RiotMatchTeamDto {
if (!isRecord(value)) {
throw new TypeError(`teams[${index}] must be an object.`);
}
const bans = value.bans;
if (!Array.isArray(bans)) {
throw new TypeError(`teams[${index}].bans must be an array.`);
}
return {
...value,
bans: bans.map((ban, banIndex) => parseBan(ban, index, banIndex)),
objectives: parseObjectives(value.objectives, index),
teamId: requireNumber(value.teamId, `teams[${index}].teamId`),
win: requireBoolean(value.win, `teams[${index}].win`),
};
}
function parseBan(
value: unknown,
teamIndex: number,
banIndex: number,
): RiotMatchBanDto {
if (!isRecord(value)) {
throw new TypeError(`teams[${teamIndex}].bans[${banIndex}] must be an object.`);
}
return {
championId: requireNumber(
value.championId,
`teams[${teamIndex}].bans[${banIndex}].championId`,
),
pickTurn: requireNumber(
value.pickTurn,
`teams[${teamIndex}].bans[${banIndex}].pickTurn`,
),
};
}
function parseObjectives(
value: unknown,
teamIndex: number,
): RiotMatchObjectivesDto {
if (!isRecord(value)) {
throw new TypeError(`teams[${teamIndex}].objectives must be an object.`);
}
return {
baron: parseObjective(value.baron, teamIndex, 'baron'),
champion: parseObjective(value.champion, teamIndex, 'champion'),
dragon: parseObjective(value.dragon, teamIndex, 'dragon'),
inhibitor: parseObjective(value.inhibitor, teamIndex, 'inhibitor'),
riftHerald: parseObjective(value.riftHerald, teamIndex, 'riftHerald'),
tower: parseObjective(value.tower, teamIndex, 'tower'),
};
}
function parseObjective(
value: unknown,
teamIndex: number,
key: keyof RiotMatchObjectivesDto,
): RiotMatchObjectiveDto {
if (!isRecord(value)) {
throw new TypeError(`teams[${teamIndex}].objectives.${key} must be an object.`);
}
return {
first: requireBoolean(
value.first,
`teams[${teamIndex}].objectives.${key}.first`,
),
kills: requireNumber(
value.kills,
`teams[${teamIndex}].objectives.${key}.kills`,
),
};
}
function requireString(value: unknown, path: string): string {
if (!isNonEmptyString(value)) {
throw new TypeError(`${path} must be a non-empty string.`);
}
return value;
}
function requireStringAllowEmpty(value: unknown, path: string): string {
if (typeof value !== 'string') {
throw new TypeError(`${path} must be a string.`);
}
return value;
}
function optionalString(value: unknown, path: string): string | undefined {
if (value === undefined || value === null) {
return undefined;
}
if (typeof value !== 'string') {
throw new TypeError(`${path} must be a string when present.`);
}
return value;
}
function requireNumber(value: unknown, path: string): number {
if (!isFiniteNumber(value)) {
throw new TypeError(`${path} must be a finite number.`);
}
return value;
}
function optionalNumber(value: unknown, path: string): number | undefined {
if (value === undefined || value === null) {
return undefined;
}
if (!isFiniteNumber(value)) {
throw new TypeError(`${path} must be a finite number when present.`);
}
return value;
}
function requireBoolean(value: unknown, path: string): boolean {
if (typeof value !== 'boolean') {
throw new TypeError(`${path} must be a boolean.`);
}
return value;
}
function assertOptionalNonNegativeInteger(
value: number | undefined,
fieldName: string,
): void {
if (value === undefined) {
return;
}
if (!Number.isInteger(value) || value < 0) {
throw new RangeError(`${fieldName} must be a non-negative integer.`);
}
}
function assertOptionalRange(
value: number | undefined,
fieldName: string,
min: number,
max: number,
): void {
if (value === undefined) {
return;
}
if (!Number.isInteger(value) || value < min || value > max) {
throw new RangeError(
`${fieldName} must be an integer between ${min} and ${max}.`,
);
}
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
function isFiniteNumber(value: unknown): value is number {
return typeof value === 'number' && Number.isFinite(value);
}
function isNonEmptyString(value: unknown): value is string {
return typeof value === 'string' && value.length > 0;
}
@@ -0,0 +1,88 @@
export type RiotQueueGroup =
| 'all'
| 'summoners-rift'
| 'aram'
| 'urf'
| 'arena';
export type RiotRankFilter = 'all' | 'solo' | 'flex' | 'normal';
export interface RiotQueueGroupConfig {
label: string;
queues: Record<RiotRankFilter, number[]>;
}
export const RIOT_QUEUE_GROUPS: Record<RiotQueueGroup, RiotQueueGroupConfig> = {
all: {
label: '전체',
queues: {
all: [400, 420, 430, 440, 450, 900, 1900, 1700, 1710],
solo: [420],
flex: [440],
normal: [400, 430, 450, 900, 1900, 1700, 1710],
},
},
'summoners-rift': {
label: '소환사의 협곡',
queues: {
all: [400, 420, 430, 440],
solo: [420],
flex: [440],
normal: [400, 430],
},
},
aram: {
label: '칼바람 나락',
queues: {
all: [450],
solo: [],
flex: [],
normal: [450],
},
},
urf: {
label: '우르프',
queues: {
all: [900, 1900],
solo: [],
flex: [],
normal: [900, 1900],
},
},
arena: {
label: '아레나',
queues: {
all: [1700, 1710],
solo: [],
flex: [],
normal: [1700, 1710],
},
},
};
export const RIOT_QUEUE_LABELS: Record<number, string> = {
400: '일반 교차 선택',
420: '솔로 랭크',
430: '일반 비공개 선택',
440: '자유 랭크',
450: '칼바람 나락',
900: '우르프',
1700: '아레나',
1710: '아레나',
1900: '우르프',
};
export function resolveRiotQueueIds(
queueGroup: RiotQueueGroup,
rank: RiotRankFilter,
): number[] {
return RIOT_QUEUE_GROUPS[queueGroup].queues[rank];
}
export function isRiotQueueGroup(value: string): value is RiotQueueGroup {
return value in RIOT_QUEUE_GROUPS;
}
export function isRiotRankFilter(value: string): value is RiotRankFilter {
return value === 'all' || value === 'solo' || value === 'flex' || value === 'normal';
}
Loaded 100 of 139 files, more files were not shown because too many files have changed in this diff. Show more