import mongoose from 'mongoose'; import { ServiceUnavailableException } from '@nestjs/common'; jest.mock('../auth/jwt.service', () => ({ JwtService: class JwtService {}, })); import { AuctionGateway } from './auction.gateway'; describe('AuctionGateway', () => { beforeEach(() => { jest.replaceProperty(process, 'env', { ...process.env }); delete process.env.AUCTION_REQUIRE_CAPTAIN_AUTH; }); afterEach(() => { jest.restoreAllMocks(); }); it('signals pending initial state so the client can retry privately after recovery', async () => { const matchId = new mongoose.Types.ObjectId().toString(); const gateway = new AuctionGateway( { getByMatchId: async () => ({}), getStateByMatchId: async () => { throw new ServiceUnavailableException({ code: 'AUCTION_STATE_RECOVERING', message: 'recovering', }); }, } as never, {} as never, {} as never, {} as never, {} as never, {} as never, {} as never, ); const socket = { data: { matchId }, join: jest.fn(), emit: jest.fn() }; await gateway.handleJoin(socket as never, { matchId }); expect(socket.emit).toHaveBeenCalledTimes(1); expect(socket.emit).toHaveBeenCalledWith('state-pending', { retryAfterMS: 500, }); }); it('sends join and resync snapshots only to the requesting socket and coalesces in-flight resyncs', async () => { const matchId = new mongoose.Types.ObjectId().toString(); const getStateByMatchId = jest.fn().mockResolvedValue({ revision: 3 }); const gateway = new AuctionGateway( { getByMatchId: async () => ({ chatMessages: [] }), getStateByMatchId, } as never, {} as never, {} as never, {} as never, {} as never, {} as never, {} as never, ); const broadcast = jest.fn(); (gateway as unknown as { server: unknown }).server = { to: () => ({ emit: broadcast }), }; const socket = { data: { matchId }, join: jest.fn(), emit: jest.fn() }; await gateway.handleJoin(socket as never, { matchId }); expect(socket.emit).toHaveBeenCalledWith('state', { revision: 3 }); expect(broadcast).not.toHaveBeenCalled(); let finish!: (value: unknown) => void; getStateByMatchId.mockImplementationOnce( () => new Promise((resolve) => { finish = resolve; }), ); const ack = jest.fn(), busyAck = jest.fn(); const pending = gateway.handleResync(socket as never, {}, ack); await gateway.handleResync(socket as never, {}, busyAck); expect(busyAck).toHaveBeenCalledWith( expect.objectContaining({ code: 'RESYNC_BUSY' }), ); finish({ revision: 4 }); await pending; expect(ack).toHaveBeenCalledWith({ ok: true, state: { revision: 4 } }); expect(getStateByMatchId).toHaveBeenCalledTimes(2); expect(broadcast).not.toHaveBeenCalled(); }); const bidderUserId = new mongoose.Types.ObjectId(); function createGateway(params?: { getCurrentRedisTimestampMS?: jest.Mock; placeBidDelta?: jest.Mock; }) { const auctionService = { placeBidDelta: params?.placeBidDelta ?? jest.fn(), }; const auctionRedisService = { getCurrentRedisTimestampMS: params?.getCurrentRedisTimestampMS ?? jest.fn().mockResolvedValue(1780000000000), }; const gateway = new AuctionGateway( auctionService as never, { resolveDevUserById: jest.fn() } as never, { verify: jest.fn() } as never, { findOrCreateByOid: jest.fn() } as never, { getModel: jest.fn() } as never, { attachAuctionNamespace: jest.fn() } as never, auctionRedisService as never, ); const emit = jest.fn(); const to = jest.fn().mockReturnValue({ emit }); (gateway as unknown as { server: { to: jest.Mock } }).server = { to }; return { auctionService, emit, gateway, auctionRedisService, to, }; } it('requires an authenticated user when captain authentication is enabled', async () => { process.env.AUCTION_REQUIRE_CAPTAIN_AUTH = 'true'; const matchId = new mongoose.Types.ObjectId().toString(); const { gateway, auctionService } = createGateway(); const ack = jest.fn(); await gateway.handleBid( { data: { matchId }, emit: jest.fn() } as never, { bidderTeamIndex: 1, bidPointAmount: 100 }, ack, ); expect(auctionService.placeBidDelta).not.toHaveBeenCalled(); expect(ack).toHaveBeenCalledWith( expect.objectContaining({ rejected: true }), ); }); it.each([undefined, bidderUserId])( 'accepts the selected team in temporary mode for user %s', async (userId) => { const matchId = new mongoose.Types.ObjectId().toString(); const placeBidDelta = jest.fn().mockResolvedValue({ auctionBidHistoryEntry: { bidderTeamIndex: 2, bidderUserId: new mongoose.Types.ObjectId().toString(), bidPointAmount: 120, bidPlacedAtTimestampMS: 1780000000000, }, currentHighestBidderTeamIndex: 2, currentHighestBidPointAmount: 120, currentServerTimestampMS: 1780000000000, revision: 9, }); const { gateway, emit } = createGateway({ placeBidDelta }); const ack = jest.fn(); await gateway.handleBid( { data: { matchId, user: userId ? { _id: userId } : undefined }, emit: jest.fn(), } as never, { bidderTeamIndex: 2, bidPointAmount: 120 }, ack, ); expect(placeBidDelta).toHaveBeenCalledWith( expect.objectContaining({ teamIndex: 2, amount: 120, bidderUserId: userId, }), ); expect(ack).toHaveBeenCalledWith(expect.objectContaining({ ok: true })); expect(emit).toHaveBeenCalledWith( 'bid', expect.objectContaining({ currentHighestBidderTeamIndex: 2 }), ); }, ); it('broadcasts a bid delta and acknowledges the matching bid request', async () => { const matchId = new mongoose.Types.ObjectId().toString(); const auctionBidHistoryEntry = { bidderTeamIndex: 2, bidderUserId: 'captain-2', bidPlacedAtTimestampMS: 1780000000000, bidPointAmount: 120, }; const placeBidDelta = jest.fn().mockResolvedValue({ auctionBidHistoryEntry, auctionLifecycleId: 'life-1', currentBidRoundDeadlineTimestampMS: 1780000030000, currentHighestBidderTeamIndex: 2, currentHighestBidPointAmount: 120, currentServerTimestampMS: 1780000000000, revision: 9, }); const { emit, gateway, to } = createGateway({ placeBidDelta }); const ack = jest.fn(); await gateway.handleBid( { data: { matchId, user: { _id: bidderUserId } }, emit: jest.fn(), } as never, { bidPointAmount: 120, bidderTeamIndex: 2, bidRequestId: 'bid-1', clientObservedAuctionLifecycleId: 'life-1', clientObservedCurrentBidRoundPlayerUserId: 'player-1', }, ack, ); expect(placeBidDelta).toHaveBeenCalledWith({ amount: 120, bidRequestId: 'bid-1', bidderUserId, clientObservedAuctionLifecycleId: 'life-1', clientObservedCurrentBidRoundPlayerUserId: 'player-1', matchId: new mongoose.Types.ObjectId(matchId), teamIndex: 2, }); expect(to).toHaveBeenCalledWith(matchId); expect(emit).toHaveBeenCalledWith('bid', { auctionBidHistoryEntry, auctionLifecycleId: 'life-1', bidRequestId: 'bid-1', currentBidRoundDeadlineTimestampMS: 1780000030000, currentHighestBidderTeamIndex: 2, currentHighestBidPointAmount: 120, currentServerTimestampMS: 1780000000000, revision: 9, }); expect(ack).toHaveBeenCalledWith( expect.objectContaining({ bidDelta: { auctionBidHistoryEntry, auctionLifecycleId: 'life-1', bidRequestId: 'bid-1', currentBidRoundDeadlineTimestampMS: 1780000030000, currentHighestBidderTeamIndex: 2, currentHighestBidPointAmount: 120, currentServerTimestampMS: 1780000000000, revision: 9, }, bidRequestId: 'bid-1', bidServerTiming: expect.objectContaining({ gatewayTotalDurationMS: expect.any(Number), }), ok: true, }), ); }); it('generates one bid request id when the client omits it', async () => { const matchId = new mongoose.Types.ObjectId().toString(); const placeBidDelta = jest.fn().mockResolvedValue({ auctionBidHistoryEntry: { bidderTeamIndex: 1, bidPointAmount: 50, }, auctionLifecycleId: 'life-1', currentHighestBidderTeamIndex: 1, currentHighestBidPointAmount: 50, revision: 3, }); const { emit, gateway } = createGateway({ placeBidDelta }); const ack = jest.fn(); await gateway.handleBid( { data: { matchId, user: { _id: bidderUserId } }, emit: jest.fn(), } as never, { bidPointAmount: 50, bidderTeamIndex: 1, }, ack, ); const generatedBidRequestId = placeBidDelta.mock.calls[0][0].bidRequestId; expect(generatedBidRequestId).toEqual(expect.any(String)); expect(generatedBidRequestId).not.toHaveLength(0); expect(emit).toHaveBeenCalledWith( 'bid', expect.objectContaining({ bidRequestId: generatedBidRequestId, }), ); expect(ack).toHaveBeenCalledWith( expect.objectContaining({ bidRequestId: generatedBidRequestId, ok: true, }), ); }); it('acknowledges bid failures with the request id used for the attempt', async () => { const matchId = new mongoose.Types.ObjectId().toString(); const placeBidDelta = jest.fn().mockRejectedValue({ getResponse: () => ({ bidDiagnostics: { currentBidRoundDeadlineTimestampMS: 1780000002500, currentServerTimestampMS: 1780000003000, }, bidServerTiming: { redisBidCommandDurationMS: 2, redisBidContextReadDurationMS: 1, serviceTotalDurationMS: 4, }, code: 'EXPIRED', message: 'Bid deadline has already expired.', }), }); const socketEmit = jest.fn(); const { gateway } = createGateway({ placeBidDelta }); const ack = jest.fn(); await gateway.handleBid( { data: { matchId, user: { _id: bidderUserId } }, emit: socketEmit, } as never, { bidPointAmount: 50, bidderTeamIndex: 1, bidRequestId: 'bid-1', }, ack, ); expect(socketEmit).toHaveBeenCalledWith('error', { message: 'Bid deadline has already expired.', }); expect(ack).toHaveBeenCalledWith( expect.objectContaining({ bidDiagnostics: { currentBidRoundDeadlineTimestampMS: 1780000002500, currentServerTimestampMS: 1780000003000, }, bidRequestId: 'bid-1', bidServerTiming: expect.objectContaining({ gatewayTotalDurationMS: expect.any(Number), redisBidCommandDurationMS: 2, redisBidContextReadDurationMS: 1, serviceTotalDurationMS: 4, }), code: 'EXPIRED', message: 'Bid deadline has already expired.', rejected: true, }), ); }); it('acknowledges time sync with Redis server time', async () => { const getCurrentRedisTimestampMS = jest .fn() .mockResolvedValue(1780000001234); const { gateway } = createGateway({ getCurrentRedisTimestampMS }); const ack = jest.fn(); await gateway.handleTimeSync( { clientSentAtTimestampMS: 1780000000000, sequence: 7, }, ack, ); expect(getCurrentRedisTimestampMS).toHaveBeenCalledTimes(1); expect(ack).toHaveBeenCalledWith( expect.objectContaining({ clientSentAtTimestampMS: 1780000000000, currentServerTimestampMS: 1780000001234, ok: true, sequence: 7, }), ); }); it('rate limits excessive bid requests from the same socket', async () => { jest.spyOn(Date, 'now').mockReturnValue(1780000000000); const matchId = new mongoose.Types.ObjectId().toString(); const placeBidDelta = jest.fn().mockResolvedValue({ auctionBidHistoryEntry: { bidderTeamIndex: 1, bidPointAmount: 50, }, currentHighestBidderTeamIndex: 1, currentHighestBidPointAmount: 50, revision: 3, }); const socketEmit = jest.fn(); const socket = { data: { matchId, user: { _id: bidderUserId } }, emit: socketEmit, }; const { gateway } = createGateway({ placeBidDelta }); const acknowledgements: Array> = []; for (let index = 0; index < 9; index += 1) { await gateway.handleBid( socket as never, { bidPointAmount: 50, bidderTeamIndex: 1, bidRequestId: `bid-${index}`, }, (response) => acknowledgements.push(response), ); } expect(placeBidDelta).toHaveBeenCalledTimes(8); expect(socketEmit).toHaveBeenCalledWith('error', { message: '입찰 요청이 너무 많습니다. 잠시 후 다시 시도해주세요.', }); expect(acknowledgements[8]).toEqual({ bidRequestId: 'bid-8', code: 'BID_RATE_LIMITED', message: '입찰 요청이 너무 많습니다. 잠시 후 다시 시도해주세요.', rejected: true, }); }); it('allows bid requests again after the rate limit window resets', async () => { const nowSpy = jest.spyOn(Date, 'now'); nowSpy.mockReturnValue(1780000000000); const matchId = new mongoose.Types.ObjectId().toString(); const placeBidDelta = jest.fn().mockResolvedValue({ auctionBidHistoryEntry: { bidderTeamIndex: 1, bidPointAmount: 50, }, currentHighestBidderTeamIndex: 1, currentHighestBidPointAmount: 50, revision: 3, }); const socket = { data: { matchId, user: { _id: bidderUserId } }, emit: jest.fn(), }; const { gateway } = createGateway({ placeBidDelta }); for (let index = 0; index < 8; index += 1) { await gateway.handleBid( socket as never, { bidPointAmount: 50, bidderTeamIndex: 1, bidRequestId: `bid-${index}`, }, jest.fn(), ); } nowSpy.mockReturnValue(1780000001000); await gateway.handleBid( socket as never, { bidPointAmount: 50, bidderTeamIndex: 1, bidRequestId: 'bid-reset', }, jest.fn(), ); expect(placeBidDelta).toHaveBeenCalledTimes(9); }); });