import { Logger } from '@nestjs/common'; import { randomUUID } from 'crypto'; import { performance } from 'perf_hooks'; import { Ack, ConnectedSocket, MessageBody, OnGatewayConnection, OnGatewayInit, SubscribeMessage, WebSocketGateway, WebSocketServer, } from '@nestjs/websockets'; import mongoose from 'mongoose'; import type { JWTPayload } from 'jose'; import type { DefaultEventsMap, 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 { AuctionChatMessage, AuctionDocument, IdentityDocument, Position, UserDocument, } from '../global/database/schema'; import { AuctionService } from './auction.service'; import type { AuctionBidDeltaResponse, AuctionStateResponse, } from './auction.service'; import { AuctionEventBusService } from './auction-event-bus.service'; import { isAuctionResyncRecommended, resolveAuctionRejectionReason, } from './auction-rejection'; import type { MatchSideEffectDelta } from './auction-side-effect.service'; import { serializeRealtimeAuction } from './auction-realtime-serializer'; import { AuctionRedisService } from './redis/auction-redis.service'; interface JoinAuctionPayload { matchId: string; } interface BidPayload { bidderTeamIndex: number; bidPointAmount: number; bidRequestId?: string; clientObservedAuctionLifecycleId?: string; clientObservedCurrentBidRoundPlayerUserId?: string; } interface TimeSyncPayload { clientSentAtTimestampMS?: number; sequence?: number; } interface SoldPayload { auctionActionRequestId?: string; assignedPosition?: Position; clientObservedAuctionLifecycleId?: string; clientObservedCurrentAuctionPlayerOrderIndex?: number; clientObservedCurrentBidRoundPlayerUserId?: string; clientObservedPhase?: string; clientObservedRevision?: number; } type AuctionActionPayload = Omit; interface ChatMessagePayload { message?: string; displayName?: string; } interface BidRateLimitState { count: number; windowStartedAtTimestampMS: number; } interface AuctionSocketData { auctionBidRateLimit?: BidRateLimitState; identity?: IdentityDocument; matchId?: string; user?: UserDocument; } type AuctionSocket = Socket< DefaultEventsMap, DefaultEventsMap, DefaultEventsMap, AuctionSocketData >; const BID_RATE_LIMIT_WINDOW_MS = 1000; const BID_RATE_LIMIT_MAX_REQUESTS_PER_WINDOW = 8; const BID_RATE_LIMIT_REJECTION_CODE = 'BID_RATE_LIMITED'; const BID_RATE_LIMIT_REJECTION_MESSAGE = '입찰 요청이 너무 많습니다. 잠시 후 다시 시도해주세요.'; @WebSocketGateway({ namespace: '/auction', cors: { origin: true, credentials: true, allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'], }, }) export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { @WebSocketServer() private server!: Namespace; private readonly logger = new Logger(AuctionGateway.name); constructor( private readonly auctionService: AuctionService, private readonly authService: AuthService, private readonly jwtService: JwtService, private readonly identityService: IdentityService, private readonly connectionService: ConnectionService, private readonly auctionEventBusService: AuctionEventBusService, private readonly auctionRedisService: AuctionRedisService, ) {} public afterInit(server: Namespace): void { this.auctionEventBusService.attachAuctionNamespace(server); } public async handleConnection(socket: AuctionSocket) { 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 : String(err) }`, ); socket.disconnect(true); } } @SubscribeMessage('join') public async handleJoin( @ConnectedSocket() socket: AuctionSocket, @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), ); const auctionState = await this.auctionService.getStateByMatchId( new mongoose.Types.ObjectId(payload.matchId), ); this.emitChatHistory(socket, auction); this.broadcastState(payload.matchId, auctionState); } catch (error) { this.emitKnownError(socket, error); } } @SubscribeMessage('bid') public async handleBid( @ConnectedSocket() socket: AuctionSocket, @MessageBody() payload: BidPayload, @Ack() ack?: (response: Record) => void, ) { const gatewayBidStartedAtMS = performance.now(); const matchId = this.requireJoinedMatchId(socket); if (!matchId) return; const bidRequestId = payload.bidRequestId ?? randomUUID(); if (!this.consumeBidRateLimit(socket)) { this.emitError(socket, BID_RATE_LIMIT_REJECTION_MESSAGE); ack?.({ bidRequestId, code: BID_RATE_LIMIT_REJECTION_CODE, message: BID_RATE_LIMIT_REJECTION_MESSAGE, rejected: true, }); return; } try { const bidResult = await this.auctionService.placeBidDelta({ matchId: new mongoose.Types.ObjectId(matchId), teamIndex: payload.bidderTeamIndex, amount: payload.bidPointAmount, bidRequestId, clientObservedAuctionLifecycleId: payload.clientObservedAuctionLifecycleId, clientObservedCurrentBidRoundPlayerUserId: payload.clientObservedCurrentBidRoundPlayerUserId, }); const bidDelta = this.isBidDeltaResponse(bidResult) ? { ...bidResult, bidRequestId: bidResult.bidRequestId ?? bidRequestId, } : this.buildBidDeltaFromAuctionState(bidResult, bidRequestId); const bidServerTiming = this.extractBidServerTiming(bidDelta); const broadcastBidDelta = this.stripBidServerTiming(bidDelta); if (broadcastBidDelta) { this.broadcastBid(matchId, broadcastBidDelta); } else { this.broadcastState(matchId, bidResult as AuctionStateResponse); } ack?.({ ...(bidDelta ? {} : { state: this.serializeAuction(bidResult as AuctionStateResponse), }), ok: true, bidRequestId, bidDelta: broadcastBidDelta, bidServerTiming: this.buildGatewayBidTiming( gatewayBidStartedAtMS, bidServerTiming, ), }); } catch (error) { const rejectionAckFields = await this.resolveRejectionAckFields( matchId, error, ); const bidServerTiming = this.extractBidServerTiming(rejectionAckFields); this.emitError( socket, typeof rejectionAckFields.message === 'string' ? rejectionAckFields.message : '', ); ack?.({ ...rejectionAckFields, bidRequestId, bidServerTiming: this.buildGatewayBidTiming( gatewayBidStartedAtMS, bidServerTiming, ), rejected: true, }); } } @SubscribeMessage('time-sync') public async handleTimeSync( @MessageBody() payload: TimeSyncPayload, @Ack() ack?: (response: Record) => void, ) { const receivedAtMonotonicMS = performance.now(); try { const currentServerTimestampMS = await this.auctionRedisService.getCurrentRedisTimestampMS(); ack?.({ clientSentAtTimestampMS: payload?.clientSentAtTimestampMS, currentServerTimestampMS, ok: true, sequence: payload?.sequence, serverProcessingDurationMS: Math.round((performance.now() - receivedAtMonotonicMS) * 10) / 10, }); } catch (error) { const errorPayload = this.resolveErrorPayload(error); ack?.({ ...errorPayload, clientSentAtTimestampMS: payload?.clientSentAtTimestampMS, rejected: true, sequence: payload?.sequence, }); } } @SubscribeMessage('open-bidding') public async handleOpenBidding( @ConnectedSocket() socket: AuctionSocket, @MessageBody() payload: AuctionActionPayload, @Ack() ack?: (response: Record) => void, ) { const matchId = this.requireJoinedMatchId(socket); if (!matchId) return; try { const auction = await this.auctionService.openBidding( new mongoose.Types.ObjectId(matchId), this.toSocketAuctionActionRequest(payload), ); this.broadcastState(matchId, auction); ack?.({ auctionActionRequestId: payload?.auctionActionRequestId, ok: true, }); } catch (error) { this.emitKnownError(socket, error); ack?.({ ...(await this.resolveRejectionAckFields(matchId, error)), auctionActionRequestId: payload?.auctionActionRequestId, rejected: true, }); } } @SubscribeMessage('sold') public async handleSold( @ConnectedSocket() socket: AuctionSocket, @MessageBody() payload: SoldPayload, @Ack() ack?: (response: Record) => void, ) { 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.toSocketAuctionActionRequest(payload), }); this.broadcastState(matchId, auction); ack?.({ auctionActionRequestId: payload?.auctionActionRequestId, ok: true, }); } catch (error) { this.emitKnownError(socket, error); ack?.({ ...(await this.resolveRejectionAckFields(matchId, error)), auctionActionRequestId: payload?.auctionActionRequestId, rejected: true, }); } } @SubscribeMessage('next') public async handleNext( @ConnectedSocket() socket: AuctionSocket, @MessageBody() payload: AuctionActionPayload, @Ack() ack?: (response: Record) => void, ) { const matchId = this.requireJoinedMatchId(socket); if (!matchId) return; try { const auction = await this.auctionService.next( new mongoose.Types.ObjectId(matchId), this.toSocketAuctionActionRequest(payload), ); this.broadcastState(matchId, auction); ack?.({ auctionActionRequestId: payload?.auctionActionRequestId, ok: true, }); } catch (error) { this.emitKnownError(socket, error); ack?.({ ...(await this.resolveRejectionAckFields(matchId, error)), auctionActionRequestId: payload?.auctionActionRequestId, rejected: true, }); } } @SubscribeMessage('passed') public async handlePassed( @ConnectedSocket() socket: AuctionSocket, @MessageBody() payload: AuctionActionPayload, @Ack() ack?: (response: Record) => void, ) { const matchId = this.requireJoinedMatchId(socket); if (!matchId) return; try { const auction = await this.auctionService.markPassed( new mongoose.Types.ObjectId(matchId), this.toSocketAuctionActionRequest(payload), ); this.broadcastState(matchId, auction); ack?.({ auctionActionRequestId: payload?.auctionActionRequestId, ok: true, }); } catch (error) { this.emitKnownError(socket, error); ack?.({ ...(await this.resolveRejectionAckFields(matchId, error)), auctionActionRequestId: payload?.auctionActionRequestId, rejected: true, }); } } @SubscribeMessage('chat-message') public async handleChatMessage( @ConnectedSocket() socket: AuctionSocket, @MessageBody() payload: ChatMessagePayload, ) { const matchId = this.requireJoinedMatchId(socket); if (!matchId) return; if (typeof payload?.message !== 'string') { this.emitError(socket, 'Chat message is required.'); return; } try { const { message } = await this.auctionService.appendChatMessage({ matchId: new mongoose.Types.ObjectId(matchId), userId: this.resolveSocketUserId(socket), displayName: this.resolveChatDisplayName(socket, payload.displayName), message: payload.message, }); this.server .to(matchId) .emit('chat-message', this.serializeChatMessage(message)); } catch (error) { this.emitKnownError(socket, error); } } private requireJoinedMatchId(socket: AuctionSocket): string | null { const matchId = this.getSocketMatchId(socket); if (!matchId) { this.emitError(socket, 'Join a match room before sending events.'); return null; } return matchId; } private consumeBidRateLimit(socket: AuctionSocket): boolean { const currentTimestampMS = Date.now(); const previousState = socket.data.auctionBidRateLimit; if ( !previousState || currentTimestampMS - previousState.windowStartedAtTimestampMS >= BID_RATE_LIMIT_WINDOW_MS ) { socket.data.auctionBidRateLimit = { count: 1, windowStartedAtTimestampMS: currentTimestampMS, }; return true; } previousState.count += 1; socket.data.auctionBidRateLimit = previousState; return previousState.count <= BID_RATE_LIMIT_MAX_REQUESTS_PER_WINDOW; } private getSocketMatchId(socket: AuctionSocket): string | undefined { return socket.data.matchId; } private toAuctionActionRequest(payload?: AuctionActionPayload) { return { auctionActionRequestId: payload?.auctionActionRequestId, clientObservedAuctionLifecycleId: payload?.clientObservedAuctionLifecycleId, clientObservedCurrentAuctionPlayerOrderIndex: payload?.clientObservedCurrentAuctionPlayerOrderIndex, clientObservedCurrentBidRoundPlayerUserId: payload?.clientObservedCurrentBidRoundPlayerUserId, clientObservedPhase: payload?.clientObservedPhase, clientObservedRevision: payload?.clientObservedRevision, }; } private toSocketAuctionActionRequest(payload?: AuctionActionPayload) { return { ...this.toAuctionActionRequest(payload), shouldBroadcastStateAfterDurability: false, }; } private readHandshakeUserId(socket: AuctionSocket): string | undefined { const handshakeAuth = socket.handshake.auth as Record; const authUserId = handshakeAuth['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 resolveSocketUserId( socket: AuctionSocket, ): mongoose.Types.ObjectId | undefined { return socket.data.user?._id; } private resolveChatDisplayName( socket: AuctionSocket, fallbackDisplayName?: string, ): string { const user = socket.data.user; const primaryRiotAccount = user?.riotAccounts.find((entry) => entry.isPrimary) ?? user?.riotAccounts[0]; if (primaryRiotAccount?.gameName) { return primaryRiotAccount.tagLine ? `${primaryRiotAccount.gameName}#${primaryRiotAccount.tagLine}` : primaryRiotAccount.gameName; } if (user?.kakaoTalkNickname) return user.kakaoTalkNickname; if (user?.discordNickname) return user.discordNickname; const identity = socket.data.identity; if (identity?.displayName) return identity.displayName; if (identity?.email) return identity.email; return fallbackDisplayName ?? '관전자'; } private async authenticateSocket(socket: AuctionSocket): Promise { 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: AuctionSocket): string | undefined { const handshakeAuth = socket.handshake.auth as Record; const authToken = handshakeAuth.token; if (typeof authToken === 'string' && authToken.trim()) { return authToken.trim().replace(/^Bearer\s+/i, ''); } const header: unknown = socket.handshake.headers.authorization; const authorization = typeof header === 'string' ? header : Array.isArray(header) && typeof header[0] === 'string' ? header[0] : undefined; if (authorization?.startsWith('Bearer ')) { return authorization.slice('Bearer '.length).trim(); } return undefined; } private async resolveSocketUserForMatch( socket: AuctionSocket, matchId: string, ): Promise { if (socket.data.user || !socket.data.identity) return; const identity = socket.data.identity; 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'); const user = await UserModel.findOne({ communityId: match.communityId, identityId: identity._id, }).exec(); socket.data.user = user ?? undefined; } 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; } public broadcastState(matchId: string, auction: AuctionStateResponse) { this.server.to(matchId).emit('state', serializeRealtimeAuction(auction)); } public broadcastBid(matchId: string, delta: Record) { this.server.to(matchId).emit('bid', delta); } public broadcastReset(matchId: string) { this.server.to(matchId).emit('reset', { matchId }); } public broadcastMatchSideEffect( matchId: string, delta: MatchSideEffectDelta, ) { this.server.to(matchId).emit('match-side-effect', delta); } private emitChatHistory(socket: AuctionSocket, auction: AuctionDocument) { socket.emit('chat-history', { messages: (auction.chatMessages ?? []).map((message) => this.serializeChatMessage(message), ), }); } private emitKnownError(socket: AuctionSocket, error: unknown) { this.emitError(socket, this.resolveErrorPayload(error).message); } private emitError(socket: AuctionSocket, message: string) { socket.emit('error', { message }); } private serializeAuction( auction: AuctionStateResponse, ): Record { const serialized: unknown = JSON.parse(JSON.stringify(auction)); return typeof serialized === 'object' && serialized !== null ? (serialized as Record) : {}; } /** * 거부 ack에 실을 공통 필드를 만든다. * * - `code`/`message`: 기존 내부 코드/문구(진단·하위호환). * - `auctionRejectionReason`: 맥락을 담은 설명적 거부코드(클라가 문구로 매핑). * - `resyncRecommended`: "내가 본 상태가 낡았다"는 신호면 true. * - `state`: resync 권장 거부에 한해 최신 권위 state를 동봉해, 클라가 join * 왕복 없이 즉시 rebaseline하도록 한다(후속 액션의 반복 CONFLICT 차단). */ private async resolveRejectionAckFields( matchId: string, error: unknown, ): Promise> { const errorPayload = this.resolveErrorPayload(error); const auctionRejectionReason = resolveAuctionRejectionReason( typeof errorPayload.code === 'string' ? errorPayload.code : undefined, errorPayload.message, ); const resyncRecommended = isAuctionResyncRecommended( auctionRejectionReason, ); const state = resyncRecommended ? await this.fetchSerializedAuctionState(matchId) : undefined; return { ...errorPayload, auctionRejectionReason, resyncRecommended, ...(state ? { state } : {}), }; } private async fetchSerializedAuctionState( matchId: string, ): Promise | undefined> { try { const state = await this.auctionService.getStateByMatchId( new mongoose.Types.ObjectId(matchId), ); return state ? this.serializeAuction(state) : undefined; } catch { return undefined; } } private resolveErrorPayload(error: unknown): Record & { message: string; } { const response = typeof (error as { getResponse?: unknown })?.getResponse === 'function' ? (error as { getResponse: () => unknown }).getResponse() : undefined; if (typeof response === 'object' && response !== null) { const record = response as Record; const message = Array.isArray(record.message) ? record.message.join(', ') : typeof record.message === 'string' ? record.message : error instanceof Error ? error.message : 'Unexpected auction gateway error.'; return { ...record, code: typeof record.code === 'string' ? record.code : error instanceof Error ? error.message : 'UNKNOWN', message, }; } return { code: error instanceof Error ? error.message : 'UNKNOWN', message: error instanceof Error ? error.message : 'Unexpected auction gateway error.', }; } private buildGatewayBidTiming( gatewayBidStartedAtMS: number, bidServerTiming?: Record, ): Record { return { ...(bidServerTiming ?? {}), gatewayTotalDurationMS: Math.round((performance.now() - gatewayBidStartedAtMS) * 10) / 10, }; } private extractBidServerTiming( bidDelta: Record | null, ): Record | undefined { const timing = bidDelta?.bidServerTiming; return typeof timing === 'object' && timing !== null ? (timing as Record) : undefined; } private stripBidServerTiming( bidDelta: Record | null, ): Record | null { if (!bidDelta || !('bidServerTiming' in bidDelta)) return bidDelta; const publicBidDelta = { ...bidDelta }; delete publicBidDelta.bidServerTiming; return publicBidDelta; } private buildBidDeltaFromAuctionState( auction: AuctionStateResponse, bidRequestId?: string, ): Record | null { const serialized = this.serializeAuction(auction); const revision = Number(serialized.revision); const currentHighestBidPointAmount = Number( serialized.currentHighestBidPointAmount ?? serialized.currentBid, ); const currentHighestBidderTeamIndex = Number( serialized.currentHighestBidderTeamIndex ?? serialized.currentBidderTeamIndex, ); const currentBidRoundDeadlineTimestampMS = Number( serialized.currentBidRoundDeadlineTimestampMS ?? (typeof serialized.currentDeadline === 'string' ? Date.parse(serialized.currentDeadline) : 0), ); const redisBidHistory: unknown[] = Array.isArray( serialized.auctionBidHistory, ) ? (serialized.auctionBidHistory as unknown[]) : []; const legacyBidHistory: unknown[] = Array.isArray(serialized.bids) ? (serialized.bids as unknown[]) : []; const auctionBidHistoryEntry = redisBidHistory[redisBidHistory.length - 1] ?? this.convertLegacyBidToRedisBidHistoryEntry( legacyBidHistory[legacyBidHistory.length - 1], ); if ( !Number.isFinite(currentHighestBidPointAmount) || !Number.isFinite(currentHighestBidderTeamIndex) || !auctionBidHistoryEntry ) { return null; } return { auctionBidHistoryEntry, auctionLifecycleId: serialized.auctionLifecycleId, bidRequestId, currentBidRoundDeadlineTimestampMS: Number.isFinite( currentBidRoundDeadlineTimestampMS, ) ? currentBidRoundDeadlineTimestampMS : undefined, currentHighestBidPointAmount, currentHighestBidderTeamIndex, currentServerTimestampMS: serialized.currentServerTimestampMS, revision: Number.isFinite(revision) ? revision : undefined, }; } private isBidDeltaResponse(value: unknown): value is AuctionBidDeltaResponse { return ( typeof value === 'object' && value !== null && 'auctionBidHistoryEntry' in value && 'currentHighestBidPointAmount' in value && 'currentHighestBidderTeamIndex' in value && 'revision' in value ); } private convertLegacyBidToRedisBidHistoryEntry( bid: unknown, ): Record | null { if (!bid || typeof bid !== 'object') return null; const record = bid as Record; return { bidderTeamIndex: record.teamIndex, bidPointAmount: record.amount, bidderUserId: record.bidderUserId, bidPlacedAtTimestampMS: typeof record.timestamp === 'string' ? Date.parse(record.timestamp) : undefined, }; } private serializeChatMessage( message: AuctionChatMessage, ): Record { const serialized: unknown = JSON.parse(JSON.stringify(message)); return typeof serialized === 'object' && serialized !== null ? (serialized as Record) : {}; } }