perf(auction): reduce polling with verified socket recovery
Keep fixed 30-second safety polling with separate recovery polling, confirm persistent heartbeat gaps, and refresh shared history after durable writes.
This commit is contained in:
1 parent
e349684523
commit
23a0a3f8dd
20 files changed
+790
-154
No files matched your search
@@ -0,0 +1,12 @@
|
||||
export const AUCTION_SAFETY_POLL_INTERVAL_MS = 30_000;
|
||||
|
||||
/** Supplements the fixed safety poll without restarting its timer. */
|
||||
export function startAuctionRecoveryPolling(
|
||||
refetch: () => void,
|
||||
isVisible = () => document.visibilityState === 'visible',
|
||||
): () => void {
|
||||
const timer = setInterval(() => {
|
||||
if (isVisible()) refetch();
|
||||
}, 5000);
|
||||
return () => clearInterval(timer);
|
||||
}
|
||||
@@ -27,6 +27,7 @@ export function createAuctionResyncRequester(
|
||||
fetchState: () => Promise<AuctionResyncReply>,
|
||||
applyState: (state: ApiAuction) => void,
|
||||
wait = waitForRetry,
|
||||
onFailure?: () => void,
|
||||
) {
|
||||
let pending: Promise<void> | undefined;
|
||||
let controller = new AbortController();
|
||||
@@ -67,6 +68,7 @@ export function createAuctionResyncRequester(
|
||||
}
|
||||
if (attempt < 2 && !signal.aborted) await wait(retryAfterMS, signal);
|
||||
}
|
||||
if (!signal.aborted) onFailure?.();
|
||||
})().finally(() => {
|
||||
if (!signal.aborted) pending = undefined;
|
||||
});
|
||||
|
||||
@@ -1,4 +1,69 @@
|
||||
import type { ApiAuction } from "./types";
|
||||
import type { AuctionStateIdentity } from "@lolympus/contracts";
|
||||
|
||||
export function resolveCurrentBidPointAmount(auction: ApiAuction): number {
|
||||
const amount = Number(
|
||||
auction.currentHighestBidPointAmount ?? auction.currentBid ?? 0,
|
||||
);
|
||||
return Number.isFinite(amount) ? Math.max(0, amount) : 0;
|
||||
}
|
||||
|
||||
export function shouldResyncForAuctionIdentity(
|
||||
current: ApiAuction | null,
|
||||
identity: AuctionStateIdentity | null,
|
||||
): boolean {
|
||||
if (!current) return true;
|
||||
// Completed runtimes expire while their archived Mongo state remains valid.
|
||||
if (!identity) {
|
||||
return (
|
||||
current.auctionEngineVersion === "redis-v1" &&
|
||||
current.phase !== "complete"
|
||||
);
|
||||
}
|
||||
if (identity.auctionLifecycleId !== current.auctionLifecycleId) return true;
|
||||
if ((identity.revision ?? -1) > (current.revision ?? -1)) return true;
|
||||
// A delayed heartbeat must not undo a newer state already received by socket.
|
||||
if ((identity.revision ?? -1) < (current.revision ?? -1)) return false;
|
||||
return (
|
||||
(identity.matchSideEffectRevision ?? -1) >
|
||||
(current.matchSideEffectRevision ?? -1)
|
||||
);
|
||||
}
|
||||
|
||||
export function createAuctionHeartbeatMonitor() {
|
||||
let pendingIdentity: AuctionStateIdentity | null | undefined;
|
||||
let consecutiveFailures = 0;
|
||||
return {
|
||||
reset() {
|
||||
pendingIdentity = undefined;
|
||||
consecutiveFailures = 0;
|
||||
},
|
||||
recordFailure(): boolean {
|
||||
pendingIdentity = undefined;
|
||||
consecutiveFailures += 1;
|
||||
return consecutiveFailures >= 2;
|
||||
},
|
||||
inspect(
|
||||
current: ApiAuction | null,
|
||||
identity: AuctionStateIdentity | null | undefined,
|
||||
) {
|
||||
consecutiveFailures = 0;
|
||||
const previousIdentity = pendingIdentity;
|
||||
const isCurrent =
|
||||
identity === undefined ||
|
||||
!shouldResyncForAuctionIdentity(current, identity);
|
||||
pendingIdentity = undefined;
|
||||
if (isCurrent) return { isCurrent: true, needsResync: false };
|
||||
// Bids received since the first heartbeat may have closed that gap, even
|
||||
// when this heartbeat observes another newer bid still in transit.
|
||||
const needsResync =
|
||||
previousIdentity !== undefined &&
|
||||
shouldResyncForAuctionIdentity(current, previousIdentity);
|
||||
if (!needsResync) pendingIdentity = identity;
|
||||
return { isCurrent: false, needsResync };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export interface BidDeltaPayload {
|
||||
currentBidRoundId?: string;
|
||||
|
||||
@@ -423,10 +423,10 @@ export function useAuction(
|
||||
) {
|
||||
return useQuery({
|
||||
queryKey: ['auction', communityId, matchId ?? null],
|
||||
queryFn: () =>
|
||||
queryFn: ({ signal }) =>
|
||||
apiFetch<ApiAuction>(
|
||||
`/communities/${communityId}/matches/${matchId}/auction`,
|
||||
{ auth: 'none' },
|
||||
{ auth: 'none', signal },
|
||||
),
|
||||
enabled: Boolean(communityId && matchId),
|
||||
retry: false,
|
||||
@@ -441,9 +441,10 @@ export function useAuctionHistory(
|
||||
) {
|
||||
return useQuery({
|
||||
queryKey: ['auction-history', communityId, matchId ?? null],
|
||||
queryFn: () =>
|
||||
queryFn: ({ signal }) =>
|
||||
apiFetch<ApiAuctionHistoryEntry[]>(
|
||||
`/communities/${communityId}/matches/${matchId}/auction/history`,
|
||||
{ signal },
|
||||
),
|
||||
enabled: Boolean(communityId && matchId && (options.enabled ?? true)),
|
||||
retry: false,
|
||||
|
||||
@@ -196,6 +196,7 @@ export interface ApiAuctionChatMessage {
|
||||
export interface ApiAuction {
|
||||
_id: string;
|
||||
matchId: string;
|
||||
auctionEngineVersion?: 'legacy-renamed' | 'redis-v1';
|
||||
phase: AuctionPhase;
|
||||
teams?: ApiAuctionTeam[];
|
||||
auctionTeams: ApiAuctionTeam[];
|
||||
|
||||
@@ -2,7 +2,12 @@ import { InteractionStatus } from '@azure/msal-browser';
|
||||
import { useMsal } from '@azure/msal-react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { io, type Socket } from 'socket.io-client';
|
||||
import type { AuctionReactionKind, AuctionReactionReply } from '@lolympus/contracts';
|
||||
import type {
|
||||
AuctionHistoryUpdatedEvent,
|
||||
AuctionReactionKind,
|
||||
AuctionReactionReply,
|
||||
AuctionStateIdentity,
|
||||
} from '@lolympus/contracts';
|
||||
import { appendAuctionReaction, isAuctionReaction, REACTION_LIFETIME_MS, sendAuctionReaction, type ActiveAuctionReaction } from './auction-reactions';
|
||||
import { API_BASE_URL, useAuthUserId } from '../config';
|
||||
import { acquireAccessToken } from '../lib/auth/token-provider';
|
||||
@@ -19,6 +24,8 @@ import {
|
||||
shouldResyncForBidDelta,
|
||||
shouldApplyPolledAuctionState,
|
||||
mergeAuctionState,
|
||||
resolveCurrentBidPointAmount,
|
||||
createAuctionHeartbeatMonitor,
|
||||
type BidDeltaPayload,
|
||||
} from './auction-state';
|
||||
import { resolveAuctionActionRejection } from './auction-action-retry';
|
||||
@@ -105,6 +112,8 @@ interface BidAckPayload {
|
||||
}
|
||||
|
||||
interface TimeSyncAckPayload {
|
||||
auctionState?: AuctionStateIdentity | null;
|
||||
auctionStateUnavailable?: boolean;
|
||||
clientSentAtTimestampMS?: number;
|
||||
currentServerTimestampMS?: number;
|
||||
ok?: boolean;
|
||||
@@ -169,6 +178,8 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
const timeSyncSequenceRef = useRef(0);
|
||||
const hasSyncedServerTimeRef = useRef(false);
|
||||
const latestAuctionRef = useRef<ApiAuction | null>(null);
|
||||
const synchronizedSocketRef = useRef<Socket | null>(null);
|
||||
const heartbeatMonitorRef = useRef(createAuctionHeartbeatMonitor());
|
||||
const cancelledLifecycleIdsRef = useRef(new Set<string>());
|
||||
const latestConfirmedBidPointAmountRef = useRef(0);
|
||||
const [auction, setAuction] = useState<ApiAuction | null>(null);
|
||||
@@ -207,6 +218,11 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
key: string;
|
||||
status: ConnectionStatus;
|
||||
}>({ key: '', status: 'idle' });
|
||||
const [synchronizationState, setSynchronizationState] = useState({
|
||||
key: '',
|
||||
ready: false,
|
||||
});
|
||||
const [historyUpdateState, setHistoryUpdateState] = useState({ key: '', count: 0 });
|
||||
const [errorState, setErrorState] = useState<{
|
||||
key: string;
|
||||
message: string | null;
|
||||
@@ -334,15 +350,32 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
timeSyncTimeoutsRef.current = {};
|
||||
}
|
||||
|
||||
function requestServerTimeSync(socket: Socket) {
|
||||
const markSynchronized = useCallback(
|
||||
(socket: Socket, key: string, ready: boolean) => {
|
||||
if (socketRef.current !== socket) return;
|
||||
setSynchronizationState((current) =>
|
||||
current.key === key && current.ready === ready ? current : { key, ready },
|
||||
);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const requestServerTimeSync = useCallback((socket: Socket, key: string) => {
|
||||
if (!socket.connected) return;
|
||||
|
||||
const recordFailure = () => {
|
||||
if (socketRef.current === socket && heartbeatMonitorRef.current.recordFailure()) {
|
||||
markSynchronized(socket, key, false);
|
||||
}
|
||||
};
|
||||
|
||||
const sequence = timeSyncSequenceRef.current + 1;
|
||||
timeSyncSequenceRef.current = sequence;
|
||||
const clientSentAtTimestampMS = Date.now();
|
||||
|
||||
timeSyncTimeoutsRef.current[sequence] = setTimeout(() => {
|
||||
delete timeSyncTimeoutsRef.current[sequence];
|
||||
recordFailure();
|
||||
}, TIME_SYNC_TIMEOUT_MS);
|
||||
|
||||
socket.emit(
|
||||
@@ -354,15 +387,35 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
if (!timeoutId) return;
|
||||
clearTimeout(timeoutId);
|
||||
delete timeSyncTimeoutsRef.current[sequence];
|
||||
if (socketRef.current !== socket) return;
|
||||
|
||||
if (
|
||||
!ack?.ok ||
|
||||
ack.sequence !== sequence ||
|
||||
typeof ack.currentServerTimestampMS !== 'number'
|
||||
) {
|
||||
recordFailure();
|
||||
return;
|
||||
}
|
||||
|
||||
if (ack.auctionStateUnavailable) {
|
||||
recordFailure();
|
||||
} else {
|
||||
const inspection = heartbeatMonitorRef.current.inspect(
|
||||
latestAuctionRef.current,
|
||||
ack.auctionState,
|
||||
);
|
||||
if (inspection.needsResync) {
|
||||
markSynchronized(socket, key, false);
|
||||
void resyncRequesterRef.current?.request(
|
||||
ack.auctionState?.revision,
|
||||
ack.auctionState?.auctionLifecycleId,
|
||||
);
|
||||
} else if (inspection.isCurrent) {
|
||||
markSynchronized(socket, key, synchronizedSocketRef.current === socket);
|
||||
}
|
||||
}
|
||||
|
||||
const totalRoundTripDurationMS = Math.max(
|
||||
0,
|
||||
clientReceivedAtTimestampMS - clientSentAtTimestampMS,
|
||||
@@ -391,7 +444,7 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}, [markSynchronized]);
|
||||
|
||||
function captureBidLatencyDiagnostics(ack?: BidAckPayload) {
|
||||
if (!ack?.bidDiagnostics && !ack?.bidServerTiming) return;
|
||||
@@ -472,6 +525,8 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
const activeConnectionKey = connectionKey;
|
||||
const cancelledLifecycleIds = cancelledLifecycleIdsRef.current;
|
||||
let disposed = false;
|
||||
let removeResumeListeners = () => {};
|
||||
let hasReceivedSnapshot = false;
|
||||
|
||||
void (async () => {
|
||||
const accessToken = await acquireAccessToken().catch((error) => {
|
||||
@@ -490,7 +545,16 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
});
|
||||
|
||||
socketRef.current = socket;
|
||||
const notifyHistoryUpdated = () => {
|
||||
setHistoryUpdateState((current) => ({
|
||||
key: activeConnectionKey,
|
||||
count: current.key === activeConnectionKey ? current.count + 1 : 1,
|
||||
}));
|
||||
};
|
||||
const receiveAuctionState = (nextAuction: ApiAuction, source: string) => {
|
||||
if (
|
||||
disposed || socketRef.current !== socket || nextAuction.matchId !== matchId
|
||||
) return;
|
||||
const previousRevision = latestAuctionRef.current?.revision ?? -1;
|
||||
const didApplyState = commitAuctionState(nextAuction, source);
|
||||
if (didApplyState && (nextAuction.revision ?? 0) > previousRevision) {
|
||||
@@ -501,6 +565,13 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
setChatMessages(mergeChatMessages([], nextAuction.chatMessages));
|
||||
}
|
||||
if (didApplyState) {
|
||||
if (hasReceivedSnapshot && synchronizedSocketRef.current !== socket) {
|
||||
notifyHistoryUpdated();
|
||||
}
|
||||
hasReceivedSnapshot = true;
|
||||
synchronizedSocketRef.current = socket;
|
||||
heartbeatMonitorRef.current.reset();
|
||||
markSynchronized(socket, activeConnectionKey, true);
|
||||
setError(null);
|
||||
}
|
||||
};
|
||||
@@ -515,27 +586,44 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
(state) => {
|
||||
receiveAuctionState(state, 'socket-resync');
|
||||
},
|
||||
undefined,
|
||||
() => markSynchronized(socket, activeConnectionKey, false),
|
||||
);
|
||||
resyncRequesterRef.current = resyncRequester;
|
||||
|
||||
socket.on('connect', () => {
|
||||
synchronizedSocketRef.current = null;
|
||||
heartbeatMonitorRef.current.reset();
|
||||
markSynchronized(socket, activeConnectionKey, false);
|
||||
setConnectionState({
|
||||
key: activeConnectionKey,
|
||||
status: 'connected',
|
||||
});
|
||||
setError(null);
|
||||
socket.emit('join', { matchId });
|
||||
requestServerTimeSync(socket);
|
||||
void socket.timeout(3000).emitWithAck('join', { matchId })
|
||||
.then((reply: { ok?: boolean }) => {
|
||||
if (!reply?.ok && synchronizedSocketRef.current !== socket) {
|
||||
markSynchronized(socket, activeConnectionKey, false);
|
||||
}
|
||||
}).catch(() => {
|
||||
if (synchronizedSocketRef.current !== socket) {
|
||||
markSynchronized(socket, activeConnectionKey, false);
|
||||
}
|
||||
});
|
||||
requestServerTimeSync(socket, activeConnectionKey);
|
||||
if (timeSyncIntervalRef.current) {
|
||||
clearInterval(timeSyncIntervalRef.current);
|
||||
}
|
||||
timeSyncIntervalRef.current = setInterval(
|
||||
() => requestServerTimeSync(socket),
|
||||
() => requestServerTimeSync(socket, activeConnectionKey),
|
||||
TIME_SYNC_INTERVAL_MS,
|
||||
);
|
||||
});
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
synchronizedSocketRef.current = null;
|
||||
heartbeatMonitorRef.current.reset();
|
||||
markSynchronized(socket, activeConnectionKey, false);
|
||||
setReactionState({ key: activeConnectionKey, items: [] });
|
||||
resyncRequester.cancel();
|
||||
clearTimeSyncTimers();
|
||||
@@ -545,6 +633,34 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
});
|
||||
});
|
||||
|
||||
socket.on('connect_error', (error: Error) => {
|
||||
markSynchronized(socket, activeConnectionKey, false);
|
||||
setConnectionState({ key: activeConnectionKey, status: 'error' });
|
||||
if (!socket.active) setError(resolveAuctionErrorMessage(error.message));
|
||||
});
|
||||
|
||||
socket.on('history-updated', (event: AuctionHistoryUpdatedEvent) => {
|
||||
if (event.matchId !== matchId) return;
|
||||
const lifecycle = latestAuctionRef.current?.auctionLifecycleId;
|
||||
if (lifecycle && lifecycle !== event.auctionLifecycleId) return;
|
||||
// Older append retries may fill a gap without increasing the maximum
|
||||
// sequence. Every committed-history notification refreshes the list.
|
||||
notifyHistoryUpdated();
|
||||
});
|
||||
|
||||
const resyncAfterResume = () => {
|
||||
if (document.visibilityState === 'visible' && socket.connected) {
|
||||
notifyHistoryUpdated();
|
||||
void resyncRequester.request();
|
||||
}
|
||||
};
|
||||
document.addEventListener('visibilitychange', resyncAfterResume);
|
||||
window.addEventListener('online', resyncAfterResume);
|
||||
removeResumeListeners = () => {
|
||||
document.removeEventListener('visibilitychange', resyncAfterResume);
|
||||
window.removeEventListener('online', resyncAfterResume);
|
||||
};
|
||||
|
||||
socket.on('state-pending', () => {
|
||||
void resyncRequester.request();
|
||||
});
|
||||
@@ -673,6 +789,7 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
|
||||
return () => {
|
||||
disposed = true;
|
||||
removeResumeListeners();
|
||||
resyncRequesterRef.current?.cancel();
|
||||
resyncRequesterRef.current = null;
|
||||
const socket = socketRef.current;
|
||||
@@ -689,6 +806,7 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
pendingBidTimeoutsRef.current = {};
|
||||
pendingActionTimeoutsRef.current = {};
|
||||
latestAuctionRef.current = null;
|
||||
synchronizedSocketRef.current = null;
|
||||
cancelledLifecycleIds.clear();
|
||||
latestConfirmedBidPointAmountRef.current = 0;
|
||||
hasSyncedServerTimeRef.current = false;
|
||||
@@ -707,6 +825,8 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
connectionKey,
|
||||
matchId,
|
||||
receiveReaction,
|
||||
markSynchronized,
|
||||
requestServerTimeSync,
|
||||
setError,
|
||||
]);
|
||||
|
||||
@@ -906,6 +1026,11 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
pendingBidRequests,
|
||||
resetAt,
|
||||
connectionStatus: visibleConnectionStatus,
|
||||
isSynchronized:
|
||||
synchronizationState.key === connectionKey &&
|
||||
synchronizationState.ready && visibleConnectionStatus === 'connected',
|
||||
historyUpdateCount:
|
||||
historyUpdateState.key === connectionKey ? historyUpdateState.count : 0,
|
||||
error: visibleError,
|
||||
bidLatencyDiagnostics,
|
||||
serverRoundTripMs: matchId ? serverRoundTripMs : null,
|
||||
@@ -1027,15 +1152,6 @@ function createClientRequestId(): string {
|
||||
return `${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
||||
}
|
||||
|
||||
function resolveCurrentBidPointAmount(auction: ApiAuction): number {
|
||||
const bidPointAmount = Math.max(
|
||||
Number(auction.currentHighestBidPointAmount),
|
||||
Number(auction.currentBid),
|
||||
0,
|
||||
);
|
||||
return Number.isFinite(bidPointAmount) ? bidPointAmount : 0;
|
||||
}
|
||||
|
||||
// [AUCTION-DEBUG] 아래 텔레메트리 헬퍼들과 호출부는 조사 종료 후 제거 대상.
|
||||
type AuctionTelemetryAttributes = Record<
|
||||
string,
|
||||
|
||||
@@ -37,6 +37,10 @@ import {
|
||||
} from "../config";
|
||||
import { ApiError } from "../lib/api";
|
||||
import { mergeAuctionState } from "../api/auction-state";
|
||||
import {
|
||||
AUCTION_SAFETY_POLL_INTERVAL_MS,
|
||||
startAuctionRecoveryPolling,
|
||||
} from "../api/auction-polling";
|
||||
import {
|
||||
profileIconUrl,
|
||||
} from "../lib/ddragon";
|
||||
@@ -1196,16 +1200,23 @@ export default function AuctionPage() {
|
||||
currentUser?.role === "owner" ||
|
||||
currentUser?.role === "admin";
|
||||
const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID);
|
||||
const socket = useAuctionSocket(id);
|
||||
const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID, {
|
||||
refetchInterval: 5000,
|
||||
refetchInterval: AUCTION_SAFETY_POLL_INTERVAL_MS,
|
||||
});
|
||||
const { refetch: refetchAuction } = auctionQuery;
|
||||
useEffect(() => {
|
||||
if (!id || socket.isSynchronized) return;
|
||||
return startAuctionRecoveryPolling(() => {
|
||||
void refetchAuction({ cancelRefetch: false });
|
||||
});
|
||||
}, [id, socket.isSynchronized, refetchAuction]);
|
||||
const historyQuery = useAuctionHistory(id, DEFAULT_COMMUNITY_ID, {
|
||||
enabled: canManageAuction,
|
||||
refetchInterval: 3000,
|
||||
refetchInterval: AUCTION_SAFETY_POLL_INTERVAL_MS,
|
||||
});
|
||||
const undoMutation = useUndoAuction(DEFAULT_COMMUNITY_ID);
|
||||
const resetAuctionMutation = useResetAuction(DEFAULT_COMMUNITY_ID);
|
||||
const socket = useAuctionSocket(id);
|
||||
const savedCaptainTeamIndex = useAuctionCaptainTeamIndex(id);
|
||||
const [assignedPositionDraft, setAssignedPositionDraft] = useState<{
|
||||
playerId: string | null;
|
||||
@@ -1256,6 +1267,13 @@ export default function AuctionPage() {
|
||||
useEffect(() => {
|
||||
syncPolledAuctionState(auctionQuery.data);
|
||||
}, [auctionQuery.data, syncPolledAuctionState]);
|
||||
useEffect(() => {
|
||||
if (!id || !canManageAuction || !socket.historyUpdateCount) return;
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: ["auction-history", DEFAULT_COMMUNITY_ID, id],
|
||||
exact: true,
|
||||
});
|
||||
}, [id, canManageAuction, queryClient, socket.historyUpdateCount]);
|
||||
const liveAuction = pickLatestAuction(socket.auction, auctionQuery.data);
|
||||
const auctionState = useMemo(
|
||||
() =>
|
||||
@@ -1384,18 +1402,25 @@ export default function AuctionPage() {
|
||||
sequence,
|
||||
},
|
||||
{
|
||||
onSuccess: async () => {
|
||||
await Promise.all([
|
||||
onSuccess: async (updatedAuction) => {
|
||||
const refreshes = [
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["auction", DEFAULT_COMMUNITY_ID, id],
|
||||
}),
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["auction-history", DEFAULT_COMMUNITY_ID, id],
|
||||
}),
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["match", DEFAULT_COMMUNITY_ID, id],
|
||||
}),
|
||||
]);
|
||||
];
|
||||
// Redis history refreshes on its post-durability event. Legacy Undo
|
||||
// commits before responding and does not emit that event.
|
||||
if (updatedAuction.auctionEngineVersion !== "redis-v1") {
|
||||
refreshes.push(
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["auction-history", DEFAULT_COMMUNITY_ID, id],
|
||||
}),
|
||||
);
|
||||
}
|
||||
await Promise.all(refreshes);
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { setImmediate } from 'node:timers/promises';
|
||||
import {
|
||||
environmentManager,
|
||||
QueryClient,
|
||||
QueryObserver,
|
||||
} from '@tanstack/react-query';
|
||||
import {
|
||||
AUCTION_SAFETY_POLL_INTERVAL_MS,
|
||||
startAuctionRecoveryPolling,
|
||||
} from '../src/api/auction-polling.ts';
|
||||
|
||||
test('repeated short recovery periods cannot postpone the safety HTTP poll', async (t) => {
|
||||
t.mock.timers.enable({ apis: ['Date', 'setTimeout', 'setInterval'], now: 0 });
|
||||
const wasServer = environmentManager.isServer();
|
||||
environmentManager.setIsServer(() => false);
|
||||
const client = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false, gcTime: Infinity } },
|
||||
});
|
||||
const requests: number[] = [];
|
||||
const observer = new QueryObserver(client, {
|
||||
queryKey: ['auction', 'match-1'],
|
||||
queryFn: async () => {
|
||||
requests.push(Date.now());
|
||||
return { revision: 1 };
|
||||
},
|
||||
refetchInterval: AUCTION_SAFETY_POLL_INTERVAL_MS,
|
||||
});
|
||||
const unsubscribe = observer.subscribe(() => {});
|
||||
let stopRecovery: (() => void) | undefined;
|
||||
t.after(() => {
|
||||
stopRecovery?.();
|
||||
unsubscribe();
|
||||
client.clear();
|
||||
environmentManager.setIsServer(() => wasServer);
|
||||
});
|
||||
await setImmediate();
|
||||
|
||||
for (let attempt = 0; attempt < 6; attempt += 1) {
|
||||
stopRecovery = startAuctionRecoveryPolling(
|
||||
() => { void observer.refetch({ cancelRefetch: false }); },
|
||||
() => true,
|
||||
);
|
||||
t.mock.timers.tick(1000);
|
||||
await setImmediate();
|
||||
stopRecovery();
|
||||
t.mock.timers.tick(9000);
|
||||
await setImmediate();
|
||||
}
|
||||
|
||||
assert.deepEqual(requests, [0, 30_000, 60_000]);
|
||||
});
|
||||
|
||||
test('recovery polls every five seconds while visible and stops after cleanup', (t) => {
|
||||
t.mock.timers.enable({ apis: ['setInterval'] });
|
||||
let visible = true;
|
||||
let requests = 0;
|
||||
const stop = startAuctionRecoveryPolling(
|
||||
() => { requests += 1; },
|
||||
() => visible,
|
||||
);
|
||||
t.after(stop);
|
||||
t.mock.timers.tick(5000);
|
||||
assert.equal(requests, 1);
|
||||
visible = false;
|
||||
t.mock.timers.tick(10_000);
|
||||
assert.equal(requests, 1);
|
||||
visible = true;
|
||||
t.mock.timers.tick(5000);
|
||||
assert.equal(requests, 2);
|
||||
stop();
|
||||
t.mock.timers.tick(10_000);
|
||||
assert.equal(requests, 2);
|
||||
});
|
||||
@@ -72,6 +72,24 @@ test('bounds retries and honors retry delay without rejoining the room', async (
|
||||
assert.deepEqual(waits, [1500, 1500]);
|
||||
});
|
||||
|
||||
test('reports failure when all replies remain behind the required revision', async () => {
|
||||
let failed = 0;
|
||||
let applied = 0;
|
||||
const sync = createAuctionResyncRequester(
|
||||
async () => ({ ok: true, state: state(10) }),
|
||||
() => {
|
||||
applied++;
|
||||
},
|
||||
noWait,
|
||||
() => {
|
||||
failed++;
|
||||
},
|
||||
);
|
||||
await sync.request(12, 'life');
|
||||
assert.equal(applied, 3);
|
||||
assert.equal(failed, 1);
|
||||
});
|
||||
|
||||
test('drops an old connection reply after cancellation and permits a new request', async () => {
|
||||
let finish!: (reply: AuctionResyncReply) => void;
|
||||
let calls = 0;
|
||||
|
||||
@@ -6,9 +6,192 @@ import {
|
||||
shouldApplyIncomingAuctionState,
|
||||
shouldApplyPolledAuctionState,
|
||||
shouldResyncForBidDelta,
|
||||
resolveCurrentBidPointAmount,
|
||||
shouldResyncForAuctionIdentity,
|
||||
createAuctionHeartbeatMonitor,
|
||||
} from "../src/api/auction-state.ts";
|
||||
import type { ApiAuction } from "../src/api/types.ts";
|
||||
|
||||
test("Redis-only snapshots retain the bid amount without a legacy alias", () => {
|
||||
assert.equal(
|
||||
resolveCurrentBidPointAmount({
|
||||
currentHighestBidPointAmount: 310,
|
||||
} as ApiAuction),
|
||||
310,
|
||||
);
|
||||
assert.equal(
|
||||
resolveCurrentBidPointAmount({ currentBid: 120 } as ApiAuction),
|
||||
120,
|
||||
);
|
||||
assert.equal(
|
||||
resolveCurrentBidPointAmount({
|
||||
currentHighestBidPointAmount: 0,
|
||||
currentBid: 120,
|
||||
} as ApiAuction),
|
||||
0,
|
||||
);
|
||||
assert.equal(
|
||||
resolveCurrentBidPointAmount({
|
||||
currentHighestBidPointAmount: NaN,
|
||||
} as ApiAuction),
|
||||
0,
|
||||
);
|
||||
});
|
||||
|
||||
test("heartbeats detect missed state and separately versioned side effects", () => {
|
||||
const state = {
|
||||
auctionLifecycleId: "life",
|
||||
revision: 10,
|
||||
matchSideEffectRevision: 2,
|
||||
} as ApiAuction;
|
||||
assert.equal(
|
||||
shouldResyncForAuctionIdentity(state, {
|
||||
auctionLifecycleId: "life",
|
||||
revision: 11,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
shouldResyncForAuctionIdentity(state, {
|
||||
auctionLifecycleId: "life",
|
||||
revision: 10,
|
||||
matchSideEffectRevision: 3,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
shouldResyncForAuctionIdentity(state, {
|
||||
auctionLifecycleId: "life",
|
||||
revision: 10,
|
||||
matchSideEffectRevision: 2,
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
shouldResyncForAuctionIdentity(state, {
|
||||
auctionLifecycleId: "new-life",
|
||||
revision: 1,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
test("a delayed heartbeat cannot pull an advanced socket backward", () => {
|
||||
const advanced = { auctionLifecycleId: "life", revision: 12 } as ApiAuction;
|
||||
assert.equal(
|
||||
shouldResyncForAuctionIdentity(advanced, {
|
||||
auctionLifecycleId: "life",
|
||||
revision: 11,
|
||||
matchSideEffectRevision: 9,
|
||||
}),
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test("expired complete runtimes and legacy archives do not repeatedly resync", () => {
|
||||
assert.equal(
|
||||
shouldResyncForAuctionIdentity(
|
||||
{ auctionLifecycleId: "life", phase: "complete" } as ApiAuction,
|
||||
null,
|
||||
),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
shouldResyncForAuctionIdentity({ phase: "bidding" } as ApiAuction, null),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
shouldResyncForAuctionIdentity(
|
||||
{
|
||||
auctionEngineVersion: "legacy-renamed",
|
||||
auctionLifecycleId: "legacy-auction:1",
|
||||
phase: "bidding",
|
||||
} as ApiAuction,
|
||||
null,
|
||||
),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
shouldResyncForAuctionIdentity(
|
||||
{
|
||||
auctionEngineVersion: "redis-v1",
|
||||
auctionLifecycleId: "life",
|
||||
phase: "bidding",
|
||||
} as ApiAuction,
|
||||
null,
|
||||
),
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
test("a new in-flight bid does not confirm an earlier gap that already closed", () => {
|
||||
const monitor = createAuctionHeartbeatMonitor();
|
||||
const client = {
|
||||
auctionEngineVersion: "redis-v1",
|
||||
auctionLifecycleId: "life",
|
||||
revision: 10,
|
||||
} as ApiAuction;
|
||||
assert.equal(
|
||||
monitor.inspect(client, { auctionLifecycleId: "life", revision: 11 })
|
||||
.needsResync,
|
||||
false,
|
||||
);
|
||||
const caughtUp = { ...client, revision: 11 };
|
||||
assert.equal(
|
||||
monitor.inspect(caughtUp, { auctionLifecycleId: "life", revision: 12 })
|
||||
.needsResync,
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
monitor.inspect(caughtUp, { auctionLifecycleId: "life", revision: 13 })
|
||||
.needsResync,
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
test("heartbeat failures require two misses and reset after a healthy reply", () => {
|
||||
const monitor = createAuctionHeartbeatMonitor();
|
||||
assert.equal(monitor.recordFailure(), false);
|
||||
assert.equal(monitor.recordFailure(), true);
|
||||
monitor.inspect(
|
||||
{ auctionEngineVersion: "legacy-renamed" } as ApiAuction,
|
||||
null,
|
||||
);
|
||||
assert.equal(monitor.recordFailure(), false);
|
||||
monitor.reset();
|
||||
assert.equal(monitor.recordFailure(), false);
|
||||
});
|
||||
|
||||
test("heartbeat confirmation covers side effects and missing runtimes", () => {
|
||||
const monitor = createAuctionHeartbeatMonitor();
|
||||
const client = {
|
||||
auctionEngineVersion: "redis-v1",
|
||||
auctionLifecycleId: "life",
|
||||
revision: 10,
|
||||
matchSideEffectRevision: 1,
|
||||
} as ApiAuction;
|
||||
const identity = {
|
||||
auctionLifecycleId: "life",
|
||||
revision: 10,
|
||||
matchSideEffectRevision: 2,
|
||||
};
|
||||
assert.equal(monitor.inspect(client, identity).needsResync, false);
|
||||
assert.equal(
|
||||
monitor.inspect({ ...client, matchSideEffectRevision: 2 }, identity)
|
||||
.isCurrent,
|
||||
true,
|
||||
);
|
||||
assert.equal(monitor.inspect(client, null).needsResync, false);
|
||||
assert.equal(monitor.inspect(client, null).needsResync, true);
|
||||
monitor.reset();
|
||||
const legacy = {
|
||||
...client,
|
||||
auctionEngineVersion: "legacy-renamed",
|
||||
} as ApiAuction;
|
||||
assert.equal(monitor.inspect(legacy, null).isCurrent, true);
|
||||
assert.equal(monitor.inspect(legacy, null).needsResync, false);
|
||||
});
|
||||
|
||||
const current = {
|
||||
auctionLifecycleId: "life",
|
||||
revision: 10,
|
||||
|
||||
Reference in new issue
Block a user