This commit is contained in:
dahyeon committed 2026-04-24 23:18:56 -07:00
1 parent 30dfb7ce58
commit 5af2c80cd1
33 files changed
+3806 -1440

No files matched your search

@@ -0,0 +1,247 @@
import { Logger } from '@nestjs/common';
import {
ConnectedSocket,
MessageBody,
OnGatewayConnection,
OnGatewayDisconnect,
SubscribeMessage,
WebSocketGateway,
WebSocketServer,
} from '@nestjs/websockets';
import mongoose from 'mongoose';
import { Namespace, Socket } from 'socket.io';
import type { AuctionDocument, Position, TeamSide } 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: ['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) {}
public handleConnection(socket: Socket) {
this.logger.debug(`Auction client connected: ${socket.id}`);
}
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 {
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 ?? 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 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));
}
}