Improve auction realtime bid responsiveness

This commit is contained in:
dahyeon committed 2026-06-23 09:46:38 -07:00
1 parent c6f5a7077f
commit b367328df0
16 files changed
+1364 -203

No files matched your search

@@ -2,6 +2,7 @@ import { Injectable } from '@nestjs/common';
import type { Namespace } from 'socket.io'; import type { Namespace } from 'socket.io';
import type { AuctionStateResponse } from './auction.service'; import type { AuctionStateResponse } from './auction.service';
import type { MatchSideEffectDelta } from './auction-side-effect.service'; import type { MatchSideEffectDelta } from './auction-side-effect.service';
import { serializeRealtimeAuction } from './auction-realtime-serializer';
@Injectable() @Injectable()
export class AuctionEventBusService { export class AuctionEventBusService {
@@ -21,7 +22,7 @@ export class AuctionEventBusService {
public broadcastState(matchId: string, state: AuctionStateResponse): void { public broadcastState(matchId: string, state: AuctionStateResponse): void {
this.auctionNamespace?.to(matchId).emit( this.auctionNamespace?.to(matchId).emit(
'state', 'state',
JSON.parse(JSON.stringify(state)), serializeRealtimeAuction(state),
); );
} }
} }
@@ -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<string, unknown>,
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<Record<string, unknown>> {
return Array.isArray(value)
? value.filter(
(item): item is Record<string, unknown> =>
typeof item === 'object' && item !== null,
)
: [];
}
function getStringField(
value: Record<string, unknown> | undefined,
fieldName: string,
): string | undefined {
const fieldValue = value?.[fieldName];
return typeof fieldValue === 'string' ? fieldValue : undefined;
}
@@ -8,10 +8,16 @@ import { AuctionGateway } from './auction.gateway';
describe('AuctionGateway', () => { describe('AuctionGateway', () => {
function createGateway(params?: { function createGateway(params?: {
placeBid?: jest.Mock; getCurrentRedisTimestampMS?: jest.Mock;
placeBidDelta?: jest.Mock;
}) { }) {
const auctionService = { 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( const gateway = new AuctionGateway(
auctionService as never, auctionService as never,
@@ -20,6 +26,7 @@ describe('AuctionGateway', () => {
{ findOrCreateByOid: jest.fn() } as never, { findOrCreateByOid: jest.fn() } as never,
{ getModel: jest.fn() } as never, { getModel: jest.fn() } as never,
{ attachAuctionNamespace: jest.fn() } as never, { attachAuctionNamespace: jest.fn() } as never,
auctionRedisService as never,
); );
const emit = jest.fn(); const emit = jest.fn();
const to = jest.fn().mockReturnValue({ emit }); const to = jest.fn().mockReturnValue({ emit });
@@ -29,6 +36,7 @@ describe('AuctionGateway', () => {
auctionService, auctionService,
emit, emit,
gateway, gateway,
auctionRedisService,
to, to,
}; };
} }
@@ -41,8 +49,8 @@ describe('AuctionGateway', () => {
bidPlacedAtTimestampMS: 1780000000000, bidPlacedAtTimestampMS: 1780000000000,
bidPointAmount: 120, bidPointAmount: 120,
}; };
const placeBid = jest.fn().mockResolvedValue({ const placeBidDelta = jest.fn().mockResolvedValue({
auctionBidHistory: [auctionBidHistoryEntry], auctionBidHistoryEntry,
auctionLifecycleId: 'life-1', auctionLifecycleId: 'life-1',
currentBidRoundDeadlineTimestampMS: 1780000030000, currentBidRoundDeadlineTimestampMS: 1780000030000,
currentHighestBidderTeamIndex: 2, currentHighestBidderTeamIndex: 2,
@@ -50,7 +58,7 @@ describe('AuctionGateway', () => {
currentServerTimestampMS: 1780000000000, currentServerTimestampMS: 1780000000000,
revision: 9, revision: 9,
}); });
const { emit, gateway, to } = createGateway({ placeBid }); const { emit, gateway, to } = createGateway({ placeBidDelta });
const ack = jest.fn(); const ack = jest.fn();
await gateway.handleBid( await gateway.handleBid(
@@ -65,7 +73,7 @@ describe('AuctionGateway', () => {
ack, ack,
); );
expect(placeBid).toHaveBeenCalledWith({ expect(placeBidDelta).toHaveBeenCalledWith({
amount: 120, amount: 120,
bidRequestId: 'bid-1', bidRequestId: 'bid-1',
clientObservedAuctionLifecycleId: 'life-1', clientObservedAuctionLifecycleId: 'life-1',
@@ -84,31 +92,40 @@ describe('AuctionGateway', () => {
currentServerTimestampMS: 1780000000000, currentServerTimestampMS: 1780000000000,
revision: 9, revision: 9,
}); });
expect(ack).toHaveBeenCalledWith({ expect(ack).toHaveBeenCalledWith(
bidRequestId: 'bid-1', expect.objectContaining({
ok: true, bidDelta: {
state: expect.objectContaining({ auctionBidHistoryEntry,
auctionLifecycleId: 'life-1', auctionLifecycleId: 'life-1',
revision: 9, 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 () => { it('generates one bid request id when the client omits it', async () => {
const matchId = new mongoose.Types.ObjectId().toString(); const matchId = new mongoose.Types.ObjectId().toString();
const placeBid = jest.fn().mockResolvedValue({ const placeBidDelta = jest.fn().mockResolvedValue({
auctionBidHistory: [ auctionBidHistoryEntry: {
{ bidderTeamIndex: 1,
bidderTeamIndex: 1, bidPointAmount: 50,
bidPointAmount: 50, },
},
],
auctionLifecycleId: 'life-1', auctionLifecycleId: 'life-1',
currentHighestBidderTeamIndex: 1, currentHighestBidderTeamIndex: 1,
currentHighestBidPointAmount: 50, currentHighestBidPointAmount: 50,
revision: 3, revision: 3,
}); });
const { emit, gateway } = createGateway({ placeBid }); const { emit, gateway } = createGateway({ placeBidDelta });
const ack = jest.fn(); const ack = jest.fn();
await gateway.handleBid( await gateway.handleBid(
@@ -120,7 +137,7 @@ describe('AuctionGateway', () => {
ack, 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).toEqual(expect.any(String));
expect(generatedBidRequestId).not.toHaveLength(0); expect(generatedBidRequestId).not.toHaveLength(0);
expect(emit).toHaveBeenCalledWith( expect(emit).toHaveBeenCalledWith(
@@ -139,9 +156,23 @@ describe('AuctionGateway', () => {
it('acknowledges bid failures with the request id used for the attempt', async () => { it('acknowledges bid failures with the request id used for the attempt', async () => {
const matchId = new mongoose.Types.ObjectId().toString(); 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 socketEmit = jest.fn();
const { gateway } = createGateway({ placeBid }); const { gateway } = createGateway({ placeBidDelta });
const ack = jest.fn(); const ack = jest.fn();
await gateway.handleBid( await gateway.handleBid(
@@ -155,32 +186,69 @@ describe('AuctionGateway', () => {
); );
expect(socketEmit).toHaveBeenCalledWith('error', { expect(socketEmit).toHaveBeenCalledWith('error', {
message: 'Bid failed', message: 'Bid deadline has already expired.',
});
expect(ack).toHaveBeenCalledWith({
bidRequestId: 'bid-1',
code: 'Bid failed',
rejected: true,
}); });
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 () => { it('rate limits excessive bid requests from the same socket', async () => {
jest.spyOn(Date, 'now').mockReturnValue(1780000000000); jest.spyOn(Date, 'now').mockReturnValue(1780000000000);
const matchId = new mongoose.Types.ObjectId().toString(); const matchId = new mongoose.Types.ObjectId().toString();
const placeBid = jest.fn().mockResolvedValue({ const placeBidDelta = jest.fn().mockResolvedValue({
auctionBidHistory: [ auctionBidHistoryEntry: {
{ bidderTeamIndex: 1,
bidderTeamIndex: 1, bidPointAmount: 50,
bidPointAmount: 50, },
},
],
currentHighestBidderTeamIndex: 1, currentHighestBidderTeamIndex: 1,
currentHighestBidPointAmount: 50, currentHighestBidPointAmount: 50,
revision: 3, revision: 3,
}); });
const socketEmit = jest.fn(); const socketEmit = jest.fn();
const socket = { data: { matchId }, emit: socketEmit }; const socket = { data: { matchId }, emit: socketEmit };
const { gateway } = createGateway({ placeBid }); const { gateway } = createGateway({ placeBidDelta });
const acknowledgements: Array<Record<string, unknown>> = []; const acknowledgements: Array<Record<string, unknown>> = [];
for (let index = 0; index < 9; index += 1) { 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', { expect(socketEmit).toHaveBeenCalledWith('error', {
message: '입찰 요청이 너무 많습니다. 잠시 후 다시 시도해주세요.', message: '입찰 요청이 너무 많습니다. 잠시 후 다시 시도해주세요.',
}); });
@@ -211,19 +279,17 @@ describe('AuctionGateway', () => {
const nowSpy = jest.spyOn(Date, 'now'); const nowSpy = jest.spyOn(Date, 'now');
nowSpy.mockReturnValue(1780000000000); nowSpy.mockReturnValue(1780000000000);
const matchId = new mongoose.Types.ObjectId().toString(); const matchId = new mongoose.Types.ObjectId().toString();
const placeBid = jest.fn().mockResolvedValue({ const placeBidDelta = jest.fn().mockResolvedValue({
auctionBidHistory: [ auctionBidHistoryEntry: {
{ bidderTeamIndex: 1,
bidderTeamIndex: 1, bidPointAmount: 50,
bidPointAmount: 50, },
},
],
currentHighestBidderTeamIndex: 1, currentHighestBidderTeamIndex: 1,
currentHighestBidPointAmount: 50, currentHighestBidPointAmount: 50,
revision: 3, revision: 3,
}); });
const socket = { data: { matchId }, emit: jest.fn() }; const socket = { data: { matchId }, emit: jest.fn() };
const { gateway } = createGateway({ placeBid }); const { gateway } = createGateway({ placeBidDelta });
for (let index = 0; index < 8; index += 1) { for (let index = 0; index < 8; index += 1) {
await gateway.handleBid( await gateway.handleBid(
@@ -248,6 +314,6 @@ describe('AuctionGateway', () => {
jest.fn(), jest.fn(),
); );
expect(placeBid).toHaveBeenCalledTimes(9); expect(placeBidDelta).toHaveBeenCalledTimes(9);
}); });
}); });
+158 -24
View File
@@ -1,5 +1,6 @@
import { Logger } from '@nestjs/common'; import { Logger } from '@nestjs/common';
import { randomUUID } from 'crypto'; import { randomUUID } from 'crypto';
import { performance } from 'perf_hooks';
import { import {
Ack, Ack,
ConnectedSocket, ConnectedSocket,
@@ -25,9 +26,14 @@ import type {
UserDocument, UserDocument,
} from '../global/database/schema'; } from '../global/database/schema';
import { AuctionService } from './auction.service'; 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 { AuctionEventBusService } from './auction-event-bus.service';
import type { MatchSideEffectDelta } from './auction-side-effect.service'; import type { MatchSideEffectDelta } from './auction-side-effect.service';
import { serializeRealtimeAuction } from './auction-realtime-serializer';
import { AuctionRedisService } from './redis/auction-redis.service';
interface JoinAuctionPayload { interface JoinAuctionPayload {
matchId: string; matchId: string;
@@ -41,6 +47,11 @@ interface BidPayload {
clientObservedCurrentBidRoundPlayerUserId?: string; clientObservedCurrentBidRoundPlayerUserId?: string;
} }
interface TimeSyncPayload {
clientSentAtTimestampMS?: number;
sequence?: number;
}
interface SoldPayload { interface SoldPayload {
auctionActionRequestId?: string; auctionActionRequestId?: string;
assignedPosition?: Position; assignedPosition?: Position;
@@ -92,6 +103,7 @@ export class AuctionGateway
private readonly identityService: IdentityService, private readonly identityService: IdentityService,
private readonly connectionService: ConnectionService, private readonly connectionService: ConnectionService,
private readonly auctionEventBusService: AuctionEventBusService, private readonly auctionEventBusService: AuctionEventBusService,
private readonly auctionRedisService: AuctionRedisService,
) {} ) {}
public afterInit(server: Namespace): void { public afterInit(server: Namespace): void {
@@ -146,6 +158,7 @@ export class AuctionGateway
@MessageBody() payload: BidPayload, @MessageBody() payload: BidPayload,
@Ack() ack?: (response: Record<string, unknown>) => void, @Ack() ack?: (response: Record<string, unknown>) => void,
) { ) {
const gatewayBidStartedAtMS = performance.now();
const matchId = this.requireJoinedMatchId(socket); const matchId = this.requireJoinedMatchId(socket);
if (!matchId) return; if (!matchId) return;
@@ -162,7 +175,7 @@ export class AuctionGateway
} }
try { try {
const auction = await this.auctionService.placeBid({ const bidResult = await this.auctionService.placeBidDelta({
matchId: new mongoose.Types.ObjectId(matchId), matchId: new mongoose.Types.ObjectId(matchId),
teamIndex: payload.bidderTeamIndex, teamIndex: payload.bidderTeamIndex,
amount: payload.bidPointAmount, amount: payload.bidPointAmount,
@@ -172,30 +185,75 @@ export class AuctionGateway
clientObservedCurrentBidRoundPlayerUserId: clientObservedCurrentBidRoundPlayerUserId:
payload.clientObservedCurrentBidRoundPlayerUserId, payload.clientObservedCurrentBidRoundPlayerUserId,
}); });
const bidDelta = this.buildBidDeltaFromAuctionState( const bidDelta = this.isBidDeltaResponse(bidResult)
auction, ? {
bidRequestId, ...bidResult,
); bidRequestId: bidResult.bidRequestId ?? bidRequestId,
if (bidDelta) { }
this.broadcastBid(matchId, bidDelta); : this.buildBidDeltaFromAuctionState(bidResult, bidRequestId);
const bidServerTiming = this.extractBidServerTiming(bidDelta);
const broadcastBidDelta = this.stripBidServerTiming(bidDelta);
if (broadcastBidDelta) {
this.broadcastBid(matchId, broadcastBidDelta);
} else { } else {
this.broadcastState(matchId, auction); this.broadcastState(matchId, bidResult as AuctionStateResponse);
} }
ack?.({ ack?.({
...(bidDelta
? {}
: { state: this.serializeAuction(bidResult as AuctionStateResponse) }),
ok: true, ok: true,
bidRequestId, bidRequestId,
state: this.serializeAuction(auction), bidDelta: broadcastBidDelta,
bidServerTiming: this.buildGatewayBidTiming(
gatewayBidStartedAtMS,
bidServerTiming,
),
}); });
} catch (error) { } catch (error) {
this.emitKnownError(socket, error); const errorPayload = this.resolveErrorPayload(error);
const bidServerTiming = this.extractBidServerTiming(errorPayload);
this.emitError(socket, errorPayload.message);
ack?.({ ack?.({
...errorPayload,
bidRequestId, bidRequestId,
code: error instanceof Error ? error.message : 'UNKNOWN', bidServerTiming: this.buildGatewayBidTiming(
gatewayBidStartedAtMS,
bidServerTiming,
),
rejected: true, rejected: true,
}); });
} }
} }
@SubscribeMessage('time-sync')
public async handleTimeSync(
@MessageBody() payload: TimeSyncPayload,
@Ack() ack?: (response: Record<string, unknown>) => 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') @SubscribeMessage('open-bidding')
public async handleOpenBidding( public async handleOpenBidding(
@ConnectedSocket() socket: Socket, @ConnectedSocket() socket: Socket,
@@ -208,13 +266,12 @@ export class AuctionGateway
try { try {
const auction = await this.auctionService.openBidding( const auction = await this.auctionService.openBidding(
new mongoose.Types.ObjectId(matchId), new mongoose.Types.ObjectId(matchId),
this.toAuctionActionRequest(payload), this.toSocketAuctionActionRequest(payload),
); );
this.broadcastState(matchId, auction); this.broadcastState(matchId, auction);
ack?.({ ack?.({
auctionActionRequestId: payload?.auctionActionRequestId, auctionActionRequestId: payload?.auctionActionRequestId,
ok: true, ok: true,
state: this.serializeAuction(auction),
}); });
} catch (error) { } catch (error) {
this.emitKnownError(socket, error); this.emitKnownError(socket, error);
@@ -239,13 +296,12 @@ export class AuctionGateway
const auction = await this.auctionService.markSold({ const auction = await this.auctionService.markSold({
matchId: new mongoose.Types.ObjectId(matchId), matchId: new mongoose.Types.ObjectId(matchId),
assignedPosition: payload?.assignedPosition, assignedPosition: payload?.assignedPosition,
...this.toAuctionActionRequest(payload), ...this.toSocketAuctionActionRequest(payload),
}); });
this.broadcastState(matchId, auction); this.broadcastState(matchId, auction);
ack?.({ ack?.({
auctionActionRequestId: payload?.auctionActionRequestId, auctionActionRequestId: payload?.auctionActionRequestId,
ok: true, ok: true,
state: this.serializeAuction(auction),
}); });
} catch (error) { } catch (error) {
this.emitKnownError(socket, error); this.emitKnownError(socket, error);
@@ -269,13 +325,12 @@ export class AuctionGateway
try { try {
const auction = await this.auctionService.next( const auction = await this.auctionService.next(
new mongoose.Types.ObjectId(matchId), new mongoose.Types.ObjectId(matchId),
this.toAuctionActionRequest(payload), this.toSocketAuctionActionRequest(payload),
); );
this.broadcastState(matchId, auction); this.broadcastState(matchId, auction);
ack?.({ ack?.({
auctionActionRequestId: payload?.auctionActionRequestId, auctionActionRequestId: payload?.auctionActionRequestId,
ok: true, ok: true,
state: this.serializeAuction(auction),
}); });
} catch (error) { } catch (error) {
this.emitKnownError(socket, error); this.emitKnownError(socket, error);
@@ -299,13 +354,12 @@ export class AuctionGateway
try { try {
const auction = await this.auctionService.markPassed( const auction = await this.auctionService.markPassed(
new mongoose.Types.ObjectId(matchId), new mongoose.Types.ObjectId(matchId),
this.toAuctionActionRequest(payload), this.toSocketAuctionActionRequest(payload),
); );
this.broadcastState(matchId, auction); this.broadcastState(matchId, auction);
ack?.({ ack?.({
auctionActionRequestId: payload?.auctionActionRequestId, auctionActionRequestId: payload?.auctionActionRequestId,
ok: true, ok: true,
state: this.serializeAuction(auction),
}); });
} catch (error) { } catch (error) {
this.emitKnownError(socket, 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 { private readHandshakeUserId(socket: Socket): string | undefined {
const authUserId = socket.handshake.auth['x-auth-user-id']; const authUserId = socket.handshake.auth['x-auth-user-id'];
if (typeof authUserId === 'string') return authUserId; if (typeof authUserId === 'string') return authUserId;
@@ -509,7 +570,7 @@ export class AuctionGateway
} }
public broadcastState(matchId: string, auction: AuctionStateResponse) { 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<string, unknown>) { public broadcastBid(matchId: string, delta: Record<string, unknown>) {
@@ -536,9 +597,7 @@ export class AuctionGateway
} }
private emitKnownError(socket: Socket, error: unknown) { private emitKnownError(socket: Socket, error: unknown) {
const message = this.emitError(socket, this.resolveErrorPayload(error).message);
error instanceof Error ? error.message : 'Unexpected auction gateway error.';
this.emitError(socket, message);
} }
private emitError(socket: Socket, message: string) { private emitError(socket: Socket, message: string) {
@@ -549,6 +608,68 @@ export class AuctionGateway
return JSON.parse(JSON.stringify(auction)); return JSON.parse(JSON.stringify(auction));
} }
private resolveErrorPayload(error: unknown): Record<string, unknown> & {
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<string, unknown>;
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<string, unknown>,
): Record<string, unknown> {
return {
...(bidServerTiming ?? {}),
gatewayTotalDurationMS:
Math.round((performance.now() - gatewayBidStartedAtMS) * 10) / 10,
};
}
private extractBidServerTiming(
bidDelta: Record<string, unknown> | null,
): Record<string, unknown> | undefined {
const timing = bidDelta?.bidServerTiming;
return typeof timing === 'object' && timing !== null
? (timing as Record<string, unknown>)
: undefined;
}
private stripBidServerTiming(
bidDelta: Record<string, unknown> | null,
): Record<string, unknown> | null {
if (!bidDelta || !('bidServerTiming' in bidDelta)) return bidDelta;
const { bidServerTiming: _bidServerTiming, ...publicBidDelta } = bidDelta;
return publicBidDelta;
}
private buildBidDeltaFromAuctionState( private buildBidDeltaFromAuctionState(
auction: AuctionStateResponse, auction: AuctionStateResponse,
bidRequestId?: string, 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( private convertLegacyBidToRedisBidHistoryEntry(
bid: unknown, bid: unknown,
): Record<string, unknown> | null { ): Record<string, unknown> | null {
@@ -91,6 +91,7 @@ describe('AuctionService', () => {
auctionLifecycleId: 'life-1', auctionLifecycleId: 'life-1',
revision: 1, revision: 1,
}), }),
readBidContext: jest.fn().mockResolvedValue(null),
readAuctionStateView: 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 () => { it('syncs match teams when a redis-v1 auction completes', async () => {
const matchId = new mongoose.Types.ObjectId(); const matchId = new mongoose.Types.ObjectId();
const captainUserId = new mongoose.Types.ObjectId(); const captainUserId = new mongoose.Types.ObjectId();
+230 -4
View File
@@ -6,6 +6,7 @@ import {
NotFoundException, NotFoundException,
} from '@nestjs/common'; } from '@nestjs/common';
import { randomUUID } from 'crypto'; import { randomUUID } from 'crypto';
import { performance } from 'perf_hooks';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service'; import { ConnectionService } from '../global/database/connection.service';
import { import {
@@ -25,7 +26,10 @@ import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.se
import type { RiotPlatformRoute, RiotRegionalRoute } from '../riot/riot.types'; import type { RiotPlatformRoute, RiotRegionalRoute } from '../riot/riot.types';
import { TournamentCodeService } from '../tournament-code/tournament-code.service'; import { TournamentCodeService } from '../tournament-code/tournament-code.service';
import { TournamentResultService } from '../tournament-result/tournament-result.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 { buildAuctionRedisKeys } from './redis/auction-redis.keys';
import { import {
buildAuctionRedisLiveStatePatchFromStructure, buildAuctionRedisLiveStatePatchFromStructure,
@@ -87,6 +91,7 @@ interface AuctionStructureActionRequestParams {
clientObservedCurrentBidRoundPlayerUserId?: string; clientObservedCurrentBidRoundPlayerUserId?: string;
clientObservedPhase?: string; clientObservedPhase?: string;
clientObservedRevision?: number; clientObservedRevision?: number;
shouldBroadcastStateAfterDurability?: boolean;
} }
interface MarkSoldParams extends AuctionStructureActionRequestParams { interface MarkSoldParams extends AuctionStructureActionRequestParams {
@@ -136,6 +141,30 @@ export interface AuctionHistoryView {
export type AuctionStateResponse = AuctionDocument | Record<string, unknown>; export type AuctionStateResponse = AuctionDocument | Record<string, unknown>;
export interface AuctionBidDeltaResponse {
auctionBidHistoryEntry: Record<string, unknown>;
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 { interface AuctionEnrichmentTarget {
userId: mongoose.Types.ObjectId; userId: mongoose.Types.ObjectId;
puuid: string; puuid: string;
@@ -591,6 +620,23 @@ export class AuctionService {
return auction; return auction;
} }
public async placeBidDelta(
params: PlaceBidParams,
): Promise<AuctionBidDeltaResponse | AuctionStateResponse> {
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( private async openRedisBidding(
auction: AuctionDocument, auction: AuctionDocument,
actionRequestParams: AuctionStructureActionRequestParams, actionRequestParams: AuctionStructureActionRequestParams,
@@ -627,6 +673,8 @@ export class AuctionService {
}, },
expectedPhase: 'presenting', expectedPhase: 'presenting',
liveStatePatch, liveStatePatch,
shouldBroadcastStateAfterDurability:
actionRequestParams.shouldBroadcastStateAfterDurability,
state, state,
structureInput, structureInput,
}); });
@@ -636,6 +684,110 @@ export class AuctionService {
auction: AuctionDocument, auction: AuctionDocument,
params: PlaceBidParams, params: PlaceBidParams,
): Promise<AuctionStateResponse> { ): Promise<AuctionStateResponse> {
const matchId = auction.matchId.toString();
await this.executeRedisBid(auction, params);
return this.requireRedisAuctionState(matchId);
}
private async placeRedisBidDelta(
auction: AuctionDocument,
params: PlaceBidParams,
): Promise<AuctionBidDeltaResponse> {
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<AuctionBidDeltaResponse | null> {
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<AuctionBidCommandResult, { ok: true }>;
state: Record<string, unknown>;
}> {
const serviceStartedAtMS = performance.now();
const matchId = auction.matchId.toString(); const matchId = auction.matchId.toString();
const state = await this.requireRedisAuctionState(matchId); const state = await this.requireRedisAuctionState(matchId);
if (state.phase !== 'bidding') { if (state.phase !== 'bidding') {
@@ -660,6 +812,7 @@ export class AuctionService {
throw new BadRequestException('Current bid round is not available.'); throw new BadRequestException('Current bid round is not available.');
} }
const redisBidCommandStartedAtMS = performance.now();
const result = await this.auctionRedisCommandService.placeBid(matchId, { const result = await this.auctionRedisCommandService.placeBid(matchId, {
bidPointAmount: params.amount, bidPointAmount: params.amount,
bidderTeamIndex: params.teamIndex, bidderTeamIndex: params.teamIndex,
@@ -677,11 +830,36 @@ export class AuctionService {
minimumBidRequestResultReplayWindowMS: minimumBidRequestResultReplayWindowMS:
AUCTION_BID_REQUEST_REPLAY_WINDOW_MS, AUCTION_BID_REQUEST_REPLAY_WINDOW_MS,
}); });
const redisBidCommandDurationMS =
performance.now() - redisBidCommandStartedAtMS;
if ('rejected' in result) { 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<string, unknown>,
result: Extract<AuctionBidCommandResult, { ok: true }>,
): 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( private async markRedisSold(
@@ -749,6 +927,8 @@ export class AuctionService {
...buildAuctionRedisLiveStatePatchFromStructure(structureInput), ...buildAuctionRedisLiveStatePatchFromStructure(structureInput),
phase: 'sold', phase: 'sold',
}, },
shouldBroadcastStateAfterDurability:
params.shouldBroadcastStateAfterDurability,
state, state,
structureInput, structureInput,
}); });
@@ -806,6 +986,8 @@ export class AuctionService {
...buildAuctionRedisLiveStatePatchFromStructure(structureInput), ...buildAuctionRedisLiveStatePatchFromStructure(structureInput),
phase: 'passed', phase: 'passed',
}, },
shouldBroadcastStateAfterDurability:
actionRequestParams.shouldBroadcastStateAfterDurability,
state, state,
structureInput, structureInput,
}); });
@@ -972,6 +1154,8 @@ export class AuctionService {
currentHighestBidderTeamIndex: -1, currentHighestBidderTeamIndex: -1,
phase: nextPhase, phase: nextPhase,
}, },
shouldBroadcastStateAfterDurability:
actionRequestParams.shouldBroadcastStateAfterDurability,
state, state,
structureInput, structureInput,
}); });
@@ -1445,6 +1629,7 @@ export class AuctionService {
historyMutation?: Record<string, unknown>; historyMutation?: Record<string, unknown>;
liveStatePatch: Record<string, string | number | boolean | null | undefined>; liveStatePatch: Record<string, string | number | boolean | null | undefined>;
matchSideEffectMutation?: Record<string, unknown>; matchSideEffectMutation?: Record<string, unknown>;
shouldBroadcastStateAfterDurability?: boolean;
shouldResetBidRuntime?: boolean; shouldResetBidRuntime?: boolean;
state: Record<string, unknown>; state: Record<string, unknown>;
structureInput: Parameters<typeof stringifyAuctionRedisStructureState>[0]; structureInput: Parameters<typeof stringifyAuctionRedisStructureState>[0];
@@ -1528,7 +1713,8 @@ export class AuctionService {
expectedRevision, expectedRevision,
liveStatePatch: params.liveStatePatch, liveStatePatch: params.liveStatePatch,
matchId, matchId,
shouldBroadcastState: true, shouldBroadcastState:
params.shouldBroadcastStateAfterDurability ?? true,
shouldResetBidRuntime: params.shouldResetBidRuntime, shouldResetBidRuntime: params.shouldResetBidRuntime,
actionRequest: params.actionRequest?.actionRequest, actionRequest: params.actionRequest?.actionRequest,
}, },
@@ -1945,6 +2131,46 @@ export class AuctionService {
} }
} }
private createRedisBidRejectedException(
result: Extract<AuctionBidCommandResult, { rejected: true }>,
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( private applyTopTierPriority(
order: AuctionPlayerSnapshot[], order: AuctionPlayerSnapshot[],
threshold: AuctionTopTierThreshold, threshold: AuctionTopTierThreshold,
@@ -67,6 +67,7 @@ describe('AuctionRedisCommandService', () => {
'TOO_LOW', 'TOO_LOW',
'bid-1', 'bid-1',
'1000', '1000',
'31000',
]); ]);
await expect( await expect(
@@ -87,6 +88,7 @@ describe('AuctionRedisCommandService', () => {
).resolves.toEqual({ ).resolves.toEqual({
bidRequestId: 'bid-1', bidRequestId: 'bid-1',
code: 'TOO_LOW', code: 'TOO_LOW',
currentBidRoundDeadlineTimestampMS: 31_000,
currentServerTimestampMS: 1000, currentServerTimestampMS: 1000,
rejected: true, rejected: true,
}); });
@@ -37,6 +37,7 @@ export type AuctionBidCommandResult =
| { | {
bidRequestId: string; bidRequestId: string;
code: string; code: string;
currentBidRoundDeadlineTimestampMS?: number;
currentServerTimestampMS: number; currentServerTimestampMS: number;
isReplay?: boolean; isReplay?: boolean;
rejected: true; rejected: true;
@@ -244,6 +245,7 @@ function parseBidCommandReply(reply: unknown[]): AuctionBidCommandResult {
return { return {
bidRequestId: values[2], bidRequestId: values[2],
code: values[4] || status, code: values[4] || status,
currentBidRoundDeadlineTimestampMS: optionalNumberValue(values[7]),
currentServerTimestampMS: numberValue(values[9]), currentServerTimestampMS: numberValue(values[9]),
isReplay: true, isReplay: true,
rejected: true, rejected: true,
@@ -252,6 +254,7 @@ function parseBidCommandReply(reply: unknown[]): AuctionBidCommandResult {
return { return {
bidRequestId: values[2] ?? '', bidRequestId: values[2] ?? '',
code: values[1] ?? 'UNKNOWN', code: values[1] ?? 'UNKNOWN',
currentBidRoundDeadlineTimestampMS: optionalNumberValue(values[4]),
currentServerTimestampMS: numberValue(values[3]), currentServerTimestampMS: numberValue(values[3]),
rejected: true, rejected: true,
}; };
@@ -373,3 +376,9 @@ function numberValue(value: string | undefined): number {
const parsed = Number(value); const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : 0; 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;
}
@@ -146,6 +146,7 @@ describe('auction redis projection helpers', () => {
currentBidRoundPlayerUserId: playerUserId.toString(), currentBidRoundPlayerUserId: playerUserId.toString(),
maximumBidRoundDurationSeconds: 30, maximumBidRoundDurationSeconds: 30,
'team:2:assignedAuctionTeamMemberCount': 2, 'team:2:assignedAuctionTeamMemberCount': 2,
'team:2:captainUserId': captainUserId.toString(),
'team:2:remainingBidPointAmount': 970, 'team:2:remainingBidPointAmount': 970,
}); });
}); });
@@ -68,6 +68,8 @@ export function buildAuctionRedisLiveStatePatchFromStructure(
} }
for (const team of input.auctionTeams) { for (const team of input.auctionTeams) {
patch[`team:${team.teamIndex}:captainUserId`] =
team.captainUserId.toString();
patch[`team:${team.teamIndex}:remainingBidPointAmount`] = patch[`team:${team.teamIndex}:remainingBidPointAmount`] =
team.remainingBidPointAmount; team.remainingBidPointAmount;
patch[`team:${team.teamIndex}:assignedAuctionTeamMemberCount`] = patch[`team:${team.teamIndex}:assignedAuctionTeamMemberCount`] =
@@ -41,6 +41,46 @@ describe('AuctionRedisStateReaderService', () => {
await expect(service.readLiveStateIdentity('match-1')).resolves.toBeNull(); 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 () => { it('assembles a public auction view from Redis state', async () => {
const { service, sendCommand } = makeService([ const { service, sendCommand } = makeService([
[ [
@@ -22,6 +22,13 @@ export interface AuctionRedisLiveStateIdentity {
revision?: number; revision?: number;
} }
export interface AuctionRedisBidContext {
auctionLifecycleId: string;
bidderTeamCaptainUserId?: string;
currentBidRoundPlayerUserId?: string;
phase: string;
}
export interface AuctionRedisStateViewReadOptions { export interface AuctionRedisStateViewReadOptions {
includeInternalLiveStateFields?: boolean; includeInternalLiveStateFields?: boolean;
shouldForceAuctionStateResync?: boolean; shouldForceAuctionStateResync?: boolean;
@@ -55,6 +62,41 @@ export class AuctionRedisStateReaderService {
}; };
} }
public async readBidContext(
matchId: string,
bidderTeamIndex: number,
): Promise<AuctionRedisBidContext | null> {
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( public async readAuctionStateView(
matchId: string, matchId: string,
options: AuctionRedisStateViewReadOptions = {}, options: AuctionRedisStateViewReadOptions = {},
@@ -102,11 +144,43 @@ export class AuctionRedisStateReaderService {
shouldForceAuctionStateResync: options.shouldForceAuctionStateResync, shouldForceAuctionStateResync: options.shouldForceAuctionStateResync,
structureState: JSON.parse(structureStateJson) as Record<string, unknown>, structureState: JSON.parse(structureStateJson) as Record<string, unknown>,
}); });
view.matchId = matchId;
if (options.includeInternalLiveStateFields) { if (options.includeInternalLiveStateFields) {
view.redisInternalPhase = liveState.phase; view.redisInternalPhase = liveState.phase;
} }
return view; return view;
} }
private async readBidderTeamCaptainUserIdFromStructure(
structureStateKey: string,
bidderTeamIndex: number,
): Promise<string | undefined> {
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<string, unknown>).teamIndex) === bidderTeamIndex
);
});
if (!bidderTeam || typeof bidderTeam !== 'object') return undefined;
return stringValue((bidderTeam as Record<string, unknown>).captainUserId);
}
}
function stringValue(value: unknown): string | undefined {
return typeof value === 'string' && value ? value : undefined;
} }
function parseHashReply( function parseHashReply(
@@ -174,6 +174,7 @@ if redis.call('LLEN', bidRequestResultOrderKey) >= maximumStoredBidRequestResult
end end
local function storeRejectedRequest(rejectCode) local function storeRejectedRequest(rejectCode)
local rejectedCurrentBidRoundDeadlineTimestampMS = redis.call('HGET', liveAuctionStateKey, 'currentBidRoundDeadlineTimestampMS') or ''
redis.call( redis.call(
'HSET', 'HSET',
bidRequestResultsKey, bidRequestResultsKey,
@@ -183,13 +184,15 @@ local function storeRejectedRequest(rejectCode)
'rejected', 'rejected',
requestField('rejectCode'), requestField('rejectCode'),
rejectCode, rejectCode,
requestField('currentBidRoundDeadlineTimestampMS'),
rejectedCurrentBidRoundDeadlineTimestampMS,
requestField('responseServerTimestampMS'), requestField('responseServerTimestampMS'),
tostring(currentRedisTimestampMS), tostring(currentRedisTimestampMS),
requestField('createdAtTimestampMS'), requestField('createdAtTimestampMS'),
tostring(currentRedisTimestampMS) tostring(currentRedisTimestampMS)
) )
redis.call('RPUSH', bidRequestResultOrderKey, bidRequestId) redis.call('RPUSH', bidRequestResultOrderKey, bidRequestId)
return {'REJECTED', rejectCode, bidRequestId, tostring(currentRedisTimestampMS)} return {'REJECTED', rejectCode, bidRequestId, tostring(currentRedisTimestampMS), rejectedCurrentBidRoundDeadlineTimestampMS}
end end
local phase = redis.call('HGET', liveAuctionStateKey, 'phase') local phase = redis.call('HGET', liveAuctionStateKey, 'phase')
+9 -10
View File
@@ -135,6 +135,7 @@ export interface AuctionStateView {
}[]; }[];
currentBid: number; currentBid: number;
currentBidder: { teamIndex: number } | null; currentBidder: { teamIndex: number } | null;
remainingMs: number;
timer: number; timer: number;
maxTimer: number; maxTimer: number;
bidExtensionSeconds: number; bidExtensionSeconds: number;
@@ -232,10 +233,11 @@ function mapAuctionPlayerToView(
player: ApiAuctionPlayerSnapshot, player: ApiAuctionPlayerSnapshot,
): AuctionPlayerView { ): AuctionPlayerView {
const { mainPosition, subPosition } = resolveMainAndSubPosition( const { mainPosition, subPosition } = resolveMainAndSubPosition(
player.preferredPositions, player.preferredPositions ?? [],
); );
const summary = player.recentStatsSummary; const summary = player.recentStatsSummary;
const primary = pickPrimary(summary, mainPosition); const primary = pickPrimary(summary, mainPosition);
const masteries = player.masteries ?? [];
return { return {
id: player.userId, id: player.userId,
@@ -246,9 +248,9 @@ function mapAuctionPlayerToView(
tierHistory: player.tierHistory ?? [], tierHistory: player.tierHistory ?? [],
mainPosition, mainPosition,
subPosition, subPosition,
profileIconId: player.profileIconId, profileIconId: player.profileIconId ?? 0,
passCount: player.passCount ?? 0, passCount: player.passCount ?? 0,
masteries: player.masteries.slice(0, 5).map((mastery) => ({ masteries: masteries.slice(0, 5).map((mastery) => ({
championId: mastery.championId, championId: mastery.championId,
level: mastery.championLevel, level: mastery.championLevel,
points: mastery.championPoints, points: mastery.championPoints,
@@ -530,14 +532,10 @@ export function mapApiAuctionToAuctionState(
) ?? null); ) ?? null);
const currentPlayerIndex = const currentPlayerIndex =
auction.phase === "complete" ? totalPlayers : currentAuctionPlayerOrderIndex; auction.phase === "complete" ? totalPlayers : currentAuctionPlayerOrderIndex;
const timer = currentBidRoundDeadlineTimestampMS const remainingMs = currentBidRoundDeadlineTimestampMS
? Math.max( ? Math.max(0, currentBidRoundDeadlineTimestampMS - now.getTime())
0,
Math.ceil(
(currentBidRoundDeadlineTimestampMS - now.getTime()) / 1000,
),
)
: 0; : 0;
const timer = Math.floor(remainingMs / 1000);
return { return {
matchId: auction.matchId, matchId: auction.matchId,
@@ -560,6 +558,7 @@ export function mapApiAuctionToAuctionState(
teamIndex: currentBidderTeamIndex, teamIndex: currentBidderTeamIndex,
} }
: null, : null,
remainingMs,
timer, timer,
maxTimer: maximumBidRoundDurationSeconds, maxTimer: maximumBidRoundDurationSeconds,
bidExtensionSeconds: bidRoundExtensionSeconds, bidExtensionSeconds: bidRoundExtensionSeconds,
+310 -85
View File
@@ -70,7 +70,49 @@ interface BidDeltaPayload {
revision?: number; 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 MAX_CHAT_MESSAGES = 200;
const TIME_SYNC_INTERVAL_MS = 5000;
const TIME_SYNC_TIMEOUT_MS = 3000;
function mergeChatMessages( function mergeChatMessages(
current: ApiAuctionChatMessage[], current: ApiAuctionChatMessage[],
@@ -95,6 +137,16 @@ export function useAuctionSocket(matchId: string | undefined) {
const pendingActionTimeoutsRef = useRef< const pendingActionTimeoutsRef = useRef<
Record<string, ReturnType<typeof setTimeout>> Record<string, ReturnType<typeof setTimeout>>
>({}); >({});
const timeSyncIntervalRef = useRef<ReturnType<typeof setInterval> | null>(
null,
);
const timeSyncTimeoutsRef = useRef<
Record<number, ReturnType<typeof setTimeout>>
>({});
const timeSyncSequenceRef = useRef(0);
const hasSyncedServerTimeRef = useRef(false);
const latestAuctionRef = useRef<ApiAuction | null>(null);
const latestConfirmedBidPointAmountRef = useRef(0);
const [auction, setAuction] = useState<ApiAuction | null>(null); const [auction, setAuction] = useState<ApiAuction | null>(null);
const [chatMessages, setChatMessages] = useState<ApiAuctionChatMessage[]>([]); const [chatMessages, setChatMessages] = useState<ApiAuctionChatMessage[]>([]);
const [pendingBidRequests, setPendingBidRequests] = useState< const [pendingBidRequests, setPendingBidRequests] = useState<
@@ -108,6 +160,153 @@ export function useAuctionSocket(matchId: string | undefined) {
useState<ConnectionStatus>('idle'); useState<ConnectionStatus>('idle');
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [serverTimeOffsetMs, setServerTimeOffsetMs] = useState(0); const [serverTimeOffsetMs, setServerTimeOffsetMs] = useState(0);
const [serverRoundTripMs, setServerRoundTripMs] = useState<number | null>(
null,
);
const [bidLatencyDiagnostics, setBidLatencyDiagnostics] =
useState<BidLatencyDiagnostics | null>(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(() => { useEffect(() => {
if (!matchId) { if (!matchId) {
@@ -139,25 +338,33 @@ export function useAuctionSocket(matchId: string | undefined) {
socket.on('connect', () => { socket.on('connect', () => {
setConnectionStatus('connected'); setConnectionStatus('connected');
socket.emit('join', { matchId }); socket.emit('join', { matchId });
requestServerTimeSync(socket);
if (timeSyncIntervalRef.current) {
clearInterval(timeSyncIntervalRef.current);
}
timeSyncIntervalRef.current = setInterval(
() => requestServerTimeSync(socket),
TIME_SYNC_INTERVAL_MS,
);
}); });
socket.on('disconnect', () => { socket.on('disconnect', () => {
clearTimeSyncTimers();
setConnectionStatus('disconnected'); setConnectionStatus('disconnected');
}); });
socket.on('state', (nextAuction: ApiAuction) => { socket.on('state', (nextAuction: ApiAuction) => {
setAuction((current) => const didApplyState = commitAuctionState(nextAuction);
shouldApplyIncomingAuctionState(current, nextAuction) if (didApplyState) {
? nextAuction clearPendingActionRequests();
: current,
);
if (typeof nextAuction.currentServerTimestampMS === 'number') {
setServerTimeOffsetMs(nextAuction.currentServerTimestampMS - Date.now());
} }
applyFallbackServerTimestamp(nextAuction.currentServerTimestampMS);
if (nextAuction.chatMessages) { if (nextAuction.chatMessages) {
setChatMessages(mergeChatMessages([], nextAuction.chatMessages)); setChatMessages(mergeChatMessages([], nextAuction.chatMessages));
} }
setError(null); if (didApplyState) {
setError(null);
}
}); });
socket.on('chat-history', (payload: ChatHistoryPayload) => { socket.on('chat-history', (payload: ChatHistoryPayload) => {
@@ -169,19 +376,20 @@ export function useAuctionSocket(matchId: string | undefined) {
}); });
socket.on('bid', (payload: BidDeltaPayload) => { socket.on('bid', (payload: BidDeltaPayload) => {
if (typeof payload?.currentServerTimestampMS === 'number') { applyFallbackServerTimestamp(payload?.currentServerTimestampMS);
setServerTimeOffsetMs(payload.currentServerTimestampMS - Date.now()); const didApplyBidDelta = commitBidDelta(payload);
}
if (payload?.bidRequestId) { 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) => { socket.on('match-side-effect', (payload: MatchSideEffectPayload) => {
if (typeof payload?.currentServerTimestampMS === 'number') { applyFallbackServerTimestamp(payload?.currentServerTimestampMS);
setServerTimeOffsetMs(payload.currentServerTimestampMS - Date.now());
}
if ( if (
!payload?.matchSideEffectStatus || !payload?.matchSideEffectStatus ||
typeof payload.matchSideEffectRevision !== 'number' typeof payload.matchSideEffectRevision !== 'number'
@@ -191,31 +399,35 @@ export function useAuctionSocket(matchId: string | undefined) {
const matchSideEffectRevision = payload.matchSideEffectRevision; const matchSideEffectRevision = payload.matchSideEffectRevision;
const matchSideEffectStatus = payload.matchSideEffectStatus; const matchSideEffectStatus = payload.matchSideEffectStatus;
setAuction((current) => { const currentAuction = latestAuctionRef.current;
if (!current) return current; if (!currentAuction) return;
if ( if (
payload.auctionLifecycleId && payload.auctionLifecycleId &&
current.auctionLifecycleId && currentAuction.auctionLifecycleId &&
payload.auctionLifecycleId !== current.auctionLifecycleId payload.auctionLifecycleId !== currentAuction.auctionLifecycleId
) { ) {
return current; return;
} }
if ( if (
matchSideEffectRevision <= matchSideEffectRevision <=
(current.matchSideEffectRevision ?? -1) (currentAuction.matchSideEffectRevision ?? -1)
) { ) {
return current; return;
} }
return {
...current, const nextAuction = {
matchSideEffectRevision, ...currentAuction,
matchSideEffectStatus, matchSideEffectRevision,
}; matchSideEffectStatus,
}); };
latestAuctionRef.current = nextAuction;
setAuction(nextAuction);
}); });
socket.on('reset', (payload: ResetPayload) => { socket.on('reset', (payload: ResetPayload) => {
if (payload.matchId && payload.matchId !== matchId) return; if (payload.matchId && payload.matchId !== matchId) return;
latestAuctionRef.current = null;
latestConfirmedBidPointAmountRef.current = 0;
setAuction(null); setAuction(null);
setChatMessages([]); setChatMessages([]);
setResetAt(Date.now()); setResetAt(Date.now());
@@ -223,7 +435,6 @@ export function useAuctionSocket(matchId: string | undefined) {
}); });
socket.on('error', (payload: { message?: string }) => { socket.on('error', (payload: { message?: string }) => {
setConnectionStatus('error');
setError(payload.message ?? '실시간 경매 연결 중 오류가 발생했습니다.'); setError(payload.message ?? '실시간 경매 연결 중 오류가 발생했습니다.');
}); });
})(); })();
@@ -234,6 +445,7 @@ export function useAuctionSocket(matchId: string | undefined) {
socket?.removeAllListeners(); socket?.removeAllListeners();
socket?.disconnect(); socket?.disconnect();
socketRef.current = null; socketRef.current = null;
clearTimeSyncTimers();
Object.values(pendingBidTimeoutsRef.current).forEach((timeoutId) => Object.values(pendingBidTimeoutsRef.current).forEach((timeoutId) =>
clearTimeout(timeoutId), clearTimeout(timeoutId),
); );
@@ -242,10 +454,15 @@ export function useAuctionSocket(matchId: string | undefined) {
); );
pendingBidTimeoutsRef.current = {}; pendingBidTimeoutsRef.current = {};
pendingActionTimeoutsRef.current = {}; pendingActionTimeoutsRef.current = {};
latestAuctionRef.current = null;
latestConfirmedBidPointAmountRef.current = 0;
hasSyncedServerTimeRef.current = false;
setPendingBidRequests({}); setPendingBidRequests({});
setPendingActionRequests({}); setPendingActionRequests({});
setConnectionStatus('idle'); setConnectionStatus('idle');
setServerTimeOffsetMs(0); setServerTimeOffsetMs(0);
setServerRoundTripMs(null);
setBidLatencyDiagnostics(null);
}; };
}, [authUserId, matchId]); }, [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) { function emit(eventName: string, payload?: unknown) {
const socket = socketRef.current; const socket = socketRef.current;
if (!socket || !socket.connected) { if (!socket || !socket.connected) {
@@ -289,15 +514,16 @@ export function useAuctionSocket(matchId: string | undefined) {
} }
function buildAuctionActionPayload(): AuctionActionPayload { function buildAuctionActionPayload(): AuctionActionPayload {
const currentAuction = latestAuctionRef.current ?? auction;
return { return {
auctionActionRequestId: createClientRequestId(), auctionActionRequestId: createClientRequestId(),
clientObservedAuctionLifecycleId: auction?.auctionLifecycleId, clientObservedAuctionLifecycleId: currentAuction?.auctionLifecycleId,
clientObservedCurrentAuctionPlayerOrderIndex: clientObservedCurrentAuctionPlayerOrderIndex:
auction?.currentAuctionPlayerOrderIndex, currentAuction?.currentAuctionPlayerOrderIndex,
clientObservedCurrentBidRoundPlayerUserId: clientObservedCurrentBidRoundPlayerUserId:
auction?.currentBidRoundPlayerUserId, currentAuction?.currentBidRoundPlayerUserId,
clientObservedPhase: auction?.phase, clientObservedPhase: currentAuction?.phase,
clientObservedRevision: auction?.revision, clientObservedRevision: currentAuction?.revision,
}; };
} }
@@ -307,6 +533,9 @@ export function useAuctionSocket(matchId: string | undefined) {
setError('소켓이 아직 연결되지 않았습니다.'); setError('소켓이 아직 연결되지 않았습니다.');
return; return;
} }
if (Object.keys(pendingActionTimeoutsRef.current).length > 0) {
return;
}
const auctionActionRequestId = const auctionActionRequestId =
payload.auctionActionRequestId ?? createClientRequestId(); payload.auctionActionRequestId ?? createClientRequestId();
@@ -332,20 +561,19 @@ export function useAuctionSocket(matchId: string | undefined) {
rejected?: boolean; rejected?: boolean;
state?: ApiAuction; state?: ApiAuction;
}) => { }) => {
clearPendingActionRequest(
ack?.auctionActionRequestId ?? auctionActionRequestId,
);
if (ack?.rejected) { if (ack?.rejected) {
clearPendingActionRequest(
ack?.auctionActionRequestId ?? auctionActionRequestId,
);
setError(ack.code ?? '경매 진행 상태가 반영되지 않았습니다.'); setError(ack.code ?? '경매 진행 상태가 반영되지 않았습니다.');
return; return;
} }
const ackState = ack?.state; const ackState = ack?.state;
if (ackState) { if (ackState) {
setAuction((current) => clearPendingActionRequest(
shouldApplyIncomingAuctionState(current, ackState) ack.auctionActionRequestId ?? auctionActionRequestId,
? ackState
: current,
); );
commitAuctionState(ackState);
} }
}, },
); );
@@ -353,9 +581,7 @@ export function useAuctionSocket(matchId: string | undefined) {
const currentAuction = auction; const currentAuction = auction;
const visibleAuction = const visibleAuction =
currentAuction && currentAuction.matchId === matchId currentAuction && currentAuction.matchId === matchId ? currentAuction : null;
? applyPendingBidOverlay(currentAuction, pendingBidRequests)
: null;
const visibleConnectionStatus: ConnectionStatus = matchId const visibleConnectionStatus: ConnectionStatus = matchId
? connectionStatus ? connectionStatus
: 'idle'; : 'idle';
@@ -370,6 +596,8 @@ export function useAuctionSocket(matchId: string | undefined) {
resetAt, resetAt,
connectionStatus: visibleConnectionStatus, connectionStatus: visibleConnectionStatus,
error, error,
bidLatencyDiagnostics,
serverRoundTripMs: matchId ? serverRoundTripMs : null,
serverTimeOffsetMs: matchId ? serverTimeOffsetMs : 0, serverTimeOffsetMs: matchId ? serverTimeOffsetMs : 0,
placeBid(payload: BidPayload) { placeBid(payload: BidPayload) {
const socket = socketRef.current; const socket = socketRef.current;
@@ -377,17 +605,24 @@ export function useAuctionSocket(matchId: string | undefined) {
setError('소켓이 아직 연결되지 않았습니다.'); setError('소켓이 아직 연결되지 않았습니다.');
return; return;
} }
if (Object.keys(pendingBidTimeoutsRef.current).length > 0) {
return;
}
if (payload.bidPointAmount <= latestConfirmedBidPointAmountRef.current) {
return;
}
const bidRequestId = payload.bidRequestId ?? createClientRequestId(); const bidRequestId = payload.bidRequestId ?? createClientRequestId();
const currentAuction = latestAuctionRef.current ?? auction;
const bidPayload: BidPayload = { const bidPayload: BidPayload = {
...payload, ...payload,
bidRequestId, bidRequestId,
clientObservedAuctionLifecycleId: clientObservedAuctionLifecycleId:
payload.clientObservedAuctionLifecycleId ?? payload.clientObservedAuctionLifecycleId ??
auction?.auctionLifecycleId, currentAuction?.auctionLifecycleId,
clientObservedCurrentBidRoundPlayerUserId: clientObservedCurrentBidRoundPlayerUserId:
payload.clientObservedCurrentBidRoundPlayerUserId ?? payload.clientObservedCurrentBidRoundPlayerUserId ??
auction?.currentBidRoundPlayerUserId, currentAuction?.currentBidRoundPlayerUserId,
}; };
setError(null); setError(null);
@@ -405,23 +640,22 @@ export function useAuctionSocket(matchId: string | undefined) {
socket.emit( socket.emit(
'bid', 'bid',
bidPayload, bidPayload,
(ack?: { (ack?: BidAckPayload) => {
code?: string; captureBidLatencyDiagnostics(ack);
rejected?: boolean;
state?: ApiAuction;
}) => {
clearPendingBidRequest(bidRequestId);
if (ack?.rejected) { if (ack?.rejected) {
setError(ack.code ?? '입찰이 반영되지 않았습니다.'); clearPendingBidRequest(bidRequestId);
setError(ack.message ?? ack.code ?? '입찰이 반영되지 않았습니다.');
return;
}
if (ack?.bidDelta) {
clearPendingBidRequest(bidRequestId);
commitBidDelta(ack.bidDelta);
return; return;
} }
const ackState = ack?.state; const ackState = ack?.state;
if (ackState) { if (ackState) {
setAuction((current) => clearPendingBidRequest(bidRequestId);
shouldApplyIncomingAuctionState(current, ackState) commitAuctionState(ackState);
? ackState
: current,
);
} }
}, },
); );
@@ -455,6 +689,15 @@ function createClientRequestId(): string {
return `${Date.now()}-${Math.random().toString(16).slice(2)}`; 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( function shouldApplyIncomingAuctionState(
current: ApiAuction | null, current: ApiAuction | null,
incoming: ApiAuction, incoming: ApiAuction,
@@ -594,21 +837,3 @@ function appendUniqueLegacyBidEntry(
} }
return [...currentBids, legacyBid]; return [...currentBids, legacyBid];
} }
function applyPendingBidOverlay(
auction: ApiAuction,
pendingBidRequests: Record<string, { amount: number; teamIndex: number }>,
): 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,
};
}
+188 -30
View File
@@ -1,5 +1,6 @@
import { import {
lazy, lazy,
memo,
Suspense, Suspense,
useEffect, useEffect,
useMemo, useMemo,
@@ -26,7 +27,10 @@ import {
type AuctionPlayerView, type AuctionPlayerView,
type AuctionStateView, type AuctionStateView,
} from '../api/mappers'; } from '../api/mappers';
import { useAuctionSocket } from '../api/useAuctionSocket'; import {
useAuctionSocket,
type BidLatencyDiagnostics,
} from '../api/useAuctionSocket';
import { import {
DEFAULT_COMMUNITY_ID, DEFAULT_COMMUNITY_ID,
setDevCaptainTeamIndex, setDevCaptainTeamIndex,
@@ -176,6 +180,53 @@ function getMaxBidForTeam(team: AuctionStateView['teams'][number]) {
return Math.max(0, team.points - getReservedPointsAfterCurrentBid(team)); 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[]) { function getSoloTierHistory(entries: ApiTierHistoryEntry[]) {
return entries.filter((entry) => entry.queueType === 'RANKED_SOLO_5x5'); return entries.filter((entry) => entry.queueType === 'RANKED_SOLO_5x5');
} }
@@ -196,7 +247,7 @@ function TimerBar({ timer, maxTimer }: { timer: number; maxTimer: number }) {
return ( return (
<div className="w-full h-1.5 bg-base-content/5"> <div className="w-full h-1.5 bg-base-content/5">
<div <div
className={`h-full transition-all duration-1000 linear ${urgent ? 'bg-red-500' : 'bg-primary'}`} className={`h-full transition-all duration-300 linear ${urgent ? 'bg-red-500' : 'bg-primary'}`}
style={{ width: `${pct}%` }} style={{ width: `${pct}%` }}
/> />
</div> </div>
@@ -426,6 +477,8 @@ function TeamPanel({
); );
} }
const MemoTeamPanel = memo(TeamPanel);
function PlayerSpotlight({ function PlayerSpotlight({
state, state,
historyBackTo, historyBackTo,
@@ -433,24 +486,52 @@ function PlayerSpotlight({
state: AuctionStateView; state: AuctionStateView;
historyBackTo: string; historyBackTo: string;
}) { }) {
const { data: ddragon } = useDdragonManifest();
const player = state.currentPlayer; 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; if (!player) return null;
return (
<div className="border border-base-content/10 bg-base-100">
<MemoPlayerProfileDetails player={player} historyBackTo={historyBackTo} />
<PlayerBidStatus state={state} />
</div>
);
}
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<AuctionStateView['currentPlayer']>;
historyBackTo: string;
}) {
const { data: ddragon } = useDdragonManifest();
const snapshotSoloTierHistory = getSoloTierHistory(player.tierHistory);
const historyProfileQuery = useUserHistoryProfile(
player.userId,
DEFAULT_COMMUNITY_ID,
snapshotSoloTierHistory.length === 0,
);
const tierHistory = const tierHistory =
snapshotSoloTierHistory.length > 0 snapshotSoloTierHistory.length > 0
? snapshotSoloTierHistory ? snapshotSoloTierHistory
: getSoloTierHistory(historyProfileQuery.data?.tierHistory ?? []); : getSoloTierHistory(historyProfileQuery.data?.tierHistory ?? []);
return ( return (
<div className="border border-base-content/10 bg-base-100"> <>
<div className="p-5 border-b border-base-content/8"> <div className="p-5 border-b border-base-content/8">
<div className="flex items-start gap-4"> <div className="flex items-start gap-4">
<Link <Link
@@ -557,7 +638,41 @@ function PlayerSpotlight({
<RecentSoloStats player={player} /> <RecentSoloStats player={player} />
</div> </div>
</>
);
}
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') && ( {(state.phase === 'bidding' || state.phase === 'sold') && (
<div className="border-t border-base-content/8 px-4 py-3 bg-base-content/[0.02]"> <div className="border-t border-base-content/8 px-4 py-3 bg-base-content/[0.02]">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
@@ -589,7 +704,7 @@ function PlayerSpotlight({
</span> </span>
</div> </div>
)} )}
</div> </>
); );
} }
@@ -616,6 +731,10 @@ function BidControls({
: 0; : 0;
const maxBid = activeTeam ? getMaxBidForTeam(activeTeam) : 0; const maxBid = activeTeam ? getMaxBidForTeam(activeTeam) : 0;
const canAffordNextBid = !isActiveTeamFull && maxBid >= minBid; 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(() => { useEffect(() => {
const nextBid = Math.max(minBid, Math.ceil(minBid / 10) * 10); const nextBid = Math.max(minBid, Math.ceil(minBid / 10) * 10);
@@ -692,12 +811,13 @@ function BidControls({
/> />
</div> </div>
<button <button
onClick={() => onBid(activeTeam.teamIndex, bidAmount)} onClick={() => onBid(activeTeam.teamIndex, effectiveBidAmount)}
disabled={ disabled={
isBidPending || isBidPending ||
!canAffordNextBid || !canAffordNextBid ||
bidAmount > maxBid || isBidExpired ||
bidAmount <= state.currentBid effectiveBidAmount > maxBid ||
effectiveBidAmount <= state.currentBid
} }
className={`w-full py-2 text-xs font-bold uppercase tracking-wide border transition-colors disabled:opacity-30 disabled:cursor-not-allowed ${ className={`w-full py-2 text-xs font-bold uppercase tracking-wide border transition-colors disabled:opacity-30 disabled:cursor-not-allowed ${
`${teamIndexColorClasses(activeTeam.teamIndex).border} ${teamIndexColorClasses(activeTeam.teamIndex).bg} ${teamIndexColorClasses(activeTeam.teamIndex).text} hover:bg-base-content/5` `${teamIndexColorClasses(activeTeam.teamIndex).border} ${teamIndexColorClasses(activeTeam.teamIndex).bg} ${teamIndexColorClasses(activeTeam.teamIndex).text} hover:bg-base-content/5`
@@ -707,9 +827,11 @@ function BidControls({
? `${teamIndexLabel(activeTeam.teamIndex, activeTeam.name)} 정원 완료 (${activeTeamSize}/${AUCTION_MAX_TEAM_SIZE})` ? `${teamIndexLabel(activeTeam.teamIndex, activeTeam.name)} 정원 완료 (${activeTeamSize}/${AUCTION_MAX_TEAM_SIZE})`
: isBidPending : isBidPending
? '입찰 반영 중...' ? '입찰 반영 중...'
: isBidExpired
? '입찰 마감 확인 중'
: !canAffordNextBid : !canAffordNextBid
? `입찰 불가 (다음 ${formatPoints(minBid)}P · 최대 ${formatPoints(maxBid)}P)` ? `입찰 불가 (다음 ${formatPoints(minBid)}P · 최대 ${formatPoints(maxBid)}P)`
: `${teamIndexLabel(activeTeam.teamIndex, activeTeam.name)} 입찰 (${formatPoints(bidAmount)}P)`} : `${teamIndexLabel(activeTeam.teamIndex, activeTeam.name)} 입찰 (${formatPoints(effectiveBidAmount)}P)`}
</button> </button>
</div> </div>
); );
@@ -752,6 +874,8 @@ function BidLog({ bids }: { bids: AuctionStateView['bids'] }) {
); );
} }
const MemoBidLog = memo(BidLog);
export default function AuctionPage() { export default function AuctionPage() {
const { id } = useParams(); const { id } = useParams();
const location = useLocation(); const location = useLocation();
@@ -814,7 +938,7 @@ export default function AuctionPage() {
} }
useEffect(() => { useEffect(() => {
const timer = window.setInterval(() => setNow(Date.now()), 1000); const timer = window.setInterval(() => setNow(Date.now()), 250);
return () => window.clearInterval(timer); return () => window.clearInterval(timer);
}, []); }, []);
@@ -825,14 +949,28 @@ export default function AuctionPage() {
const liveAuction = pickLatestAuction(socket.auction, auctionQuery.data); const liveAuction = pickLatestAuction(socket.auction, auctionQuery.data);
const syncedNow = now + socket.serverTimeOffsetMs; const syncedNow = now + socket.serverTimeOffsetMs;
const auctionState = const baseAuctionState = useMemo(
liveAuction && matchQuery.data () =>
? mapApiAuctionToAuctionState( liveAuction && matchQuery.data
liveAuction, ? mapApiAuctionToAuctionState(liveAuction, matchQuery.data)
matchQuery.data, : null,
new Date(syncedNow), [liveAuction, matchQuery.data],
) );
: null; 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 availableTeamIndexes = useMemo(() => {
const indexes = new Set((auctionState?.teams ?? []).map((team) => team.teamIndex)); const indexes = new Set((auctionState?.teams ?? []).map((team) => team.teamIndex));
return [...indexes].sort((left, right) => left - right); return [...indexes].sort((left, right) => left - right);
@@ -915,6 +1053,9 @@ export default function AuctionPage() {
const errorMessage = const errorMessage =
socket.error ?? socket.error ??
(auctionQuery.error instanceof Error ? auctionQuery.error.message : null); (auctionQuery.error instanceof Error ? auctionQuery.error.message : null);
const bidLatencyMessage = formatBidLatencyDiagnostics(
socket.bidLatencyDiagnostics,
);
const matchSideEffectMessage = resolveMatchSideEffectMessage( const matchSideEffectMessage = resolveMatchSideEffectMessage(
auctionState.matchSideEffectStatus, auctionState.matchSideEffectStatus,
); );
@@ -1040,6 +1181,12 @@ export default function AuctionPage() {
</div> </div>
)} )}
{import.meta.env.DEV && canManageAuction && bidLatencyMessage && (
<div className="mb-4 border border-base-content/10 bg-base-100 px-4 py-2 text-xs text-base-content/45">
입찰 계측 · {bidLatencyMessage}
</div>
)}
{undoMutation.error instanceof Error && ( {undoMutation.error instanceof Error && (
<div className="mb-4 border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm text-red-500"> <div className="mb-4 border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm text-red-500">
{undoMutation.error.message} {undoMutation.error.message}
@@ -1116,12 +1263,12 @@ export default function AuctionPage() {
<div className="grid grid-cols-1 xl:grid-cols-[260px_minmax(0,1fr)_minmax(340px,440px)_320px] gap-4 mt-4"> <div className="grid grid-cols-1 xl:grid-cols-[260px_minmax(0,1fr)_minmax(340px,440px)_320px] gap-4 mt-4">
<aside className="hidden xl:block"> <aside className="hidden xl:block">
<PoolPanel state={auctionState} /> <MemoPoolPanel state={auctionState} />
</aside> </aside>
<div className="grid sm:grid-cols-2 gap-4 content-start"> <div className="grid sm:grid-cols-2 gap-4 content-start">
{auctionState.teams.map((team) => ( {auctionState.teams.map((team) => (
<TeamPanel <MemoTeamPanel
key={team.teamIndex} key={team.teamIndex}
team={team} team={team}
isActive={isCurrentBidder(auctionState.currentBidder, team)} isActive={isCurrentBidder(auctionState.currentBidder, team)}
@@ -1157,7 +1304,7 @@ export default function AuctionPage() {
</> </>
) : ( ) : (
<> <>
<PlayerSpotlight <MemoPlayerSpotlight
state={auctionState} state={auctionState}
historyBackTo={historyBackTo} historyBackTo={historyBackTo}
/> />
@@ -1184,7 +1331,7 @@ export default function AuctionPage() {
}) })
} }
/> />
<BidLog bids={auctionState.bids} /> <MemoBidLog bids={auctionState.bids} />
{canManageAuction && ( {canManageAuction && (
<div className="border border-base-content/10 bg-base-100 p-4 space-y-3"> <div className="border border-base-content/10 bg-base-100 p-4 space-y-3">
@@ -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({ function PoolTabButton({
label, label,
count, count,