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

+310 -85
View File
@@ -70,7 +70,49 @@ interface BidDeltaPayload {
revision?: number;
}
interface BidServerTimingPayload {
fallbackFullStatePath?: boolean;
gatewayTotalDurationMS?: number;
redisBidCommandDurationMS?: number;
redisBidContextReadDurationMS?: number;
serviceTotalDurationMS?: number;
}
interface BidDiagnosticsPayload {
currentBidRoundDeadlineTimestampMS?: number;
currentServerTimestampMS?: number;
}
interface BidAckPayload {
bidDelta?: BidDeltaPayload | null;
bidDiagnostics?: BidDiagnosticsPayload;
bidServerTiming?: BidServerTimingPayload;
code?: string;
message?: string;
rejected?: boolean;
state?: ApiAuction;
}
interface TimeSyncAckPayload {
clientSentAtTimestampMS?: number;
currentServerTimestampMS?: number;
ok?: boolean;
rejected?: boolean;
sequence?: number;
serverProcessingDurationMS?: number;
}
export interface BidLatencyDiagnostics {
bidDiagnostics?: BidDiagnosticsPayload;
bidServerTiming?: BidServerTimingPayload;
clientObservedRemainingBidRoundTimeMS?: number;
serverObservedRemainingBidRoundTimeMS?: number;
serverRoundTripDurationMS?: number;
}
const MAX_CHAT_MESSAGES = 200;
const TIME_SYNC_INTERVAL_MS = 5000;
const TIME_SYNC_TIMEOUT_MS = 3000;
function mergeChatMessages(
current: ApiAuctionChatMessage[],
@@ -95,6 +137,16 @@ export function useAuctionSocket(matchId: string | undefined) {
const pendingActionTimeoutsRef = useRef<
Record<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 [chatMessages, setChatMessages] = useState<ApiAuctionChatMessage[]>([]);
const [pendingBidRequests, setPendingBidRequests] = useState<
@@ -108,6 +160,153 @@ export function useAuctionSocket(matchId: string | undefined) {
useState<ConnectionStatus>('idle');
const [error, setError] = useState<string | null>(null);
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(() => {
if (!matchId) {
@@ -139,25 +338,33 @@ export function useAuctionSocket(matchId: string | undefined) {
socket.on('connect', () => {
setConnectionStatus('connected');
socket.emit('join', { matchId });
requestServerTimeSync(socket);
if (timeSyncIntervalRef.current) {
clearInterval(timeSyncIntervalRef.current);
}
timeSyncIntervalRef.current = setInterval(
() => requestServerTimeSync(socket),
TIME_SYNC_INTERVAL_MS,
);
});
socket.on('disconnect', () => {
clearTimeSyncTimers();
setConnectionStatus('disconnected');
});
socket.on('state', (nextAuction: ApiAuction) => {
setAuction((current) =>
shouldApplyIncomingAuctionState(current, nextAuction)
? nextAuction
: current,
);
if (typeof nextAuction.currentServerTimestampMS === 'number') {
setServerTimeOffsetMs(nextAuction.currentServerTimestampMS - Date.now());
const didApplyState = commitAuctionState(nextAuction);
if (didApplyState) {
clearPendingActionRequests();
}
applyFallbackServerTimestamp(nextAuction.currentServerTimestampMS);
if (nextAuction.chatMessages) {
setChatMessages(mergeChatMessages([], nextAuction.chatMessages));
}
setError(null);
if (didApplyState) {
setError(null);
}
});
socket.on('chat-history', (payload: ChatHistoryPayload) => {
@@ -169,19 +376,20 @@ export function useAuctionSocket(matchId: string | undefined) {
});
socket.on('bid', (payload: BidDeltaPayload) => {
if (typeof payload?.currentServerTimestampMS === 'number') {
setServerTimeOffsetMs(payload.currentServerTimestampMS - Date.now());
}
applyFallbackServerTimestamp(payload?.currentServerTimestampMS);
const didApplyBidDelta = commitBidDelta(payload);
if (payload?.bidRequestId) {
clearPendingBidRequest(payload.bidRequestId);
if (
didApplyBidDelta ||
pendingBidTimeoutsRef.current[payload.bidRequestId]
) {
clearPendingBidRequest(payload.bidRequestId);
}
}
setAuction((current) => applyBidDelta(current, payload));
});
socket.on('match-side-effect', (payload: MatchSideEffectPayload) => {
if (typeof payload?.currentServerTimestampMS === 'number') {
setServerTimeOffsetMs(payload.currentServerTimestampMS - Date.now());
}
applyFallbackServerTimestamp(payload?.currentServerTimestampMS);
if (
!payload?.matchSideEffectStatus ||
typeof payload.matchSideEffectRevision !== 'number'
@@ -191,31 +399,35 @@ export function useAuctionSocket(matchId: string | undefined) {
const matchSideEffectRevision = payload.matchSideEffectRevision;
const matchSideEffectStatus = payload.matchSideEffectStatus;
setAuction((current) => {
if (!current) return current;
if (
payload.auctionLifecycleId &&
current.auctionLifecycleId &&
payload.auctionLifecycleId !== current.auctionLifecycleId
) {
return current;
}
if (
matchSideEffectRevision <=
(current.matchSideEffectRevision ?? -1)
) {
return current;
}
return {
...current,
matchSideEffectRevision,
matchSideEffectStatus,
};
});
const currentAuction = latestAuctionRef.current;
if (!currentAuction) return;
if (
payload.auctionLifecycleId &&
currentAuction.auctionLifecycleId &&
payload.auctionLifecycleId !== currentAuction.auctionLifecycleId
) {
return;
}
if (
matchSideEffectRevision <=
(currentAuction.matchSideEffectRevision ?? -1)
) {
return;
}
const nextAuction = {
...currentAuction,
matchSideEffectRevision,
matchSideEffectStatus,
};
latestAuctionRef.current = nextAuction;
setAuction(nextAuction);
});
socket.on('reset', (payload: ResetPayload) => {
if (payload.matchId && payload.matchId !== matchId) return;
latestAuctionRef.current = null;
latestConfirmedBidPointAmountRef.current = 0;
setAuction(null);
setChatMessages([]);
setResetAt(Date.now());
@@ -223,7 +435,6 @@ export function useAuctionSocket(matchId: string | undefined) {
});
socket.on('error', (payload: { message?: string }) => {
setConnectionStatus('error');
setError(payload.message ?? '실시간 경매 연결 중 오류가 발생했습니다.');
});
})();
@@ -234,6 +445,7 @@ export function useAuctionSocket(matchId: string | undefined) {
socket?.removeAllListeners();
socket?.disconnect();
socketRef.current = null;
clearTimeSyncTimers();
Object.values(pendingBidTimeoutsRef.current).forEach((timeoutId) =>
clearTimeout(timeoutId),
);
@@ -242,10 +454,15 @@ export function useAuctionSocket(matchId: string | undefined) {
);
pendingBidTimeoutsRef.current = {};
pendingActionTimeoutsRef.current = {};
latestAuctionRef.current = null;
latestConfirmedBidPointAmountRef.current = 0;
hasSyncedServerTimeRef.current = false;
setPendingBidRequests({});
setPendingActionRequests({});
setConnectionStatus('idle');
setServerTimeOffsetMs(0);
setServerRoundTripMs(null);
setBidLatencyDiagnostics(null);
};
}, [authUserId, matchId]);
@@ -271,6 +488,14 @@ export function useAuctionSocket(matchId: string | undefined) {
});
}
function clearPendingActionRequests() {
Object.values(pendingActionTimeoutsRef.current).forEach((timeoutId) =>
clearTimeout(timeoutId),
);
pendingActionTimeoutsRef.current = {};
setPendingActionRequests({});
}
function emit(eventName: string, payload?: unknown) {
const socket = socketRef.current;
if (!socket || !socket.connected) {
@@ -289,15 +514,16 @@ export function useAuctionSocket(matchId: string | undefined) {
}
function buildAuctionActionPayload(): AuctionActionPayload {
const currentAuction = latestAuctionRef.current ?? auction;
return {
auctionActionRequestId: createClientRequestId(),
clientObservedAuctionLifecycleId: auction?.auctionLifecycleId,
clientObservedAuctionLifecycleId: currentAuction?.auctionLifecycleId,
clientObservedCurrentAuctionPlayerOrderIndex:
auction?.currentAuctionPlayerOrderIndex,
currentAuction?.currentAuctionPlayerOrderIndex,
clientObservedCurrentBidRoundPlayerUserId:
auction?.currentBidRoundPlayerUserId,
clientObservedPhase: auction?.phase,
clientObservedRevision: auction?.revision,
currentAuction?.currentBidRoundPlayerUserId,
clientObservedPhase: currentAuction?.phase,
clientObservedRevision: currentAuction?.revision,
};
}
@@ -307,6 +533,9 @@ export function useAuctionSocket(matchId: string | undefined) {
setError('소켓이 아직 연결되지 않았습니다.');
return;
}
if (Object.keys(pendingActionTimeoutsRef.current).length > 0) {
return;
}
const auctionActionRequestId =
payload.auctionActionRequestId ?? createClientRequestId();
@@ -332,20 +561,19 @@ export function useAuctionSocket(matchId: string | undefined) {
rejected?: boolean;
state?: ApiAuction;
}) => {
clearPendingActionRequest(
ack?.auctionActionRequestId ?? auctionActionRequestId,
);
if (ack?.rejected) {
clearPendingActionRequest(
ack?.auctionActionRequestId ?? auctionActionRequestId,
);
setError(ack.code ?? '경매 진행 상태가 반영되지 않았습니다.');
return;
}
const ackState = ack?.state;
if (ackState) {
setAuction((current) =>
shouldApplyIncomingAuctionState(current, ackState)
? ackState
: current,
clearPendingActionRequest(
ack.auctionActionRequestId ?? auctionActionRequestId,
);
commitAuctionState(ackState);
}
},
);
@@ -353,9 +581,7 @@ export function useAuctionSocket(matchId: string | undefined) {
const currentAuction = auction;
const visibleAuction =
currentAuction && currentAuction.matchId === matchId
? applyPendingBidOverlay(currentAuction, pendingBidRequests)
: null;
currentAuction && currentAuction.matchId === matchId ? currentAuction : null;
const visibleConnectionStatus: ConnectionStatus = matchId
? connectionStatus
: 'idle';
@@ -370,6 +596,8 @@ export function useAuctionSocket(matchId: string | undefined) {
resetAt,
connectionStatus: visibleConnectionStatus,
error,
bidLatencyDiagnostics,
serverRoundTripMs: matchId ? serverRoundTripMs : null,
serverTimeOffsetMs: matchId ? serverTimeOffsetMs : 0,
placeBid(payload: BidPayload) {
const socket = socketRef.current;
@@ -377,17 +605,24 @@ export function useAuctionSocket(matchId: string | undefined) {
setError('소켓이 아직 연결되지 않았습니다.');
return;
}
if (Object.keys(pendingBidTimeoutsRef.current).length > 0) {
return;
}
if (payload.bidPointAmount <= latestConfirmedBidPointAmountRef.current) {
return;
}
const bidRequestId = payload.bidRequestId ?? createClientRequestId();
const currentAuction = latestAuctionRef.current ?? auction;
const bidPayload: BidPayload = {
...payload,
bidRequestId,
clientObservedAuctionLifecycleId:
payload.clientObservedAuctionLifecycleId ??
auction?.auctionLifecycleId,
currentAuction?.auctionLifecycleId,
clientObservedCurrentBidRoundPlayerUserId:
payload.clientObservedCurrentBidRoundPlayerUserId ??
auction?.currentBidRoundPlayerUserId,
currentAuction?.currentBidRoundPlayerUserId,
};
setError(null);
@@ -405,23 +640,22 @@ export function useAuctionSocket(matchId: string | undefined) {
socket.emit(
'bid',
bidPayload,
(ack?: {
code?: string;
rejected?: boolean;
state?: ApiAuction;
}) => {
clearPendingBidRequest(bidRequestId);
(ack?: BidAckPayload) => {
captureBidLatencyDiagnostics(ack);
if (ack?.rejected) {
setError(ack.code ?? '입찰이 반영되지 않았습니다.');
clearPendingBidRequest(bidRequestId);
setError(ack.message ?? ack.code ?? '입찰이 반영되지 않았습니다.');
return;
}
if (ack?.bidDelta) {
clearPendingBidRequest(bidRequestId);
commitBidDelta(ack.bidDelta);
return;
}
const ackState = ack?.state;
if (ackState) {
setAuction((current) =>
shouldApplyIncomingAuctionState(current, ackState)
? ackState
: current,
);
clearPendingBidRequest(bidRequestId);
commitAuctionState(ackState);
}
},
);
@@ -455,6 +689,15 @@ function createClientRequestId(): string {
return `${Date.now()}-${Math.random().toString(16).slice(2)}`;
}
function resolveCurrentBidPointAmount(auction: ApiAuction): number {
const bidPointAmount = Math.max(
Number(auction.currentHighestBidPointAmount),
Number(auction.currentBid),
0,
);
return Number.isFinite(bidPointAmount) ? bidPointAmount : 0;
}
function shouldApplyIncomingAuctionState(
current: ApiAuction | null,
incoming: ApiAuction,
@@ -594,21 +837,3 @@ function appendUniqueLegacyBidEntry(
}
return [...currentBids, legacyBid];
}
function applyPendingBidOverlay(
auction: ApiAuction,
pendingBidRequests: Record<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,
};
}