fix(auction): harden lifecycle and durable bid storage

Serialize lifecycle changes and make cancellation, deadlines, and match side effects recoverable and idempotent.

Archive accepted bids durably, quarantine invalid payloads, and preserve compatibility with empty round IDs. Synchronize HTTP polling and socket state with scoped resync events.

Add cancellation cleanup index migration and regression coverage. Validated with 744 API tests, 65 Redis integration tests, and 28 Mongo integration tests.
This commit is contained in:
dahyeon committed 2026-11-09 23:24:11 +09:00
1 parent f2eec479d9
commit f649490cd2
55 files changed
+5374 -522

No files matched your search

+83
View File
@@ -0,0 +1,83 @@
import type { ApiAuction } from './types';
export interface AuctionResyncReply {
ok?: boolean;
state?: ApiAuction;
retryAfterMS?: number;
}
function waitForRetry(
milliseconds: number,
signal: AbortSignal,
): Promise<void> {
return new Promise((resolve) => {
const finish = () => {
clearTimeout(timer);
signal.removeEventListener('abort', finish);
resolve();
};
const timer = setTimeout(finish, milliseconds);
signal.addEventListener('abort', finish, { once: true });
if (signal.aborted) finish();
});
}
/** Coalesces simultaneous gaps and discards replies from an old connection. */
export function createAuctionResyncRequester(
fetchState: () => Promise<AuctionResyncReply>,
applyState: (state: ApiAuction) => void,
wait = waitForRetry,
) {
let pending: Promise<void> | undefined;
let controller = new AbortController();
let minimumRevision = -1;
let lifecycleId: string | undefined;
return {
request(revision = -1, lifecycle?: string): Promise<void> {
if (revision >= 0) {
minimumRevision =
lifecycle === lifecycleId
? Math.max(minimumRevision, revision)
: revision;
lifecycleId = lifecycle;
}
if (pending) return pending;
const signal = controller.signal;
pending = (async () => {
for (let attempt = 0; attempt < 3 && !signal.aborted; attempt++) {
let retryAfterMS = 500 * (attempt + 1);
try {
const reply = await fetchState();
if (signal.aborted) return;
if (reply.ok && reply.state) {
applyState(reply.state);
// Another gap may have arrived while this snapshot was in flight.
if (
reply.state.auctionLifecycleId !== lifecycleId ||
(reply.state.revision ?? -1) >= minimumRevision
)
return;
}
retryAfterMS = Math.min(
3000,
Math.max(retryAfterMS, reply.retryAfterMS ?? 0),
);
} catch {
/* A timeout gets a bounded retry, never another room join. */
}
if (attempt < 2 && !signal.aborted) await wait(retryAfterMS, signal);
}
})().finally(() => {
if (!signal.aborted) pending = undefined;
});
return pending;
},
cancel() {
controller.abort();
controller = new AbortController();
pending = undefined;
minimumRevision = -1;
lifecycleId = undefined;
},
};
}
+239
View File
@@ -0,0 +1,239 @@
import type { ApiAuction } from "./types";
export interface BidDeltaPayload {
currentBidRoundId?: string;
auctionBidHistoryEntry?: {
bidderTeamIndex?: number;
bidPointAmount?: number;
bidderUserId?: string;
bidPlacedAtTimestampMS?: number;
bidRoundId?: string;
playerUserId?: string;
};
auctionLifecycleId?: string;
bidRequestId?: string;
currentBidRoundDeadlineTimestampMS?: number;
currentHighestBidderTeamIndex?: number;
currentHighestBidPointAmount?: number;
currentServerTimestampMS?: number;
revision?: number;
}
export 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;
}
/** Full state can repair a delta at the same revision; side effects have a
* separate revision and must not regress when a delayed full state arrives. */
export function mergeAuctionState(
current: ApiAuction | null,
incoming: ApiAuction,
): ApiAuction {
if (
current?.auctionLifecycleId === incoming.auctionLifecycleId &&
current?.matchSideEffectTransitionId ===
incoming.matchSideEffectTransitionId &&
(current?.matchSideEffectRevision ?? -1) >
(incoming.matchSideEffectRevision ?? -1)
) {
return {
...incoming,
matchSideEffectRevision: current!.matchSideEffectRevision,
matchSideEffectStatus: current!.matchSideEffectStatus,
};
}
return incoming;
}
export function shouldResyncForBidDelta(
current: ApiAuction | null,
payload: BidDeltaPayload,
): boolean {
if (!current) return true;
if (
payload.auctionLifecycleId &&
current.auctionLifecycleId &&
payload.auctionLifecycleId !== current.auctionLifecycleId
)
return true;
if (
typeof payload.revision !== "number" ||
typeof current.revision !== "number"
)
return true;
if (payload.revision <= current.revision) return false;
return (
payload.revision !== current.revision + 1 ||
current.phase !== "bidding" ||
Boolean(
current.currentBidRoundId &&
payload.currentBidRoundId !== current.currentBidRoundId,
)
);
}
export function applyBidDelta(
current: ApiAuction | null,
payload: BidDeltaPayload,
): ApiAuction | null {
if (!current) return current;
if (shouldResyncForBidDelta(current, payload)) 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,
currentBidRoundId: payload.currentBidRoundId ?? current.currentBidRoundId,
};
}
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 {
bidRoundId: entry.bidRoundId,
playerUserId: entry.playerUserId,
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].slice(-1000);
}
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].slice(-1000);
}
/** HTTP 폴링 결과를 소켓 내부 상태(입찰 기준가·라운드 ID)에도 반영할지 결정한다.
* lifecycle 교체는 소켓 이벤트로만 받는다. 늦게 도착한 이전 경매의 응답이
* 새 경매를 덮어쓰지 않도록 기존 상태가 있으면 같은 lifecycle만 반영한다. */
export function shouldApplyPolledAuctionState(
current: ApiAuction | null,
incoming: ApiAuction,
matchId: string | undefined,
): boolean {
if (!matchId || incoming.matchId !== matchId) return false;
if (!incoming.auctionLifecycleId || !Number.isFinite(incoming.revision))
return false;
if (!current) return true;
if (
!current.auctionLifecycleId ||
current.auctionLifecycleId !== incoming.auctionLifecycleId
)
return false;
return (
typeof current.revision === "number" &&
typeof incoming.revision === "number" &&
incoming.revision >= current.revision
);
}
+7 -2
View File
@@ -28,7 +28,10 @@ const REASON_TO_USER_MESSAGE: Record<string, string> = {
AUCTION_TRANSITION_REJECTED_BECAUSE_REQUEST_COORDINATION_RETRYABLE:
'잠시 처리 중이라 반영되지 않았어요. 다시 시도해 주세요.',
// 입찰
BID_REJECTED_BECAUSE_BID_ROUND_ALREADY_ADVANCED: '이미 다음 선수로 넘어갔어요.',
BID_REJECTED_BECAUSE_CLIENT_UPDATE_REQUIRED:
'경매 화면이 업데이트되었습니다. 새로고침한 뒤 다시 입찰해 주세요.',
BID_REJECTED_BECAUSE_BID_ROUND_ALREADY_ADVANCED:
'이미 다음 선수로 넘어갔어요.',
BID_REJECTED_BECAUSE_BID_ROUND_DEADLINE_PASSED: '마감되어 반영되지 않았어요.',
BID_REJECTED_BECAUSE_AUCTION_NOT_IN_BIDDING_PHASE:
'지금은 입찰할 수 없는 단계예요.',
@@ -100,6 +103,8 @@ export function resolveAuctionErrorMessage(message?: string): string {
}
/** 최신 상태로 rebaseline 후 재시도가 권장되는 거부인지. */
export function isAuctionResyncRecommended(ack: AuctionRejectionAckLike): boolean {
export function isAuctionResyncRecommended(
ack: AuctionRejectionAckLike,
): boolean {
return ack.resyncRecommended === true;
}
+4
View File
@@ -197,6 +197,8 @@ export interface ApiAuction {
currentAuctionPlayerOrderIndex: number;
bids?: ApiAuctionBid[];
auctionBidHistory?: Array<{
bidRoundId?: string;
playerUserId?: string;
bidderTeamIndex: number;
bidPointAmount: number;
bidderUserId: string;
@@ -213,6 +215,7 @@ export interface ApiAuction {
currentDeadline?: string;
currentBidRoundDeadlineTimestampMS?: number;
currentBidRoundPlayerUserId?: string;
currentBidRoundId?: string;
currentServerTimestampMS?: number;
initialPoints?: number;
initialTeamBidPointAmount: number;
@@ -224,6 +227,7 @@ export interface ApiAuction {
auctionLifecycleId?: string;
matchSideEffectRevision?: number;
matchSideEffectStatus?: 'none' | 'pending' | 'processing' | 'completed' | 'failed';
matchSideEffectTransitionId?: string;
canPlaceBidInCurrentBidRound?: boolean;
isAuctionStateTransitionInProgress?: boolean;
shouldForceAuctionStateResync?: boolean;
+174 -211
View File
@@ -3,6 +3,18 @@ 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 {
createAuctionResyncRequester,
type AuctionResyncReply,
} from './auction-resync';
import {
applyBidDelta,
shouldApplyIncomingAuctionState,
shouldResyncForBidDelta,
shouldApplyPolledAuctionState,
mergeAuctionState,
type BidDeltaPayload,
} from './auction-state';
import { resolveAuctionActionRejection } from './auction-action-retry';
import {
isAuctionResyncRecommended,
@@ -21,6 +33,7 @@ type ConnectionStatus =
| 'error';
interface BidPayload {
clientObservedBidRoundId?: string;
bidderTeamIndex: number;
bidPointAmount: number;
bidRequestId?: string;
@@ -52,33 +65,19 @@ interface ChatHistoryPayload {
interface ResetPayload {
matchId?: string;
auctionLifecycleId?: string;
}
type MatchSideEffectStatus = NonNullable<ApiAuction['matchSideEffectStatus']>;
interface MatchSideEffectPayload {
auctionLifecycleId?: string;
auctionStateTransitionId?: 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;
@@ -145,6 +144,9 @@ export function useAuctionSocket(matchId: string | undefined) {
? JSON.stringify([matchId, authUserId ?? null])
: null;
const socketRef = useRef<Socket | null>(null);
const resyncRequesterRef = useRef<ReturnType<
typeof createAuctionResyncRequester
> | null>(null);
const pendingBidTimeoutsRef = useRef<
Record<string, ReturnType<typeof setTimeout>>
>({});
@@ -160,6 +162,7 @@ export function useAuctionSocket(matchId: string | undefined) {
const timeSyncSequenceRef = useRef(0);
const hasSyncedServerTimeRef = useRef(false);
const latestAuctionRef = useRef<ApiAuction | null>(null);
const cancelledLifecycleIdsRef = useRef(new Set<string>());
const latestConfirmedBidPointAmountRef = useRef(0);
const [auction, setAuction] = useState<ApiAuction | null>(null);
const [chatMessages, setChatMessages] = useState<ApiAuctionChatMessage[]>([]);
@@ -187,6 +190,11 @@ export function useAuctionSocket(matchId: string | undefined) {
const commitAuctionState = useCallback(
(nextAuction: ApiAuction, source = 'socket-state'): boolean => {
if (
nextAuction.auctionLifecycleId &&
cancelledLifecycleIdsRef.current.has(nextAuction.auctionLifecycleId)
)
return false;
const currentAuction = latestAuctionRef.current;
const applied = shouldApplyIncomingAuctionState(
currentAuction,
@@ -198,13 +206,12 @@ export function useAuctionSocket(matchId: string | undefined) {
: -1;
const incomingRevision =
typeof nextAuction?.revision === 'number' ? nextAuction.revision : -1;
// 단조성을 깨고 적용되는 경우(=revision이 같거나 뒤로 가는데도 반영됨).
// force-resync/lifecycle 교체로만 발생하며, "2~3 버전 롤백"의 직접 증거가 된다.
// 같은 revision의 전체 상태는 delta 누락 복구이므로 역행으로 기록하지 않는다.
const isBackwardApply =
applied &&
currentRevision >= 0 &&
incomingRevision >= 0 &&
incomingRevision <= currentRevision;
incomingRevision < currentRevision;
addNewRelicPageAction('AuctionClientStateApply', {
matchId: matchId ?? 'none',
source,
@@ -219,6 +226,7 @@ export function useAuctionSocket(matchId: string | undefined) {
return false;
}
nextAuction = mergeAuctionState(currentAuction, nextAuction);
latestAuctionRef.current = nextAuction;
latestConfirmedBidPointAmountRef.current =
resolveCurrentBidPointAmount(nextAuction);
@@ -230,6 +238,13 @@ export function useAuctionSocket(matchId: string | undefined) {
const commitBidDelta = useCallback((payload: BidDeltaPayload): boolean => {
const currentAuction = latestAuctionRef.current;
if (shouldResyncForBidDelta(currentAuction, payload)) {
void resyncRequesterRef.current?.request(
payload.revision,
payload.auctionLifecycleId,
);
return false;
}
const nextAuction = applyBidDelta(currentAuction, payload);
if (!nextAuction || nextAuction === currentAuction) {
return false;
@@ -242,6 +257,29 @@ export function useAuctionSocket(matchId: string | undefined) {
return true;
}, []);
// HTTP 폴링은 화면만 갱신하므로, 소켓이 전이를 놓친 경우 입찰 기준가와
// 라운드 ID가 낡은 채 남는다. 같은 경매의 더 새 상태면 소켓 상태에도 반영한다.
const syncPolledAuctionState = useCallback(
(polledAuction: ApiAuction | null | undefined) => {
if (!polledAuction) return;
if (
polledAuction.auctionLifecycleId &&
cancelledLifecycleIdsRef.current.has(polledAuction.auctionLifecycleId)
)
return;
if (
!shouldApplyPolledAuctionState(
latestAuctionRef.current,
polledAuction,
matchId,
)
)
return;
commitAuctionState(polledAuction, 'http-poll');
},
[commitAuctionState, matchId],
);
const setError = useCallback(
(message: string | null) => {
setErrorState({ key: connectionKey ?? '', message });
@@ -336,7 +374,10 @@ export function useAuctionSocket(matchId: string | undefined) {
: undefined);
const clientObservedRemainingBidRoundTimeMS =
typeof currentDeadlineTimestampMS === 'number'
? Math.max(0, currentDeadlineTimestampMS - (Date.now() + serverTimeOffsetMs))
? Math.max(
0,
currentDeadlineTimestampMS - (Date.now() + serverTimeOffsetMs),
)
: undefined;
const serverDeadlineTimestampMS =
ack.bidDiagnostics?.currentBidRoundDeadlineTimestampMS ??
@@ -399,6 +440,7 @@ export function useAuctionSocket(matchId: string | undefined) {
}
const activeConnectionKey = connectionKey;
const cancelledLifecycleIds = cancelledLifecycleIdsRef.current;
let disposed = false;
void (async () => {
@@ -418,6 +460,33 @@ export function useAuctionSocket(matchId: string | undefined) {
});
socketRef.current = socket;
const receiveAuctionState = (nextAuction: ApiAuction, source: string) => {
const previousRevision = latestAuctionRef.current?.revision ?? -1;
const didApplyState = commitAuctionState(nextAuction, source);
if (didApplyState && (nextAuction.revision ?? 0) > previousRevision) {
clearPendingActionRequests();
}
applyFallbackServerTimestamp(nextAuction.currentServerTimestampMS);
if (nextAuction.chatMessages) {
setChatMessages(mergeChatMessages([], nextAuction.chatMessages));
}
if (didApplyState) {
setError(null);
}
};
const resyncRequester = createAuctionResyncRequester(
async () => {
if (!socket.connected)
throw new Error('Auction socket is disconnected.');
return (await socket
.timeout(3000)
.emitWithAck('resync', {})) as AuctionResyncReply;
},
(state) => {
receiveAuctionState(state, 'socket-resync');
},
);
resyncRequesterRef.current = resyncRequester;
socket.on('connect', () => {
setConnectionState({
@@ -437,6 +506,7 @@ export function useAuctionSocket(matchId: string | undefined) {
});
socket.on('disconnect', () => {
resyncRequester.cancel();
clearTimeSyncTimers();
setConnectionState({
key: activeConnectionKey,
@@ -444,18 +514,12 @@ export function useAuctionSocket(matchId: string | undefined) {
});
});
socket.on('state-pending', () => {
void resyncRequester.request();
});
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);
}
receiveAuctionState(nextAuction, 'socket-state');
});
socket.on('chat-history', (payload: ChatHistoryPayload) => {
@@ -509,6 +573,13 @@ export function useAuctionSocket(matchId: string | undefined) {
const currentAuction = latestAuctionRef.current;
if (!currentAuction) return;
if (
payload.auctionStateTransitionId &&
currentAuction.matchSideEffectTransitionId &&
payload.auctionStateTransitionId !==
currentAuction.matchSideEffectTransitionId
)
return;
if (
payload.auctionLifecycleId &&
currentAuction.auctionLifecycleId &&
@@ -540,6 +611,18 @@ export function useAuctionSocket(matchId: string | undefined) {
socket.on('reset', (payload: ResetPayload) => {
if (payload.matchId && payload.matchId !== matchId) return;
const lifecycle =
payload.auctionLifecycleId ??
latestAuctionRef.current?.auctionLifecycleId;
if (lifecycle) cancelledLifecycleIdsRef.current.add(lifecycle);
if (
payload.auctionLifecycleId &&
latestAuctionRef.current?.auctionLifecycleId &&
payload.auctionLifecycleId !==
latestAuctionRef.current.auctionLifecycleId
)
return;
resyncRequester.cancel();
latestAuctionRef.current = null;
latestConfirmedBidPointAmountRef.current = 0;
setAuction(null);
@@ -556,6 +639,8 @@ export function useAuctionSocket(matchId: string | undefined) {
return () => {
disposed = true;
resyncRequesterRef.current?.cancel();
resyncRequesterRef.current = null;
const socket = socketRef.current;
socket?.removeAllListeners();
socket?.disconnect();
@@ -570,6 +655,7 @@ export function useAuctionSocket(matchId: string | undefined) {
pendingBidTimeoutsRef.current = {};
pendingActionTimeoutsRef.current = {};
latestAuctionRef.current = null;
cancelledLifecycleIds.clear();
latestConfirmedBidPointAmountRef.current = 0;
hasSyncedServerTimeRef.current = false;
setPendingBidRequests({});
@@ -621,12 +707,11 @@ export function useAuctionSocket(matchId: string | undefined) {
}
// 거부 등으로 클라 상태가 낡았을 때 서버 최신 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 });
void resyncRequesterRef.current?.request();
}
// retryAttempt: 거부 후 자동 재시도 횟수(루프 방지를 위해 1회로 제한).
@@ -655,10 +740,13 @@ export function useAuctionSocket(matchId: string | undefined) {
...current,
[auctionActionRequestId]: { action: eventName },
}));
pendingActionTimeoutsRef.current[auctionActionRequestId] = setTimeout(() => {
clearPendingActionRequest(auctionActionRequestId);
setError('경매 진행 응답이 지연되어 최신 상태를 다시 확인해주세요.');
}, 10_000);
pendingActionTimeoutsRef.current[auctionActionRequestId] = setTimeout(
() => {
clearPendingActionRequest(auctionActionRequestId);
setError('경매 진행 응답이 지연되어 최신 상태를 다시 확인해주세요.');
},
10_000,
);
addNewRelicPageAction('AuctionClientActionSent', {
matchId: matchId ?? 'none',
action: eventName,
@@ -731,7 +819,10 @@ export function useAuctionSocket(matchId: string | undefined) {
sentPlayerUserId:
payload.clientObservedCurrentBidRoundPlayerUserId ?? 'none',
sentPhase: payload.clientObservedPhase ?? 'none',
...describeAuctionForTelemetry('observed', latestAuctionRef.current),
...describeAuctionForTelemetry(
'observed',
latestAuctionRef.current,
),
...describeAuctionForTelemetry('server', ack?.state ?? null),
});
if (canAutoRetry) {
@@ -772,7 +863,9 @@ export function useAuctionSocket(matchId: string | undefined) {
const currentAuction = auction;
const visibleAuction =
currentAuction && currentAuction.matchId === matchId ? currentAuction : null;
currentAuction && currentAuction.matchId === matchId
? currentAuction
: null;
const visibleConnectionStatus: ConnectionStatus =
connectionKey === null
? 'idle'
@@ -797,6 +890,7 @@ export function useAuctionSocket(matchId: string | undefined) {
bidLatencyDiagnostics,
serverRoundTripMs: matchId ? serverRoundTripMs : null,
serverTimeOffsetMs: matchId ? serverTimeOffsetMs : 0,
syncPolledAuctionState,
placeBid(payload: BidPayload) {
const socket = socketRef.current;
if (!socket || !socket.connected) {
@@ -807,6 +901,12 @@ export function useAuctionSocket(matchId: string | undefined) {
return;
}
if (payload.bidPointAmount <= latestConfirmedBidPointAmountRef.current) {
// 조용히 무시하면 화면과 내부 기준가가 어긋났을 때 입찰 버튼이 반응하지
// 않는 것처럼 보인다. 안내하고 최신 상태를 다시 받는다.
setError(
'현재 최고 입찰가보다 높은 금액만 입찰할 수 있어요. 최신 경매 상태를 다시 불러올게요.',
);
resyncAuctionState();
return;
}
@@ -815,6 +915,8 @@ export function useAuctionSocket(matchId: string | undefined) {
const bidPayload: BidPayload = {
...payload,
bidRequestId,
clientObservedBidRoundId:
payload.clientObservedBidRoundId ?? currentAuction?.currentBidRoundId,
clientObservedAuctionLifecycleId:
payload.clientObservedAuctionLifecycleId ??
currentAuction?.auctionLifecycleId,
@@ -835,36 +937,32 @@ export function useAuctionSocket(matchId: string | undefined) {
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;
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();
}
if (ack?.bidDelta) {
clearPendingBidRequest(bidRequestId);
commitBidDelta(ack.bidDelta);
return;
}
const ackState = ack?.state;
if (ackState) {
clearPendingBidRequest(bidRequestId);
commitAuctionState(ackState);
}
},
);
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());
@@ -905,7 +1003,10 @@ function resolveCurrentBidPointAmount(auction: ApiAuction): number {
}
// [AUCTION-DEBUG] 아래 텔레메트리 헬퍼들과 호출부는 조사 종료 후 제거 대상.
type AuctionTelemetryAttributes = Record<string, string | number | boolean | null>;
type AuctionTelemetryAttributes = Record<
string,
string | number | boolean | null
>;
function readAuctionHistorySequence(auction: ApiAuction | null | undefined) {
const value = (auction as { currentAuctionHistorySequence?: unknown } | null)
@@ -914,7 +1015,9 @@ function readAuctionHistorySequence(auction: ApiAuction | null | undefined) {
}
function summarizeAuctionTeams(auction: ApiAuction | null | undefined) {
const teams = Array.isArray(auction?.auctionTeams) ? auction.auctionTeams : [];
const teams = Array.isArray(auction?.auctionTeams)
? auction.auctionTeams
: [];
let assignedMemberCount = 0;
for (const team of teams) {
const members = (team as { members?: unknown[] }).members;
@@ -956,143 +1059,3 @@ function describeAuctionForTelemetry(
[`${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];
}