Files
lolympus-tournament-support/apps/api/src/modules/auction/auction.gateway.ts
T

355 lines
10 KiB
TypeScript

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));
}
}