diff --git a/apps/api/src/modules/auction/auction-event-bus.service.ts b/apps/api/src/modules/auction/auction-event-bus.service.ts index d4cac7d5..f4032730 100644 --- a/apps/api/src/modules/auction/auction-event-bus.service.ts +++ b/apps/api/src/modules/auction/auction-event-bus.service.ts @@ -2,6 +2,7 @@ import { Injectable } from '@nestjs/common'; import type { Namespace } from 'socket.io'; import type { AuctionStateResponse } from './auction.service'; import type { MatchSideEffectDelta } from './auction-side-effect.service'; +import { serializeRealtimeAuction } from './auction-realtime-serializer'; @Injectable() export class AuctionEventBusService { @@ -21,7 +22,7 @@ export class AuctionEventBusService { public broadcastState(matchId: string, state: AuctionStateResponse): void { this.auctionNamespace?.to(matchId).emit( 'state', - JSON.parse(JSON.stringify(state)), + serializeRealtimeAuction(state), ); } } diff --git a/apps/api/src/modules/auction/auction-realtime-serializer.ts b/apps/api/src/modules/auction/auction-realtime-serializer.ts new file mode 100644 index 00000000..2a3c75de --- /dev/null +++ b/apps/api/src/modules/auction/auction-realtime-serializer.ts @@ -0,0 +1,103 @@ +import type { AuctionStateResponse } from './auction.service'; + +export function serializeRealtimeAuction(auction: AuctionStateResponse) { + const serialized = JSON.parse(JSON.stringify(auction)) as Record< + string, + unknown + >; + const auctionPlayerOrder = getRecordArray( + serialized.auctionPlayerOrder ?? serialized.order, + ); + const currentAuctionPlayerOrderIndex = Number( + serialized.currentAuctionPlayerOrderIndex ?? serialized.currentIndex ?? 0, + ); + const currentBidRoundPlayerUserId = + typeof serialized.currentBidRoundPlayerUserId === 'string' + ? serialized.currentBidRoundPlayerUserId + : getStringField( + auctionPlayerOrder[currentAuctionPlayerOrderIndex], + 'userId', + ); + + if (Array.isArray(serialized.auctionPlayerOrder)) { + serialized.auctionPlayerOrder = auctionPlayerOrder.map((player) => + serializeRealtimeAuctionPlayer(player, currentBidRoundPlayerUserId), + ); + } else if (Array.isArray(serialized.order)) { + serialized.order = auctionPlayerOrder.map((player) => + serializeRealtimeAuctionPlayer(player, currentBidRoundPlayerUserId), + ); + } + + const passedAuctionPlayerQueue = getRecordArray( + serialized.passedAuctionPlayerQueue ?? serialized.passedQueue, + ); + if (Array.isArray(serialized.passedAuctionPlayerQueue)) { + serialized.passedAuctionPlayerQueue = passedAuctionPlayerQueue.map( + (player) => + serializeRealtimeAuctionPlayer(player, currentBidRoundPlayerUserId), + ); + } else if (Array.isArray(serialized.passedQueue)) { + serialized.passedQueue = passedAuctionPlayerQueue.map((player) => + serializeRealtimeAuctionPlayer(player, currentBidRoundPlayerUserId), + ); + } + + if ('auctionPlayerOrder' in serialized) delete serialized.order; + if ('auctionTeams' in serialized) delete serialized.teams; + if ('passedAuctionPlayerQueue' in serialized) delete serialized.passedQueue; + if ('auctionBidHistory' in serialized) delete serialized.bids; + if ('maximumBidRoundDurationSeconds' in serialized) { + delete serialized.maxTimerSeconds; + } + if ('bidRoundExtensionSeconds' in serialized) { + delete serialized.bidExtensionSeconds; + } + if ('initialTeamBidPointAmount' in serialized) { + delete serialized.initialPoints; + } + if ('topTierAuctionPriorityThreshold' in serialized) { + delete serialized.topTierThreshold; + } + if ('manualTopTierAuctionPriorityUserIds' in serialized) { + delete serialized.manualTopTierUserIds; + } + + return serialized; +} + +function serializeRealtimeAuctionPlayer( + player: Record, + currentBidRoundPlayerUserId?: string, +) { + if (getStringField(player, 'userId') === currentBidRoundPlayerUserId) { + return player; + } + + const { + masteries: _masteries, + puuid: _puuid, + recentStatsSummary: _recentStatsSummary, + tierHistory: _tierHistory, + ...lightweightPlayer + } = player; + + return lightweightPlayer; +} + +function getRecordArray(value: unknown): Array> { + return Array.isArray(value) + ? value.filter( + (item): item is Record => + typeof item === 'object' && item !== null, + ) + : []; +} + +function getStringField( + value: Record | undefined, + fieldName: string, +): string | undefined { + const fieldValue = value?.[fieldName]; + return typeof fieldValue === 'string' ? fieldValue : undefined; +} diff --git a/apps/api/src/modules/auction/auction.gateway.spec.ts b/apps/api/src/modules/auction/auction.gateway.spec.ts index 6bdf1beb..7a8ba603 100644 --- a/apps/api/src/modules/auction/auction.gateway.spec.ts +++ b/apps/api/src/modules/auction/auction.gateway.spec.ts @@ -8,10 +8,16 @@ import { AuctionGateway } from './auction.gateway'; describe('AuctionGateway', () => { function createGateway(params?: { - placeBid?: jest.Mock; + getCurrentRedisTimestampMS?: jest.Mock; + placeBidDelta?: jest.Mock; }) { const auctionService = { - placeBid: params?.placeBid ?? jest.fn(), + placeBidDelta: params?.placeBidDelta ?? jest.fn(), + }; + const auctionRedisService = { + getCurrentRedisTimestampMS: + params?.getCurrentRedisTimestampMS ?? + jest.fn().mockResolvedValue(1780000000000), }; const gateway = new AuctionGateway( auctionService as never, @@ -20,6 +26,7 @@ describe('AuctionGateway', () => { { 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 }); @@ -29,6 +36,7 @@ describe('AuctionGateway', () => { auctionService, emit, gateway, + auctionRedisService, to, }; } @@ -41,8 +49,8 @@ describe('AuctionGateway', () => { bidPlacedAtTimestampMS: 1780000000000, bidPointAmount: 120, }; - const placeBid = jest.fn().mockResolvedValue({ - auctionBidHistory: [auctionBidHistoryEntry], + const placeBidDelta = jest.fn().mockResolvedValue({ + auctionBidHistoryEntry, auctionLifecycleId: 'life-1', currentBidRoundDeadlineTimestampMS: 1780000030000, currentHighestBidderTeamIndex: 2, @@ -50,7 +58,7 @@ describe('AuctionGateway', () => { currentServerTimestampMS: 1780000000000, revision: 9, }); - const { emit, gateway, to } = createGateway({ placeBid }); + const { emit, gateway, to } = createGateway({ placeBidDelta }); const ack = jest.fn(); await gateway.handleBid( @@ -65,7 +73,7 @@ describe('AuctionGateway', () => { ack, ); - expect(placeBid).toHaveBeenCalledWith({ + expect(placeBidDelta).toHaveBeenCalledWith({ amount: 120, bidRequestId: 'bid-1', clientObservedAuctionLifecycleId: 'life-1', @@ -84,31 +92,40 @@ describe('AuctionGateway', () => { currentServerTimestampMS: 1780000000000, revision: 9, }); - expect(ack).toHaveBeenCalledWith({ - bidRequestId: 'bid-1', - ok: true, - state: expect.objectContaining({ - auctionLifecycleId: 'life-1', - 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 placeBid = jest.fn().mockResolvedValue({ - auctionBidHistory: [ - { - bidderTeamIndex: 1, - bidPointAmount: 50, - }, - ], + const placeBidDelta = jest.fn().mockResolvedValue({ + auctionBidHistoryEntry: { + bidderTeamIndex: 1, + bidPointAmount: 50, + }, auctionLifecycleId: 'life-1', currentHighestBidderTeamIndex: 1, currentHighestBidPointAmount: 50, revision: 3, }); - const { emit, gateway } = createGateway({ placeBid }); + const { emit, gateway } = createGateway({ placeBidDelta }); const ack = jest.fn(); await gateway.handleBid( @@ -120,7 +137,7 @@ describe('AuctionGateway', () => { ack, ); - const generatedBidRequestId = placeBid.mock.calls[0][0].bidRequestId; + const generatedBidRequestId = placeBidDelta.mock.calls[0][0].bidRequestId; expect(generatedBidRequestId).toEqual(expect.any(String)); expect(generatedBidRequestId).not.toHaveLength(0); expect(emit).toHaveBeenCalledWith( @@ -139,9 +156,23 @@ describe('AuctionGateway', () => { it('acknowledges bid failures with the request id used for the attempt', async () => { const matchId = new mongoose.Types.ObjectId().toString(); - const placeBid = jest.fn().mockRejectedValue(new Error('Bid failed')); + 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({ placeBid }); + const { gateway } = createGateway({ placeBidDelta }); const ack = jest.fn(); await gateway.handleBid( @@ -155,32 +186,69 @@ describe('AuctionGateway', () => { ); expect(socketEmit).toHaveBeenCalledWith('error', { - message: 'Bid failed', - }); - expect(ack).toHaveBeenCalledWith({ - bidRequestId: 'bid-1', - code: 'Bid failed', - rejected: true, + 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 placeBid = jest.fn().mockResolvedValue({ - auctionBidHistory: [ - { - bidderTeamIndex: 1, - bidPointAmount: 50, - }, - ], + const placeBidDelta = jest.fn().mockResolvedValue({ + auctionBidHistoryEntry: { + bidderTeamIndex: 1, + bidPointAmount: 50, + }, currentHighestBidderTeamIndex: 1, currentHighestBidPointAmount: 50, revision: 3, }); const socketEmit = jest.fn(); const socket = { data: { matchId }, emit: socketEmit }; - const { gateway } = createGateway({ placeBid }); + const { gateway } = createGateway({ placeBidDelta }); const acknowledgements: Array> = []; for (let index = 0; index < 9; index += 1) { @@ -195,7 +263,7 @@ describe('AuctionGateway', () => { ); } - expect(placeBid).toHaveBeenCalledTimes(8); + expect(placeBidDelta).toHaveBeenCalledTimes(8); expect(socketEmit).toHaveBeenCalledWith('error', { message: '입찰 요청이 너무 많습니다. 잠시 후 다시 시도해주세요.', }); @@ -211,19 +279,17 @@ describe('AuctionGateway', () => { const nowSpy = jest.spyOn(Date, 'now'); nowSpy.mockReturnValue(1780000000000); const matchId = new mongoose.Types.ObjectId().toString(); - const placeBid = jest.fn().mockResolvedValue({ - auctionBidHistory: [ - { - bidderTeamIndex: 1, - bidPointAmount: 50, - }, - ], + const placeBidDelta = jest.fn().mockResolvedValue({ + auctionBidHistoryEntry: { + bidderTeamIndex: 1, + bidPointAmount: 50, + }, currentHighestBidderTeamIndex: 1, currentHighestBidPointAmount: 50, revision: 3, }); const socket = { data: { matchId }, emit: jest.fn() }; - const { gateway } = createGateway({ placeBid }); + const { gateway } = createGateway({ placeBidDelta }); for (let index = 0; index < 8; index += 1) { await gateway.handleBid( @@ -248,6 +314,6 @@ describe('AuctionGateway', () => { jest.fn(), ); - expect(placeBid).toHaveBeenCalledTimes(9); + expect(placeBidDelta).toHaveBeenCalledTimes(9); }); }); diff --git a/apps/api/src/modules/auction/auction.gateway.ts b/apps/api/src/modules/auction/auction.gateway.ts index bc2477c9..a1db43b5 100644 --- a/apps/api/src/modules/auction/auction.gateway.ts +++ b/apps/api/src/modules/auction/auction.gateway.ts @@ -1,5 +1,6 @@ import { Logger } from '@nestjs/common'; import { randomUUID } from 'crypto'; +import { performance } from 'perf_hooks'; import { Ack, ConnectedSocket, @@ -25,9 +26,14 @@ import type { UserDocument, } from '../global/database/schema'; import { AuctionService } from './auction.service'; -import type { AuctionStateResponse } from './auction.service'; +import type { + AuctionBidDeltaResponse, + AuctionStateResponse, +} from './auction.service'; import { AuctionEventBusService } from './auction-event-bus.service'; 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; @@ -41,6 +47,11 @@ interface BidPayload { clientObservedCurrentBidRoundPlayerUserId?: string; } +interface TimeSyncPayload { + clientSentAtTimestampMS?: number; + sequence?: number; +} + interface SoldPayload { auctionActionRequestId?: string; assignedPosition?: Position; @@ -92,6 +103,7 @@ export class AuctionGateway private readonly identityService: IdentityService, private readonly connectionService: ConnectionService, private readonly auctionEventBusService: AuctionEventBusService, + private readonly auctionRedisService: AuctionRedisService, ) {} public afterInit(server: Namespace): void { @@ -146,6 +158,7 @@ export class AuctionGateway @MessageBody() payload: BidPayload, @Ack() ack?: (response: Record) => void, ) { + const gatewayBidStartedAtMS = performance.now(); const matchId = this.requireJoinedMatchId(socket); if (!matchId) return; @@ -162,7 +175,7 @@ export class AuctionGateway } try { - const auction = await this.auctionService.placeBid({ + const bidResult = await this.auctionService.placeBidDelta({ matchId: new mongoose.Types.ObjectId(matchId), teamIndex: payload.bidderTeamIndex, amount: payload.bidPointAmount, @@ -172,30 +185,75 @@ export class AuctionGateway clientObservedCurrentBidRoundPlayerUserId: payload.clientObservedCurrentBidRoundPlayerUserId, }); - const bidDelta = this.buildBidDeltaFromAuctionState( - auction, - bidRequestId, - ); - if (bidDelta) { - this.broadcastBid(matchId, bidDelta); + 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, auction); + this.broadcastState(matchId, bidResult as AuctionStateResponse); } ack?.({ + ...(bidDelta + ? {} + : { state: this.serializeAuction(bidResult as AuctionStateResponse) }), ok: true, bidRequestId, - state: this.serializeAuction(auction), + bidDelta: broadcastBidDelta, + bidServerTiming: this.buildGatewayBidTiming( + gatewayBidStartedAtMS, + bidServerTiming, + ), }); } catch (error) { - this.emitKnownError(socket, error); + const errorPayload = this.resolveErrorPayload(error); + const bidServerTiming = this.extractBidServerTiming(errorPayload); + this.emitError(socket, errorPayload.message); ack?.({ + ...errorPayload, bidRequestId, - code: error instanceof Error ? error.message : 'UNKNOWN', + 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: Socket, @@ -208,13 +266,12 @@ export class AuctionGateway try { const auction = await this.auctionService.openBidding( new mongoose.Types.ObjectId(matchId), - this.toAuctionActionRequest(payload), + this.toSocketAuctionActionRequest(payload), ); this.broadcastState(matchId, auction); ack?.({ auctionActionRequestId: payload?.auctionActionRequestId, ok: true, - state: this.serializeAuction(auction), }); } catch (error) { this.emitKnownError(socket, error); @@ -239,13 +296,12 @@ export class AuctionGateway const auction = await this.auctionService.markSold({ matchId: new mongoose.Types.ObjectId(matchId), assignedPosition: payload?.assignedPosition, - ...this.toAuctionActionRequest(payload), + ...this.toSocketAuctionActionRequest(payload), }); this.broadcastState(matchId, auction); ack?.({ auctionActionRequestId: payload?.auctionActionRequestId, ok: true, - state: this.serializeAuction(auction), }); } catch (error) { this.emitKnownError(socket, error); @@ -269,13 +325,12 @@ export class AuctionGateway try { const auction = await this.auctionService.next( new mongoose.Types.ObjectId(matchId), - this.toAuctionActionRequest(payload), + this.toSocketAuctionActionRequest(payload), ); this.broadcastState(matchId, auction); ack?.({ auctionActionRequestId: payload?.auctionActionRequestId, ok: true, - state: this.serializeAuction(auction), }); } catch (error) { this.emitKnownError(socket, error); @@ -299,13 +354,12 @@ export class AuctionGateway try { const auction = await this.auctionService.markPassed( new mongoose.Types.ObjectId(matchId), - this.toAuctionActionRequest(payload), + this.toSocketAuctionActionRequest(payload), ); this.broadcastState(matchId, auction); ack?.({ auctionActionRequestId: payload?.auctionActionRequestId, ok: true, - state: this.serializeAuction(auction), }); } catch (error) { this.emitKnownError(socket, error); @@ -395,6 +449,13 @@ export class AuctionGateway }; } + private toSocketAuctionActionRequest(payload?: AuctionActionPayload) { + return { + ...this.toAuctionActionRequest(payload), + shouldBroadcastStateAfterDurability: false, + }; + } + private readHandshakeUserId(socket: Socket): string | undefined { const authUserId = socket.handshake.auth['x-auth-user-id']; if (typeof authUserId === 'string') return authUserId; @@ -509,7 +570,7 @@ export class AuctionGateway } public broadcastState(matchId: string, auction: AuctionStateResponse) { - this.server.to(matchId).emit('state', this.serializeAuction(auction)); + this.server.to(matchId).emit('state', serializeRealtimeAuction(auction)); } public broadcastBid(matchId: string, delta: Record) { @@ -536,9 +597,7 @@ export class AuctionGateway } private emitKnownError(socket: Socket, error: unknown) { - const message = - error instanceof Error ? error.message : 'Unexpected auction gateway error.'; - this.emitError(socket, message); + this.emitError(socket, this.resolveErrorPayload(error).message); } private emitError(socket: Socket, message: string) { @@ -549,6 +608,68 @@ export class AuctionGateway return JSON.parse(JSON.stringify(auction)); } + 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 { bidServerTiming: _bidServerTiming, ...publicBidDelta } = bidDelta; + return publicBidDelta; + } + private buildBidDeltaFromAuctionState( auction: AuctionStateResponse, bidRequestId?: string, @@ -604,6 +725,19 @@ export class AuctionGateway }; } + 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 { diff --git a/apps/api/src/modules/auction/auction.service.spec.ts b/apps/api/src/modules/auction/auction.service.spec.ts index 9d0a7cad..ef3b7854 100644 --- a/apps/api/src/modules/auction/auction.service.spec.ts +++ b/apps/api/src/modules/auction/auction.service.spec.ts @@ -91,6 +91,7 @@ describe('AuctionService', () => { auctionLifecycleId: 'life-1', revision: 1, }), + readBidContext: jest.fn().mockResolvedValue(null), readAuctionStateView: jest.fn().mockResolvedValue(null), }; @@ -1006,6 +1007,123 @@ describe('AuctionService', () => { ); }); + it('returns bid deltas without re-reading the full Redis state', async () => { + const matchId = new mongoose.Types.ObjectId(); + const captainUserId = new mongoose.Types.ObjectId(); + const playerUserId = new mongoose.Types.ObjectId(); + const biddingContext = { + auctionLifecycleId: 'life-1', + bidderTeamCaptainUserId: captainUserId.toString(), + currentBidRoundPlayerUserId: playerUserId.toString(), + phase: 'bidding', + }; + const auctionBidHistoryEntry = { + bidderTeamIndex: 1, + bidderUserId: captainUserId.toString(), + bidPlacedAtTimestampMS: 1780000000000, + bidPointAmount: 120, + }; + const { + connectionService, + service, + auctionRedisCommandService, + auctionRedisStateReaderService, + } = createService({}); + auctionRedisStateReaderService.readBidContext.mockResolvedValueOnce( + biddingContext, + ); + auctionRedisCommandService.placeBid.mockResolvedValueOnce({ + auctionBidHistoryEntry, + bidRequestId: '00000000-0000-4000-8000-000000000050', + currentBidRoundDeadlineTimestampMS: 1780000030000, + currentHighestBidderTeamIndex: 1, + currentHighestBidPointAmount: 120, + currentServerTimestampMS: 1780000000000, + ok: true, + revision: 3, + }); + + await expect( + service.placeBidDelta({ + amount: 120, + bidRequestId: '00000000-0000-4000-8000-000000000050', + matchId, + teamIndex: 1, + }), + ).resolves.toEqual( + expect.objectContaining({ + auctionBidHistoryEntry, + auctionLifecycleId: 'life-1', + bidRequestId: '00000000-0000-4000-8000-000000000050', + bidServerTiming: expect.objectContaining({ + redisBidCommandDurationMS: expect.any(Number), + redisBidContextReadDurationMS: expect.any(Number), + serviceTotalDurationMS: expect.any(Number), + }), + currentBidRoundDeadlineTimestampMS: 1780000030000, + currentHighestBidderTeamIndex: 1, + currentHighestBidPointAmount: 120, + currentServerTimestampMS: 1780000000000, + revision: 3, + }), + ); + expect( + auctionRedisStateReaderService.readAuctionStateView, + ).not.toHaveBeenCalled(); + expect(connectionService.getModel).not.toHaveBeenCalledWith('auction'); + }); + + it('includes redis bid diagnostics and timing on realtime bid rejection', async () => { + const matchId = new mongoose.Types.ObjectId(); + const captainUserId = new mongoose.Types.ObjectId(); + const playerUserId = new mongoose.Types.ObjectId(); + const { + service, + auctionRedisCommandService, + auctionRedisStateReaderService, + } = createService({}); + auctionRedisStateReaderService.readBidContext.mockResolvedValueOnce({ + auctionLifecycleId: 'life-1', + bidderTeamCaptainUserId: captainUserId.toString(), + currentBidRoundPlayerUserId: playerUserId.toString(), + phase: 'bidding', + }); + auctionRedisCommandService.placeBid.mockResolvedValueOnce({ + bidRequestId: 'bid-1', + code: 'EXPIRED', + currentBidRoundDeadlineTimestampMS: 1780000002500, + currentServerTimestampMS: 1780000003000, + rejected: true, + }); + + try { + await service.placeBidDelta({ + amount: 120, + bidRequestId: 'bid-1', + matchId, + teamIndex: 1, + }); + throw new Error('Expected bid rejection.'); + } catch (error) { + const response = (error as { getResponse: () => unknown }).getResponse(); + expect(response).toEqual( + expect.objectContaining({ + bidDiagnostics: { + currentBidRoundDeadlineTimestampMS: 1780000002500, + currentServerTimestampMS: 1780000003000, + }, + bidServerTiming: expect.objectContaining({ + redisBidCommandDurationMS: expect.any(Number), + redisBidContextReadDurationMS: expect.any(Number), + serviceTotalDurationMS: expect.any(Number), + }), + code: 'EXPIRED', + message: 'Bid deadline has already expired.', + }), + ); + } + }); + it('syncs match teams when a redis-v1 auction completes', async () => { const matchId = new mongoose.Types.ObjectId(); const captainUserId = new mongoose.Types.ObjectId(); diff --git a/apps/api/src/modules/auction/auction.service.ts b/apps/api/src/modules/auction/auction.service.ts index cae1b3bf..a76e1d87 100644 --- a/apps/api/src/modules/auction/auction.service.ts +++ b/apps/api/src/modules/auction/auction.service.ts @@ -6,6 +6,7 @@ import { NotFoundException, } from '@nestjs/common'; import { randomUUID } from 'crypto'; +import { performance } from 'perf_hooks'; import mongoose from 'mongoose'; import { ConnectionService } from '../global/database/connection.service'; import { @@ -25,7 +26,10 @@ import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.se import type { RiotPlatformRoute, RiotRegionalRoute } from '../riot/riot.types'; import { TournamentCodeService } from '../tournament-code/tournament-code.service'; import { TournamentResultService } from '../tournament-result/tournament-result.service'; -import { AuctionRedisCommandService } from './redis/auction-redis-command.service'; +import { + AuctionRedisCommandService, + type AuctionBidCommandResult, +} from './redis/auction-redis-command.service'; import { buildAuctionRedisKeys } from './redis/auction-redis.keys'; import { buildAuctionRedisLiveStatePatchFromStructure, @@ -87,6 +91,7 @@ interface AuctionStructureActionRequestParams { clientObservedCurrentBidRoundPlayerUserId?: string; clientObservedPhase?: string; clientObservedRevision?: number; + shouldBroadcastStateAfterDurability?: boolean; } interface MarkSoldParams extends AuctionStructureActionRequestParams { @@ -136,6 +141,30 @@ export interface AuctionHistoryView { export type AuctionStateResponse = AuctionDocument | Record; +export interface AuctionBidDeltaResponse { + auctionBidHistoryEntry: Record; + auctionLifecycleId?: string; + bidServerTiming?: AuctionBidServerTiming; + bidRequestId: string; + currentBidRoundDeadlineTimestampMS: number; + currentHighestBidderTeamIndex: number; + currentHighestBidPointAmount: number; + currentServerTimestampMS: number; + revision: number; +} + +export interface AuctionBidServerTiming { + fallbackFullStatePath?: boolean; + redisBidCommandDurationMS?: number; + redisBidContextReadDurationMS?: number; + serviceTotalDurationMS?: number; +} + +export interface AuctionBidRejectDiagnostics { + currentBidRoundDeadlineTimestampMS?: number; + currentServerTimestampMS?: number; +} + interface AuctionEnrichmentTarget { userId: mongoose.Types.ObjectId; puuid: string; @@ -591,6 +620,23 @@ export class AuctionService { return auction; } + public async placeBidDelta( + params: PlaceBidParams, + ): Promise { + this.assertValidBidPointAmount(params.amount); + const redisBidDelta = await this.tryPlaceRedisBidDeltaFromRealtimeState( + params, + ); + if (redisBidDelta) return redisBidDelta; + + const auction = await this.getByMatchId(params.matchId); + this.assertLiveAuctionOperationSupported(auction); + if (this.isRedisV1Auction(auction)) { + return this.placeRedisBidDelta(auction, params); + } + return this.placeBid(params); + } + private async openRedisBidding( auction: AuctionDocument, actionRequestParams: AuctionStructureActionRequestParams, @@ -627,6 +673,8 @@ export class AuctionService { }, expectedPhase: 'presenting', liveStatePatch, + shouldBroadcastStateAfterDurability: + actionRequestParams.shouldBroadcastStateAfterDurability, state, structureInput, }); @@ -636,6 +684,110 @@ export class AuctionService { auction: AuctionDocument, params: PlaceBidParams, ): Promise { + const matchId = auction.matchId.toString(); + await this.executeRedisBid(auction, params); + return this.requireRedisAuctionState(matchId); + } + + private async placeRedisBidDelta( + auction: AuctionDocument, + params: PlaceBidParams, + ): Promise { + const serviceStartedAtMS = performance.now(); + const { redisBidCommandDurationMS, result, state } = + await this.executeRedisBid(auction, params); + const bidDelta = this.buildBidDeltaFromRedisBidResult(state, result); + bidDelta.bidServerTiming = this.roundBidServerTiming({ + fallbackFullStatePath: true, + redisBidCommandDurationMS, + serviceTotalDurationMS: performance.now() - serviceStartedAtMS, + }); + this.logSlowBidTiming(auction.matchId.toString(), bidDelta.bidServerTiming); + return bidDelta; + } + + private async tryPlaceRedisBidDeltaFromRealtimeState( + params: PlaceBidParams, + ): Promise { + const serviceStartedAtMS = performance.now(); + const matchId = params.matchId.toString(); + const bidContextReadStartedAtMS = performance.now(); + const bidContext = + await this.auctionRedisStateReaderService.readBidContext( + matchId, + params.teamIndex, + ); + const redisBidContextReadDurationMS = + performance.now() - bidContextReadStartedAtMS; + if (!bidContext) return null; + if (bidContext.phase !== 'bidding') { + throw new BadRequestException('Auction is not in bidding phase.'); + } + if (!bidContext.bidderTeamCaptainUserId) { + throw new BadRequestException('Unknown team.'); + } + + const auctionLifecycleId = + params.clientObservedAuctionLifecycleId ?? bidContext.auctionLifecycleId; + const currentBidRoundPlayerUserId = + params.clientObservedCurrentBidRoundPlayerUserId ?? + bidContext.currentBidRoundPlayerUserId; + if (!auctionLifecycleId || !currentBidRoundPlayerUserId) { + throw new BadRequestException('Current bid round is not available.'); + } + + const redisBidCommandStartedAtMS = performance.now(); + const result = await this.auctionRedisCommandService.placeBid(matchId, { + bidPointAmount: params.amount, + bidderTeamIndex: params.teamIndex, + bidderUserId: bidContext.bidderTeamCaptainUserId, + bidRequestId: params.bidRequestId ?? randomUUID(), + clientObservedAuctionLifecycleId: auctionLifecycleId, + clientObservedCurrentBidRoundPlayerUserId: currentBidRoundPlayerUserId, + matchId, + maximumAuctionTeamMemberCount: AUCTION_MAX_TEAM_SIZE, + maximumStoredAuctionBidHistoryCount: AUCTION_MAX_STORED_BID_HISTORY_COUNT, + maximumStoredBidRequestResultCount: + AUCTION_MAX_STORED_BID_REQUEST_RESULT_COUNT, + minimumBidPointReservePerRemainingAuctionTeamMemberSlot: + AUCTION_MIN_BID_POINTS, + minimumBidRequestResultReplayWindowMS: + AUCTION_BID_REQUEST_REPLAY_WINDOW_MS, + }); + const redisBidCommandDurationMS = + performance.now() - redisBidCommandStartedAtMS; + if ('rejected' in result) { + const bidServerTiming = this.roundBidServerTiming({ + redisBidCommandDurationMS, + redisBidContextReadDurationMS, + serviceTotalDurationMS: performance.now() - serviceStartedAtMS, + }); + this.logSlowBidTiming(matchId, bidServerTiming); + throw this.createRedisBidRejectedException(result, bidServerTiming); + } + + const bidDelta = this.buildBidDeltaFromRedisBidResult( + { auctionLifecycleId: bidContext.auctionLifecycleId }, + result, + ); + bidDelta.bidServerTiming = this.roundBidServerTiming({ + redisBidCommandDurationMS, + redisBidContextReadDurationMS, + serviceTotalDurationMS: performance.now() - serviceStartedAtMS, + }); + this.logSlowBidTiming(matchId, bidDelta.bidServerTiming); + return bidDelta; + } + + private async executeRedisBid( + auction: AuctionDocument, + params: PlaceBidParams, + ): Promise<{ + redisBidCommandDurationMS: number; + result: Extract; + state: Record; + }> { + const serviceStartedAtMS = performance.now(); const matchId = auction.matchId.toString(); const state = await this.requireRedisAuctionState(matchId); if (state.phase !== 'bidding') { @@ -660,6 +812,7 @@ export class AuctionService { throw new BadRequestException('Current bid round is not available.'); } + const redisBidCommandStartedAtMS = performance.now(); const result = await this.auctionRedisCommandService.placeBid(matchId, { bidPointAmount: params.amount, bidderTeamIndex: params.teamIndex, @@ -677,11 +830,36 @@ export class AuctionService { minimumBidRequestResultReplayWindowMS: AUCTION_BID_REQUEST_REPLAY_WINDOW_MS, }); + const redisBidCommandDurationMS = + performance.now() - redisBidCommandStartedAtMS; if ('rejected' in result) { - throw new BadRequestException(this.formatRedisBidRejectCode(result.code)); + const bidServerTiming = this.roundBidServerTiming({ + fallbackFullStatePath: true, + redisBidCommandDurationMS, + serviceTotalDurationMS: performance.now() - serviceStartedAtMS, + }); + this.logSlowBidTiming(matchId, bidServerTiming); + throw this.createRedisBidRejectedException(result, bidServerTiming); } - return this.requireRedisAuctionState(matchId); + return { redisBidCommandDurationMS, result, state }; + } + + private buildBidDeltaFromRedisBidResult( + state: Record, + result: Extract, + ): AuctionBidDeltaResponse { + return { + auctionBidHistoryEntry: result.auctionBidHistoryEntry, + auctionLifecycleId: this.stringFromState(state.auctionLifecycleId), + bidRequestId: result.bidRequestId, + currentBidRoundDeadlineTimestampMS: + result.currentBidRoundDeadlineTimestampMS, + currentHighestBidderTeamIndex: result.currentHighestBidderTeamIndex, + currentHighestBidPointAmount: result.currentHighestBidPointAmount, + currentServerTimestampMS: result.currentServerTimestampMS, + revision: result.revision, + }; } private async markRedisSold( @@ -749,6 +927,8 @@ export class AuctionService { ...buildAuctionRedisLiveStatePatchFromStructure(structureInput), phase: 'sold', }, + shouldBroadcastStateAfterDurability: + params.shouldBroadcastStateAfterDurability, state, structureInput, }); @@ -806,6 +986,8 @@ export class AuctionService { ...buildAuctionRedisLiveStatePatchFromStructure(structureInput), phase: 'passed', }, + shouldBroadcastStateAfterDurability: + actionRequestParams.shouldBroadcastStateAfterDurability, state, structureInput, }); @@ -972,6 +1154,8 @@ export class AuctionService { currentHighestBidderTeamIndex: -1, phase: nextPhase, }, + shouldBroadcastStateAfterDurability: + actionRequestParams.shouldBroadcastStateAfterDurability, state, structureInput, }); @@ -1445,6 +1629,7 @@ export class AuctionService { historyMutation?: Record; liveStatePatch: Record; matchSideEffectMutation?: Record; + shouldBroadcastStateAfterDurability?: boolean; shouldResetBidRuntime?: boolean; state: Record; structureInput: Parameters[0]; @@ -1528,7 +1713,8 @@ export class AuctionService { expectedRevision, liveStatePatch: params.liveStatePatch, matchId, - shouldBroadcastState: true, + shouldBroadcastState: + params.shouldBroadcastStateAfterDurability ?? true, shouldResetBidRuntime: params.shouldResetBidRuntime, actionRequest: params.actionRequest?.actionRequest, }, @@ -1945,6 +2131,46 @@ export class AuctionService { } } + private createRedisBidRejectedException( + result: Extract, + bidServerTiming?: AuctionBidServerTiming, + ): BadRequestException { + const message = this.formatRedisBidRejectCode(result.code); + const bidDiagnostics: AuctionBidRejectDiagnostics = { + currentBidRoundDeadlineTimestampMS: + result.currentBidRoundDeadlineTimestampMS, + currentServerTimestampMS: result.currentServerTimestampMS, + }; + return new BadRequestException({ + bidDiagnostics, + ...(bidServerTiming ? { bidServerTiming } : {}), + code: result.code, + message, + }); + } + + private roundBidServerTiming( + timing: AuctionBidServerTiming, + ): AuctionBidServerTiming { + return Object.fromEntries( + Object.entries(timing).map(([key, value]) => [ + key, + typeof value === 'number' ? Math.round(value * 10) / 10 : value, + ]), + ) as AuctionBidServerTiming; + } + + private logSlowBidTiming( + matchId: string, + timing: AuctionBidServerTiming, + ): void { + const serviceTotalDurationMS = timing.serviceTotalDurationMS ?? 0; + if (serviceTotalDurationMS < 250) return; + this.logger.warn( + `Auction bid latency match=${matchId} service=${serviceTotalDurationMS}ms context=${timing.redisBidContextReadDurationMS ?? 0}ms redisBid=${timing.redisBidCommandDurationMS ?? 0}ms fallback=${timing.fallbackFullStatePath ? '1' : '0'}`, + ); + } + private applyTopTierPriority( order: AuctionPlayerSnapshot[], threshold: AuctionTopTierThreshold, diff --git a/apps/api/src/modules/auction/redis/auction-redis-command.service.spec.ts b/apps/api/src/modules/auction/redis/auction-redis-command.service.spec.ts index 9362c45c..515cdb51 100644 --- a/apps/api/src/modules/auction/redis/auction-redis-command.service.spec.ts +++ b/apps/api/src/modules/auction/redis/auction-redis-command.service.spec.ts @@ -67,6 +67,7 @@ describe('AuctionRedisCommandService', () => { 'TOO_LOW', 'bid-1', '1000', + '31000', ]); await expect( @@ -87,6 +88,7 @@ describe('AuctionRedisCommandService', () => { ).resolves.toEqual({ bidRequestId: 'bid-1', code: 'TOO_LOW', + currentBidRoundDeadlineTimestampMS: 31_000, currentServerTimestampMS: 1000, rejected: true, }); diff --git a/apps/api/src/modules/auction/redis/auction-redis-command.service.ts b/apps/api/src/modules/auction/redis/auction-redis-command.service.ts index fa979c80..0c9d7e75 100644 --- a/apps/api/src/modules/auction/redis/auction-redis-command.service.ts +++ b/apps/api/src/modules/auction/redis/auction-redis-command.service.ts @@ -37,6 +37,7 @@ export type AuctionBidCommandResult = | { bidRequestId: string; code: string; + currentBidRoundDeadlineTimestampMS?: number; currentServerTimestampMS: number; isReplay?: boolean; rejected: true; @@ -244,6 +245,7 @@ function parseBidCommandReply(reply: unknown[]): AuctionBidCommandResult { return { bidRequestId: values[2], code: values[4] || status, + currentBidRoundDeadlineTimestampMS: optionalNumberValue(values[7]), currentServerTimestampMS: numberValue(values[9]), isReplay: true, rejected: true, @@ -252,6 +254,7 @@ function parseBidCommandReply(reply: unknown[]): AuctionBidCommandResult { return { bidRequestId: values[2] ?? '', code: values[1] ?? 'UNKNOWN', + currentBidRoundDeadlineTimestampMS: optionalNumberValue(values[4]), currentServerTimestampMS: numberValue(values[3]), rejected: true, }; @@ -373,3 +376,9 @@ function numberValue(value: string | undefined): number { const parsed = Number(value); return Number.isFinite(parsed) ? parsed : 0; } + +function optionalNumberValue(value: string | undefined): number | undefined { + if (value === undefined || value === '') return undefined; + const parsed = Number(value); + return Number.isFinite(parsed) ? parsed : undefined; +} diff --git a/apps/api/src/modules/auction/redis/auction-redis-projection.spec.ts b/apps/api/src/modules/auction/redis/auction-redis-projection.spec.ts index d365d96e..4bedf58a 100644 --- a/apps/api/src/modules/auction/redis/auction-redis-projection.spec.ts +++ b/apps/api/src/modules/auction/redis/auction-redis-projection.spec.ts @@ -146,6 +146,7 @@ describe('auction redis projection helpers', () => { currentBidRoundPlayerUserId: playerUserId.toString(), maximumBidRoundDurationSeconds: 30, 'team:2:assignedAuctionTeamMemberCount': 2, + 'team:2:captainUserId': captainUserId.toString(), 'team:2:remainingBidPointAmount': 970, }); }); diff --git a/apps/api/src/modules/auction/redis/auction-redis-projection.ts b/apps/api/src/modules/auction/redis/auction-redis-projection.ts index 500a61b8..3993a4a9 100644 --- a/apps/api/src/modules/auction/redis/auction-redis-projection.ts +++ b/apps/api/src/modules/auction/redis/auction-redis-projection.ts @@ -68,6 +68,8 @@ export function buildAuctionRedisLiveStatePatchFromStructure( } for (const team of input.auctionTeams) { + patch[`team:${team.teamIndex}:captainUserId`] = + team.captainUserId.toString(); patch[`team:${team.teamIndex}:remainingBidPointAmount`] = team.remainingBidPointAmount; patch[`team:${team.teamIndex}:assignedAuctionTeamMemberCount`] = diff --git a/apps/api/src/modules/auction/redis/auction-redis-state-reader.service.spec.ts b/apps/api/src/modules/auction/redis/auction-redis-state-reader.service.spec.ts index 1d78ed31..ed81edfe 100644 --- a/apps/api/src/modules/auction/redis/auction-redis-state-reader.service.spec.ts +++ b/apps/api/src/modules/auction/redis/auction-redis-state-reader.service.spec.ts @@ -41,6 +41,46 @@ describe('AuctionRedisStateReaderService', () => { await expect(service.readLiveStateIdentity('match-1')).resolves.toBeNull(); }); + it('reads bid context from the live state hot path fields', async () => { + const { service, sendCommand } = makeService([ + ['bidding', 'life-1', 'player-1', 'captain-2'], + ]); + + await expect(service.readBidContext('match-1', 2)).resolves.toEqual({ + auctionLifecycleId: 'life-1', + bidderTeamCaptainUserId: 'captain-2', + currentBidRoundPlayerUserId: 'player-1', + phase: 'bidding', + }); + expect(sendCommand).toHaveBeenCalledTimes(1); + expect(sendCommand).toHaveBeenCalledWith([ + 'HMGET', + 'auction:match-1:liveAuctionState', + 'phase', + 'auctionLifecycleId', + 'currentBidRoundPlayerUserId', + 'team:2:captainUserId', + ]); + }); + + it('falls back to structure state when bid context has no live captain field', async () => { + const { service, sendCommand } = makeService([ + ['bidding', 'life-1', 'player-1', null], + '{"auctionTeams":[{"teamIndex":2,"captainUserId":"captain-2"}]}', + ]); + + await expect(service.readBidContext('match-1', 2)).resolves.toEqual({ + auctionLifecycleId: 'life-1', + bidderTeamCaptainUserId: 'captain-2', + currentBidRoundPlayerUserId: 'player-1', + phase: 'bidding', + }); + expect(sendCommand).toHaveBeenNthCalledWith(2, [ + 'GET', + 'auction:match-1:auctionStructureState', + ]); + }); + it('assembles a public auction view from Redis state', async () => { const { service, sendCommand } = makeService([ [ diff --git a/apps/api/src/modules/auction/redis/auction-redis-state-reader.service.ts b/apps/api/src/modules/auction/redis/auction-redis-state-reader.service.ts index 3f9019a7..fc0b5384 100644 --- a/apps/api/src/modules/auction/redis/auction-redis-state-reader.service.ts +++ b/apps/api/src/modules/auction/redis/auction-redis-state-reader.service.ts @@ -22,6 +22,13 @@ export interface AuctionRedisLiveStateIdentity { revision?: number; } +export interface AuctionRedisBidContext { + auctionLifecycleId: string; + bidderTeamCaptainUserId?: string; + currentBidRoundPlayerUserId?: string; + phase: string; +} + export interface AuctionRedisStateViewReadOptions { includeInternalLiveStateFields?: boolean; shouldForceAuctionStateResync?: boolean; @@ -55,6 +62,41 @@ export class AuctionRedisStateReaderService { }; } + public async readBidContext( + matchId: string, + bidderTeamIndex: number, + ): Promise { + const keys = buildAuctionRedisKeys(matchId); + const bidderTeamCaptainUserIdField = `team:${bidderTeamIndex}:captainUserId`; + const liveReply = await this.auctionRedisService.raw().sendCommand([ + 'HMGET', + keys.liveStateKey, + 'phase', + 'auctionLifecycleId', + 'currentBidRoundPlayerUserId', + bidderTeamCaptainUserIdField, + ]); + if (!Array.isArray(liveReply)) return null; + + const phase = stringValue(liveReply[0]); + const auctionLifecycleId = stringValue(liveReply[1]); + const currentBidRoundPlayerUserId = stringValue(liveReply[2]); + const liveCaptainUserId = stringValue(liveReply[3]); + if (!phase || !auctionLifecycleId) return null; + + return { + auctionLifecycleId, + bidderTeamCaptainUserId: + liveCaptainUserId ?? + (await this.readBidderTeamCaptainUserIdFromStructure( + keys.structureStateKey, + bidderTeamIndex, + )), + currentBidRoundPlayerUserId, + phase, + }; + } + public async readAuctionStateView( matchId: string, options: AuctionRedisStateViewReadOptions = {}, @@ -102,11 +144,43 @@ export class AuctionRedisStateReaderService { shouldForceAuctionStateResync: options.shouldForceAuctionStateResync, structureState: JSON.parse(structureStateJson) as Record, }); + view.matchId = matchId; if (options.includeInternalLiveStateFields) { view.redisInternalPhase = liveState.phase; } return view; } + + private async readBidderTeamCaptainUserIdFromStructure( + structureStateKey: string, + bidderTeamIndex: number, + ): Promise { + const structureStateJson = await this.auctionRedisService + .raw() + .sendCommand(['GET', structureStateKey]); + if (typeof structureStateJson !== 'string' || !structureStateJson) { + return undefined; + } + const structureState = JSON.parse(structureStateJson) as Record< + string, + unknown + >; + const auctionTeams = Array.isArray(structureState.auctionTeams) + ? structureState.auctionTeams + : []; + const bidderTeam = auctionTeams.find((entry) => { + if (!entry || typeof entry !== 'object') return false; + return ( + Number((entry as Record).teamIndex) === bidderTeamIndex + ); + }); + if (!bidderTeam || typeof bidderTeam !== 'object') return undefined; + return stringValue((bidderTeam as Record).captainUserId); + } +} + +function stringValue(value: unknown): string | undefined { + return typeof value === 'string' && value ? value : undefined; } function parseHashReply( diff --git a/apps/api/src/modules/auction/redis/auction-redis.bid.ts b/apps/api/src/modules/auction/redis/auction-redis.bid.ts index 88c6c763..882fce34 100644 --- a/apps/api/src/modules/auction/redis/auction-redis.bid.ts +++ b/apps/api/src/modules/auction/redis/auction-redis.bid.ts @@ -174,6 +174,7 @@ if redis.call('LLEN', bidRequestResultOrderKey) >= maximumStoredBidRequestResult end local function storeRejectedRequest(rejectCode) + local rejectedCurrentBidRoundDeadlineTimestampMS = redis.call('HGET', liveAuctionStateKey, 'currentBidRoundDeadlineTimestampMS') or '' redis.call( 'HSET', bidRequestResultsKey, @@ -183,13 +184,15 @@ local function storeRejectedRequest(rejectCode) 'rejected', requestField('rejectCode'), rejectCode, + requestField('currentBidRoundDeadlineTimestampMS'), + rejectedCurrentBidRoundDeadlineTimestampMS, requestField('responseServerTimestampMS'), tostring(currentRedisTimestampMS), requestField('createdAtTimestampMS'), tostring(currentRedisTimestampMS) ) redis.call('RPUSH', bidRequestResultOrderKey, bidRequestId) - return {'REJECTED', rejectCode, bidRequestId, tostring(currentRedisTimestampMS)} + return {'REJECTED', rejectCode, bidRequestId, tostring(currentRedisTimestampMS), rejectedCurrentBidRoundDeadlineTimestampMS} end local phase = redis.call('HGET', liveAuctionStateKey, 'phase') diff --git a/apps/web/src/api/mappers.ts b/apps/web/src/api/mappers.ts index 1c7eece1..911eb540 100644 --- a/apps/web/src/api/mappers.ts +++ b/apps/web/src/api/mappers.ts @@ -135,6 +135,7 @@ export interface AuctionStateView { }[]; currentBid: number; currentBidder: { teamIndex: number } | null; + remainingMs: number; timer: number; maxTimer: number; bidExtensionSeconds: number; @@ -232,10 +233,11 @@ function mapAuctionPlayerToView( player: ApiAuctionPlayerSnapshot, ): AuctionPlayerView { const { mainPosition, subPosition } = resolveMainAndSubPosition( - player.preferredPositions, + player.preferredPositions ?? [], ); const summary = player.recentStatsSummary; const primary = pickPrimary(summary, mainPosition); + const masteries = player.masteries ?? []; return { id: player.userId, @@ -246,9 +248,9 @@ function mapAuctionPlayerToView( tierHistory: player.tierHistory ?? [], mainPosition, subPosition, - profileIconId: player.profileIconId, + profileIconId: player.profileIconId ?? 0, passCount: player.passCount ?? 0, - masteries: player.masteries.slice(0, 5).map((mastery) => ({ + masteries: masteries.slice(0, 5).map((mastery) => ({ championId: mastery.championId, level: mastery.championLevel, points: mastery.championPoints, @@ -530,14 +532,10 @@ export function mapApiAuctionToAuctionState( ) ?? null); const currentPlayerIndex = auction.phase === "complete" ? totalPlayers : currentAuctionPlayerOrderIndex; - const timer = currentBidRoundDeadlineTimestampMS - ? Math.max( - 0, - Math.ceil( - (currentBidRoundDeadlineTimestampMS - now.getTime()) / 1000, - ), - ) + const remainingMs = currentBidRoundDeadlineTimestampMS + ? Math.max(0, currentBidRoundDeadlineTimestampMS - now.getTime()) : 0; + const timer = Math.floor(remainingMs / 1000); return { matchId: auction.matchId, @@ -560,6 +558,7 @@ export function mapApiAuctionToAuctionState( teamIndex: currentBidderTeamIndex, } : null, + remainingMs, timer, maxTimer: maximumBidRoundDurationSeconds, bidExtensionSeconds: bidRoundExtensionSeconds, diff --git a/apps/web/src/api/useAuctionSocket.ts b/apps/web/src/api/useAuctionSocket.ts index ec2dfdb9..b7500686 100644 --- a/apps/web/src/api/useAuctionSocket.ts +++ b/apps/web/src/api/useAuctionSocket.ts @@ -70,7 +70,49 @@ interface BidDeltaPayload { revision?: number; } +interface BidServerTimingPayload { + fallbackFullStatePath?: boolean; + gatewayTotalDurationMS?: number; + redisBidCommandDurationMS?: number; + redisBidContextReadDurationMS?: number; + serviceTotalDurationMS?: number; +} + +interface BidDiagnosticsPayload { + currentBidRoundDeadlineTimestampMS?: number; + currentServerTimestampMS?: number; +} + +interface BidAckPayload { + bidDelta?: BidDeltaPayload | null; + bidDiagnostics?: BidDiagnosticsPayload; + bidServerTiming?: BidServerTimingPayload; + code?: string; + message?: string; + rejected?: boolean; + state?: ApiAuction; +} + +interface TimeSyncAckPayload { + clientSentAtTimestampMS?: number; + currentServerTimestampMS?: number; + ok?: boolean; + rejected?: boolean; + sequence?: number; + serverProcessingDurationMS?: number; +} + +export interface BidLatencyDiagnostics { + bidDiagnostics?: BidDiagnosticsPayload; + bidServerTiming?: BidServerTimingPayload; + clientObservedRemainingBidRoundTimeMS?: number; + serverObservedRemainingBidRoundTimeMS?: number; + serverRoundTripDurationMS?: number; +} + const MAX_CHAT_MESSAGES = 200; +const TIME_SYNC_INTERVAL_MS = 5000; +const TIME_SYNC_TIMEOUT_MS = 3000; function mergeChatMessages( current: ApiAuctionChatMessage[], @@ -95,6 +137,16 @@ export function useAuctionSocket(matchId: string | undefined) { const pendingActionTimeoutsRef = useRef< Record> >({}); + const timeSyncIntervalRef = useRef | null>( + null, + ); + const timeSyncTimeoutsRef = useRef< + Record> + >({}); + const timeSyncSequenceRef = useRef(0); + const hasSyncedServerTimeRef = useRef(false); + const latestAuctionRef = useRef(null); + const latestConfirmedBidPointAmountRef = useRef(0); const [auction, setAuction] = useState(null); const [chatMessages, setChatMessages] = useState([]); const [pendingBidRequests, setPendingBidRequests] = useState< @@ -108,6 +160,153 @@ export function useAuctionSocket(matchId: string | undefined) { useState('idle'); const [error, setError] = useState(null); const [serverTimeOffsetMs, setServerTimeOffsetMs] = useState(0); + const [serverRoundTripMs, setServerRoundTripMs] = useState( + null, + ); + const [bidLatencyDiagnostics, setBidLatencyDiagnostics] = + useState(null); + + function syncLatestConfirmedBidPointAmountFromAuction( + nextAuction: ApiAuction, + ) { + latestConfirmedBidPointAmountRef.current = + resolveCurrentBidPointAmount(nextAuction); + } + + function commitAuctionState(nextAuction: ApiAuction): boolean { + const currentAuction = latestAuctionRef.current; + if (!shouldApplyIncomingAuctionState(currentAuction, nextAuction)) { + return false; + } + + latestAuctionRef.current = nextAuction; + syncLatestConfirmedBidPointAmountFromAuction(nextAuction); + setAuction(nextAuction); + return true; + } + + function commitBidDelta(payload: BidDeltaPayload): boolean { + const currentAuction = latestAuctionRef.current; + const nextAuction = applyBidDelta(currentAuction, payload); + if (!nextAuction || nextAuction === currentAuction) { + return false; + } + + latestAuctionRef.current = nextAuction; + syncLatestConfirmedBidPointAmountFromAuction(nextAuction); + setAuction(nextAuction); + return true; + } + + function applyFallbackServerTimestamp(currentServerTimestampMS?: number) { + if (hasSyncedServerTimeRef.current) return; + if (typeof currentServerTimestampMS !== 'number') return; + setServerTimeOffsetMs(currentServerTimestampMS - Date.now()); + } + + function clearTimeSyncTimers() { + if (timeSyncIntervalRef.current) { + clearInterval(timeSyncIntervalRef.current); + timeSyncIntervalRef.current = null; + } + Object.values(timeSyncTimeoutsRef.current).forEach((timeoutId) => + clearTimeout(timeoutId), + ); + timeSyncTimeoutsRef.current = {}; + } + + function requestServerTimeSync(socket: Socket) { + if (!socket.connected) return; + + const sequence = timeSyncSequenceRef.current + 1; + timeSyncSequenceRef.current = sequence; + const clientSentAtTimestampMS = Date.now(); + + timeSyncTimeoutsRef.current[sequence] = setTimeout(() => { + delete timeSyncTimeoutsRef.current[sequence]; + }, TIME_SYNC_TIMEOUT_MS); + + socket.emit( + 'time-sync', + { clientSentAtTimestampMS, sequence }, + (ack?: TimeSyncAckPayload) => { + const clientReceivedAtTimestampMS = Date.now(); + const timeoutId = timeSyncTimeoutsRef.current[sequence]; + if (!timeoutId) return; + clearTimeout(timeoutId); + delete timeSyncTimeoutsRef.current[sequence]; + + if ( + !ack?.ok || + ack.sequence !== sequence || + typeof ack.currentServerTimestampMS !== 'number' + ) { + return; + } + + const totalRoundTripDurationMS = Math.max( + 0, + clientReceivedAtTimestampMS - clientSentAtTimestampMS, + ); + const serverProcessingDurationMS = Number( + ack.serverProcessingDurationMS, + ); + const estimatedNetworkOneWayDurationMS = + Math.max( + 0, + totalRoundTripDurationMS - + (Number.isFinite(serverProcessingDurationMS) + ? serverProcessingDurationMS + : 0), + ) / 2; + const estimatedServerTimestampAtClientReceiveMS = + ack.currentServerTimestampMS + estimatedNetworkOneWayDurationMS; + + hasSyncedServerTimeRef.current = true; + setServerRoundTripMs(Math.round(totalRoundTripDurationMS)); + setServerTimeOffsetMs( + Math.round( + estimatedServerTimestampAtClientReceiveMS - + clientReceivedAtTimestampMS, + ), + ); + }, + ); + } + + function captureBidLatencyDiagnostics(ack?: BidAckPayload) { + if (!ack?.bidDiagnostics && !ack?.bidServerTiming) return; + + const currentAuction = latestAuctionRef.current; + const currentDeadlineTimestampMS = + currentAuction?.currentBidRoundDeadlineTimestampMS ?? + (currentAuction?.currentDeadline + ? Date.parse(currentAuction.currentDeadline) + : undefined); + const clientObservedRemainingBidRoundTimeMS = + typeof currentDeadlineTimestampMS === 'number' + ? Math.max(0, currentDeadlineTimestampMS - (Date.now() + serverTimeOffsetMs)) + : undefined; + const serverDeadlineTimestampMS = + ack.bidDiagnostics?.currentBidRoundDeadlineTimestampMS ?? + ack.bidDelta?.currentBidRoundDeadlineTimestampMS; + const serverTimestampMS = + ack.bidDiagnostics?.currentServerTimestampMS ?? + ack.bidDelta?.currentServerTimestampMS; + const serverObservedRemainingBidRoundTimeMS = + typeof serverDeadlineTimestampMS === 'number' && + typeof serverTimestampMS === 'number' + ? serverDeadlineTimestampMS - serverTimestampMS + : undefined; + + setBidLatencyDiagnostics({ + bidDiagnostics: ack?.bidDiagnostics, + bidServerTiming: ack?.bidServerTiming, + clientObservedRemainingBidRoundTimeMS, + serverObservedRemainingBidRoundTimeMS, + serverRoundTripDurationMS: serverRoundTripMs ?? undefined, + }); + } useEffect(() => { if (!matchId) { @@ -139,25 +338,33 @@ export function useAuctionSocket(matchId: string | undefined) { socket.on('connect', () => { setConnectionStatus('connected'); socket.emit('join', { matchId }); + requestServerTimeSync(socket); + if (timeSyncIntervalRef.current) { + clearInterval(timeSyncIntervalRef.current); + } + timeSyncIntervalRef.current = setInterval( + () => requestServerTimeSync(socket), + TIME_SYNC_INTERVAL_MS, + ); }); socket.on('disconnect', () => { + clearTimeSyncTimers(); setConnectionStatus('disconnected'); }); socket.on('state', (nextAuction: ApiAuction) => { - setAuction((current) => - shouldApplyIncomingAuctionState(current, nextAuction) - ? nextAuction - : current, - ); - if (typeof nextAuction.currentServerTimestampMS === 'number') { - setServerTimeOffsetMs(nextAuction.currentServerTimestampMS - Date.now()); + const didApplyState = commitAuctionState(nextAuction); + if (didApplyState) { + clearPendingActionRequests(); } + applyFallbackServerTimestamp(nextAuction.currentServerTimestampMS); if (nextAuction.chatMessages) { setChatMessages(mergeChatMessages([], nextAuction.chatMessages)); } - setError(null); + if (didApplyState) { + setError(null); + } }); socket.on('chat-history', (payload: ChatHistoryPayload) => { @@ -169,19 +376,20 @@ export function useAuctionSocket(matchId: string | undefined) { }); socket.on('bid', (payload: BidDeltaPayload) => { - if (typeof payload?.currentServerTimestampMS === 'number') { - setServerTimeOffsetMs(payload.currentServerTimestampMS - Date.now()); - } + applyFallbackServerTimestamp(payload?.currentServerTimestampMS); + const didApplyBidDelta = commitBidDelta(payload); if (payload?.bidRequestId) { - clearPendingBidRequest(payload.bidRequestId); + if ( + didApplyBidDelta || + pendingBidTimeoutsRef.current[payload.bidRequestId] + ) { + clearPendingBidRequest(payload.bidRequestId); + } } - setAuction((current) => applyBidDelta(current, payload)); }); socket.on('match-side-effect', (payload: MatchSideEffectPayload) => { - if (typeof payload?.currentServerTimestampMS === 'number') { - setServerTimeOffsetMs(payload.currentServerTimestampMS - Date.now()); - } + applyFallbackServerTimestamp(payload?.currentServerTimestampMS); if ( !payload?.matchSideEffectStatus || typeof payload.matchSideEffectRevision !== 'number' @@ -191,31 +399,35 @@ export function useAuctionSocket(matchId: string | undefined) { const matchSideEffectRevision = payload.matchSideEffectRevision; const matchSideEffectStatus = payload.matchSideEffectStatus; - setAuction((current) => { - if (!current) return current; - if ( - payload.auctionLifecycleId && - current.auctionLifecycleId && - payload.auctionLifecycleId !== current.auctionLifecycleId - ) { - return current; - } - if ( - matchSideEffectRevision <= - (current.matchSideEffectRevision ?? -1) - ) { - return current; - } - return { - ...current, - matchSideEffectRevision, - matchSideEffectStatus, - }; - }); + const currentAuction = latestAuctionRef.current; + if (!currentAuction) return; + if ( + payload.auctionLifecycleId && + currentAuction.auctionLifecycleId && + payload.auctionLifecycleId !== currentAuction.auctionLifecycleId + ) { + return; + } + if ( + matchSideEffectRevision <= + (currentAuction.matchSideEffectRevision ?? -1) + ) { + return; + } + + const nextAuction = { + ...currentAuction, + matchSideEffectRevision, + matchSideEffectStatus, + }; + latestAuctionRef.current = nextAuction; + setAuction(nextAuction); }); socket.on('reset', (payload: ResetPayload) => { if (payload.matchId && payload.matchId !== matchId) return; + latestAuctionRef.current = null; + latestConfirmedBidPointAmountRef.current = 0; setAuction(null); setChatMessages([]); setResetAt(Date.now()); @@ -223,7 +435,6 @@ export function useAuctionSocket(matchId: string | undefined) { }); socket.on('error', (payload: { message?: string }) => { - setConnectionStatus('error'); setError(payload.message ?? '실시간 경매 연결 중 오류가 발생했습니다.'); }); })(); @@ -234,6 +445,7 @@ export function useAuctionSocket(matchId: string | undefined) { socket?.removeAllListeners(); socket?.disconnect(); socketRef.current = null; + clearTimeSyncTimers(); Object.values(pendingBidTimeoutsRef.current).forEach((timeoutId) => clearTimeout(timeoutId), ); @@ -242,10 +454,15 @@ export function useAuctionSocket(matchId: string | undefined) { ); pendingBidTimeoutsRef.current = {}; pendingActionTimeoutsRef.current = {}; + latestAuctionRef.current = null; + latestConfirmedBidPointAmountRef.current = 0; + hasSyncedServerTimeRef.current = false; setPendingBidRequests({}); setPendingActionRequests({}); setConnectionStatus('idle'); setServerTimeOffsetMs(0); + setServerRoundTripMs(null); + setBidLatencyDiagnostics(null); }; }, [authUserId, matchId]); @@ -271,6 +488,14 @@ export function useAuctionSocket(matchId: string | undefined) { }); } + function clearPendingActionRequests() { + Object.values(pendingActionTimeoutsRef.current).forEach((timeoutId) => + clearTimeout(timeoutId), + ); + pendingActionTimeoutsRef.current = {}; + setPendingActionRequests({}); + } + function emit(eventName: string, payload?: unknown) { const socket = socketRef.current; if (!socket || !socket.connected) { @@ -289,15 +514,16 @@ export function useAuctionSocket(matchId: string | undefined) { } function buildAuctionActionPayload(): AuctionActionPayload { + const currentAuction = latestAuctionRef.current ?? auction; return { auctionActionRequestId: createClientRequestId(), - clientObservedAuctionLifecycleId: auction?.auctionLifecycleId, + clientObservedAuctionLifecycleId: currentAuction?.auctionLifecycleId, clientObservedCurrentAuctionPlayerOrderIndex: - auction?.currentAuctionPlayerOrderIndex, + currentAuction?.currentAuctionPlayerOrderIndex, clientObservedCurrentBidRoundPlayerUserId: - auction?.currentBidRoundPlayerUserId, - clientObservedPhase: auction?.phase, - clientObservedRevision: auction?.revision, + currentAuction?.currentBidRoundPlayerUserId, + clientObservedPhase: currentAuction?.phase, + clientObservedRevision: currentAuction?.revision, }; } @@ -307,6 +533,9 @@ export function useAuctionSocket(matchId: string | undefined) { setError('소켓이 아직 연결되지 않았습니다.'); return; } + if (Object.keys(pendingActionTimeoutsRef.current).length > 0) { + return; + } const auctionActionRequestId = payload.auctionActionRequestId ?? createClientRequestId(); @@ -332,20 +561,19 @@ export function useAuctionSocket(matchId: string | undefined) { rejected?: boolean; state?: ApiAuction; }) => { - clearPendingActionRequest( - ack?.auctionActionRequestId ?? auctionActionRequestId, - ); if (ack?.rejected) { + clearPendingActionRequest( + ack?.auctionActionRequestId ?? auctionActionRequestId, + ); setError(ack.code ?? '경매 진행 상태가 반영되지 않았습니다.'); return; } const ackState = ack?.state; if (ackState) { - setAuction((current) => - shouldApplyIncomingAuctionState(current, ackState) - ? ackState - : current, + clearPendingActionRequest( + ack.auctionActionRequestId ?? auctionActionRequestId, ); + commitAuctionState(ackState); } }, ); @@ -353,9 +581,7 @@ export function useAuctionSocket(matchId: string | undefined) { const currentAuction = auction; const visibleAuction = - currentAuction && currentAuction.matchId === matchId - ? applyPendingBidOverlay(currentAuction, pendingBidRequests) - : null; + currentAuction && currentAuction.matchId === matchId ? currentAuction : null; const visibleConnectionStatus: ConnectionStatus = matchId ? connectionStatus : 'idle'; @@ -370,6 +596,8 @@ export function useAuctionSocket(matchId: string | undefined) { resetAt, connectionStatus: visibleConnectionStatus, error, + bidLatencyDiagnostics, + serverRoundTripMs: matchId ? serverRoundTripMs : null, serverTimeOffsetMs: matchId ? serverTimeOffsetMs : 0, placeBid(payload: BidPayload) { const socket = socketRef.current; @@ -377,17 +605,24 @@ export function useAuctionSocket(matchId: string | undefined) { setError('소켓이 아직 연결되지 않았습니다.'); return; } + if (Object.keys(pendingBidTimeoutsRef.current).length > 0) { + return; + } + if (payload.bidPointAmount <= latestConfirmedBidPointAmountRef.current) { + return; + } const bidRequestId = payload.bidRequestId ?? createClientRequestId(); + const currentAuction = latestAuctionRef.current ?? auction; const bidPayload: BidPayload = { ...payload, bidRequestId, clientObservedAuctionLifecycleId: payload.clientObservedAuctionLifecycleId ?? - auction?.auctionLifecycleId, + currentAuction?.auctionLifecycleId, clientObservedCurrentBidRoundPlayerUserId: payload.clientObservedCurrentBidRoundPlayerUserId ?? - auction?.currentBidRoundPlayerUserId, + currentAuction?.currentBidRoundPlayerUserId, }; setError(null); @@ -405,23 +640,22 @@ export function useAuctionSocket(matchId: string | undefined) { socket.emit( 'bid', bidPayload, - (ack?: { - code?: string; - rejected?: boolean; - state?: ApiAuction; - }) => { - clearPendingBidRequest(bidRequestId); + (ack?: BidAckPayload) => { + captureBidLatencyDiagnostics(ack); if (ack?.rejected) { - setError(ack.code ?? '입찰이 반영되지 않았습니다.'); + clearPendingBidRequest(bidRequestId); + setError(ack.message ?? ack.code ?? '입찰이 반영되지 않았습니다.'); + return; + } + if (ack?.bidDelta) { + clearPendingBidRequest(bidRequestId); + commitBidDelta(ack.bidDelta); return; } const ackState = ack?.state; if (ackState) { - setAuction((current) => - shouldApplyIncomingAuctionState(current, ackState) - ? ackState - : current, - ); + clearPendingBidRequest(bidRequestId); + commitAuctionState(ackState); } }, ); @@ -455,6 +689,15 @@ function createClientRequestId(): string { return `${Date.now()}-${Math.random().toString(16).slice(2)}`; } +function resolveCurrentBidPointAmount(auction: ApiAuction): number { + const bidPointAmount = Math.max( + Number(auction.currentHighestBidPointAmount), + Number(auction.currentBid), + 0, + ); + return Number.isFinite(bidPointAmount) ? bidPointAmount : 0; +} + function shouldApplyIncomingAuctionState( current: ApiAuction | null, incoming: ApiAuction, @@ -594,21 +837,3 @@ function appendUniqueLegacyBidEntry( } return [...currentBids, legacyBid]; } - -function applyPendingBidOverlay( - auction: ApiAuction, - pendingBidRequests: Record, -): ApiAuction { - const pendingBids = Object.values(pendingBidRequests); - const latestPendingBid = pendingBids[pendingBids.length - 1]; - if (!latestPendingBid || latestPendingBid.amount <= (auction.currentBid ?? 0)) { - return auction; - } - return { - ...auction, - currentBid: latestPendingBid.amount, - currentBidderTeamIndex: latestPendingBid.teamIndex, - currentHighestBidPointAmount: latestPendingBid.amount, - currentHighestBidderTeamIndex: latestPendingBid.teamIndex, - }; -} diff --git a/apps/web/src/pages/AuctionPage.tsx b/apps/web/src/pages/AuctionPage.tsx index 7978cecd..982690e1 100644 --- a/apps/web/src/pages/AuctionPage.tsx +++ b/apps/web/src/pages/AuctionPage.tsx @@ -1,5 +1,6 @@ import { lazy, + memo, Suspense, useEffect, useMemo, @@ -26,7 +27,10 @@ import { type AuctionPlayerView, type AuctionStateView, } from '../api/mappers'; -import { useAuctionSocket } from '../api/useAuctionSocket'; +import { + useAuctionSocket, + type BidLatencyDiagnostics, +} from '../api/useAuctionSocket'; import { DEFAULT_COMMUNITY_ID, setDevCaptainTeamIndex, @@ -176,6 +180,53 @@ function getMaxBidForTeam(team: AuctionStateView['teams'][number]) { return Math.max(0, team.points - getReservedPointsAfterCurrentBid(team)); } +function formatLatencyMs(value: number | undefined) { + return typeof value === 'number' && Number.isFinite(value) + ? `${Math.round(value)}ms` + : '-'; +} + +function formatBidLatencyDiagnostics( + diagnostics: BidLatencyDiagnostics | null, +) { + if (!diagnostics) return null; + + const serverDeadlineTimestampMS = + diagnostics.bidDiagnostics?.currentBidRoundDeadlineTimestampMS; + const serverTimestampMS = diagnostics.bidDiagnostics?.currentServerTimestampMS; + const serverRemainingMS = + typeof diagnostics.serverObservedRemainingBidRoundTimeMS === 'number' + ? diagnostics.serverObservedRemainingBidRoundTimeMS + : typeof serverDeadlineTimestampMS === 'number' && + typeof serverTimestampMS === 'number' + ? serverDeadlineTimestampMS - serverTimestampMS + : undefined; + const timing = diagnostics.bidServerTiming; + const parts = [ + `RTT ${formatLatencyMs(diagnostics.serverRoundTripDurationMS)}`, + `gateway ${formatLatencyMs(timing?.gatewayTotalDurationMS)}`, + `service ${formatLatencyMs(timing?.serviceTotalDurationMS)}`, + `redis ${formatLatencyMs(timing?.redisBidCommandDurationMS)}`, + `context ${formatLatencyMs(timing?.redisBidContextReadDurationMS)}`, + ]; + + if (timing?.fallbackFullStatePath) { + parts.push('fallback full-state'); + } + if (typeof diagnostics.clientObservedRemainingBidRoundTimeMS === 'number') { + parts.push( + `client-left ${formatLatencyMs( + diagnostics.clientObservedRemainingBidRoundTimeMS, + )}`, + ); + } + if (typeof serverRemainingMS === 'number') { + parts.push(`server-left ${formatLatencyMs(serverRemainingMS)}`); + } + + return parts.join(' · '); +} + function getSoloTierHistory(entries: ApiTierHistoryEntry[]) { return entries.filter((entry) => entry.queueType === 'RANKED_SOLO_5x5'); } @@ -196,7 +247,7 @@ function TimerBar({ timer, maxTimer }: { timer: number; maxTimer: number }) { return (
@@ -426,6 +477,8 @@ function TeamPanel({ ); } +const MemoTeamPanel = memo(TeamPanel); + function PlayerSpotlight({ state, historyBackTo, @@ -433,24 +486,52 @@ function PlayerSpotlight({ state: AuctionStateView; historyBackTo: string; }) { - const { data: ddragon } = useDdragonManifest(); const player = state.currentPlayer; - const snapshotSoloTierHistory = player - ? getSoloTierHistory(player.tierHistory) - : []; - const historyProfileQuery = useUserHistoryProfile( - player?.userId, - DEFAULT_COMMUNITY_ID, - Boolean(player && snapshotSoloTierHistory.length === 0), - ); if (!player) return null; + + return ( +
+ + +
+ ); +} + +const MemoPlayerSpotlight = memo( + PlayerSpotlight, + (previous, next) => + previous.historyBackTo === next.historyBackTo && + areSameAuctionPlayerProfile( + previous.state.currentPlayer, + next.state.currentPlayer, + ) && + previous.state.phase === next.state.phase && + previous.state.currentBid === next.state.currentBid && + previous.state.currentBidder?.teamIndex === next.state.currentBidder?.teamIndex && + previous.state.auctionRound === next.state.auctionRound, +); + +function PlayerProfileDetails({ + player, + historyBackTo, +}: { + player: NonNullable; + historyBackTo: string; +}) { + const { data: ddragon } = useDdragonManifest(); + const snapshotSoloTierHistory = getSoloTierHistory(player.tierHistory); + const historyProfileQuery = useUserHistoryProfile( + player.userId, + DEFAULT_COMMUNITY_ID, + snapshotSoloTierHistory.length === 0, + ); const tierHistory = snapshotSoloTierHistory.length > 0 ? snapshotSoloTierHistory : getSoloTierHistory(historyProfileQuery.data?.tierHistory ?? []); return ( -
+ <>
+ + ); +} +const MemoPlayerProfileDetails = memo( + PlayerProfileDetails, + (previous, next) => + areSameAuctionPlayerProfile(previous.player, next.player) && + previous.historyBackTo === next.historyBackTo, +); + +function areSameAuctionPlayerProfile( + previous: AuctionPlayerView | null, + next: AuctionPlayerView | null, +) { + if (previous === next) return true; + if (!previous || !next) return false; + return ( + previous.userId === next.userId && + previous.summonerName === next.summonerName && + previous.tag === next.tag && + previous.mainPosition === next.mainPosition && + previous.subPosition === next.subPosition && + previous.profileIconId === next.profileIconId && + previous.passCount === next.passCount && + JSON.stringify(previous.tier) === JSON.stringify(next.tier) && + JSON.stringify(previous.tierHistory) === JSON.stringify(next.tierHistory) && + JSON.stringify(previous.masteries) === JSON.stringify(next.masteries) && + JSON.stringify(previous.recentStats) === JSON.stringify(next.recentStats) + ); +} + +function PlayerBidStatus({ state }: { state: AuctionStateView }) { + return ( + <> {(state.phase === 'bidding' || state.phase === 'sold') && (
@@ -589,7 +704,7 @@ function PlayerSpotlight({
)} -
+ ); } @@ -616,6 +731,10 @@ function BidControls({ : 0; const maxBid = activeTeam ? getMaxBidForTeam(activeTeam) : 0; const canAffordNextBid = !isActiveTeamFull && maxBid >= minBid; + const isBidExpired = state.remainingMs <= 0; + const effectiveBidAmount = activeTeam + ? Math.min(maxBid, Math.max(minBid, bidAmount)) + : Math.max(minBid, bidAmount); useEffect(() => { const nextBid = Math.max(minBid, Math.ceil(minBid / 10) * 10); @@ -692,12 +811,13 @@ function BidControls({ />
); @@ -752,6 +874,8 @@ function BidLog({ bids }: { bids: AuctionStateView['bids'] }) { ); } +const MemoBidLog = memo(BidLog); + export default function AuctionPage() { const { id } = useParams(); const location = useLocation(); @@ -814,7 +938,7 @@ export default function AuctionPage() { } useEffect(() => { - const timer = window.setInterval(() => setNow(Date.now()), 1000); + const timer = window.setInterval(() => setNow(Date.now()), 250); return () => window.clearInterval(timer); }, []); @@ -825,14 +949,28 @@ export default function AuctionPage() { const liveAuction = pickLatestAuction(socket.auction, auctionQuery.data); const syncedNow = now + socket.serverTimeOffsetMs; - const auctionState = - liveAuction && matchQuery.data - ? mapApiAuctionToAuctionState( - liveAuction, - matchQuery.data, - new Date(syncedNow), - ) - : null; + const baseAuctionState = useMemo( + () => + liveAuction && matchQuery.data + ? mapApiAuctionToAuctionState(liveAuction, matchQuery.data) + : null, + [liveAuction, matchQuery.data], + ); + const auctionState = useMemo(() => { + if (!baseAuctionState) return null; + const deadlineTimestampMS = baseAuctionState.deadline + ? Date.parse(baseAuctionState.deadline) + : undefined; + const remainingMs = + typeof deadlineTimestampMS === 'number' && Number.isFinite(deadlineTimestampMS) + ? Math.max(0, deadlineTimestampMS - syncedNow) + : 0; + return { + ...baseAuctionState, + remainingMs, + timer: Math.floor(remainingMs / 1000), + }; + }, [baseAuctionState, syncedNow]); const availableTeamIndexes = useMemo(() => { const indexes = new Set((auctionState?.teams ?? []).map((team) => team.teamIndex)); return [...indexes].sort((left, right) => left - right); @@ -915,6 +1053,9 @@ export default function AuctionPage() { const errorMessage = socket.error ?? (auctionQuery.error instanceof Error ? auctionQuery.error.message : null); + const bidLatencyMessage = formatBidLatencyDiagnostics( + socket.bidLatencyDiagnostics, + ); const matchSideEffectMessage = resolveMatchSideEffectMessage( auctionState.matchSideEffectStatus, ); @@ -1040,6 +1181,12 @@ export default function AuctionPage() {
)} + {import.meta.env.DEV && canManageAuction && bidLatencyMessage && ( +
+ 입찰 계측 · {bidLatencyMessage} +
+ )} + {undoMutation.error instanceof Error && (
{undoMutation.error.message} @@ -1116,12 +1263,12 @@ export default function AuctionPage() {
{auctionState.teams.map((team) => ( - ) : ( <> - @@ -1184,7 +1331,7 @@ export default function AuctionPage() { }) } /> - + {canManageAuction && (
@@ -1470,6 +1617,17 @@ function PoolPanel({ state }: { state: AuctionStateView }) { ); } +const MemoPoolPanel = memo( + PoolPanel, + (previous, next) => + previous.state.phase === next.state.phase && + previous.state.currentPlayerIndex === next.state.currentPlayerIndex && + previous.state.currentPlayer?.userId === next.state.currentPlayer?.userId && + previous.state.auctionOrder === next.state.auctionOrder && + previous.state.passedQueue === next.state.passedQueue && + previous.state.teams === next.state.teams, +); + function PoolTabButton({ label, count,