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
@@ -233,6 +233,56 @@ describe('auction durability projection helpers', () => {
|
||||
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 () => {
|
||||
const session = {
|
||||
abortTransaction: jest.fn().mockResolvedValue(undefined),
|
||||
@@ -265,7 +315,7 @@ describe('auction durability projection helpers', () => {
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
{ broadcastState } as never,
|
||||
{ broadcastState, broadcastHistoryUpdated: jest.fn() } as never,
|
||||
{ readAuctionStateView } as never,
|
||||
);
|
||||
|
||||
@@ -315,7 +365,7 @@ describe('auction durability projection helpers', () => {
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
{ broadcastState } as never,
|
||||
{ broadcastState, broadcastHistoryUpdated: jest.fn() } as never,
|
||||
{ readAuctionStateView } as never,
|
||||
);
|
||||
|
||||
@@ -407,60 +457,71 @@ describe('auction durability projection helpers', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('skips destructive history mutation for stale payloads', async () => {
|
||||
const session = {
|
||||
abortTransaction: jest.fn().mockResolvedValue(undefined),
|
||||
commitTransaction: jest.fn().mockResolvedValue(undefined),
|
||||
endSession: jest.fn().mockResolvedValue(undefined),
|
||||
startTransaction: jest.fn(),
|
||||
};
|
||||
const historyDeleteMany = jest.fn();
|
||||
const historyUpdateOne = jest.fn();
|
||||
const auctionUpdateOne = jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue({ matchedCount: 0, modifiedCount: 0 }),
|
||||
});
|
||||
const projectionExec = jest.fn().mockResolvedValue({
|
||||
auctionLifecycleId: 'life-1',
|
||||
revision: 10,
|
||||
});
|
||||
const auctionFindById = jest.fn().mockReturnValue({
|
||||
select: jest.fn().mockReturnValue({
|
||||
session: jest.fn().mockReturnValue({
|
||||
lean: jest.fn().mockReturnValue({ exec: projectionExec }),
|
||||
it.each(['life-1', 'new-life'])(
|
||||
'skips stale history changes and notifications for current lifecycle %s',
|
||||
async (auctionLifecycleId) => {
|
||||
const broadcastHistoryUpdated = jest.fn();
|
||||
const session = {
|
||||
abortTransaction: jest.fn().mockResolvedValue(undefined),
|
||||
commitTransaction: jest.fn().mockResolvedValue(undefined),
|
||||
endSession: jest.fn().mockResolvedValue(undefined),
|
||||
startTransaction: jest.fn(),
|
||||
};
|
||||
const historyDeleteMany = jest.fn();
|
||||
const historyUpdateOne = jest.fn();
|
||||
const auctionUpdateOne = jest.fn().mockReturnValue({
|
||||
exec: jest
|
||||
.fn()
|
||||
.mockResolvedValue({ matchedCount: 0, modifiedCount: 0 }),
|
||||
});
|
||||
const projectionExec = jest.fn().mockResolvedValue({
|
||||
auctionLifecycleId,
|
||||
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(
|
||||
{
|
||||
createSession: jest.fn().mockResolvedValue(session),
|
||||
getModel: jest.fn((name: string) => {
|
||||
if (name === 'auctionHistory') {
|
||||
return {
|
||||
deleteMany: historyDeleteMany,
|
||||
updateOne: historyUpdateOne,
|
||||
};
|
||||
}
|
||||
if (name === 'auction') {
|
||||
return { findById: auctionFindById, updateOne: auctionUpdateOne };
|
||||
}
|
||||
return { updateOne: jest.fn() };
|
||||
}),
|
||||
} as never,
|
||||
{ raw: jest.fn() } as never,
|
||||
);
|
||||
});
|
||||
const scheduler = new AuctionDurabilityScheduler(
|
||||
{
|
||||
createSession: jest.fn().mockResolvedValue(session),
|
||||
getModel: jest.fn((name: string) => {
|
||||
if (name === 'auctionHistory') {
|
||||
return {
|
||||
deleteMany: historyDeleteMany,
|
||||
updateOne: historyUpdateOne,
|
||||
};
|
||||
}
|
||||
if (name === 'auction') {
|
||||
return { findById: auctionFindById, updateOne: auctionUpdateOne };
|
||||
}
|
||||
return { updateOne: jest.fn() };
|
||||
}),
|
||||
} as never,
|
||||
{ raw: jest.fn() } as never,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
{ broadcastHistoryUpdated } as never,
|
||||
);
|
||||
|
||||
await scheduler.applyDurabilityPayload({
|
||||
...payload,
|
||||
historyMutation: {
|
||||
targetHistorySequence: 2,
|
||||
type: 'deleteAfterSequenceAndAppendUndo',
|
||||
},
|
||||
});
|
||||
await scheduler.applyDurabilityPayload({
|
||||
...payload,
|
||||
historyMutation: {
|
||||
targetHistorySequence: 2,
|
||||
type: 'deleteAfterSequenceAndAppendUndo',
|
||||
},
|
||||
});
|
||||
|
||||
expect(historyDeleteMany).not.toHaveBeenCalled();
|
||||
expect(historyUpdateOne).not.toHaveBeenCalled();
|
||||
expect(auctionUpdateOne).not.toHaveBeenCalled();
|
||||
});
|
||||
expect(historyDeleteMany).not.toHaveBeenCalled();
|
||||
expect(historyUpdateOne).not.toHaveBeenCalled();
|
||||
expect(auctionUpdateOne).not.toHaveBeenCalled();
|
||||
expect(broadcastHistoryUpdated).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it('recovers stale append payloads as history-only records', async () => {
|
||||
const session = {
|
||||
@@ -597,6 +658,7 @@ describe('auction durability projection helpers', () => {
|
||||
});
|
||||
|
||||
it('clears stale append payloads after history-only recovery', async () => {
|
||||
const broadcastHistoryUpdated = jest.fn();
|
||||
const sendCommand = jest
|
||||
.fn()
|
||||
.mockResolvedValueOnce(['payload-1'])
|
||||
@@ -653,6 +715,10 @@ describe('auction durability projection helpers', () => {
|
||||
getCurrentRedisTimestampMS: jest.fn().mockResolvedValue(1000),
|
||||
raw: jest.fn().mockReturnValue({ sendCommand }),
|
||||
} as never,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
{ broadcastHistoryUpdated } as never,
|
||||
);
|
||||
|
||||
await expect(scheduler.processDueDurabilityPayloads(10)).resolves.toEqual({
|
||||
@@ -662,6 +728,11 @@ describe('auction durability projection helpers', () => {
|
||||
});
|
||||
|
||||
expect(historyUpdateOne).toHaveBeenCalledTimes(1);
|
||||
expect(broadcastHistoryUpdated).toHaveBeenCalledWith({
|
||||
matchId: 'match-1',
|
||||
auctionLifecycleId: 'life-1',
|
||||
auctionStateTransitionId: 'transition-1',
|
||||
});
|
||||
expect(auctionUpdateOne).not.toHaveBeenCalled();
|
||||
expect(sideEffectUpdateOne).not.toHaveBeenCalled();
|
||||
expect(sendCommand).toHaveBeenNthCalledWith(3, [
|
||||
@@ -1006,7 +1077,7 @@ describe('auction durability projection helpers', () => {
|
||||
{ reserveForMatch } as never,
|
||||
{ scheduleInitialPoll } as never,
|
||||
{ mirrorMatchSideEffectStatus } as never,
|
||||
{ broadcastMatchSideEffect } as never,
|
||||
{ broadcastMatchSideEffect, broadcastHistoryUpdated: jest.fn() } as never,
|
||||
);
|
||||
|
||||
await scheduler.applyDurabilityPayload(completePayload);
|
||||
@@ -1203,7 +1274,7 @@ describe('auction durability projection helpers', () => {
|
||||
{ reserveForMatch } as never,
|
||||
{ scheduleInitialPoll } as never,
|
||||
{ mirrorMatchSideEffectStatus } as never,
|
||||
{ broadcastMatchSideEffect } as never,
|
||||
{ broadcastMatchSideEffect, broadcastHistoryUpdated: jest.fn() } as never,
|
||||
);
|
||||
|
||||
await expect(
|
||||
@@ -1332,7 +1403,7 @@ describe('auction durability projection helpers', () => {
|
||||
{ releaseFromMatch } as never,
|
||||
{ cancelPolling } as never,
|
||||
{ mirrorMatchSideEffectStatus } as never,
|
||||
{ broadcastMatchSideEffect } as never,
|
||||
{ broadcastMatchSideEffect, broadcastHistoryUpdated: jest.fn() } as never,
|
||||
);
|
||||
|
||||
await scheduler.applyDurabilityPayload(resetPayload);
|
||||
|
||||
@@ -356,6 +356,15 @@ export class AuctionDurabilityScheduler
|
||||
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);
|
||||
|
||||
if (sideEffectMutation && shouldApplySideEffects) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type { Namespace } from 'socket.io';
|
||||
import type { AuctionHistoryUpdatedEvent } from '@lolympus/contracts';
|
||||
import type { AuctionStateResponse } from './auction.service';
|
||||
import type { MatchSideEffectDelta } from './auction-side-effect.service';
|
||||
import { serializeRealtimeAuction } from './auction-realtime-serializer';
|
||||
@@ -25,6 +26,10 @@ export class AuctionEventBusService {
|
||||
.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 {
|
||||
this.auctionNamespace
|
||||
?.to(matchId)
|
||||
|
||||
@@ -37,7 +37,11 @@ describe('AuctionGateway', () => {
|
||||
{} as never,
|
||||
);
|
||||
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).toHaveBeenCalledWith('state-pending', {
|
||||
retryAfterMS: 500,
|
||||
@@ -92,9 +96,12 @@ describe('AuctionGateway', () => {
|
||||
function createGateway(params?: {
|
||||
getCurrentRedisTimestampMS?: jest.Mock;
|
||||
placeBidDelta?: jest.Mock;
|
||||
getRealtimeIdentity?: jest.Mock;
|
||||
}) {
|
||||
const auctionService = {
|
||||
placeBidDelta: params?.placeBidDelta ?? jest.fn(),
|
||||
getRealtimeIdentity:
|
||||
params?.getRealtimeIdentity ?? jest.fn().mockResolvedValue(null),
|
||||
};
|
||||
const auctionRedisService = {
|
||||
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 () => {
|
||||
jest.spyOn(Date, 'now').mockReturnValue(1780000000000);
|
||||
const matchId = new mongoose.Types.ObjectId().toString();
|
||||
|
||||
@@ -180,9 +180,11 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
public async handleJoin(
|
||||
@ConnectedSocket() socket: AuctionSocket,
|
||||
@MessageBody() payload: JoinAuctionPayload,
|
||||
@Ack() ack?: (response: Record<string, unknown>) => void,
|
||||
) {
|
||||
if (!payload?.matchId || !mongoose.isValidObjectId(payload.matchId)) {
|
||||
this.emitError(socket, 'Invalid matchId.');
|
||||
ack?.({ ok: false, code: 'INVALID_MATCH_ID' });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -201,8 +203,10 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
);
|
||||
this.emitChatHistory(socket, auction);
|
||||
socket.emit('state', serializeRealtimeAuction(auctionState));
|
||||
ack?.({ ok: true });
|
||||
} catch (error) {
|
||||
const rejection = this.resolveErrorPayload(error);
|
||||
ack?.({ ...rejection, ok: false });
|
||||
if (rejection.code === 'AUCTION_STATE_RECOVERING') {
|
||||
socket.emit('state-pending', { retryAfterMS: 500 });
|
||||
} else {
|
||||
@@ -347,14 +351,27 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
public async handleTimeSync(
|
||||
@MessageBody() payload: TimeSyncPayload,
|
||||
@Ack() ack?: (response: Record<string, unknown>) => void,
|
||||
@ConnectedSocket() socket?: AuctionSocket,
|
||||
) {
|
||||
const receivedAtMonotonicMS = performance.now();
|
||||
try {
|
||||
const currentServerTimestampMS =
|
||||
await this.auctionRedisService.getCurrentRedisTimestampMS();
|
||||
const [currentServerTimestampMS, auctionState] = await Promise.all([
|
||||
this.auctionRedisService.getCurrentRedisTimestampMS(),
|
||||
socket?.data.matchId
|
||||
? this.auctionService
|
||||
.getRealtimeIdentity(socket.data.matchId)
|
||||
.catch(() => undefined)
|
||||
: undefined,
|
||||
]);
|
||||
ack?.({
|
||||
clientSentAtTimestampMS: payload?.clientSentAtTimestampMS,
|
||||
currentServerTimestampMS,
|
||||
...(socket?.data.matchId
|
||||
? {
|
||||
auctionState,
|
||||
auctionStateUnavailable: auctionState === undefined,
|
||||
}
|
||||
: {}),
|
||||
ok: true,
|
||||
sequence: payload?.sequence,
|
||||
serverProcessingDurationMS:
|
||||
|
||||
@@ -215,8 +215,7 @@ describe('AuctionService', () => {
|
||||
expect(auctionRedisCommandService.placeBid).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('lists auction history with a summary projection and short local cache', async () => {
|
||||
const nowSpy = jest.spyOn(Date, 'now').mockReturnValue(1000);
|
||||
it('reads committed history on every node without retaining a local cache', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const match = {
|
||||
@@ -242,7 +241,7 @@ describe('AuctionService', () => {
|
||||
const historySort = jest.fn().mockReturnValue({ limit: historyLimit });
|
||||
const historySelect = jest.fn().mockReturnValue({ sort: historySort });
|
||||
const historyFind = jest.fn().mockReturnValue({ select: historySelect });
|
||||
const { service } = createService({
|
||||
const models = {
|
||||
auctionHistory: {
|
||||
find: historyFind,
|
||||
},
|
||||
@@ -251,7 +250,9 @@ describe('AuctionService', () => {
|
||||
select: jest.fn().mockResolvedValue(match),
|
||||
}),
|
||||
},
|
||||
});
|
||||
};
|
||||
const { service } = createService(models);
|
||||
const otherNode = createService(models).service;
|
||||
|
||||
await expect(
|
||||
service.listHistory({ matchId, communityId }),
|
||||
@@ -271,7 +272,7 @@ describe('AuctionService', () => {
|
||||
]);
|
||||
await service.listHistory({ matchId, communityId });
|
||||
|
||||
expect(historyFind).toHaveBeenCalledTimes(1);
|
||||
expect(historyFind).toHaveBeenCalledTimes(2);
|
||||
expect(historySelect).toHaveBeenCalledWith({
|
||||
_id: 0,
|
||||
action: 1,
|
||||
@@ -281,9 +282,17 @@ describe('AuctionService', () => {
|
||||
expect(historySort).toHaveBeenCalledWith({ sequence: -1 });
|
||||
expect(historyLimit).toHaveBeenCalledWith(100);
|
||||
|
||||
nowSpy.mockReturnValue(3101);
|
||||
await service.listHistory({ matchId, communityId });
|
||||
expect(historyFind).toHaveBeenCalledTimes(2);
|
||||
historyExec.mockResolvedValue([
|
||||
{ action: 'undo', sequence: 5, takenAt: new Date() },
|
||||
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 () => {
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
Optional,
|
||||
} from '@nestjs/common';
|
||||
import { randomUUID } from 'crypto';
|
||||
import type { AuctionStateIdentity } from '@lolympus/contracts';
|
||||
import {
|
||||
AuctionLifecycleLock,
|
||||
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_LEASE_DURATION_MS = 15 * 1000;
|
||||
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 {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
@@ -163,11 +162,6 @@ interface AuctionHistorySummaryRecord {
|
||||
takenAt: Date;
|
||||
}
|
||||
|
||||
interface AuctionHistoryListCacheEntry {
|
||||
entries: AuctionHistoryView[];
|
||||
expiresAtTimestampMS: number;
|
||||
}
|
||||
|
||||
export type AuctionStateResponse = AuctionDocument | Record<string, unknown>;
|
||||
|
||||
export interface AuctionBidDeltaResponse {
|
||||
@@ -211,10 +205,6 @@ function isMongoDuplicateKeyError(error: unknown): boolean {
|
||||
@Injectable()
|
||||
export class AuctionService {
|
||||
private readonly logger = new Logger(AuctionService.name);
|
||||
private readonly auctionHistoryListCache = new Map<
|
||||
string,
|
||||
AuctionHistoryListCacheEntry
|
||||
>();
|
||||
|
||||
constructor(
|
||||
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(
|
||||
matchId: mongoose.Types.ObjectId,
|
||||
): Promise<AuctionStateResponse> {
|
||||
@@ -737,10 +733,6 @@ export class AuctionService {
|
||||
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 })
|
||||
.select({ _id: 0, action: 1, sequence: 1, takenAt: 1 })
|
||||
.sort({ sequence: -1 })
|
||||
@@ -754,49 +746,9 @@ export class AuctionService {
|
||||
actionLabel: this.formatHistoryActionLabel(entry.action),
|
||||
takenAt: entry.takenAt,
|
||||
}));
|
||||
this.setCachedAuctionHistoryList(cacheKey, 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(
|
||||
matchId: mongoose.Types.ObjectId,
|
||||
actionRequest: AuctionStructureActionRequestParams = {},
|
||||
|
||||
@@ -30,17 +30,23 @@ function makeService(
|
||||
|
||||
describe('AuctionRedisStateReaderService', () => {
|
||||
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({
|
||||
auctionLifecycleId: 'life-1',
|
||||
revision: 7,
|
||||
matchSideEffectRevision: 3,
|
||||
matchSideEffectTransitionId: 'transition-1',
|
||||
});
|
||||
expect(sendCommand).toHaveBeenCalledWith([
|
||||
'HMGET',
|
||||
'auction:match-1:liveAuctionState',
|
||||
'auctionLifecycleId',
|
||||
'revision',
|
||||
'matchSideEffectRevision',
|
||||
'matchSideEffectTransitionId',
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -118,7 +124,9 @@ describe('AuctionRedisStateReaderService', () => {
|
||||
|
||||
expect(view).toMatchObject({
|
||||
auctionBidHistory: [{ bidPointAmount: 100, bidderTeamIndex: 2 }],
|
||||
auctionEngineVersion: 'redis-v1',
|
||||
auctionLifecycleId: 'life-1',
|
||||
matchId: 'match-1',
|
||||
auctionTeams: [{ teamIndex: 1 }],
|
||||
canPlaceBidInCurrentBidRound: false,
|
||||
currentHighestBidderTeamIndex: 2,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type { AuctionStateIdentity } from '@lolympus/contracts';
|
||||
import { buildAuctionRedisKeys } from './auction-redis.keys';
|
||||
import { AuctionRedisService } from './auction-redis.service';
|
||||
import { assembleAuctionViewFromRedisState } from './auction-redis.state';
|
||||
@@ -17,10 +18,7 @@ const NUMERIC_LIVE_STATE_FIELDS = new Set([
|
||||
'revision',
|
||||
]);
|
||||
|
||||
export interface AuctionRedisLiveStateIdentity {
|
||||
auctionLifecycleId?: string;
|
||||
revision?: number;
|
||||
}
|
||||
export type AuctionRedisLiveStateIdentity = AuctionStateIdentity;
|
||||
|
||||
export interface AuctionRedisBidContext {
|
||||
auctionLifecycleId: string;
|
||||
@@ -49,6 +47,8 @@ export class AuctionRedisStateReaderService {
|
||||
keys.liveStateKey,
|
||||
'auctionLifecycleId',
|
||||
'revision',
|
||||
'matchSideEffectRevision',
|
||||
'matchSideEffectTransitionId',
|
||||
]);
|
||||
if (!Array.isArray(reply)) return null;
|
||||
const auctionLifecycleId =
|
||||
@@ -61,6 +61,12 @@ export class AuctionRedisStateReaderService {
|
||||
return {
|
||||
auctionLifecycleId,
|
||||
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),
|
||||
});
|
||||
view.matchId = matchId;
|
||||
view.auctionEngineVersion = 'redis-v1';
|
||||
if (options.includeInternalLiveStateFields) {
|
||||
view.redisInternalPhase = liveState.phase;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user