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:
dahyeon committed 2026-11-12 01:49:27 +09:00
1 parent e349684523
commit 23a0a3f8dd
20 files changed
+790 -154

No files matched your search

@@ -233,6 +233,56 @@ describe('auction durability projection helpers', () => {
expect(session.endSession).toHaveBeenCalledTimes(1); expect(session.endSession).toHaveBeenCalledTimes(1);
}); });
it('notifies history only after commit, including when state rebroadcast is disabled', async () => {
let finishCommit!: () => void;
const session = {
startTransaction: jest.fn(),
commitTransaction: jest.fn().mockImplementation(
() =>
new Promise<void>((resolve) => {
finishCommit = resolve;
}),
),
abortTransaction: jest.fn().mockResolvedValue(undefined),
endSession: jest.fn().mockResolvedValue(undefined),
};
const updateOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ upsertedCount: 1 }),
});
const broadcastHistoryUpdated = jest.fn();
const scheduler = new AuctionDurabilityScheduler(
{
createSession: async () => session,
getModel: async () => ({ updateOne }),
} as never,
{} as never,
undefined,
undefined,
undefined,
{ broadcastHistoryUpdated } as never,
);
const pending = scheduler.applyDurabilityPayload({
...payload,
shouldBroadcastState: false,
});
await new Promise((resolve) => setImmediate(resolve));
expect(session.commitTransaction).toHaveBeenCalledTimes(1);
expect(broadcastHistoryUpdated).not.toHaveBeenCalled();
finishCommit();
await pending;
expect(broadcastHistoryUpdated).toHaveBeenCalledWith({
matchId: 'match-1',
auctionLifecycleId: 'life-1',
auctionStateTransitionId: 'transition-1',
});
session.commitTransaction.mockRejectedValueOnce(new Error('commit failed'));
await expect(scheduler.applyDurabilityPayload(payload)).rejects.toThrow(
'commit failed',
);
expect(broadcastHistoryUpdated).toHaveBeenCalledTimes(1);
expect(session.abortTransaction).toHaveBeenCalledTimes(1);
});
it('broadcasts latest Redis state when durability payload requests it', async () => { it('broadcasts latest Redis state when durability payload requests it', async () => {
const session = { const session = {
abortTransaction: jest.fn().mockResolvedValue(undefined), abortTransaction: jest.fn().mockResolvedValue(undefined),
@@ -265,7 +315,7 @@ describe('auction durability projection helpers', () => {
undefined, undefined,
undefined, undefined,
undefined, undefined,
{ broadcastState } as never, { broadcastState, broadcastHistoryUpdated: jest.fn() } as never,
{ readAuctionStateView } as never, { readAuctionStateView } as never,
); );
@@ -315,7 +365,7 @@ describe('auction durability projection helpers', () => {
undefined, undefined,
undefined, undefined,
undefined, undefined,
{ broadcastState } as never, { broadcastState, broadcastHistoryUpdated: jest.fn() } as never,
{ readAuctionStateView } as never, { readAuctionStateView } as never,
); );
@@ -407,60 +457,71 @@ describe('auction durability projection helpers', () => {
); );
}); });
it('skips destructive history mutation for stale payloads', async () => { it.each(['life-1', 'new-life'])(
const session = { 'skips stale history changes and notifications for current lifecycle %s',
abortTransaction: jest.fn().mockResolvedValue(undefined), async (auctionLifecycleId) => {
commitTransaction: jest.fn().mockResolvedValue(undefined), const broadcastHistoryUpdated = jest.fn();
endSession: jest.fn().mockResolvedValue(undefined), const session = {
startTransaction: jest.fn(), abortTransaction: jest.fn().mockResolvedValue(undefined),
}; commitTransaction: jest.fn().mockResolvedValue(undefined),
const historyDeleteMany = jest.fn(); endSession: jest.fn().mockResolvedValue(undefined),
const historyUpdateOne = jest.fn(); startTransaction: jest.fn(),
const auctionUpdateOne = jest.fn().mockReturnValue({ };
exec: jest.fn().mockResolvedValue({ matchedCount: 0, modifiedCount: 0 }), const historyDeleteMany = jest.fn();
}); const historyUpdateOne = jest.fn();
const projectionExec = jest.fn().mockResolvedValue({ const auctionUpdateOne = jest.fn().mockReturnValue({
auctionLifecycleId: 'life-1', exec: jest
revision: 10, .fn()
}); .mockResolvedValue({ matchedCount: 0, modifiedCount: 0 }),
const auctionFindById = jest.fn().mockReturnValue({ });
select: jest.fn().mockReturnValue({ const projectionExec = jest.fn().mockResolvedValue({
session: jest.fn().mockReturnValue({ auctionLifecycleId,
lean: jest.fn().mockReturnValue({ exec: projectionExec }), revision: 10,
});
const auctionFindById = jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
session: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({ exec: projectionExec }),
}),
}), }),
}), });
}); const scheduler = new AuctionDurabilityScheduler(
const scheduler = new AuctionDurabilityScheduler( {
{ createSession: jest.fn().mockResolvedValue(session),
createSession: jest.fn().mockResolvedValue(session), getModel: jest.fn((name: string) => {
getModel: jest.fn((name: string) => { if (name === 'auctionHistory') {
if (name === 'auctionHistory') { return {
return { deleteMany: historyDeleteMany,
deleteMany: historyDeleteMany, updateOne: historyUpdateOne,
updateOne: historyUpdateOne, };
}; }
} if (name === 'auction') {
if (name === 'auction') { return { findById: auctionFindById, updateOne: auctionUpdateOne };
return { findById: auctionFindById, updateOne: auctionUpdateOne }; }
} return { updateOne: jest.fn() };
return { updateOne: jest.fn() }; }),
}), } as never,
} as never, { raw: jest.fn() } as never,
{ raw: jest.fn() } as never, undefined,
); undefined,
undefined,
{ broadcastHistoryUpdated } as never,
);
await scheduler.applyDurabilityPayload({ await scheduler.applyDurabilityPayload({
...payload, ...payload,
historyMutation: { historyMutation: {
targetHistorySequence: 2, targetHistorySequence: 2,
type: 'deleteAfterSequenceAndAppendUndo', type: 'deleteAfterSequenceAndAppendUndo',
}, },
}); });
expect(historyDeleteMany).not.toHaveBeenCalled(); expect(historyDeleteMany).not.toHaveBeenCalled();
expect(historyUpdateOne).not.toHaveBeenCalled(); expect(historyUpdateOne).not.toHaveBeenCalled();
expect(auctionUpdateOne).not.toHaveBeenCalled(); expect(auctionUpdateOne).not.toHaveBeenCalled();
}); expect(broadcastHistoryUpdated).not.toHaveBeenCalled();
},
);
it('recovers stale append payloads as history-only records', async () => { it('recovers stale append payloads as history-only records', async () => {
const session = { const session = {
@@ -597,6 +658,7 @@ describe('auction durability projection helpers', () => {
}); });
it('clears stale append payloads after history-only recovery', async () => { it('clears stale append payloads after history-only recovery', async () => {
const broadcastHistoryUpdated = jest.fn();
const sendCommand = jest const sendCommand = jest
.fn() .fn()
.mockResolvedValueOnce(['payload-1']) .mockResolvedValueOnce(['payload-1'])
@@ -653,6 +715,10 @@ describe('auction durability projection helpers', () => {
getCurrentRedisTimestampMS: jest.fn().mockResolvedValue(1000), getCurrentRedisTimestampMS: jest.fn().mockResolvedValue(1000),
raw: jest.fn().mockReturnValue({ sendCommand }), raw: jest.fn().mockReturnValue({ sendCommand }),
} as never, } as never,
undefined,
undefined,
undefined,
{ broadcastHistoryUpdated } as never,
); );
await expect(scheduler.processDueDurabilityPayloads(10)).resolves.toEqual({ await expect(scheduler.processDueDurabilityPayloads(10)).resolves.toEqual({
@@ -662,6 +728,11 @@ describe('auction durability projection helpers', () => {
}); });
expect(historyUpdateOne).toHaveBeenCalledTimes(1); expect(historyUpdateOne).toHaveBeenCalledTimes(1);
expect(broadcastHistoryUpdated).toHaveBeenCalledWith({
matchId: 'match-1',
auctionLifecycleId: 'life-1',
auctionStateTransitionId: 'transition-1',
});
expect(auctionUpdateOne).not.toHaveBeenCalled(); expect(auctionUpdateOne).not.toHaveBeenCalled();
expect(sideEffectUpdateOne).not.toHaveBeenCalled(); expect(sideEffectUpdateOne).not.toHaveBeenCalled();
expect(sendCommand).toHaveBeenNthCalledWith(3, [ expect(sendCommand).toHaveBeenNthCalledWith(3, [
@@ -1006,7 +1077,7 @@ describe('auction durability projection helpers', () => {
{ reserveForMatch } as never, { reserveForMatch } as never,
{ scheduleInitialPoll } as never, { scheduleInitialPoll } as never,
{ mirrorMatchSideEffectStatus } as never, { mirrorMatchSideEffectStatus } as never,
{ broadcastMatchSideEffect } as never, { broadcastMatchSideEffect, broadcastHistoryUpdated: jest.fn() } as never,
); );
await scheduler.applyDurabilityPayload(completePayload); await scheduler.applyDurabilityPayload(completePayload);
@@ -1203,7 +1274,7 @@ describe('auction durability projection helpers', () => {
{ reserveForMatch } as never, { reserveForMatch } as never,
{ scheduleInitialPoll } as never, { scheduleInitialPoll } as never,
{ mirrorMatchSideEffectStatus } as never, { mirrorMatchSideEffectStatus } as never,
{ broadcastMatchSideEffect } as never, { broadcastMatchSideEffect, broadcastHistoryUpdated: jest.fn() } as never,
); );
await expect( await expect(
@@ -1332,7 +1403,7 @@ describe('auction durability projection helpers', () => {
{ releaseFromMatch } as never, { releaseFromMatch } as never,
{ cancelPolling } as never, { cancelPolling } as never,
{ mirrorMatchSideEffectStatus } as never, { mirrorMatchSideEffectStatus } as never,
{ broadcastMatchSideEffect } as never, { broadcastMatchSideEffect, broadcastHistoryUpdated: jest.fn() } as never,
); );
await scheduler.applyDurabilityPayload(resetPayload); await scheduler.applyDurabilityPayload(resetPayload);
@@ -356,6 +356,15 @@ export class AuctionDurabilityScheduler
if (session) await session.endSession(); if (session) await session.endSession();
} }
if (shouldApplyHistoryMutation) {
// This is independent of the primary state broadcast. HTTP reads on every
// node can see the committed history before clients are notified.
this.auctionEventBusService?.broadcastHistoryUpdated({
matchId: String(payload.matchId),
auctionLifecycleId: payload.auctionLifecycleId,
auctionStateTransitionId: payload.auctionStateTransitionId,
});
}
await this.broadcastLatestRedisAuctionStateIfRequested(payload); await this.broadcastLatestRedisAuctionStateIfRequested(payload);
if (sideEffectMutation && shouldApplySideEffects) { if (sideEffectMutation && shouldApplySideEffects) {
@@ -1,5 +1,6 @@
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import type { Namespace } from 'socket.io'; import type { Namespace } from 'socket.io';
import type { AuctionHistoryUpdatedEvent } from '@lolympus/contracts';
import type { AuctionStateResponse } from './auction.service'; import type { AuctionStateResponse } from './auction.service';
import type { MatchSideEffectDelta } from './auction-side-effect.service'; import type { MatchSideEffectDelta } from './auction-side-effect.service';
import { serializeRealtimeAuction } from './auction-realtime-serializer'; import { serializeRealtimeAuction } from './auction-realtime-serializer';
@@ -25,6 +26,10 @@ export class AuctionEventBusService {
.emit('state', serializeRealtimeAuction(state)); .emit('state', serializeRealtimeAuction(state));
} }
public broadcastHistoryUpdated(event: AuctionHistoryUpdatedEvent): void {
this.auctionNamespace?.to(event.matchId).emit('history-updated', event);
}
public broadcastReset(matchId: string, auctionLifecycleId: string): void { public broadcastReset(matchId: string, auctionLifecycleId: string): void {
this.auctionNamespace this.auctionNamespace
?.to(matchId) ?.to(matchId)
@@ -37,7 +37,11 @@ describe('AuctionGateway', () => {
{} as never, {} as never,
); );
const socket = { data: { matchId }, join: jest.fn(), emit: jest.fn() }; const socket = { data: { matchId }, join: jest.fn(), emit: jest.fn() };
await gateway.handleJoin(socket as never, { matchId }); const ack = jest.fn();
await gateway.handleJoin(socket as never, { matchId }, ack);
expect(ack).toHaveBeenCalledWith(
expect.objectContaining({ ok: false, code: 'AUCTION_STATE_RECOVERING' }),
);
expect(socket.emit).toHaveBeenCalledTimes(1); expect(socket.emit).toHaveBeenCalledTimes(1);
expect(socket.emit).toHaveBeenCalledWith('state-pending', { expect(socket.emit).toHaveBeenCalledWith('state-pending', {
retryAfterMS: 500, retryAfterMS: 500,
@@ -92,9 +96,12 @@ describe('AuctionGateway', () => {
function createGateway(params?: { function createGateway(params?: {
getCurrentRedisTimestampMS?: jest.Mock; getCurrentRedisTimestampMS?: jest.Mock;
placeBidDelta?: jest.Mock; placeBidDelta?: jest.Mock;
getRealtimeIdentity?: jest.Mock;
}) { }) {
const auctionService = { const auctionService = {
placeBidDelta: params?.placeBidDelta ?? jest.fn(), placeBidDelta: params?.placeBidDelta ?? jest.fn(),
getRealtimeIdentity:
params?.getRealtimeIdentity ?? jest.fn().mockResolvedValue(null),
}; };
const auctionRedisService = { const auctionRedisService = {
getCurrentRedisTimestampMS: getCurrentRedisTimestampMS:
@@ -387,6 +394,46 @@ describe('AuctionGateway', () => {
); );
}); });
it('adds lightweight auction identity to heartbeats for the joined match', async () => {
const matchId = new mongoose.Types.ObjectId().toString();
const identity = {
auctionLifecycleId: 'life-1',
revision: 11,
matchSideEffectRevision: 3,
};
const getRealtimeIdentity = jest.fn().mockResolvedValue(identity);
const { gateway } = createGateway({ getRealtimeIdentity });
const ack = jest.fn();
await gateway.handleTimeSync({ sequence: 1 }, ack, {
data: { matchId },
} as never);
expect(getRealtimeIdentity).toHaveBeenCalledWith(matchId);
expect(ack).toHaveBeenCalledWith(
expect.objectContaining({ ok: true, auctionState: identity }),
);
});
it('continues clock sync when the optional auction identity read fails', async () => {
const matchId = new mongoose.Types.ObjectId().toString();
const { gateway } = createGateway({
getRealtimeIdentity: jest
.fn()
.mockRejectedValue(new Error('identity unavailable')),
});
const ack = jest.fn();
await gateway.handleTimeSync({ sequence: 2 }, ack, {
data: { matchId },
} as never);
expect(ack).toHaveBeenCalledWith(
expect.objectContaining({
ok: true,
sequence: 2,
currentServerTimestampMS: 1780000000000,
auctionStateUnavailable: true,
}),
);
});
it('rate limits excessive bid requests from the same socket', async () => { it('rate limits excessive bid requests from the same socket', async () => {
jest.spyOn(Date, 'now').mockReturnValue(1780000000000); jest.spyOn(Date, 'now').mockReturnValue(1780000000000);
const matchId = new mongoose.Types.ObjectId().toString(); const matchId = new mongoose.Types.ObjectId().toString();
@@ -180,9 +180,11 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
public async handleJoin( public async handleJoin(
@ConnectedSocket() socket: AuctionSocket, @ConnectedSocket() socket: AuctionSocket,
@MessageBody() payload: JoinAuctionPayload, @MessageBody() payload: JoinAuctionPayload,
@Ack() ack?: (response: Record<string, unknown>) => void,
) { ) {
if (!payload?.matchId || !mongoose.isValidObjectId(payload.matchId)) { if (!payload?.matchId || !mongoose.isValidObjectId(payload.matchId)) {
this.emitError(socket, 'Invalid matchId.'); this.emitError(socket, 'Invalid matchId.');
ack?.({ ok: false, code: 'INVALID_MATCH_ID' });
return; return;
} }
@@ -201,8 +203,10 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
); );
this.emitChatHistory(socket, auction); this.emitChatHistory(socket, auction);
socket.emit('state', serializeRealtimeAuction(auctionState)); socket.emit('state', serializeRealtimeAuction(auctionState));
ack?.({ ok: true });
} catch (error) { } catch (error) {
const rejection = this.resolveErrorPayload(error); const rejection = this.resolveErrorPayload(error);
ack?.({ ...rejection, ok: false });
if (rejection.code === 'AUCTION_STATE_RECOVERING') { if (rejection.code === 'AUCTION_STATE_RECOVERING') {
socket.emit('state-pending', { retryAfterMS: 500 }); socket.emit('state-pending', { retryAfterMS: 500 });
} else { } else {
@@ -347,14 +351,27 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
public async handleTimeSync( public async handleTimeSync(
@MessageBody() payload: TimeSyncPayload, @MessageBody() payload: TimeSyncPayload,
@Ack() ack?: (response: Record<string, unknown>) => void, @Ack() ack?: (response: Record<string, unknown>) => void,
@ConnectedSocket() socket?: AuctionSocket,
) { ) {
const receivedAtMonotonicMS = performance.now(); const receivedAtMonotonicMS = performance.now();
try { try {
const currentServerTimestampMS = const [currentServerTimestampMS, auctionState] = await Promise.all([
await this.auctionRedisService.getCurrentRedisTimestampMS(); this.auctionRedisService.getCurrentRedisTimestampMS(),
socket?.data.matchId
? this.auctionService
.getRealtimeIdentity(socket.data.matchId)
.catch(() => undefined)
: undefined,
]);
ack?.({ ack?.({
clientSentAtTimestampMS: payload?.clientSentAtTimestampMS, clientSentAtTimestampMS: payload?.clientSentAtTimestampMS,
currentServerTimestampMS, currentServerTimestampMS,
...(socket?.data.matchId
? {
auctionState,
auctionStateUnavailable: auctionState === undefined,
}
: {}),
ok: true, ok: true,
sequence: payload?.sequence, sequence: payload?.sequence,
serverProcessingDurationMS: serverProcessingDurationMS:
@@ -215,8 +215,7 @@ describe('AuctionService', () => {
expect(auctionRedisCommandService.placeBid).not.toHaveBeenCalled(); expect(auctionRedisCommandService.placeBid).not.toHaveBeenCalled();
}); });
it('lists auction history with a summary projection and short local cache', async () => { it('reads committed history on every node without retaining a local cache', async () => {
const nowSpy = jest.spyOn(Date, 'now').mockReturnValue(1000);
const matchId = new mongoose.Types.ObjectId(); const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId(); const communityId = new mongoose.Types.ObjectId();
const match = { const match = {
@@ -242,7 +241,7 @@ describe('AuctionService', () => {
const historySort = jest.fn().mockReturnValue({ limit: historyLimit }); const historySort = jest.fn().mockReturnValue({ limit: historyLimit });
const historySelect = jest.fn().mockReturnValue({ sort: historySort }); const historySelect = jest.fn().mockReturnValue({ sort: historySort });
const historyFind = jest.fn().mockReturnValue({ select: historySelect }); const historyFind = jest.fn().mockReturnValue({ select: historySelect });
const { service } = createService({ const models = {
auctionHistory: { auctionHistory: {
find: historyFind, find: historyFind,
}, },
@@ -251,7 +250,9 @@ describe('AuctionService', () => {
select: jest.fn().mockResolvedValue(match), select: jest.fn().mockResolvedValue(match),
}), }),
}, },
}); };
const { service } = createService(models);
const otherNode = createService(models).service;
await expect( await expect(
service.listHistory({ matchId, communityId }), service.listHistory({ matchId, communityId }),
@@ -271,7 +272,7 @@ describe('AuctionService', () => {
]); ]);
await service.listHistory({ matchId, communityId }); await service.listHistory({ matchId, communityId });
expect(historyFind).toHaveBeenCalledTimes(1); expect(historyFind).toHaveBeenCalledTimes(2);
expect(historySelect).toHaveBeenCalledWith({ expect(historySelect).toHaveBeenCalledWith({
_id: 0, _id: 0,
action: 1, action: 1,
@@ -281,9 +282,17 @@ describe('AuctionService', () => {
expect(historySort).toHaveBeenCalledWith({ sequence: -1 }); expect(historySort).toHaveBeenCalledWith({ sequence: -1 });
expect(historyLimit).toHaveBeenCalledWith(100); expect(historyLimit).toHaveBeenCalledWith(100);
nowSpy.mockReturnValue(3101); historyExec.mockResolvedValue([
await service.listHistory({ matchId, communityId }); { action: 'undo', sequence: 5, takenAt: new Date() },
expect(historyFind).toHaveBeenCalledTimes(2); historyRows[1],
]);
const [firstNodeHistory, secondNodeHistory] = await Promise.all([
service.listHistory({ matchId, communityId }),
otherNode.listHistory({ matchId, communityId }),
]);
expect(firstNodeHistory.map(({ sequence }) => sequence)).toEqual([5, 3]);
expect(secondNodeHistory).toEqual(firstNodeHistory);
expect(historyFind).toHaveBeenCalledTimes(4);
}); });
it('starts an auction without reserving tournament codes before teams are complete', async () => { it('starts an auction without reserving tournament codes before teams are complete', async () => {
@@ -10,6 +10,7 @@ import {
Optional, Optional,
} from '@nestjs/common'; } from '@nestjs/common';
import { randomUUID } from 'crypto'; import { randomUUID } from 'crypto';
import type { AuctionStateIdentity } from '@lolympus/contracts';
import { import {
AuctionLifecycleLock, AuctionLifecycleLock,
AuctionLifecycleBusyError, AuctionLifecycleBusyError,
@@ -69,8 +70,6 @@ const AUCTION_MAX_STORED_ACTION_REQUEST_RESULT_COUNT = 500;
const AUCTION_ACTION_REQUEST_REPLAY_WINDOW_MS = 5 * 60 * 1000; const AUCTION_ACTION_REQUEST_REPLAY_WINDOW_MS = 5 * 60 * 1000;
const AUCTION_ACTION_REQUEST_LEASE_DURATION_MS = 15 * 1000; const AUCTION_ACTION_REQUEST_LEASE_DURATION_MS = 15 * 1000;
const AUCTION_HISTORY_LIST_LIMIT = 100; const AUCTION_HISTORY_LIST_LIMIT = 100;
const AUCTION_HISTORY_LIST_CACHE_TTL_MS = 2 * 1000;
const AUCTION_HISTORY_LIST_CACHE_MAX_ENTRIES = 256;
interface StartAuctionParams { interface StartAuctionParams {
matchId: mongoose.Types.ObjectId; matchId: mongoose.Types.ObjectId;
@@ -163,11 +162,6 @@ interface AuctionHistorySummaryRecord {
takenAt: Date; takenAt: Date;
} }
interface AuctionHistoryListCacheEntry {
entries: AuctionHistoryView[];
expiresAtTimestampMS: number;
}
export type AuctionStateResponse = AuctionDocument | Record<string, unknown>; export type AuctionStateResponse = AuctionDocument | Record<string, unknown>;
export interface AuctionBidDeltaResponse { export interface AuctionBidDeltaResponse {
@@ -211,10 +205,6 @@ function isMongoDuplicateKeyError(error: unknown): boolean {
@Injectable() @Injectable()
export class AuctionService { export class AuctionService {
private readonly logger = new Logger(AuctionService.name); private readonly logger = new Logger(AuctionService.name);
private readonly auctionHistoryListCache = new Map<
string,
AuctionHistoryListCacheEntry
>();
constructor( constructor(
private readonly connectionService: ConnectionService, private readonly connectionService: ConnectionService,
@@ -579,6 +569,12 @@ export class AuctionService {
} }
} }
public getRealtimeIdentity(
matchId: string,
): Promise<AuctionStateIdentity | null> {
return this.auctionRedisStateReaderService.readLiveStateIdentity(matchId);
}
private async getStateByMatchIdOnce( private async getStateByMatchIdOnce(
matchId: mongoose.Types.ObjectId, matchId: mongoose.Types.ObjectId,
): Promise<AuctionStateResponse> { ): Promise<AuctionStateResponse> {
@@ -737,10 +733,6 @@ export class AuctionService {
throw new BadRequestException('Match does not belong to this community.'); throw new BadRequestException('Match does not belong to this community.');
} }
const cacheKey = this.buildAuctionHistoryListCacheKey(params);
const cachedHistory = this.getCachedAuctionHistoryList(cacheKey);
if (cachedHistory) return cachedHistory;
const entries = (await AuctionHistoryModel.find({ matchId: params.matchId }) const entries = (await AuctionHistoryModel.find({ matchId: params.matchId })
.select({ _id: 0, action: 1, sequence: 1, takenAt: 1 }) .select({ _id: 0, action: 1, sequence: 1, takenAt: 1 })
.sort({ sequence: -1 }) .sort({ sequence: -1 })
@@ -754,49 +746,9 @@ export class AuctionService {
actionLabel: this.formatHistoryActionLabel(entry.action), actionLabel: this.formatHistoryActionLabel(entry.action),
takenAt: entry.takenAt, takenAt: entry.takenAt,
})); }));
this.setCachedAuctionHistoryList(cacheKey, history);
return history; return history;
} }
private buildAuctionHistoryListCacheKey(params: {
matchId: mongoose.Types.ObjectId;
communityId: mongoose.Types.ObjectId;
}): string {
return `${params.communityId.toString()}:${params.matchId.toString()}`;
}
private getCachedAuctionHistoryList(
cacheKey: string,
): AuctionHistoryView[] | null {
const cached = this.auctionHistoryListCache.get(cacheKey);
if (!cached) return null;
if (cached.expiresAtTimestampMS <= Date.now()) {
this.auctionHistoryListCache.delete(cacheKey);
return null;
}
return cached.entries;
}
private setCachedAuctionHistoryList(
cacheKey: string,
entries: AuctionHistoryView[],
): void {
if (
!this.auctionHistoryListCache.has(cacheKey) &&
this.auctionHistoryListCache.size >=
AUCTION_HISTORY_LIST_CACHE_MAX_ENTRIES
) {
const oldestKey = this.auctionHistoryListCache.keys().next().value as
| string
| undefined;
if (oldestKey) this.auctionHistoryListCache.delete(oldestKey);
}
this.auctionHistoryListCache.set(cacheKey, {
entries,
expiresAtTimestampMS: Date.now() + AUCTION_HISTORY_LIST_CACHE_TTL_MS,
});
}
public async openBidding( public async openBidding(
matchId: mongoose.Types.ObjectId, matchId: mongoose.Types.ObjectId,
actionRequest: AuctionStructureActionRequestParams = {}, actionRequest: AuctionStructureActionRequestParams = {},
@@ -30,17 +30,23 @@ function makeService(
describe('AuctionRedisStateReaderService', () => { describe('AuctionRedisStateReaderService', () => {
it('reads live state identity', async () => { it('reads live state identity', async () => {
const { service, sendCommand } = makeService([['life-1', '7']]); const { service, sendCommand } = makeService([
['life-1', '7', '3', 'transition-1'],
]);
await expect(service.readLiveStateIdentity('match-1')).resolves.toEqual({ await expect(service.readLiveStateIdentity('match-1')).resolves.toEqual({
auctionLifecycleId: 'life-1', auctionLifecycleId: 'life-1',
revision: 7, revision: 7,
matchSideEffectRevision: 3,
matchSideEffectTransitionId: 'transition-1',
}); });
expect(sendCommand).toHaveBeenCalledWith([ expect(sendCommand).toHaveBeenCalledWith([
'HMGET', 'HMGET',
'auction:match-1:liveAuctionState', 'auction:match-1:liveAuctionState',
'auctionLifecycleId', 'auctionLifecycleId',
'revision', 'revision',
'matchSideEffectRevision',
'matchSideEffectTransitionId',
]); ]);
}); });
@@ -118,7 +124,9 @@ describe('AuctionRedisStateReaderService', () => {
expect(view).toMatchObject({ expect(view).toMatchObject({
auctionBidHistory: [{ bidPointAmount: 100, bidderTeamIndex: 2 }], auctionBidHistory: [{ bidPointAmount: 100, bidderTeamIndex: 2 }],
auctionEngineVersion: 'redis-v1',
auctionLifecycleId: 'life-1', auctionLifecycleId: 'life-1',
matchId: 'match-1',
auctionTeams: [{ teamIndex: 1 }], auctionTeams: [{ teamIndex: 1 }],
canPlaceBidInCurrentBidRound: false, canPlaceBidInCurrentBidRound: false,
currentHighestBidderTeamIndex: 2, currentHighestBidderTeamIndex: 2,
@@ -1,4 +1,5 @@
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import type { AuctionStateIdentity } from '@lolympus/contracts';
import { buildAuctionRedisKeys } from './auction-redis.keys'; import { buildAuctionRedisKeys } from './auction-redis.keys';
import { AuctionRedisService } from './auction-redis.service'; import { AuctionRedisService } from './auction-redis.service';
import { assembleAuctionViewFromRedisState } from './auction-redis.state'; import { assembleAuctionViewFromRedisState } from './auction-redis.state';
@@ -17,10 +18,7 @@ const NUMERIC_LIVE_STATE_FIELDS = new Set([
'revision', 'revision',
]); ]);
export interface AuctionRedisLiveStateIdentity { export type AuctionRedisLiveStateIdentity = AuctionStateIdentity;
auctionLifecycleId?: string;
revision?: number;
}
export interface AuctionRedisBidContext { export interface AuctionRedisBidContext {
auctionLifecycleId: string; auctionLifecycleId: string;
@@ -49,6 +47,8 @@ export class AuctionRedisStateReaderService {
keys.liveStateKey, keys.liveStateKey,
'auctionLifecycleId', 'auctionLifecycleId',
'revision', 'revision',
'matchSideEffectRevision',
'matchSideEffectTransitionId',
]); ]);
if (!Array.isArray(reply)) return null; if (!Array.isArray(reply)) return null;
const auctionLifecycleId = const auctionLifecycleId =
@@ -61,6 +61,12 @@ export class AuctionRedisStateReaderService {
return { return {
auctionLifecycleId, auctionLifecycleId,
revision: Number.isFinite(revision) ? revision : undefined, revision: Number.isFinite(revision) ? revision : undefined,
matchSideEffectRevision:
reply[2] !== null && Number.isFinite(Number(reply[2]))
? Number(reply[2])
: undefined,
matchSideEffectTransitionId:
typeof reply[3] === 'string' && reply[3] ? reply[3] : undefined,
}; };
} }
@@ -147,6 +153,7 @@ export class AuctionRedisStateReaderService {
structureState: parseJsonRecord(structureStateJson), structureState: parseJsonRecord(structureStateJson),
}); });
view.matchId = matchId; view.matchId = matchId;
view.auctionEngineVersion = 'redis-v1';
if (options.includeInternalLiveStateFields) { if (options.includeInternalLiveStateFields) {
view.redisInternalPhase = liveState.phase; view.redisInternalPhase = liveState.phase;
} }
+12
View File
@@ -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);
}
+2
View File
@@ -27,6 +27,7 @@ export function createAuctionResyncRequester(
fetchState: () => Promise<AuctionResyncReply>, fetchState: () => Promise<AuctionResyncReply>,
applyState: (state: ApiAuction) => void, applyState: (state: ApiAuction) => void,
wait = waitForRetry, wait = waitForRetry,
onFailure?: () => void,
) { ) {
let pending: Promise<void> | undefined; let pending: Promise<void> | undefined;
let controller = new AbortController(); let controller = new AbortController();
@@ -67,6 +68,7 @@ export function createAuctionResyncRequester(
} }
if (attempt < 2 && !signal.aborted) await wait(retryAfterMS, signal); if (attempt < 2 && !signal.aborted) await wait(retryAfterMS, signal);
} }
if (!signal.aborted) onFailure?.();
})().finally(() => { })().finally(() => {
if (!signal.aborted) pending = undefined; if (!signal.aborted) pending = undefined;
}); });
+65
View File
@@ -1,4 +1,69 @@
import type { ApiAuction } from "./types"; 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 { export interface BidDeltaPayload {
currentBidRoundId?: string; currentBidRoundId?: string;
+4 -3
View File
@@ -423,10 +423,10 @@ export function useAuction(
) { ) {
return useQuery({ return useQuery({
queryKey: ['auction', communityId, matchId ?? null], queryKey: ['auction', communityId, matchId ?? null],
queryFn: () => queryFn: ({ signal }) =>
apiFetch<ApiAuction>( apiFetch<ApiAuction>(
`/communities/${communityId}/matches/${matchId}/auction`, `/communities/${communityId}/matches/${matchId}/auction`,
{ auth: 'none' }, { auth: 'none', signal },
), ),
enabled: Boolean(communityId && matchId), enabled: Boolean(communityId && matchId),
retry: false, retry: false,
@@ -441,9 +441,10 @@ export function useAuctionHistory(
) { ) {
return useQuery({ return useQuery({
queryKey: ['auction-history', communityId, matchId ?? null], queryKey: ['auction-history', communityId, matchId ?? null],
queryFn: () => queryFn: ({ signal }) =>
apiFetch<ApiAuctionHistoryEntry[]>( apiFetch<ApiAuctionHistoryEntry[]>(
`/communities/${communityId}/matches/${matchId}/auction/history`, `/communities/${communityId}/matches/${matchId}/auction/history`,
{ signal },
), ),
enabled: Boolean(communityId && matchId && (options.enabled ?? true)), enabled: Boolean(communityId && matchId && (options.enabled ?? true)),
retry: false, retry: false,
+1
View File
@@ -196,6 +196,7 @@ export interface ApiAuctionChatMessage {
export interface ApiAuction { export interface ApiAuction {
_id: string; _id: string;
matchId: string; matchId: string;
auctionEngineVersion?: 'legacy-renamed' | 'redis-v1';
phase: AuctionPhase; phase: AuctionPhase;
teams?: ApiAuctionTeam[]; teams?: ApiAuctionTeam[];
auctionTeams: ApiAuctionTeam[]; auctionTeams: ApiAuctionTeam[];
+131 -15
View File
@@ -2,7 +2,12 @@ import { InteractionStatus } from '@azure/msal-browser';
import { useMsal } from '@azure/msal-react'; import { useMsal } from '@azure/msal-react';
import { useCallback, useEffect, useRef, useState } from 'react'; import { useCallback, useEffect, useRef, useState } from 'react';
import { io, type Socket } from 'socket.io-client'; 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 { appendAuctionReaction, isAuctionReaction, REACTION_LIFETIME_MS, sendAuctionReaction, type ActiveAuctionReaction } from './auction-reactions';
import { API_BASE_URL, useAuthUserId } from '../config'; import { API_BASE_URL, useAuthUserId } from '../config';
import { acquireAccessToken } from '../lib/auth/token-provider'; import { acquireAccessToken } from '../lib/auth/token-provider';
@@ -19,6 +24,8 @@ import {
shouldResyncForBidDelta, shouldResyncForBidDelta,
shouldApplyPolledAuctionState, shouldApplyPolledAuctionState,
mergeAuctionState, mergeAuctionState,
resolveCurrentBidPointAmount,
createAuctionHeartbeatMonitor,
type BidDeltaPayload, type BidDeltaPayload,
} from './auction-state'; } from './auction-state';
import { resolveAuctionActionRejection } from './auction-action-retry'; import { resolveAuctionActionRejection } from './auction-action-retry';
@@ -105,6 +112,8 @@ interface BidAckPayload {
} }
interface TimeSyncAckPayload { interface TimeSyncAckPayload {
auctionState?: AuctionStateIdentity | null;
auctionStateUnavailable?: boolean;
clientSentAtTimestampMS?: number; clientSentAtTimestampMS?: number;
currentServerTimestampMS?: number; currentServerTimestampMS?: number;
ok?: boolean; ok?: boolean;
@@ -169,6 +178,8 @@ export function useAuctionSocket(matchId: string | undefined) {
const timeSyncSequenceRef = useRef(0); const timeSyncSequenceRef = useRef(0);
const hasSyncedServerTimeRef = useRef(false); const hasSyncedServerTimeRef = useRef(false);
const latestAuctionRef = useRef<ApiAuction | null>(null); const latestAuctionRef = useRef<ApiAuction | null>(null);
const synchronizedSocketRef = useRef<Socket | null>(null);
const heartbeatMonitorRef = useRef(createAuctionHeartbeatMonitor());
const cancelledLifecycleIdsRef = useRef(new Set<string>()); const cancelledLifecycleIdsRef = useRef(new Set<string>());
const latestConfirmedBidPointAmountRef = useRef(0); const latestConfirmedBidPointAmountRef = useRef(0);
const [auction, setAuction] = useState<ApiAuction | null>(null); const [auction, setAuction] = useState<ApiAuction | null>(null);
@@ -207,6 +218,11 @@ export function useAuctionSocket(matchId: string | undefined) {
key: string; key: string;
status: ConnectionStatus; status: ConnectionStatus;
}>({ key: '', status: 'idle' }); }>({ key: '', status: 'idle' });
const [synchronizationState, setSynchronizationState] = useState({
key: '',
ready: false,
});
const [historyUpdateState, setHistoryUpdateState] = useState({ key: '', count: 0 });
const [errorState, setErrorState] = useState<{ const [errorState, setErrorState] = useState<{
key: string; key: string;
message: string | null; message: string | null;
@@ -334,15 +350,32 @@ export function useAuctionSocket(matchId: string | undefined) {
timeSyncTimeoutsRef.current = {}; 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; if (!socket.connected) return;
const recordFailure = () => {
if (socketRef.current === socket && heartbeatMonitorRef.current.recordFailure()) {
markSynchronized(socket, key, false);
}
};
const sequence = timeSyncSequenceRef.current + 1; const sequence = timeSyncSequenceRef.current + 1;
timeSyncSequenceRef.current = sequence; timeSyncSequenceRef.current = sequence;
const clientSentAtTimestampMS = Date.now(); const clientSentAtTimestampMS = Date.now();
timeSyncTimeoutsRef.current[sequence] = setTimeout(() => { timeSyncTimeoutsRef.current[sequence] = setTimeout(() => {
delete timeSyncTimeoutsRef.current[sequence]; delete timeSyncTimeoutsRef.current[sequence];
recordFailure();
}, TIME_SYNC_TIMEOUT_MS); }, TIME_SYNC_TIMEOUT_MS);
socket.emit( socket.emit(
@@ -354,15 +387,35 @@ export function useAuctionSocket(matchId: string | undefined) {
if (!timeoutId) return; if (!timeoutId) return;
clearTimeout(timeoutId); clearTimeout(timeoutId);
delete timeSyncTimeoutsRef.current[sequence]; delete timeSyncTimeoutsRef.current[sequence];
if (socketRef.current !== socket) return;
if ( if (
!ack?.ok || !ack?.ok ||
ack.sequence !== sequence || ack.sequence !== sequence ||
typeof ack.currentServerTimestampMS !== 'number' typeof ack.currentServerTimestampMS !== 'number'
) { ) {
recordFailure();
return; 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( const totalRoundTripDurationMS = Math.max(
0, 0,
clientReceivedAtTimestampMS - clientSentAtTimestampMS, clientReceivedAtTimestampMS - clientSentAtTimestampMS,
@@ -391,7 +444,7 @@ export function useAuctionSocket(matchId: string | undefined) {
); );
}, },
); );
} }, [markSynchronized]);
function captureBidLatencyDiagnostics(ack?: BidAckPayload) { function captureBidLatencyDiagnostics(ack?: BidAckPayload) {
if (!ack?.bidDiagnostics && !ack?.bidServerTiming) return; if (!ack?.bidDiagnostics && !ack?.bidServerTiming) return;
@@ -472,6 +525,8 @@ export function useAuctionSocket(matchId: string | undefined) {
const activeConnectionKey = connectionKey; const activeConnectionKey = connectionKey;
const cancelledLifecycleIds = cancelledLifecycleIdsRef.current; const cancelledLifecycleIds = cancelledLifecycleIdsRef.current;
let disposed = false; let disposed = false;
let removeResumeListeners = () => {};
let hasReceivedSnapshot = false;
void (async () => { void (async () => {
const accessToken = await acquireAccessToken().catch((error) => { const accessToken = await acquireAccessToken().catch((error) => {
@@ -490,7 +545,16 @@ export function useAuctionSocket(matchId: string | undefined) {
}); });
socketRef.current = socket; socketRef.current = socket;
const notifyHistoryUpdated = () => {
setHistoryUpdateState((current) => ({
key: activeConnectionKey,
count: current.key === activeConnectionKey ? current.count + 1 : 1,
}));
};
const receiveAuctionState = (nextAuction: ApiAuction, source: string) => { const receiveAuctionState = (nextAuction: ApiAuction, source: string) => {
if (
disposed || socketRef.current !== socket || nextAuction.matchId !== matchId
) return;
const previousRevision = latestAuctionRef.current?.revision ?? -1; const previousRevision = latestAuctionRef.current?.revision ?? -1;
const didApplyState = commitAuctionState(nextAuction, source); const didApplyState = commitAuctionState(nextAuction, source);
if (didApplyState && (nextAuction.revision ?? 0) > previousRevision) { if (didApplyState && (nextAuction.revision ?? 0) > previousRevision) {
@@ -501,6 +565,13 @@ export function useAuctionSocket(matchId: string | undefined) {
setChatMessages(mergeChatMessages([], nextAuction.chatMessages)); setChatMessages(mergeChatMessages([], nextAuction.chatMessages));
} }
if (didApplyState) { if (didApplyState) {
if (hasReceivedSnapshot && synchronizedSocketRef.current !== socket) {
notifyHistoryUpdated();
}
hasReceivedSnapshot = true;
synchronizedSocketRef.current = socket;
heartbeatMonitorRef.current.reset();
markSynchronized(socket, activeConnectionKey, true);
setError(null); setError(null);
} }
}; };
@@ -515,27 +586,44 @@ export function useAuctionSocket(matchId: string | undefined) {
(state) => { (state) => {
receiveAuctionState(state, 'socket-resync'); receiveAuctionState(state, 'socket-resync');
}, },
undefined,
() => markSynchronized(socket, activeConnectionKey, false),
); );
resyncRequesterRef.current = resyncRequester; resyncRequesterRef.current = resyncRequester;
socket.on('connect', () => { socket.on('connect', () => {
synchronizedSocketRef.current = null;
heartbeatMonitorRef.current.reset();
markSynchronized(socket, activeConnectionKey, false);
setConnectionState({ setConnectionState({
key: activeConnectionKey, key: activeConnectionKey,
status: 'connected', status: 'connected',
}); });
setError(null); setError(null);
socket.emit('join', { matchId }); void socket.timeout(3000).emitWithAck('join', { matchId })
requestServerTimeSync(socket); .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) { if (timeSyncIntervalRef.current) {
clearInterval(timeSyncIntervalRef.current); clearInterval(timeSyncIntervalRef.current);
} }
timeSyncIntervalRef.current = setInterval( timeSyncIntervalRef.current = setInterval(
() => requestServerTimeSync(socket), () => requestServerTimeSync(socket, activeConnectionKey),
TIME_SYNC_INTERVAL_MS, TIME_SYNC_INTERVAL_MS,
); );
}); });
socket.on('disconnect', () => { socket.on('disconnect', () => {
synchronizedSocketRef.current = null;
heartbeatMonitorRef.current.reset();
markSynchronized(socket, activeConnectionKey, false);
setReactionState({ key: activeConnectionKey, items: [] }); setReactionState({ key: activeConnectionKey, items: [] });
resyncRequester.cancel(); resyncRequester.cancel();
clearTimeSyncTimers(); 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', () => { socket.on('state-pending', () => {
void resyncRequester.request(); void resyncRequester.request();
}); });
@@ -673,6 +789,7 @@ export function useAuctionSocket(matchId: string | undefined) {
return () => { return () => {
disposed = true; disposed = true;
removeResumeListeners();
resyncRequesterRef.current?.cancel(); resyncRequesterRef.current?.cancel();
resyncRequesterRef.current = null; resyncRequesterRef.current = null;
const socket = socketRef.current; const socket = socketRef.current;
@@ -689,6 +806,7 @@ export function useAuctionSocket(matchId: string | undefined) {
pendingBidTimeoutsRef.current = {}; pendingBidTimeoutsRef.current = {};
pendingActionTimeoutsRef.current = {}; pendingActionTimeoutsRef.current = {};
latestAuctionRef.current = null; latestAuctionRef.current = null;
synchronizedSocketRef.current = null;
cancelledLifecycleIds.clear(); cancelledLifecycleIds.clear();
latestConfirmedBidPointAmountRef.current = 0; latestConfirmedBidPointAmountRef.current = 0;
hasSyncedServerTimeRef.current = false; hasSyncedServerTimeRef.current = false;
@@ -707,6 +825,8 @@ export function useAuctionSocket(matchId: string | undefined) {
connectionKey, connectionKey,
matchId, matchId,
receiveReaction, receiveReaction,
markSynchronized,
requestServerTimeSync,
setError, setError,
]); ]);
@@ -906,6 +1026,11 @@ export function useAuctionSocket(matchId: string | undefined) {
pendingBidRequests, pendingBidRequests,
resetAt, resetAt,
connectionStatus: visibleConnectionStatus, connectionStatus: visibleConnectionStatus,
isSynchronized:
synchronizationState.key === connectionKey &&
synchronizationState.ready && visibleConnectionStatus === 'connected',
historyUpdateCount:
historyUpdateState.key === connectionKey ? historyUpdateState.count : 0,
error: visibleError, error: visibleError,
bidLatencyDiagnostics, bidLatencyDiagnostics,
serverRoundTripMs: matchId ? serverRoundTripMs : null, serverRoundTripMs: matchId ? serverRoundTripMs : null,
@@ -1027,15 +1152,6 @@ function createClientRequestId(): string {
return `${Date.now()}-${Math.random().toString(16).slice(2)}`; 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] 아래 텔레메트리 헬퍼들과 호출부는 조사 종료 후 제거 대상. // [AUCTION-DEBUG] 아래 텔레메트리 헬퍼들과 호출부는 조사 종료 후 제거 대상.
type AuctionTelemetryAttributes = Record< type AuctionTelemetryAttributes = Record<
string, string,
+34 -9
View File
@@ -37,6 +37,10 @@ import {
} from "../config"; } from "../config";
import { ApiError } from "../lib/api"; import { ApiError } from "../lib/api";
import { mergeAuctionState } from "../api/auction-state"; import { mergeAuctionState } from "../api/auction-state";
import {
AUCTION_SAFETY_POLL_INTERVAL_MS,
startAuctionRecoveryPolling,
} from "../api/auction-polling";
import { import {
profileIconUrl, profileIconUrl,
} from "../lib/ddragon"; } from "../lib/ddragon";
@@ -1196,16 +1200,23 @@ export default function AuctionPage() {
currentUser?.role === "owner" || currentUser?.role === "owner" ||
currentUser?.role === "admin"; currentUser?.role === "admin";
const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID); const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID);
const socket = useAuctionSocket(id);
const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_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, { const historyQuery = useAuctionHistory(id, DEFAULT_COMMUNITY_ID, {
enabled: canManageAuction, enabled: canManageAuction,
refetchInterval: 3000, refetchInterval: AUCTION_SAFETY_POLL_INTERVAL_MS,
}); });
const undoMutation = useUndoAuction(DEFAULT_COMMUNITY_ID); const undoMutation = useUndoAuction(DEFAULT_COMMUNITY_ID);
const resetAuctionMutation = useResetAuction(DEFAULT_COMMUNITY_ID); const resetAuctionMutation = useResetAuction(DEFAULT_COMMUNITY_ID);
const socket = useAuctionSocket(id);
const savedCaptainTeamIndex = useAuctionCaptainTeamIndex(id); const savedCaptainTeamIndex = useAuctionCaptainTeamIndex(id);
const [assignedPositionDraft, setAssignedPositionDraft] = useState<{ const [assignedPositionDraft, setAssignedPositionDraft] = useState<{
playerId: string | null; playerId: string | null;
@@ -1256,6 +1267,13 @@ export default function AuctionPage() {
useEffect(() => { useEffect(() => {
syncPolledAuctionState(auctionQuery.data); syncPolledAuctionState(auctionQuery.data);
}, [auctionQuery.data, syncPolledAuctionState]); }, [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 liveAuction = pickLatestAuction(socket.auction, auctionQuery.data);
const auctionState = useMemo( const auctionState = useMemo(
() => () =>
@@ -1384,18 +1402,25 @@ export default function AuctionPage() {
sequence, sequence,
}, },
{ {
onSuccess: async () => { onSuccess: async (updatedAuction) => {
await Promise.all([ const refreshes = [
queryClient.invalidateQueries({ queryClient.invalidateQueries({
queryKey: ["auction", DEFAULT_COMMUNITY_ID, id], queryKey: ["auction", DEFAULT_COMMUNITY_ID, id],
}), }),
queryClient.invalidateQueries({
queryKey: ["auction-history", DEFAULT_COMMUNITY_ID, id],
}),
queryClient.invalidateQueries({ queryClient.invalidateQueries({
queryKey: ["match", DEFAULT_COMMUNITY_ID, id], 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);
}, },
}, },
); );
+75
View File
@@ -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);
});
+18
View File
@@ -72,6 +72,24 @@ test('bounds retries and honors retry delay without rejoining the room', async (
assert.deepEqual(waits, [1500, 1500]); 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 () => { test('drops an old connection reply after cancellation and permits a new request', async () => {
let finish!: (reply: AuctionResyncReply) => void; let finish!: (reply: AuctionResyncReply) => void;
let calls = 0; let calls = 0;
+183
View File
@@ -6,9 +6,192 @@ import {
shouldApplyIncomingAuctionState, shouldApplyIncomingAuctionState,
shouldApplyPolledAuctionState, shouldApplyPolledAuctionState,
shouldResyncForBidDelta, shouldResyncForBidDelta,
resolveCurrentBidPointAmount,
shouldResyncForAuctionIdentity,
createAuctionHeartbeatMonitor,
} from "../src/api/auction-state.ts"; } from "../src/api/auction-state.ts";
import type { ApiAuction } from "../src/api/types.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 = { const current = {
auctionLifecycleId: "life", auctionLifecycleId: "life",
revision: 10, revision: 10,
+13
View File
@@ -30,3 +30,16 @@ export interface AuctionReactionReply {
reaction?: AuctionReactionEvent; reaction?: AuctionReactionEvent;
code?: "NOT_JOINED" | "INVALID_REACTION" | "REACTION_RATE_LIMITED"; code?: "NOT_JOINED" | "INVALID_REACTION" | "REACTION_RATE_LIMITED";
} }
export interface AuctionStateIdentity {
auctionLifecycleId?: string;
revision?: number;
matchSideEffectRevision?: number;
matchSideEffectTransitionId?: string;
}
export interface AuctionHistoryUpdatedEvent {
matchId: string;
auctionLifecycleId: string;
auctionStateTransitionId: string;
}