Improve auction realtime bid responsiveness
This commit is contained in:
1 parent
c6f5a7077f
commit
b367328df0
16 files changed
+1364
-203
No files matched your search
@@ -135,6 +135,7 @@ export interface AuctionStateView {
|
||||
}[];
|
||||
currentBid: number;
|
||||
currentBidder: { teamIndex: number } | null;
|
||||
remainingMs: number;
|
||||
timer: number;
|
||||
maxTimer: number;
|
||||
bidExtensionSeconds: number;
|
||||
@@ -232,10 +233,11 @@ function mapAuctionPlayerToView(
|
||||
player: ApiAuctionPlayerSnapshot,
|
||||
): AuctionPlayerView {
|
||||
const { mainPosition, subPosition } = resolveMainAndSubPosition(
|
||||
player.preferredPositions,
|
||||
player.preferredPositions ?? [],
|
||||
);
|
||||
const summary = player.recentStatsSummary;
|
||||
const primary = pickPrimary(summary, mainPosition);
|
||||
const masteries = player.masteries ?? [];
|
||||
|
||||
return {
|
||||
id: player.userId,
|
||||
@@ -246,9 +248,9 @@ function mapAuctionPlayerToView(
|
||||
tierHistory: player.tierHistory ?? [],
|
||||
mainPosition,
|
||||
subPosition,
|
||||
profileIconId: player.profileIconId,
|
||||
profileIconId: player.profileIconId ?? 0,
|
||||
passCount: player.passCount ?? 0,
|
||||
masteries: player.masteries.slice(0, 5).map((mastery) => ({
|
||||
masteries: masteries.slice(0, 5).map((mastery) => ({
|
||||
championId: mastery.championId,
|
||||
level: mastery.championLevel,
|
||||
points: mastery.championPoints,
|
||||
@@ -530,14 +532,10 @@ export function mapApiAuctionToAuctionState(
|
||||
) ?? null);
|
||||
const currentPlayerIndex =
|
||||
auction.phase === "complete" ? totalPlayers : currentAuctionPlayerOrderIndex;
|
||||
const timer = currentBidRoundDeadlineTimestampMS
|
||||
? Math.max(
|
||||
0,
|
||||
Math.ceil(
|
||||
(currentBidRoundDeadlineTimestampMS - now.getTime()) / 1000,
|
||||
),
|
||||
)
|
||||
const remainingMs = currentBidRoundDeadlineTimestampMS
|
||||
? Math.max(0, currentBidRoundDeadlineTimestampMS - now.getTime())
|
||||
: 0;
|
||||
const timer = Math.floor(remainingMs / 1000);
|
||||
|
||||
return {
|
||||
matchId: auction.matchId,
|
||||
@@ -560,6 +558,7 @@ export function mapApiAuctionToAuctionState(
|
||||
teamIndex: currentBidderTeamIndex,
|
||||
}
|
||||
: null,
|
||||
remainingMs,
|
||||
timer,
|
||||
maxTimer: maximumBidRoundDurationSeconds,
|
||||
bidExtensionSeconds: bidRoundExtensionSeconds,
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
lazy,
|
||||
memo,
|
||||
Suspense,
|
||||
useEffect,
|
||||
useMemo,
|
||||
@@ -26,7 +27,10 @@ import {
|
||||
type AuctionPlayerView,
|
||||
type AuctionStateView,
|
||||
} from '../api/mappers';
|
||||
import { useAuctionSocket } from '../api/useAuctionSocket';
|
||||
import {
|
||||
useAuctionSocket,
|
||||
type BidLatencyDiagnostics,
|
||||
} from '../api/useAuctionSocket';
|
||||
import {
|
||||
DEFAULT_COMMUNITY_ID,
|
||||
setDevCaptainTeamIndex,
|
||||
@@ -176,6 +180,53 @@ function getMaxBidForTeam(team: AuctionStateView['teams'][number]) {
|
||||
return Math.max(0, team.points - getReservedPointsAfterCurrentBid(team));
|
||||
}
|
||||
|
||||
function formatLatencyMs(value: number | undefined) {
|
||||
return typeof value === 'number' && Number.isFinite(value)
|
||||
? `${Math.round(value)}ms`
|
||||
: '-';
|
||||
}
|
||||
|
||||
function formatBidLatencyDiagnostics(
|
||||
diagnostics: BidLatencyDiagnostics | null,
|
||||
) {
|
||||
if (!diagnostics) return null;
|
||||
|
||||
const serverDeadlineTimestampMS =
|
||||
diagnostics.bidDiagnostics?.currentBidRoundDeadlineTimestampMS;
|
||||
const serverTimestampMS = diagnostics.bidDiagnostics?.currentServerTimestampMS;
|
||||
const serverRemainingMS =
|
||||
typeof diagnostics.serverObservedRemainingBidRoundTimeMS === 'number'
|
||||
? diagnostics.serverObservedRemainingBidRoundTimeMS
|
||||
: typeof serverDeadlineTimestampMS === 'number' &&
|
||||
typeof serverTimestampMS === 'number'
|
||||
? serverDeadlineTimestampMS - serverTimestampMS
|
||||
: undefined;
|
||||
const timing = diagnostics.bidServerTiming;
|
||||
const parts = [
|
||||
`RTT ${formatLatencyMs(diagnostics.serverRoundTripDurationMS)}`,
|
||||
`gateway ${formatLatencyMs(timing?.gatewayTotalDurationMS)}`,
|
||||
`service ${formatLatencyMs(timing?.serviceTotalDurationMS)}`,
|
||||
`redis ${formatLatencyMs(timing?.redisBidCommandDurationMS)}`,
|
||||
`context ${formatLatencyMs(timing?.redisBidContextReadDurationMS)}`,
|
||||
];
|
||||
|
||||
if (timing?.fallbackFullStatePath) {
|
||||
parts.push('fallback full-state');
|
||||
}
|
||||
if (typeof diagnostics.clientObservedRemainingBidRoundTimeMS === 'number') {
|
||||
parts.push(
|
||||
`client-left ${formatLatencyMs(
|
||||
diagnostics.clientObservedRemainingBidRoundTimeMS,
|
||||
)}`,
|
||||
);
|
||||
}
|
||||
if (typeof serverRemainingMS === 'number') {
|
||||
parts.push(`server-left ${formatLatencyMs(serverRemainingMS)}`);
|
||||
}
|
||||
|
||||
return parts.join(' · ');
|
||||
}
|
||||
|
||||
function getSoloTierHistory(entries: ApiTierHistoryEntry[]) {
|
||||
return entries.filter((entry) => entry.queueType === 'RANKED_SOLO_5x5');
|
||||
}
|
||||
@@ -196,7 +247,7 @@ function TimerBar({ timer, maxTimer }: { timer: number; maxTimer: number }) {
|
||||
return (
|
||||
<div className="w-full h-1.5 bg-base-content/5">
|
||||
<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}%` }}
|
||||
/>
|
||||
</div>
|
||||
@@ -426,6 +477,8 @@ function TeamPanel({
|
||||
);
|
||||
}
|
||||
|
||||
const MemoTeamPanel = memo(TeamPanel);
|
||||
|
||||
function PlayerSpotlight({
|
||||
state,
|
||||
historyBackTo,
|
||||
@@ -433,24 +486,52 @@ function PlayerSpotlight({
|
||||
state: AuctionStateView;
|
||||
historyBackTo: string;
|
||||
}) {
|
||||
const { data: ddragon } = useDdragonManifest();
|
||||
const player = state.currentPlayer;
|
||||
const snapshotSoloTierHistory = player
|
||||
? getSoloTierHistory(player.tierHistory)
|
||||
: [];
|
||||
const historyProfileQuery = useUserHistoryProfile(
|
||||
player?.userId,
|
||||
DEFAULT_COMMUNITY_ID,
|
||||
Boolean(player && snapshotSoloTierHistory.length === 0),
|
||||
);
|
||||
if (!player) return null;
|
||||
|
||||
return (
|
||||
<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 =
|
||||
snapshotSoloTierHistory.length > 0
|
||||
? snapshotSoloTierHistory
|
||||
: getSoloTierHistory(historyProfileQuery.data?.tierHistory ?? []);
|
||||
|
||||
return (
|
||||
<div className="border border-base-content/10 bg-base-100">
|
||||
<>
|
||||
<div className="p-5 border-b border-base-content/8">
|
||||
<div className="flex items-start gap-4">
|
||||
<Link
|
||||
@@ -557,7 +638,41 @@ function PlayerSpotlight({
|
||||
|
||||
<RecentSoloStats player={player} />
|
||||
</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') && (
|
||||
<div className="border-t border-base-content/8 px-4 py-3 bg-base-content/[0.02]">
|
||||
<div className="flex items-center justify-between">
|
||||
@@ -589,7 +704,7 @@ function PlayerSpotlight({
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -616,6 +731,10 @@ function BidControls({
|
||||
: 0;
|
||||
const maxBid = activeTeam ? getMaxBidForTeam(activeTeam) : 0;
|
||||
const canAffordNextBid = !isActiveTeamFull && maxBid >= minBid;
|
||||
const isBidExpired = state.remainingMs <= 0;
|
||||
const effectiveBidAmount = activeTeam
|
||||
? Math.min(maxBid, Math.max(minBid, bidAmount))
|
||||
: Math.max(minBid, bidAmount);
|
||||
|
||||
useEffect(() => {
|
||||
const nextBid = Math.max(minBid, Math.ceil(minBid / 10) * 10);
|
||||
@@ -692,12 +811,13 @@ function BidControls({
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => onBid(activeTeam.teamIndex, bidAmount)}
|
||||
onClick={() => onBid(activeTeam.teamIndex, effectiveBidAmount)}
|
||||
disabled={
|
||||
isBidPending ||
|
||||
!canAffordNextBid ||
|
||||
bidAmount > maxBid ||
|
||||
bidAmount <= state.currentBid
|
||||
isBidExpired ||
|
||||
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 ${
|
||||
`${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})`
|
||||
: isBidPending
|
||||
? '입찰 반영 중...'
|
||||
: isBidExpired
|
||||
? '입찰 마감 확인 중'
|
||||
: !canAffordNextBid
|
||||
? `입찰 불가 (다음 ${formatPoints(minBid)}P · 최대 ${formatPoints(maxBid)}P)`
|
||||
: `${teamIndexLabel(activeTeam.teamIndex, activeTeam.name)} 입찰 (${formatPoints(bidAmount)}P)`}
|
||||
: `${teamIndexLabel(activeTeam.teamIndex, activeTeam.name)} 입찰 (${formatPoints(effectiveBidAmount)}P)`}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
@@ -752,6 +874,8 @@ function BidLog({ bids }: { bids: AuctionStateView['bids'] }) {
|
||||
);
|
||||
}
|
||||
|
||||
const MemoBidLog = memo(BidLog);
|
||||
|
||||
export default function AuctionPage() {
|
||||
const { id } = useParams();
|
||||
const location = useLocation();
|
||||
@@ -814,7 +938,7 @@ export default function AuctionPage() {
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const timer = window.setInterval(() => setNow(Date.now()), 1000);
|
||||
const timer = window.setInterval(() => setNow(Date.now()), 250);
|
||||
return () => window.clearInterval(timer);
|
||||
}, []);
|
||||
|
||||
@@ -825,14 +949,28 @@ export default function AuctionPage() {
|
||||
|
||||
const liveAuction = pickLatestAuction(socket.auction, auctionQuery.data);
|
||||
const syncedNow = now + socket.serverTimeOffsetMs;
|
||||
const auctionState =
|
||||
liveAuction && matchQuery.data
|
||||
? mapApiAuctionToAuctionState(
|
||||
liveAuction,
|
||||
matchQuery.data,
|
||||
new Date(syncedNow),
|
||||
)
|
||||
: null;
|
||||
const baseAuctionState = useMemo(
|
||||
() =>
|
||||
liveAuction && matchQuery.data
|
||||
? mapApiAuctionToAuctionState(liveAuction, matchQuery.data)
|
||||
: null,
|
||||
[liveAuction, matchQuery.data],
|
||||
);
|
||||
const auctionState = useMemo(() => {
|
||||
if (!baseAuctionState) return null;
|
||||
const deadlineTimestampMS = baseAuctionState.deadline
|
||||
? Date.parse(baseAuctionState.deadline)
|
||||
: undefined;
|
||||
const remainingMs =
|
||||
typeof deadlineTimestampMS === 'number' && Number.isFinite(deadlineTimestampMS)
|
||||
? Math.max(0, deadlineTimestampMS - syncedNow)
|
||||
: 0;
|
||||
return {
|
||||
...baseAuctionState,
|
||||
remainingMs,
|
||||
timer: Math.floor(remainingMs / 1000),
|
||||
};
|
||||
}, [baseAuctionState, syncedNow]);
|
||||
const availableTeamIndexes = useMemo(() => {
|
||||
const indexes = new Set((auctionState?.teams ?? []).map((team) => team.teamIndex));
|
||||
return [...indexes].sort((left, right) => left - right);
|
||||
@@ -915,6 +1053,9 @@ export default function AuctionPage() {
|
||||
const errorMessage =
|
||||
socket.error ??
|
||||
(auctionQuery.error instanceof Error ? auctionQuery.error.message : null);
|
||||
const bidLatencyMessage = formatBidLatencyDiagnostics(
|
||||
socket.bidLatencyDiagnostics,
|
||||
);
|
||||
const matchSideEffectMessage = resolveMatchSideEffectMessage(
|
||||
auctionState.matchSideEffectStatus,
|
||||
);
|
||||
@@ -1040,6 +1181,12 @@ export default function AuctionPage() {
|
||||
</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 && (
|
||||
<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}
|
||||
@@ -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">
|
||||
<aside className="hidden xl:block">
|
||||
<PoolPanel state={auctionState} />
|
||||
<MemoPoolPanel state={auctionState} />
|
||||
</aside>
|
||||
|
||||
<div className="grid sm:grid-cols-2 gap-4 content-start">
|
||||
{auctionState.teams.map((team) => (
|
||||
<TeamPanel
|
||||
<MemoTeamPanel
|
||||
key={team.teamIndex}
|
||||
team={team}
|
||||
isActive={isCurrentBidder(auctionState.currentBidder, team)}
|
||||
@@ -1157,7 +1304,7 @@ export default function AuctionPage() {
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<PlayerSpotlight
|
||||
<MemoPlayerSpotlight
|
||||
state={auctionState}
|
||||
historyBackTo={historyBackTo}
|
||||
/>
|
||||
@@ -1184,7 +1331,7 @@ export default function AuctionPage() {
|
||||
})
|
||||
}
|
||||
/>
|
||||
<BidLog bids={auctionState.bids} />
|
||||
<MemoBidLog bids={auctionState.bids} />
|
||||
|
||||
{canManageAuction && (
|
||||
<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({
|
||||
label,
|
||||
count,
|
||||
|
||||
Reference in new issue
Block a user