feat: redesign auction engine with redis sot
This commit is contained in:
1 parent
737702d78c
commit
e8bb20d988
75 files changed
+12737
-542
No files matched your search
@@ -12,9 +12,11 @@ type ConnectionStatus =
|
||||
| 'error';
|
||||
|
||||
interface BidPayload {
|
||||
teamIndex: number;
|
||||
amount: number;
|
||||
bidderUserId?: string;
|
||||
bidderTeamIndex: number;
|
||||
bidPointAmount: number;
|
||||
bidRequestId?: string;
|
||||
clientObservedAuctionLifecycleId?: string;
|
||||
clientObservedCurrentBidRoundPlayerUserId?: string;
|
||||
}
|
||||
|
||||
interface ChatMessagePayload {
|
||||
@@ -22,6 +24,19 @@ interface ChatMessagePayload {
|
||||
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[];
|
||||
}
|
||||
@@ -30,9 +45,29 @@ interface ResetPayload {
|
||||
matchId?: string;
|
||||
}
|
||||
|
||||
interface TickPayload {
|
||||
deadline?: string;
|
||||
serverTime?: 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;
|
||||
}
|
||||
|
||||
const MAX_CHAT_MESSAGES = 200;
|
||||
@@ -54,8 +89,20 @@ function mergeChatMessages(
|
||||
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 [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');
|
||||
@@ -99,23 +146,20 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
});
|
||||
|
||||
socket.on('state', (nextAuction: ApiAuction) => {
|
||||
setAuction(nextAuction);
|
||||
setAuction((current) =>
|
||||
shouldApplyIncomingAuctionState(current, nextAuction)
|
||||
? nextAuction
|
||||
: current,
|
||||
);
|
||||
if (typeof nextAuction.currentServerTimestampMS === 'number') {
|
||||
setServerTimeOffsetMs(nextAuction.currentServerTimestampMS - Date.now());
|
||||
}
|
||||
if (nextAuction.chatMessages) {
|
||||
setChatMessages(mergeChatMessages([], nextAuction.chatMessages));
|
||||
}
|
||||
setError(null);
|
||||
});
|
||||
|
||||
socket.on('tick', (payload: TickPayload) => {
|
||||
const serverTime =
|
||||
typeof payload?.serverTime === 'string'
|
||||
? Date.parse(payload.serverTime)
|
||||
: NaN;
|
||||
if (Number.isFinite(serverTime)) {
|
||||
setServerTimeOffsetMs(serverTime - Date.now());
|
||||
}
|
||||
});
|
||||
|
||||
socket.on('chat-history', (payload: ChatHistoryPayload) => {
|
||||
setChatMessages(mergeChatMessages([], payload.messages ?? []));
|
||||
});
|
||||
@@ -124,6 +168,52 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
setChatMessages((current) => mergeChatMessages(current, [message]));
|
||||
});
|
||||
|
||||
socket.on('bid', (payload: BidDeltaPayload) => {
|
||||
if (typeof payload?.currentServerTimestampMS === 'number') {
|
||||
setServerTimeOffsetMs(payload.currentServerTimestampMS - Date.now());
|
||||
}
|
||||
if (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());
|
||||
}
|
||||
if (
|
||||
!payload?.matchSideEffectStatus ||
|
||||
typeof payload.matchSideEffectRevision !== 'number'
|
||||
) {
|
||||
return;
|
||||
}
|
||||
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,
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
socket.on('reset', (payload: ResetPayload) => {
|
||||
if (payload.matchId && payload.matchId !== matchId) return;
|
||||
setAuction(null);
|
||||
@@ -144,11 +234,43 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
socket?.removeAllListeners();
|
||||
socket?.disconnect();
|
||||
socketRef.current = null;
|
||||
Object.values(pendingBidTimeoutsRef.current).forEach((timeoutId) =>
|
||||
clearTimeout(timeoutId),
|
||||
);
|
||||
Object.values(pendingActionTimeoutsRef.current).forEach((timeoutId) =>
|
||||
clearTimeout(timeoutId),
|
||||
);
|
||||
pendingBidTimeoutsRef.current = {};
|
||||
pendingActionTimeoutsRef.current = {};
|
||||
setPendingBidRequests({});
|
||||
setPendingActionRequests({});
|
||||
setConnectionStatus('idle');
|
||||
setServerTimeOffsetMs(0);
|
||||
};
|
||||
}, [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 emit(eventName: string, payload?: unknown) {
|
||||
const socket = socketRef.current;
|
||||
if (!socket || !socket.connected) {
|
||||
@@ -166,7 +288,74 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
socket.emit(eventName, payload);
|
||||
}
|
||||
|
||||
const visibleAuction = auction?.matchId === matchId ? auction : null;
|
||||
function buildAuctionActionPayload(): AuctionActionPayload {
|
||||
return {
|
||||
auctionActionRequestId: createClientRequestId(),
|
||||
clientObservedAuctionLifecycleId: auction?.auctionLifecycleId,
|
||||
clientObservedCurrentAuctionPlayerOrderIndex:
|
||||
auction?.currentAuctionPlayerOrderIndex,
|
||||
clientObservedCurrentBidRoundPlayerUserId:
|
||||
auction?.currentBidRoundPlayerUserId,
|
||||
clientObservedPhase: auction?.phase,
|
||||
clientObservedRevision: auction?.revision,
|
||||
};
|
||||
}
|
||||
|
||||
function emitAuctionAction(eventName: string, payload: AuctionActionPayload) {
|
||||
const socket = socketRef.current;
|
||||
if (!socket || !socket.connected) {
|
||||
setError('소켓이 아직 연결되지 않았습니다.');
|
||||
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);
|
||||
socket.emit(
|
||||
eventName,
|
||||
actionPayload,
|
||||
(ack?: {
|
||||
auctionActionRequestId?: string;
|
||||
code?: string;
|
||||
rejected?: boolean;
|
||||
state?: ApiAuction;
|
||||
}) => {
|
||||
clearPendingActionRequest(
|
||||
ack?.auctionActionRequestId ?? auctionActionRequestId,
|
||||
);
|
||||
if (ack?.rejected) {
|
||||
setError(ack.code ?? '경매 진행 상태가 반영되지 않았습니다.');
|
||||
return;
|
||||
}
|
||||
const ackState = ack?.state;
|
||||
if (ackState) {
|
||||
setAuction((current) =>
|
||||
shouldApplyIncomingAuctionState(current, ackState)
|
||||
? ackState
|
||||
: current,
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const currentAuction = auction;
|
||||
const visibleAuction =
|
||||
currentAuction && currentAuction.matchId === matchId
|
||||
? applyPendingBidOverlay(currentAuction, pendingBidRequests)
|
||||
: null;
|
||||
const visibleConnectionStatus: ConnectionStatus = matchId
|
||||
? connectionStatus
|
||||
: 'idle';
|
||||
@@ -174,24 +363,252 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
return {
|
||||
auction: visibleAuction,
|
||||
chatMessages: visibleAuction ? chatMessages : [],
|
||||
isAuctionActionPending: Object.keys(pendingActionRequests).length > 0,
|
||||
isBidPending: Object.keys(pendingBidRequests).length > 0,
|
||||
pendingActionRequests,
|
||||
pendingBidRequests,
|
||||
resetAt,
|
||||
connectionStatus: visibleConnectionStatus,
|
||||
error,
|
||||
serverTimeOffsetMs: matchId ? serverTimeOffsetMs : 0,
|
||||
placeBid(payload: BidPayload) {
|
||||
emit('bid', payload);
|
||||
const socket = socketRef.current;
|
||||
if (!socket || !socket.connected) {
|
||||
setError('소켓이 아직 연결되지 않았습니다.');
|
||||
return;
|
||||
}
|
||||
|
||||
const bidRequestId = payload.bidRequestId ?? createClientRequestId();
|
||||
const bidPayload: BidPayload = {
|
||||
...payload,
|
||||
bidRequestId,
|
||||
clientObservedAuctionLifecycleId:
|
||||
payload.clientObservedAuctionLifecycleId ??
|
||||
auction?.auctionLifecycleId,
|
||||
clientObservedCurrentBidRoundPlayerUserId:
|
||||
payload.clientObservedCurrentBidRoundPlayerUserId ??
|
||||
auction?.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?: {
|
||||
code?: string;
|
||||
rejected?: boolean;
|
||||
state?: ApiAuction;
|
||||
}) => {
|
||||
clearPendingBidRequest(bidRequestId);
|
||||
if (ack?.rejected) {
|
||||
setError(ack.code ?? '입찰이 반영되지 않았습니다.');
|
||||
return;
|
||||
}
|
||||
const ackState = ack?.state;
|
||||
if (ackState) {
|
||||
setAuction((current) =>
|
||||
shouldApplyIncomingAuctionState(current, ackState)
|
||||
? ackState
|
||||
: current,
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
},
|
||||
openBidding() {
|
||||
emit('open-bidding', {});
|
||||
emitAuctionAction('open-bidding', buildAuctionActionPayload());
|
||||
},
|
||||
markSold(assignedPosition?: Position) {
|
||||
emit('sold', assignedPosition ? { assignedPosition } : {});
|
||||
const payload: SoldPayload = {
|
||||
...buildAuctionActionPayload(),
|
||||
assignedPosition,
|
||||
};
|
||||
emitAuctionAction('sold', payload);
|
||||
},
|
||||
markPassed() {
|
||||
emitAuctionAction('passed', buildAuctionActionPayload());
|
||||
},
|
||||
next() {
|
||||
emit('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 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];
|
||||
}
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user