1056 lines
36 KiB
TypeScript
1056 lines
36 KiB
TypeScript
import { useEffect, useRef, useState } from 'react';
|
|
import { io, type Socket } from 'socket.io-client';
|
|
import { API_BASE_URL, useAuthUserId } from '../config';
|
|
import { acquireAccessToken } from '../lib/auth/token-provider';
|
|
import type { ApiAuction, ApiAuctionChatMessage, Position } from './types';
|
|
import {
|
|
isAuctionResyncRecommended,
|
|
resolveAuctionErrorMessage,
|
|
resolveAuctionRejectionMessage,
|
|
} from './auctionRejectionMessages';
|
|
// [AUCTION-DEBUG] 경매 "중복 멤버" 조사용 임시 계측. 조사 종료 후 제거 대상
|
|
// (호출부는 전부 addNewRelicPageAction / describeAuctionForTelemetry 로 grep 가능).
|
|
import { addNewRelicPageAction } from '../lib/observability/new-relic';
|
|
|
|
type ConnectionStatus =
|
|
| 'idle'
|
|
| 'connecting'
|
|
| 'connected'
|
|
| 'disconnected'
|
|
| 'error';
|
|
|
|
interface BidPayload {
|
|
bidderTeamIndex: number;
|
|
bidPointAmount: number;
|
|
bidRequestId?: string;
|
|
clientObservedAuctionLifecycleId?: string;
|
|
clientObservedCurrentBidRoundPlayerUserId?: string;
|
|
}
|
|
|
|
interface ChatMessagePayload {
|
|
displayName?: string;
|
|
message: string;
|
|
}
|
|
|
|
interface AuctionActionPayload {
|
|
auctionActionRequestId?: string;
|
|
clientObservedAuctionLifecycleId?: string;
|
|
clientObservedCurrentAuctionPlayerOrderIndex?: number;
|
|
clientObservedCurrentBidRoundPlayerUserId?: string;
|
|
clientObservedPhase?: string;
|
|
clientObservedRevision?: number;
|
|
}
|
|
|
|
interface SoldPayload extends AuctionActionPayload {
|
|
assignedPosition?: Position;
|
|
}
|
|
|
|
interface ChatHistoryPayload {
|
|
messages?: ApiAuctionChatMessage[];
|
|
}
|
|
|
|
interface ResetPayload {
|
|
matchId?: string;
|
|
}
|
|
|
|
type MatchSideEffectStatus = NonNullable<ApiAuction['matchSideEffectStatus']>;
|
|
|
|
interface MatchSideEffectPayload {
|
|
auctionLifecycleId?: string;
|
|
currentServerTimestampMS?: number;
|
|
matchSideEffectRevision?: number;
|
|
matchSideEffectStatus?: MatchSideEffectStatus;
|
|
}
|
|
|
|
interface BidDeltaPayload {
|
|
auctionBidHistoryEntry?: {
|
|
bidderTeamIndex?: number;
|
|
bidPointAmount?: number;
|
|
bidderUserId?: string;
|
|
bidPlacedAtTimestampMS?: number;
|
|
};
|
|
auctionLifecycleId?: string;
|
|
bidRequestId?: string;
|
|
currentBidRoundDeadlineTimestampMS?: number;
|
|
currentHighestBidderTeamIndex?: number;
|
|
currentHighestBidPointAmount?: number;
|
|
currentServerTimestampMS?: number;
|
|
revision?: number;
|
|
}
|
|
|
|
interface BidServerTimingPayload {
|
|
fallbackFullStatePath?: boolean;
|
|
gatewayTotalDurationMS?: number;
|
|
redisBidCommandDurationMS?: number;
|
|
redisBidContextReadDurationMS?: number;
|
|
serviceTotalDurationMS?: number;
|
|
}
|
|
|
|
interface BidDiagnosticsPayload {
|
|
currentBidRoundDeadlineTimestampMS?: number;
|
|
currentServerTimestampMS?: number;
|
|
}
|
|
|
|
interface BidAckPayload {
|
|
auctionRejectionReason?: string;
|
|
bidDelta?: BidDeltaPayload | null;
|
|
bidDiagnostics?: BidDiagnosticsPayload;
|
|
bidServerTiming?: BidServerTimingPayload;
|
|
code?: string;
|
|
message?: string;
|
|
rejected?: boolean;
|
|
resyncRecommended?: 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[],
|
|
incoming: ApiAuctionChatMessage[],
|
|
) {
|
|
const byId = new Map(current.map((message) => [message.id, message]));
|
|
for (const message of incoming) {
|
|
byId.set(message.id, message);
|
|
}
|
|
|
|
return [...byId.values()]
|
|
.sort((left, right) => Date.parse(left.sentAt) - Date.parse(right.sentAt))
|
|
.slice(-MAX_CHAT_MESSAGES);
|
|
}
|
|
|
|
export function useAuctionSocket(matchId: string | undefined) {
|
|
const authUserId = useAuthUserId();
|
|
const socketRef = useRef<Socket | null>(null);
|
|
const pendingBidTimeoutsRef = useRef<
|
|
Record<string, ReturnType<typeof setTimeout>>
|
|
>({});
|
|
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<
|
|
Record<string, { amount: number; teamIndex: number }>
|
|
>({});
|
|
const [pendingActionRequests, setPendingActionRequests] = useState<
|
|
Record<string, { action: string }>
|
|
>({});
|
|
const [resetAt, setResetAt] = useState<number | null>(null);
|
|
const [connectionStatus, setConnectionStatus] =
|
|
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,
|
|
source = 'socket-state',
|
|
): boolean {
|
|
const currentAuction = latestAuctionRef.current;
|
|
const applied = shouldApplyIncomingAuctionState(currentAuction, nextAuction);
|
|
const currentRevision =
|
|
typeof currentAuction?.revision === 'number'
|
|
? currentAuction.revision
|
|
: -1;
|
|
const incomingRevision =
|
|
typeof nextAuction?.revision === 'number' ? nextAuction.revision : -1;
|
|
// 단조성을 깨고 적용되는 경우(=revision이 같거나 뒤로 가는데도 반영됨).
|
|
// force-resync/lifecycle 교체로만 발생하며, "2~3 버전 롤백"의 직접 증거가 된다.
|
|
const isBackwardApply =
|
|
applied &&
|
|
currentRevision >= 0 &&
|
|
incomingRevision >= 0 &&
|
|
incomingRevision <= currentRevision;
|
|
addNewRelicPageAction('AuctionClientStateApply', {
|
|
matchId: matchId ?? 'none',
|
|
source,
|
|
applied,
|
|
isBackwardApply,
|
|
revisionDelta: incomingRevision - currentRevision,
|
|
...describeAuctionForTelemetry('current', currentAuction),
|
|
...describeAuctionForTelemetry('incoming', nextAuction),
|
|
});
|
|
|
|
if (!applied) {
|
|
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) {
|
|
return;
|
|
}
|
|
|
|
let disposed = false;
|
|
setConnectionStatus('connecting');
|
|
setError(null);
|
|
|
|
void (async () => {
|
|
const accessToken = await acquireAccessToken().catch((error) => {
|
|
console.warn('Failed to acquire socket access token:', error);
|
|
return null;
|
|
});
|
|
if (disposed) return;
|
|
|
|
const socket = io(`${API_BASE_URL}/auction`, {
|
|
transports: ['websocket'],
|
|
auth: accessToken
|
|
? { token: accessToken }
|
|
: authUserId
|
|
? { 'x-auth-user-id': authUserId }
|
|
: {},
|
|
});
|
|
|
|
socketRef.current = socket;
|
|
|
|
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) => {
|
|
const didApplyState = commitAuctionState(nextAuction, 'socket-state');
|
|
if (didApplyState) {
|
|
clearPendingActionRequests();
|
|
}
|
|
applyFallbackServerTimestamp(nextAuction.currentServerTimestampMS);
|
|
if (nextAuction.chatMessages) {
|
|
setChatMessages(mergeChatMessages([], nextAuction.chatMessages));
|
|
}
|
|
if (didApplyState) {
|
|
setError(null);
|
|
}
|
|
});
|
|
|
|
socket.on('chat-history', (payload: ChatHistoryPayload) => {
|
|
setChatMessages(mergeChatMessages([], payload.messages ?? []));
|
|
});
|
|
|
|
socket.on('chat-message', (message: ApiAuctionChatMessage) => {
|
|
setChatMessages((current) => mergeChatMessages(current, [message]));
|
|
});
|
|
|
|
socket.on('bid', (payload: BidDeltaPayload) => {
|
|
applyFallbackServerTimestamp(payload?.currentServerTimestampMS);
|
|
const beforeBid = latestAuctionRef.current;
|
|
const didApplyBidDelta = commitBidDelta(payload);
|
|
addNewRelicPageAction('AuctionClientBidDelta', {
|
|
matchId: matchId ?? 'none',
|
|
applied: didApplyBidDelta,
|
|
deltaRevision:
|
|
typeof payload?.revision === 'number' ? payload.revision : -1,
|
|
deltaBidAmount: Number(payload?.currentHighestBidPointAmount ?? -1),
|
|
deltaBidderTeamIndex: Number(
|
|
payload?.currentHighestBidderTeamIndex ?? -1,
|
|
),
|
|
beforeRevision:
|
|
typeof beforeBid?.revision === 'number' ? beforeBid.revision : -1,
|
|
beforeBidAmount: beforeBid
|
|
? resolveCurrentBidPointAmount(beforeBid)
|
|
: -1,
|
|
beforePlayerUserId: beforeBid?.currentBidRoundPlayerUserId ?? 'none',
|
|
});
|
|
if (payload?.bidRequestId) {
|
|
if (
|
|
didApplyBidDelta ||
|
|
pendingBidTimeoutsRef.current[payload.bidRequestId]
|
|
) {
|
|
clearPendingBidRequest(payload.bidRequestId);
|
|
}
|
|
}
|
|
});
|
|
|
|
socket.on('match-side-effect', (payload: MatchSideEffectPayload) => {
|
|
applyFallbackServerTimestamp(payload?.currentServerTimestampMS);
|
|
if (
|
|
!payload?.matchSideEffectStatus ||
|
|
typeof payload.matchSideEffectRevision !== 'number'
|
|
) {
|
|
return;
|
|
}
|
|
const matchSideEffectRevision = payload.matchSideEffectRevision;
|
|
const matchSideEffectStatus = payload.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);
|
|
addNewRelicPageAction('AuctionClientSideEffect', {
|
|
matchId: matchId ?? 'none',
|
|
matchSideEffectStatus: matchSideEffectStatus ?? 'unknown',
|
|
matchSideEffectRevision,
|
|
...describeAuctionForTelemetry('current', currentAuction),
|
|
});
|
|
});
|
|
|
|
socket.on('reset', (payload: ResetPayload) => {
|
|
if (payload.matchId && payload.matchId !== matchId) return;
|
|
latestAuctionRef.current = null;
|
|
latestConfirmedBidPointAmountRef.current = 0;
|
|
setAuction(null);
|
|
setChatMessages([]);
|
|
setResetAt(Date.now());
|
|
setError('경매가 취소되었습니다.');
|
|
});
|
|
|
|
socket.on('error', (payload: { message?: string }) => {
|
|
// ack 없는 error 채널(영문 message만)도 같은 톤의 한국어로 매핑한다.
|
|
setError(resolveAuctionErrorMessage(payload.message));
|
|
});
|
|
})();
|
|
|
|
return () => {
|
|
disposed = true;
|
|
const socket = socketRef.current;
|
|
socket?.removeAllListeners();
|
|
socket?.disconnect();
|
|
socketRef.current = null;
|
|
clearTimeSyncTimers();
|
|
Object.values(pendingBidTimeoutsRef.current).forEach((timeoutId) =>
|
|
clearTimeout(timeoutId),
|
|
);
|
|
Object.values(pendingActionTimeoutsRef.current).forEach((timeoutId) =>
|
|
clearTimeout(timeoutId),
|
|
);
|
|
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]);
|
|
|
|
function clearPendingBidRequest(bidRequestId: string) {
|
|
const timeoutId = pendingBidTimeoutsRef.current[bidRequestId];
|
|
if (timeoutId) clearTimeout(timeoutId);
|
|
delete pendingBidTimeoutsRef.current[bidRequestId];
|
|
setPendingBidRequests((current) => {
|
|
const next = { ...current };
|
|
delete next[bidRequestId];
|
|
return next;
|
|
});
|
|
}
|
|
|
|
function clearPendingActionRequest(auctionActionRequestId: string) {
|
|
const timeoutId = pendingActionTimeoutsRef.current[auctionActionRequestId];
|
|
if (timeoutId) clearTimeout(timeoutId);
|
|
delete pendingActionTimeoutsRef.current[auctionActionRequestId];
|
|
setPendingActionRequests((current) => {
|
|
const next = { ...current };
|
|
delete next[auctionActionRequestId];
|
|
return next;
|
|
});
|
|
}
|
|
|
|
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) {
|
|
setError('소켓이 아직 연결되지 않았습니다.');
|
|
return;
|
|
}
|
|
|
|
setError(null);
|
|
|
|
if (payload === undefined) {
|
|
socket.emit(eventName);
|
|
return;
|
|
}
|
|
|
|
socket.emit(eventName, payload);
|
|
}
|
|
|
|
function buildAuctionActionPayload(): AuctionActionPayload {
|
|
const currentAuction = latestAuctionRef.current ?? auction;
|
|
return {
|
|
auctionActionRequestId: createClientRequestId(),
|
|
clientObservedAuctionLifecycleId: currentAuction?.auctionLifecycleId,
|
|
clientObservedCurrentAuctionPlayerOrderIndex:
|
|
currentAuction?.currentAuctionPlayerOrderIndex,
|
|
clientObservedCurrentBidRoundPlayerUserId:
|
|
currentAuction?.currentBidRoundPlayerUserId,
|
|
clientObservedPhase: currentAuction?.phase,
|
|
clientObservedRevision: currentAuction?.revision,
|
|
};
|
|
}
|
|
|
|
// 거부 등으로 클라 상태가 낡았을 때 서버 최신 state를 다시 받아 rebaseline한다.
|
|
// join 핸들러가 getStateByMatchId → broadcastState로 fresh state를 내려주고,
|
|
// revision 가드상 더 높은 revision이라 정상 적용된다(force-resync 아님).
|
|
function resyncAuctionState() {
|
|
const socket = socketRef.current;
|
|
if (!socket || !socket.connected || !matchId) return;
|
|
socket.emit('join', { matchId });
|
|
}
|
|
|
|
// retryAttempt: 거부 후 자동 재시도 횟수(루프 방지를 위해 1회로 제한).
|
|
function emitAuctionAction(
|
|
eventName: string,
|
|
payload: AuctionActionPayload,
|
|
retryAttempt = 0,
|
|
) {
|
|
const socket = socketRef.current;
|
|
if (!socket || !socket.connected) {
|
|
setError('소켓이 아직 연결되지 않았습니다.');
|
|
return;
|
|
}
|
|
if (Object.keys(pendingActionTimeoutsRef.current).length > 0) {
|
|
return;
|
|
}
|
|
|
|
const auctionActionRequestId =
|
|
payload.auctionActionRequestId ?? createClientRequestId();
|
|
const actionPayload = {
|
|
...payload,
|
|
auctionActionRequestId,
|
|
};
|
|
setError(null);
|
|
setPendingActionRequests((current) => ({
|
|
...current,
|
|
[auctionActionRequestId]: { action: eventName },
|
|
}));
|
|
pendingActionTimeoutsRef.current[auctionActionRequestId] = setTimeout(() => {
|
|
clearPendingActionRequest(auctionActionRequestId);
|
|
setError('경매 진행 응답이 지연되어 최신 상태를 다시 확인해주세요.');
|
|
}, 10_000);
|
|
addNewRelicPageAction('AuctionClientActionSent', {
|
|
matchId: matchId ?? 'none',
|
|
action: eventName,
|
|
retryAttempt,
|
|
sentRevision:
|
|
typeof payload.clientObservedRevision === 'number'
|
|
? payload.clientObservedRevision
|
|
: -1,
|
|
sentOrderIndex:
|
|
typeof payload.clientObservedCurrentAuctionPlayerOrderIndex === 'number'
|
|
? payload.clientObservedCurrentAuctionPlayerOrderIndex
|
|
: -1,
|
|
sentPlayerUserId:
|
|
payload.clientObservedCurrentBidRoundPlayerUserId ?? 'none',
|
|
sentPhase: payload.clientObservedPhase ?? 'none',
|
|
...describeAuctionForTelemetry('observed', latestAuctionRef.current),
|
|
});
|
|
socket.emit(
|
|
eventName,
|
|
actionPayload,
|
|
(ack?: {
|
|
auctionActionRequestId?: string;
|
|
auctionRejectionReason?: string;
|
|
code?: string;
|
|
message?: string;
|
|
rejected?: boolean;
|
|
resyncRecommended?: boolean;
|
|
state?: ApiAuction;
|
|
}) => {
|
|
if (ack?.rejected) {
|
|
clearPendingActionRequest(
|
|
ack?.auctionActionRequestId ?? auctionActionRequestId,
|
|
);
|
|
// 2) 자동 재시도: "낡은 화면 때문에 거부"였고 동기 rebaseline 소스(state)가
|
|
// 있을 때만 1회. assignedPosition 등 원래 payload는 유지하고 관측값/요청
|
|
// id만 새로 만든다. 재시도 시에는 중간 에러 문구를 띄우지 않는다(무음 복구).
|
|
const canAutoRetry =
|
|
Boolean(ack.state) &&
|
|
isAuctionResyncRecommended(ack) &&
|
|
retryAttempt < 1;
|
|
// 거부 시 "클라가 보낸 관측 revision"과 "서버가 동봉한 진짜 state"를 함께
|
|
// 기록한다. observedRevision < serverRevision 이면 stale-client CONFLICT 확정.
|
|
addNewRelicPageAction('AuctionClientActionRejected', {
|
|
matchId: matchId ?? 'none',
|
|
action: eventName,
|
|
retryAttempt,
|
|
rejectionReason:
|
|
ack?.auctionRejectionReason ?? ack?.code ?? 'unknown',
|
|
rejectionCode: ack?.code ?? 'none',
|
|
resyncRecommended: isAuctionResyncRecommended(ack),
|
|
hasAckState: Boolean(ack?.state),
|
|
willAutoRetry: canAutoRetry,
|
|
sentRevision:
|
|
typeof payload.clientObservedRevision === 'number'
|
|
? payload.clientObservedRevision
|
|
: -1,
|
|
sentOrderIndex:
|
|
typeof payload.clientObservedCurrentAuctionPlayerOrderIndex ===
|
|
'number'
|
|
? payload.clientObservedCurrentAuctionPlayerOrderIndex
|
|
: -1,
|
|
sentPlayerUserId:
|
|
payload.clientObservedCurrentBidRoundPlayerUserId ?? 'none',
|
|
sentPhase: payload.clientObservedPhase ?? 'none',
|
|
...describeAuctionForTelemetry('observed', latestAuctionRef.current),
|
|
...describeAuctionForTelemetry('server', ack?.state ?? null),
|
|
});
|
|
// 1) rebaseline: 서버가 동봉한 최신 state를 즉시 반영(없으면 join으로 재요청).
|
|
// commitAuctionState는 latestAuctionRef를 동기로 갱신하므로, 이후
|
|
// buildAuctionActionPayload는 최신 관측값(revision/phase/선수)을 읽는다.
|
|
if (ack.state) {
|
|
commitAuctionState(ack.state, 'action-reject-rebaseline');
|
|
} else if (isAuctionResyncRecommended(ack)) {
|
|
resyncAuctionState();
|
|
}
|
|
if (canAutoRetry) {
|
|
emitAuctionAction(
|
|
eventName,
|
|
{ ...payload, ...buildAuctionActionPayload() },
|
|
retryAttempt + 1,
|
|
);
|
|
} else {
|
|
setError(resolveAuctionRejectionMessage(ack));
|
|
}
|
|
return;
|
|
}
|
|
const ackState = ack?.state;
|
|
if (ackState) {
|
|
clearPendingActionRequest(
|
|
ack.auctionActionRequestId ?? auctionActionRequestId,
|
|
);
|
|
addNewRelicPageAction('AuctionClientActionAck', {
|
|
matchId: matchId ?? 'none',
|
|
action: eventName,
|
|
retryAttempt,
|
|
sentRevision:
|
|
typeof payload.clientObservedRevision === 'number'
|
|
? payload.clientObservedRevision
|
|
: -1,
|
|
...describeAuctionForTelemetry('server', ackState),
|
|
});
|
|
commitAuctionState(ackState, 'action-ack');
|
|
}
|
|
},
|
|
);
|
|
}
|
|
|
|
const currentAuction = auction;
|
|
const visibleAuction =
|
|
currentAuction && currentAuction.matchId === matchId ? currentAuction : null;
|
|
const visibleConnectionStatus: ConnectionStatus = matchId
|
|
? connectionStatus
|
|
: 'idle';
|
|
|
|
return {
|
|
auction: visibleAuction,
|
|
chatMessages: visibleAuction ? chatMessages : [],
|
|
isAuctionActionPending: Object.keys(pendingActionRequests).length > 0,
|
|
isBidPending: Object.keys(pendingBidRequests).length > 0,
|
|
pendingActionRequests,
|
|
pendingBidRequests,
|
|
resetAt,
|
|
connectionStatus: visibleConnectionStatus,
|
|
error,
|
|
bidLatencyDiagnostics,
|
|
serverRoundTripMs: matchId ? serverRoundTripMs : null,
|
|
serverTimeOffsetMs: matchId ? serverTimeOffsetMs : 0,
|
|
placeBid(payload: BidPayload) {
|
|
const socket = socketRef.current;
|
|
if (!socket || !socket.connected) {
|
|
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 ??
|
|
currentAuction?.auctionLifecycleId,
|
|
clientObservedCurrentBidRoundPlayerUserId:
|
|
payload.clientObservedCurrentBidRoundPlayerUserId ??
|
|
currentAuction?.currentBidRoundPlayerUserId,
|
|
};
|
|
|
|
setError(null);
|
|
setPendingBidRequests((current) => ({
|
|
...current,
|
|
[bidRequestId]: {
|
|
amount: bidPayload.bidPointAmount,
|
|
teamIndex: bidPayload.bidderTeamIndex,
|
|
},
|
|
}));
|
|
pendingBidTimeoutsRef.current[bidRequestId] = setTimeout(() => {
|
|
clearPendingBidRequest(bidRequestId);
|
|
setError('입찰 응답이 지연되어 최신 상태를 다시 확인해주세요.');
|
|
}, 10_000);
|
|
socket.emit(
|
|
'bid',
|
|
bidPayload,
|
|
(ack?: BidAckPayload) => {
|
|
captureBidLatencyDiagnostics(ack);
|
|
if (ack?.rejected) {
|
|
clearPendingBidRequest(bidRequestId);
|
|
// 입찰 거부도 최신 state로 rebaseline(예: 0초 입찰 EXPIRED → 만료된
|
|
// 라운드 화면에서 벗어나게). 단 입찰은 자동 재시도하지 않는다(의도치
|
|
// 않은 금액 재입찰 방지).
|
|
if (ack.state) {
|
|
commitAuctionState(ack.state);
|
|
} else if (isAuctionResyncRecommended(ack)) {
|
|
resyncAuctionState();
|
|
}
|
|
setError(resolveAuctionRejectionMessage(ack));
|
|
return;
|
|
}
|
|
if (ack?.bidDelta) {
|
|
clearPendingBidRequest(bidRequestId);
|
|
commitBidDelta(ack.bidDelta);
|
|
return;
|
|
}
|
|
const ackState = ack?.state;
|
|
if (ackState) {
|
|
clearPendingBidRequest(bidRequestId);
|
|
commitAuctionState(ackState);
|
|
}
|
|
},
|
|
);
|
|
},
|
|
openBidding() {
|
|
emitAuctionAction('open-bidding', buildAuctionActionPayload());
|
|
},
|
|
markSold(assignedPosition?: Position) {
|
|
const payload: SoldPayload = {
|
|
...buildAuctionActionPayload(),
|
|
assignedPosition,
|
|
};
|
|
emitAuctionAction('sold', payload);
|
|
},
|
|
markPassed() {
|
|
emitAuctionAction('passed', buildAuctionActionPayload());
|
|
},
|
|
next() {
|
|
emitAuctionAction('next', buildAuctionActionPayload());
|
|
},
|
|
sendChatMessage(payload: ChatMessagePayload) {
|
|
emit('chat-message', payload);
|
|
},
|
|
};
|
|
}
|
|
|
|
function createClientRequestId(): string {
|
|
if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) {
|
|
return crypto.randomUUID();
|
|
}
|
|
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;
|
|
}
|
|
|
|
// [AUCTION-DEBUG] 아래 텔레메트리 헬퍼들과 호출부는 조사 종료 후 제거 대상.
|
|
type AuctionTelemetryAttributes = Record<string, string | number | boolean | null>;
|
|
|
|
function readAuctionHistorySequence(auction: ApiAuction | null | undefined) {
|
|
const value = (auction as { currentAuctionHistorySequence?: unknown } | null)
|
|
?.currentAuctionHistorySequence;
|
|
return typeof value === 'number' ? value : -1;
|
|
}
|
|
|
|
function summarizeAuctionTeams(auction: ApiAuction | null | undefined) {
|
|
const teams = Array.isArray(auction?.auctionTeams) ? auction.auctionTeams : [];
|
|
let assignedMemberCount = 0;
|
|
for (const team of teams) {
|
|
const members = (team as { members?: unknown[] }).members;
|
|
if (Array.isArray(members)) assignedMemberCount += members.length;
|
|
}
|
|
return { teamCount: teams.length, assignedMemberCount };
|
|
}
|
|
|
|
// New Relic로 보내기 위해 경매 상태를 평탄한 속성 집합으로 요약한다.
|
|
// prefix로 두 상태(예: 현재 vs 수신)를 한 이벤트에 같이 실어 revision 어긋남을
|
|
// 한눈에 비교할 수 있게 한다.
|
|
function describeAuctionForTelemetry(
|
|
prefix: string,
|
|
auction: ApiAuction | null | undefined,
|
|
): AuctionTelemetryAttributes {
|
|
const teamSummary = summarizeAuctionTeams(auction);
|
|
return {
|
|
[`${prefix}Revision`]:
|
|
typeof auction?.revision === 'number' ? auction.revision : -1,
|
|
[`${prefix}HistorySequence`]: readAuctionHistorySequence(auction),
|
|
[`${prefix}Phase`]: auction?.phase ?? 'unknown',
|
|
[`${prefix}LifecycleId`]: auction?.auctionLifecycleId ?? 'none',
|
|
[`${prefix}OrderIndex`]:
|
|
typeof auction?.currentAuctionPlayerOrderIndex === 'number'
|
|
? auction.currentAuctionPlayerOrderIndex
|
|
: -1,
|
|
[`${prefix}PlayerUserId`]: auction?.currentBidRoundPlayerUserId ?? 'none',
|
|
[`${prefix}BidAmount`]: auction
|
|
? resolveCurrentBidPointAmount(auction)
|
|
: -1,
|
|
[`${prefix}BidderTeamIndex`]:
|
|
typeof auction?.currentHighestBidderTeamIndex === 'number'
|
|
? auction.currentHighestBidderTeamIndex
|
|
: typeof auction?.currentBidderTeamIndex === 'number'
|
|
? auction.currentBidderTeamIndex
|
|
: -1,
|
|
[`${prefix}TeamCount`]: teamSummary.teamCount,
|
|
[`${prefix}AssignedMemberCount`]: teamSummary.assignedMemberCount,
|
|
[`${prefix}ForceResync`]: Boolean(auction?.shouldForceAuctionStateResync),
|
|
};
|
|
}
|
|
|
|
function shouldApplyIncomingAuctionState(
|
|
current: ApiAuction | null,
|
|
incoming: ApiAuction,
|
|
): boolean {
|
|
if (!current) return true;
|
|
if (incoming.shouldForceAuctionStateResync) return true;
|
|
if (
|
|
current.auctionLifecycleId &&
|
|
incoming.auctionLifecycleId &&
|
|
current.auctionLifecycleId !== incoming.auctionLifecycleId
|
|
) {
|
|
return true;
|
|
}
|
|
if (
|
|
typeof current.revision === 'number' &&
|
|
typeof incoming.revision === 'number' &&
|
|
incoming.revision <= current.revision
|
|
) {
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
function applyBidDelta(
|
|
current: ApiAuction | null,
|
|
payload: BidDeltaPayload,
|
|
): ApiAuction | null {
|
|
if (!current) return current;
|
|
if (
|
|
payload.auctionLifecycleId &&
|
|
current.auctionLifecycleId &&
|
|
payload.auctionLifecycleId !== current.auctionLifecycleId
|
|
) {
|
|
return current;
|
|
}
|
|
if (
|
|
typeof current.revision === 'number' &&
|
|
typeof payload.revision === 'number' &&
|
|
payload.revision <= current.revision
|
|
) {
|
|
return current;
|
|
}
|
|
|
|
const bidPointAmount = Number(payload.currentHighestBidPointAmount);
|
|
const bidderTeamIndex = Number(payload.currentHighestBidderTeamIndex);
|
|
if (!Number.isFinite(bidPointAmount) || !Number.isFinite(bidderTeamIndex)) {
|
|
return current;
|
|
}
|
|
|
|
const bidHistoryEntry = normalizeBidHistoryEntry(payload.auctionBidHistoryEntry);
|
|
const currentBidRoundDeadlineTimestampMS =
|
|
typeof payload.currentBidRoundDeadlineTimestampMS === 'number'
|
|
? payload.currentBidRoundDeadlineTimestampMS
|
|
: current.currentBidRoundDeadlineTimestampMS;
|
|
|
|
return {
|
|
...current,
|
|
auctionBidHistory: appendUniqueAuctionBidHistoryEntry(
|
|
current.auctionBidHistory ?? [],
|
|
bidHistoryEntry,
|
|
),
|
|
bids: bidHistoryEntry
|
|
? appendUniqueLegacyBidEntry(current.bids ?? [], bidHistoryEntry)
|
|
: current.bids,
|
|
currentBid: bidPointAmount,
|
|
currentBidderTeamIndex: bidderTeamIndex,
|
|
currentDeadline: currentBidRoundDeadlineTimestampMS
|
|
? new Date(currentBidRoundDeadlineTimestampMS).toISOString()
|
|
: current.currentDeadline,
|
|
currentHighestBidPointAmount: bidPointAmount,
|
|
currentHighestBidderTeamIndex: bidderTeamIndex,
|
|
currentBidRoundDeadlineTimestampMS,
|
|
currentServerTimestampMS:
|
|
payload.currentServerTimestampMS ?? current.currentServerTimestampMS,
|
|
revision: payload.revision ?? current.revision,
|
|
};
|
|
}
|
|
|
|
function normalizeBidHistoryEntry(
|
|
entry: BidDeltaPayload['auctionBidHistoryEntry'],
|
|
): NonNullable<ApiAuction['auctionBidHistory']>[number] | null {
|
|
if (!entry) return null;
|
|
const bidderTeamIndex = Number(entry.bidderTeamIndex);
|
|
const bidPointAmount = Number(entry.bidPointAmount);
|
|
const bidPlacedAtTimestampMS = Number(entry.bidPlacedAtTimestampMS);
|
|
if (!Number.isFinite(bidderTeamIndex) || !Number.isFinite(bidPointAmount)) {
|
|
return null;
|
|
}
|
|
return {
|
|
bidderTeamIndex,
|
|
bidPointAmount,
|
|
bidderUserId: entry.bidderUserId ?? '',
|
|
bidPlacedAtTimestampMS: Number.isFinite(bidPlacedAtTimestampMS)
|
|
? bidPlacedAtTimestampMS
|
|
: Date.now(),
|
|
};
|
|
}
|
|
|
|
function appendUniqueAuctionBidHistoryEntry(
|
|
current: NonNullable<ApiAuction['auctionBidHistory']>,
|
|
entry: NonNullable<ApiAuction['auctionBidHistory']>[number] | null,
|
|
) {
|
|
if (!entry) return current;
|
|
if (
|
|
current.some(
|
|
(existing) =>
|
|
existing.bidderTeamIndex === entry.bidderTeamIndex &&
|
|
existing.bidPointAmount === entry.bidPointAmount &&
|
|
existing.bidPlacedAtTimestampMS === entry.bidPlacedAtTimestampMS,
|
|
)
|
|
) {
|
|
return current;
|
|
}
|
|
return [...current, entry];
|
|
}
|
|
|
|
function appendUniqueLegacyBidEntry(
|
|
current: ApiAuction['bids'],
|
|
entry: NonNullable<ApiAuction['auctionBidHistory']>[number],
|
|
) {
|
|
const currentBids = current ?? [];
|
|
const legacyBid = {
|
|
amount: entry.bidPointAmount,
|
|
bidderUserId: entry.bidderUserId,
|
|
teamIndex: entry.bidderTeamIndex,
|
|
timestamp: new Date(entry.bidPlacedAtTimestampMS).toISOString(),
|
|
};
|
|
if (
|
|
currentBids.some(
|
|
(existing) =>
|
|
existing.teamIndex === legacyBid.teamIndex &&
|
|
existing.amount === legacyBid.amount &&
|
|
existing.timestamp === legacyBid.timestamp,
|
|
)
|
|
) {
|
|
return currentBids;
|
|
}
|
|
return [...currentBids, legacyBid];
|
|
}
|