feat: redesign auction engine with redis sot

This commit is contained in:
dahyeon committed 2026-06-23 03:16:04 -07:00
1 parent 737702d78c
commit e8bb20d988
75 files changed
+12737 -542

No files matched your search

+46 -2
View File
@@ -221,9 +221,21 @@ export function useAuctionHistory(
export function useUndoAuction(communityId = DEFAULT_COMMUNITY_ID) {
return useMutation({
mutationFn: ({
auctionActionRequestId,
clientObservedAuctionLifecycleId,
clientObservedCurrentAuctionPlayerOrderIndex,
clientObservedCurrentBidRoundPlayerUserId,
clientObservedPhase,
clientObservedRevision,
matchId,
sequence,
}: {
auctionActionRequestId?: string;
clientObservedAuctionLifecycleId?: string;
clientObservedCurrentAuctionPlayerOrderIndex?: number;
clientObservedCurrentBidRoundPlayerUserId?: string;
clientObservedPhase?: string;
clientObservedRevision?: number;
matchId: string;
sequence: number;
}) =>
@@ -231,7 +243,15 @@ export function useUndoAuction(communityId = DEFAULT_COMMUNITY_ID) {
`/communities/${communityId}/matches/${matchId}/auction/undo`,
{
method: 'POST',
body: JSON.stringify({ sequence }),
body: JSON.stringify({
auctionActionRequestId,
clientObservedAuctionLifecycleId,
clientObservedCurrentAuctionPlayerOrderIndex,
clientObservedCurrentBidRoundPlayerUserId,
clientObservedPhase,
clientObservedRevision,
sequence,
}),
},
),
});
@@ -239,9 +259,33 @@ export function useUndoAuction(communityId = DEFAULT_COMMUNITY_ID) {
export function useResetAuction(communityId = DEFAULT_COMMUNITY_ID) {
return useMutation({
mutationFn: ({ matchId }: { matchId: string }) =>
mutationFn: ({
auctionActionRequestId,
clientObservedAuctionLifecycleId,
clientObservedCurrentAuctionPlayerOrderIndex,
clientObservedCurrentBidRoundPlayerUserId,
clientObservedPhase,
clientObservedRevision,
matchId,
}: {
auctionActionRequestId?: string;
clientObservedAuctionLifecycleId?: string;
clientObservedCurrentAuctionPlayerOrderIndex?: number;
clientObservedCurrentBidRoundPlayerUserId?: string;
clientObservedPhase?: string;
clientObservedRevision?: number;
matchId: string;
}) =>
apiFetch<void>(`/communities/${communityId}/matches/${matchId}/auction`, {
method: 'DELETE',
body: JSON.stringify({
auctionActionRequestId,
clientObservedAuctionLifecycleId,
clientObservedCurrentAuctionPlayerOrderIndex,
clientObservedCurrentBidRoundPlayerUserId,
clientObservedPhase,
clientObservedRevision,
}),
}),
});
}
+71 -20
View File
@@ -119,6 +119,8 @@ export interface AuctionTeamView {
export interface AuctionStateView {
matchId: string;
phase: ApiAuction["phase"];
matchSideEffectRevision?: number;
matchSideEffectStatus?: ApiAuction["matchSideEffectStatus"];
teams: AuctionTeamView[];
currentPlayer: AuctionPlayerView | null;
currentPlayerIndex: number;
@@ -273,7 +275,7 @@ function createFallbackParticipant(userId: string): ParticipantView {
}
function mapAuctionTeamToView(
team: ApiAuctionTeam,
team: NormalizedApiAuctionTeam,
playerLookup: Map<string, AuctionPlayerView>,
participantLookup: Map<string, ParticipantView>,
): AuctionTeamView {
@@ -489,12 +491,33 @@ export function mapApiAuctionToAuctionState(
.map(mapMatchParticipantToView)
.map((participant) => [participant.userId, participant]),
);
const auctionOrder = auction.order.map(mapAuctionPlayerToView);
const passedQueue = (auction.passedQueue ?? []).map(mapAuctionPlayerToView);
const rawAuctionOrder = auction.auctionPlayerOrder ?? auction.order ?? [];
const rawPassedQueue =
auction.passedAuctionPlayerQueue ?? auction.passedQueue ?? [];
const rawAuctionTeams = auction.auctionTeams ?? auction.teams ?? [];
const currentAuctionPlayerOrderIndex =
auction.currentAuctionPlayerOrderIndex ?? auction.currentIndex ?? 0;
const currentBid =
auction.currentHighestBidPointAmount ?? auction.currentBid ?? 0;
const rawCurrentBidderTeamIndex =
auction.currentHighestBidderTeamIndex ?? auction.currentBidderTeamIndex;
const currentBidderTeamIndex =
rawCurrentBidderTeamIndex !== undefined && rawCurrentBidderTeamIndex > 0
? rawCurrentBidderTeamIndex
: undefined;
const maximumBidRoundDurationSeconds =
auction.maximumBidRoundDurationSeconds ?? auction.maxTimerSeconds ?? 30;
const bidRoundExtensionSeconds =
auction.bidRoundExtensionSeconds ?? auction.bidExtensionSeconds ?? 5;
const currentBidRoundDeadlineTimestampMS =
auction.currentBidRoundDeadlineTimestampMS ??
(auction.currentDeadline ? Date.parse(auction.currentDeadline) : undefined);
const auctionOrder = rawAuctionOrder.map(mapAuctionPlayerToView);
const passedQueue = rawPassedQueue.map(mapAuctionPlayerToView);
const auctionPlayerLookup = new Map(
auctionOrder.map((player) => [player.userId, player]),
);
const teams = [...auction.teams].sort(
const teams = rawAuctionTeams.map(normalizeApiAuctionTeam).sort(
(left, right) => left.teamIndex - right.teamIndex,
);
@@ -503,15 +526,15 @@ export function mapApiAuctionToAuctionState(
auction.phase === "complete"
? null
: (auctionPlayerLookup.get(
auction.order[auction.currentIndex]?.userId ?? "",
rawAuctionOrder[currentAuctionPlayerOrderIndex]?.userId ?? "",
) ?? null);
const currentPlayerIndex =
auction.phase === "complete" ? totalPlayers : auction.currentIndex;
const timer = auction.currentDeadline
auction.phase === "complete" ? totalPlayers : currentAuctionPlayerOrderIndex;
const timer = currentBidRoundDeadlineTimestampMS
? Math.max(
0,
Math.ceil(
(new Date(auction.currentDeadline).getTime() - now.getTime()) / 1000,
(currentBidRoundDeadlineTimestampMS - now.getTime()) / 1000,
),
)
: 0;
@@ -519,6 +542,8 @@ export function mapApiAuctionToAuctionState(
return {
matchId: auction.matchId,
phase: auction.phase,
matchSideEffectRevision: auction.matchSideEffectRevision,
matchSideEffectStatus: auction.matchSideEffectStatus,
teams: teams.map((team) =>
mapAuctionTeamToView(team, auctionPlayerLookup, participantLookup),
),
@@ -527,21 +552,47 @@ export function mapApiAuctionToAuctionState(
totalPlayers,
auctionOrder,
passedQueue,
auctionRound: auction.auctionRound ?? 1,
bids: auction.bids.map((bid) => ({
teamIndex: bid.teamIndex,
amount: bid.amount,
timestamp: bid.timestamp,
})),
currentBid: auction.currentBid,
currentBidder: auction.currentBidderTeamIndex
auctionRound: auction.currentAuctionRound ?? auction.auctionRound ?? 1,
bids: normalizeApiAuctionBids(auction),
currentBid,
currentBidder: currentBidderTeamIndex !== undefined
? {
teamIndex: auction.currentBidderTeamIndex,
teamIndex: currentBidderTeamIndex,
}
: null,
timer,
maxTimer: auction.maxTimerSeconds,
bidExtensionSeconds: auction.bidExtensionSeconds ?? 5,
deadline: auction.currentDeadline,
maxTimer: maximumBidRoundDurationSeconds,
bidExtensionSeconds: bidRoundExtensionSeconds,
deadline: currentBidRoundDeadlineTimestampMS
? new Date(currentBidRoundDeadlineTimestampMS).toISOString()
: undefined,
};
}
type NormalizedApiAuctionTeam = ApiAuctionTeam & { points: number };
function normalizeApiAuctionTeam(team: ApiAuctionTeam): NormalizedApiAuctionTeam {
return {
...team,
points: team.points ?? team.remainingBidPointAmount ?? 0,
members: (team.members ?? []).map((member) => ({
...member,
cost: member.cost ?? member.memberAcquisitionBidPointAmount ?? 0,
})),
};
}
function normalizeApiAuctionBids(auction: ApiAuction) {
if (auction.auctionBidHistory) {
return auction.auctionBidHistory.map((bid) => ({
amount: bid.bidPointAmount,
teamIndex: bid.bidderTeamIndex,
timestamp: new Date(bid.bidPlacedAtTimestampMS).toISOString(),
}));
}
return (auction.bids ?? []).map((bid) => ({
teamIndex: bid.teamIndex,
amount: bid.amount,
timestamp: bid.timestamp,
}));
}
+46 -14
View File
@@ -278,12 +278,14 @@ export interface ApiAuctionTeamMember {
userId: string;
assignedPosition: Position;
cost: number;
memberAcquisitionBidPointAmount?: number;
}
export interface ApiAuctionTeam {
teamIndex: number;
captainUserId: string;
points: number;
points?: number;
remainingBidPointAmount?: number;
members: ApiAuctionTeamMember[];
}
@@ -306,20 +308,48 @@ export interface ApiAuction {
_id: string;
matchId: string;
phase: AuctionPhase;
teams: ApiAuctionTeam[];
order: ApiAuctionPlayerSnapshot[];
passedQueue: ApiAuctionPlayerSnapshot[];
auctionRound: number;
currentIndex: number;
bids: ApiAuctionBid[];
currentBid: number;
teams?: ApiAuctionTeam[];
auctionTeams: ApiAuctionTeam[];
order?: ApiAuctionPlayerSnapshot[];
auctionPlayerOrder: ApiAuctionPlayerSnapshot[];
passedQueue?: ApiAuctionPlayerSnapshot[];
passedAuctionPlayerQueue: ApiAuctionPlayerSnapshot[];
auctionRound?: number;
currentAuctionRound: number;
currentIndex?: number;
currentAuctionPlayerOrderIndex: number;
bids?: ApiAuctionBid[];
auctionBidHistory?: Array<{
bidderTeamIndex: number;
bidPointAmount: number;
bidderUserId: string;
bidPlacedAtTimestampMS: number;
}>;
currentBid?: number;
currentHighestBidPointAmount: number;
currentBidderTeamIndex?: number;
maxTimerSeconds: number;
bidExtensionSeconds: number;
currentHighestBidderTeamIndex?: number;
maxTimerSeconds?: number;
maximumBidRoundDurationSeconds: number;
bidExtensionSeconds?: number;
bidRoundExtensionSeconds: number;
currentDeadline?: string;
initialPoints: number;
topTierThreshold: AuctionTopTierThreshold;
manualTopTierUserIds: string[];
currentBidRoundDeadlineTimestampMS?: number;
currentBidRoundPlayerUserId?: string;
currentServerTimestampMS?: number;
initialPoints?: number;
initialTeamBidPointAmount: number;
topTierThreshold?: AuctionTopTierThreshold;
topTierAuctionPriorityThreshold: AuctionTopTierThreshold;
manualTopTierUserIds?: string[];
manualTopTierAuctionPriorityUserIds: string[];
revision?: number;
auctionLifecycleId?: string;
matchSideEffectRevision?: number;
matchSideEffectStatus?: 'none' | 'pending' | 'processing' | 'completed' | 'failed';
canPlaceBidInCurrentBidRound?: boolean;
isAuctionStateTransitionInProgress?: boolean;
shouldForceAuctionStateResync?: boolean;
chatMessages?: ApiAuctionChatMessage[];
startedAt?: string;
completedAt?: string;
@@ -336,7 +366,9 @@ export interface ApiAuctionHistoryEntry {
| 'sold'
| 'passed'
| 'next'
| 'complete';
| 'complete'
| 'undo'
| 'reset';
actionLabel: string;
takenAt: string;
}
+439 -22
View File
@@ -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,
};
}