Improve auction realtime bid responsiveness
This commit is contained in:
1 parent
c6f5a7077f
commit
b367328df0
16 files changed
+1364
-203
No files matched your search
@@ -2,6 +2,7 @@ import { Injectable } from '@nestjs/common';
|
||||
import type { Namespace } from 'socket.io';
|
||||
import type { AuctionStateResponse } from './auction.service';
|
||||
import type { MatchSideEffectDelta } from './auction-side-effect.service';
|
||||
import { serializeRealtimeAuction } from './auction-realtime-serializer';
|
||||
|
||||
@Injectable()
|
||||
export class AuctionEventBusService {
|
||||
@@ -21,7 +22,7 @@ export class AuctionEventBusService {
|
||||
public broadcastState(matchId: string, state: AuctionStateResponse): void {
|
||||
this.auctionNamespace?.to(matchId).emit(
|
||||
'state',
|
||||
JSON.parse(JSON.stringify(state)),
|
||||
serializeRealtimeAuction(state),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import type { AuctionStateResponse } from './auction.service';
|
||||
|
||||
export function serializeRealtimeAuction(auction: AuctionStateResponse) {
|
||||
const serialized = JSON.parse(JSON.stringify(auction)) as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
const auctionPlayerOrder = getRecordArray(
|
||||
serialized.auctionPlayerOrder ?? serialized.order,
|
||||
);
|
||||
const currentAuctionPlayerOrderIndex = Number(
|
||||
serialized.currentAuctionPlayerOrderIndex ?? serialized.currentIndex ?? 0,
|
||||
);
|
||||
const currentBidRoundPlayerUserId =
|
||||
typeof serialized.currentBidRoundPlayerUserId === 'string'
|
||||
? serialized.currentBidRoundPlayerUserId
|
||||
: getStringField(
|
||||
auctionPlayerOrder[currentAuctionPlayerOrderIndex],
|
||||
'userId',
|
||||
);
|
||||
|
||||
if (Array.isArray(serialized.auctionPlayerOrder)) {
|
||||
serialized.auctionPlayerOrder = auctionPlayerOrder.map((player) =>
|
||||
serializeRealtimeAuctionPlayer(player, currentBidRoundPlayerUserId),
|
||||
);
|
||||
} else if (Array.isArray(serialized.order)) {
|
||||
serialized.order = auctionPlayerOrder.map((player) =>
|
||||
serializeRealtimeAuctionPlayer(player, currentBidRoundPlayerUserId),
|
||||
);
|
||||
}
|
||||
|
||||
const passedAuctionPlayerQueue = getRecordArray(
|
||||
serialized.passedAuctionPlayerQueue ?? serialized.passedQueue,
|
||||
);
|
||||
if (Array.isArray(serialized.passedAuctionPlayerQueue)) {
|
||||
serialized.passedAuctionPlayerQueue = passedAuctionPlayerQueue.map(
|
||||
(player) =>
|
||||
serializeRealtimeAuctionPlayer(player, currentBidRoundPlayerUserId),
|
||||
);
|
||||
} else if (Array.isArray(serialized.passedQueue)) {
|
||||
serialized.passedQueue = passedAuctionPlayerQueue.map((player) =>
|
||||
serializeRealtimeAuctionPlayer(player, currentBidRoundPlayerUserId),
|
||||
);
|
||||
}
|
||||
|
||||
if ('auctionPlayerOrder' in serialized) delete serialized.order;
|
||||
if ('auctionTeams' in serialized) delete serialized.teams;
|
||||
if ('passedAuctionPlayerQueue' in serialized) delete serialized.passedQueue;
|
||||
if ('auctionBidHistory' in serialized) delete serialized.bids;
|
||||
if ('maximumBidRoundDurationSeconds' in serialized) {
|
||||
delete serialized.maxTimerSeconds;
|
||||
}
|
||||
if ('bidRoundExtensionSeconds' in serialized) {
|
||||
delete serialized.bidExtensionSeconds;
|
||||
}
|
||||
if ('initialTeamBidPointAmount' in serialized) {
|
||||
delete serialized.initialPoints;
|
||||
}
|
||||
if ('topTierAuctionPriorityThreshold' in serialized) {
|
||||
delete serialized.topTierThreshold;
|
||||
}
|
||||
if ('manualTopTierAuctionPriorityUserIds' in serialized) {
|
||||
delete serialized.manualTopTierUserIds;
|
||||
}
|
||||
|
||||
return serialized;
|
||||
}
|
||||
|
||||
function serializeRealtimeAuctionPlayer(
|
||||
player: Record<string, unknown>,
|
||||
currentBidRoundPlayerUserId?: string,
|
||||
) {
|
||||
if (getStringField(player, 'userId') === currentBidRoundPlayerUserId) {
|
||||
return player;
|
||||
}
|
||||
|
||||
const {
|
||||
masteries: _masteries,
|
||||
puuid: _puuid,
|
||||
recentStatsSummary: _recentStatsSummary,
|
||||
tierHistory: _tierHistory,
|
||||
...lightweightPlayer
|
||||
} = player;
|
||||
|
||||
return lightweightPlayer;
|
||||
}
|
||||
|
||||
function getRecordArray(value: unknown): Array<Record<string, unknown>> {
|
||||
return Array.isArray(value)
|
||||
? value.filter(
|
||||
(item): item is Record<string, unknown> =>
|
||||
typeof item === 'object' && item !== null,
|
||||
)
|
||||
: [];
|
||||
}
|
||||
|
||||
function getStringField(
|
||||
value: Record<string, unknown> | undefined,
|
||||
fieldName: string,
|
||||
): string | undefined {
|
||||
const fieldValue = value?.[fieldName];
|
||||
return typeof fieldValue === 'string' ? fieldValue : undefined;
|
||||
}
|
||||
@@ -8,10 +8,16 @@ import { AuctionGateway } from './auction.gateway';
|
||||
|
||||
describe('AuctionGateway', () => {
|
||||
function createGateway(params?: {
|
||||
placeBid?: jest.Mock;
|
||||
getCurrentRedisTimestampMS?: jest.Mock;
|
||||
placeBidDelta?: jest.Mock;
|
||||
}) {
|
||||
const auctionService = {
|
||||
placeBid: params?.placeBid ?? jest.fn(),
|
||||
placeBidDelta: params?.placeBidDelta ?? jest.fn(),
|
||||
};
|
||||
const auctionRedisService = {
|
||||
getCurrentRedisTimestampMS:
|
||||
params?.getCurrentRedisTimestampMS ??
|
||||
jest.fn().mockResolvedValue(1780000000000),
|
||||
};
|
||||
const gateway = new AuctionGateway(
|
||||
auctionService as never,
|
||||
@@ -20,6 +26,7 @@ describe('AuctionGateway', () => {
|
||||
{ findOrCreateByOid: jest.fn() } as never,
|
||||
{ getModel: jest.fn() } as never,
|
||||
{ attachAuctionNamespace: jest.fn() } as never,
|
||||
auctionRedisService as never,
|
||||
);
|
||||
const emit = jest.fn();
|
||||
const to = jest.fn().mockReturnValue({ emit });
|
||||
@@ -29,6 +36,7 @@ describe('AuctionGateway', () => {
|
||||
auctionService,
|
||||
emit,
|
||||
gateway,
|
||||
auctionRedisService,
|
||||
to,
|
||||
};
|
||||
}
|
||||
@@ -41,8 +49,8 @@ describe('AuctionGateway', () => {
|
||||
bidPlacedAtTimestampMS: 1780000000000,
|
||||
bidPointAmount: 120,
|
||||
};
|
||||
const placeBid = jest.fn().mockResolvedValue({
|
||||
auctionBidHistory: [auctionBidHistoryEntry],
|
||||
const placeBidDelta = jest.fn().mockResolvedValue({
|
||||
auctionBidHistoryEntry,
|
||||
auctionLifecycleId: 'life-1',
|
||||
currentBidRoundDeadlineTimestampMS: 1780000030000,
|
||||
currentHighestBidderTeamIndex: 2,
|
||||
@@ -50,7 +58,7 @@ describe('AuctionGateway', () => {
|
||||
currentServerTimestampMS: 1780000000000,
|
||||
revision: 9,
|
||||
});
|
||||
const { emit, gateway, to } = createGateway({ placeBid });
|
||||
const { emit, gateway, to } = createGateway({ placeBidDelta });
|
||||
const ack = jest.fn();
|
||||
|
||||
await gateway.handleBid(
|
||||
@@ -65,7 +73,7 @@ describe('AuctionGateway', () => {
|
||||
ack,
|
||||
);
|
||||
|
||||
expect(placeBid).toHaveBeenCalledWith({
|
||||
expect(placeBidDelta).toHaveBeenCalledWith({
|
||||
amount: 120,
|
||||
bidRequestId: 'bid-1',
|
||||
clientObservedAuctionLifecycleId: 'life-1',
|
||||
@@ -84,31 +92,40 @@ describe('AuctionGateway', () => {
|
||||
currentServerTimestampMS: 1780000000000,
|
||||
revision: 9,
|
||||
});
|
||||
expect(ack).toHaveBeenCalledWith({
|
||||
bidRequestId: 'bid-1',
|
||||
ok: true,
|
||||
state: expect.objectContaining({
|
||||
auctionLifecycleId: 'life-1',
|
||||
revision: 9,
|
||||
expect(ack).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
bidDelta: {
|
||||
auctionBidHistoryEntry,
|
||||
auctionLifecycleId: 'life-1',
|
||||
bidRequestId: 'bid-1',
|
||||
currentBidRoundDeadlineTimestampMS: 1780000030000,
|
||||
currentHighestBidderTeamIndex: 2,
|
||||
currentHighestBidPointAmount: 120,
|
||||
currentServerTimestampMS: 1780000000000,
|
||||
revision: 9,
|
||||
},
|
||||
bidRequestId: 'bid-1',
|
||||
bidServerTiming: expect.objectContaining({
|
||||
gatewayTotalDurationMS: expect.any(Number),
|
||||
}),
|
||||
ok: true,
|
||||
}),
|
||||
});
|
||||
);
|
||||
});
|
||||
|
||||
it('generates one bid request id when the client omits it', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId().toString();
|
||||
const placeBid = jest.fn().mockResolvedValue({
|
||||
auctionBidHistory: [
|
||||
{
|
||||
bidderTeamIndex: 1,
|
||||
bidPointAmount: 50,
|
||||
},
|
||||
],
|
||||
const placeBidDelta = jest.fn().mockResolvedValue({
|
||||
auctionBidHistoryEntry: {
|
||||
bidderTeamIndex: 1,
|
||||
bidPointAmount: 50,
|
||||
},
|
||||
auctionLifecycleId: 'life-1',
|
||||
currentHighestBidderTeamIndex: 1,
|
||||
currentHighestBidPointAmount: 50,
|
||||
revision: 3,
|
||||
});
|
||||
const { emit, gateway } = createGateway({ placeBid });
|
||||
const { emit, gateway } = createGateway({ placeBidDelta });
|
||||
const ack = jest.fn();
|
||||
|
||||
await gateway.handleBid(
|
||||
@@ -120,7 +137,7 @@ describe('AuctionGateway', () => {
|
||||
ack,
|
||||
);
|
||||
|
||||
const generatedBidRequestId = placeBid.mock.calls[0][0].bidRequestId;
|
||||
const generatedBidRequestId = placeBidDelta.mock.calls[0][0].bidRequestId;
|
||||
expect(generatedBidRequestId).toEqual(expect.any(String));
|
||||
expect(generatedBidRequestId).not.toHaveLength(0);
|
||||
expect(emit).toHaveBeenCalledWith(
|
||||
@@ -139,9 +156,23 @@ describe('AuctionGateway', () => {
|
||||
|
||||
it('acknowledges bid failures with the request id used for the attempt', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId().toString();
|
||||
const placeBid = jest.fn().mockRejectedValue(new Error('Bid failed'));
|
||||
const placeBidDelta = jest.fn().mockRejectedValue({
|
||||
getResponse: () => ({
|
||||
bidDiagnostics: {
|
||||
currentBidRoundDeadlineTimestampMS: 1780000002500,
|
||||
currentServerTimestampMS: 1780000003000,
|
||||
},
|
||||
bidServerTiming: {
|
||||
redisBidCommandDurationMS: 2,
|
||||
redisBidContextReadDurationMS: 1,
|
||||
serviceTotalDurationMS: 4,
|
||||
},
|
||||
code: 'EXPIRED',
|
||||
message: 'Bid deadline has already expired.',
|
||||
}),
|
||||
});
|
||||
const socketEmit = jest.fn();
|
||||
const { gateway } = createGateway({ placeBid });
|
||||
const { gateway } = createGateway({ placeBidDelta });
|
||||
const ack = jest.fn();
|
||||
|
||||
await gateway.handleBid(
|
||||
@@ -155,32 +186,69 @@ describe('AuctionGateway', () => {
|
||||
);
|
||||
|
||||
expect(socketEmit).toHaveBeenCalledWith('error', {
|
||||
message: 'Bid failed',
|
||||
});
|
||||
expect(ack).toHaveBeenCalledWith({
|
||||
bidRequestId: 'bid-1',
|
||||
code: 'Bid failed',
|
||||
rejected: true,
|
||||
message: 'Bid deadline has already expired.',
|
||||
});
|
||||
expect(ack).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
bidDiagnostics: {
|
||||
currentBidRoundDeadlineTimestampMS: 1780000002500,
|
||||
currentServerTimestampMS: 1780000003000,
|
||||
},
|
||||
bidRequestId: 'bid-1',
|
||||
bidServerTiming: expect.objectContaining({
|
||||
gatewayTotalDurationMS: expect.any(Number),
|
||||
redisBidCommandDurationMS: 2,
|
||||
redisBidContextReadDurationMS: 1,
|
||||
serviceTotalDurationMS: 4,
|
||||
}),
|
||||
code: 'EXPIRED',
|
||||
message: 'Bid deadline has already expired.',
|
||||
rejected: true,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('acknowledges time sync with Redis server time', async () => {
|
||||
const getCurrentRedisTimestampMS = jest
|
||||
.fn()
|
||||
.mockResolvedValue(1780000001234);
|
||||
const { gateway } = createGateway({ getCurrentRedisTimestampMS });
|
||||
const ack = jest.fn();
|
||||
|
||||
await gateway.handleTimeSync(
|
||||
{
|
||||
clientSentAtTimestampMS: 1780000000000,
|
||||
sequence: 7,
|
||||
},
|
||||
ack,
|
||||
);
|
||||
|
||||
expect(getCurrentRedisTimestampMS).toHaveBeenCalledTimes(1);
|
||||
expect(ack).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
clientSentAtTimestampMS: 1780000000000,
|
||||
currentServerTimestampMS: 1780000001234,
|
||||
ok: true,
|
||||
sequence: 7,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('rate limits excessive bid requests from the same socket', async () => {
|
||||
jest.spyOn(Date, 'now').mockReturnValue(1780000000000);
|
||||
const matchId = new mongoose.Types.ObjectId().toString();
|
||||
const placeBid = jest.fn().mockResolvedValue({
|
||||
auctionBidHistory: [
|
||||
{
|
||||
bidderTeamIndex: 1,
|
||||
bidPointAmount: 50,
|
||||
},
|
||||
],
|
||||
const placeBidDelta = jest.fn().mockResolvedValue({
|
||||
auctionBidHistoryEntry: {
|
||||
bidderTeamIndex: 1,
|
||||
bidPointAmount: 50,
|
||||
},
|
||||
currentHighestBidderTeamIndex: 1,
|
||||
currentHighestBidPointAmount: 50,
|
||||
revision: 3,
|
||||
});
|
||||
const socketEmit = jest.fn();
|
||||
const socket = { data: { matchId }, emit: socketEmit };
|
||||
const { gateway } = createGateway({ placeBid });
|
||||
const { gateway } = createGateway({ placeBidDelta });
|
||||
const acknowledgements: Array<Record<string, unknown>> = [];
|
||||
|
||||
for (let index = 0; index < 9; index += 1) {
|
||||
@@ -195,7 +263,7 @@ describe('AuctionGateway', () => {
|
||||
);
|
||||
}
|
||||
|
||||
expect(placeBid).toHaveBeenCalledTimes(8);
|
||||
expect(placeBidDelta).toHaveBeenCalledTimes(8);
|
||||
expect(socketEmit).toHaveBeenCalledWith('error', {
|
||||
message: '입찰 요청이 너무 많습니다. 잠시 후 다시 시도해주세요.',
|
||||
});
|
||||
@@ -211,19 +279,17 @@ describe('AuctionGateway', () => {
|
||||
const nowSpy = jest.spyOn(Date, 'now');
|
||||
nowSpy.mockReturnValue(1780000000000);
|
||||
const matchId = new mongoose.Types.ObjectId().toString();
|
||||
const placeBid = jest.fn().mockResolvedValue({
|
||||
auctionBidHistory: [
|
||||
{
|
||||
bidderTeamIndex: 1,
|
||||
bidPointAmount: 50,
|
||||
},
|
||||
],
|
||||
const placeBidDelta = jest.fn().mockResolvedValue({
|
||||
auctionBidHistoryEntry: {
|
||||
bidderTeamIndex: 1,
|
||||
bidPointAmount: 50,
|
||||
},
|
||||
currentHighestBidderTeamIndex: 1,
|
||||
currentHighestBidPointAmount: 50,
|
||||
revision: 3,
|
||||
});
|
||||
const socket = { data: { matchId }, emit: jest.fn() };
|
||||
const { gateway } = createGateway({ placeBid });
|
||||
const { gateway } = createGateway({ placeBidDelta });
|
||||
|
||||
for (let index = 0; index < 8; index += 1) {
|
||||
await gateway.handleBid(
|
||||
@@ -248,6 +314,6 @@ describe('AuctionGateway', () => {
|
||||
jest.fn(),
|
||||
);
|
||||
|
||||
expect(placeBid).toHaveBeenCalledTimes(9);
|
||||
expect(placeBidDelta).toHaveBeenCalledTimes(9);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { performance } from 'perf_hooks';
|
||||
import {
|
||||
Ack,
|
||||
ConnectedSocket,
|
||||
@@ -25,9 +26,14 @@ import type {
|
||||
UserDocument,
|
||||
} from '../global/database/schema';
|
||||
import { AuctionService } from './auction.service';
|
||||
import type { AuctionStateResponse } from './auction.service';
|
||||
import type {
|
||||
AuctionBidDeltaResponse,
|
||||
AuctionStateResponse,
|
||||
} from './auction.service';
|
||||
import { AuctionEventBusService } from './auction-event-bus.service';
|
||||
import type { MatchSideEffectDelta } from './auction-side-effect.service';
|
||||
import { serializeRealtimeAuction } from './auction-realtime-serializer';
|
||||
import { AuctionRedisService } from './redis/auction-redis.service';
|
||||
|
||||
interface JoinAuctionPayload {
|
||||
matchId: string;
|
||||
@@ -41,6 +47,11 @@ interface BidPayload {
|
||||
clientObservedCurrentBidRoundPlayerUserId?: string;
|
||||
}
|
||||
|
||||
interface TimeSyncPayload {
|
||||
clientSentAtTimestampMS?: number;
|
||||
sequence?: number;
|
||||
}
|
||||
|
||||
interface SoldPayload {
|
||||
auctionActionRequestId?: string;
|
||||
assignedPosition?: Position;
|
||||
@@ -92,6 +103,7 @@ export class AuctionGateway
|
||||
private readonly identityService: IdentityService,
|
||||
private readonly connectionService: ConnectionService,
|
||||
private readonly auctionEventBusService: AuctionEventBusService,
|
||||
private readonly auctionRedisService: AuctionRedisService,
|
||||
) {}
|
||||
|
||||
public afterInit(server: Namespace): void {
|
||||
@@ -146,6 +158,7 @@ export class AuctionGateway
|
||||
@MessageBody() payload: BidPayload,
|
||||
@Ack() ack?: (response: Record<string, unknown>) => void,
|
||||
) {
|
||||
const gatewayBidStartedAtMS = performance.now();
|
||||
const matchId = this.requireJoinedMatchId(socket);
|
||||
if (!matchId) return;
|
||||
|
||||
@@ -162,7 +175,7 @@ export class AuctionGateway
|
||||
}
|
||||
|
||||
try {
|
||||
const auction = await this.auctionService.placeBid({
|
||||
const bidResult = await this.auctionService.placeBidDelta({
|
||||
matchId: new mongoose.Types.ObjectId(matchId),
|
||||
teamIndex: payload.bidderTeamIndex,
|
||||
amount: payload.bidPointAmount,
|
||||
@@ -172,30 +185,75 @@ export class AuctionGateway
|
||||
clientObservedCurrentBidRoundPlayerUserId:
|
||||
payload.clientObservedCurrentBidRoundPlayerUserId,
|
||||
});
|
||||
const bidDelta = this.buildBidDeltaFromAuctionState(
|
||||
auction,
|
||||
bidRequestId,
|
||||
);
|
||||
if (bidDelta) {
|
||||
this.broadcastBid(matchId, bidDelta);
|
||||
const bidDelta = this.isBidDeltaResponse(bidResult)
|
||||
? {
|
||||
...bidResult,
|
||||
bidRequestId: bidResult.bidRequestId ?? bidRequestId,
|
||||
}
|
||||
: this.buildBidDeltaFromAuctionState(bidResult, bidRequestId);
|
||||
const bidServerTiming = this.extractBidServerTiming(bidDelta);
|
||||
const broadcastBidDelta = this.stripBidServerTiming(bidDelta);
|
||||
if (broadcastBidDelta) {
|
||||
this.broadcastBid(matchId, broadcastBidDelta);
|
||||
} else {
|
||||
this.broadcastState(matchId, auction);
|
||||
this.broadcastState(matchId, bidResult as AuctionStateResponse);
|
||||
}
|
||||
ack?.({
|
||||
...(bidDelta
|
||||
? {}
|
||||
: { state: this.serializeAuction(bidResult as AuctionStateResponse) }),
|
||||
ok: true,
|
||||
bidRequestId,
|
||||
state: this.serializeAuction(auction),
|
||||
bidDelta: broadcastBidDelta,
|
||||
bidServerTiming: this.buildGatewayBidTiming(
|
||||
gatewayBidStartedAtMS,
|
||||
bidServerTiming,
|
||||
),
|
||||
});
|
||||
} catch (error) {
|
||||
this.emitKnownError(socket, error);
|
||||
const errorPayload = this.resolveErrorPayload(error);
|
||||
const bidServerTiming = this.extractBidServerTiming(errorPayload);
|
||||
this.emitError(socket, errorPayload.message);
|
||||
ack?.({
|
||||
...errorPayload,
|
||||
bidRequestId,
|
||||
code: error instanceof Error ? error.message : 'UNKNOWN',
|
||||
bidServerTiming: this.buildGatewayBidTiming(
|
||||
gatewayBidStartedAtMS,
|
||||
bidServerTiming,
|
||||
),
|
||||
rejected: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeMessage('time-sync')
|
||||
public async handleTimeSync(
|
||||
@MessageBody() payload: TimeSyncPayload,
|
||||
@Ack() ack?: (response: Record<string, unknown>) => void,
|
||||
) {
|
||||
const receivedAtMonotonicMS = performance.now();
|
||||
try {
|
||||
const currentServerTimestampMS =
|
||||
await this.auctionRedisService.getCurrentRedisTimestampMS();
|
||||
ack?.({
|
||||
clientSentAtTimestampMS: payload?.clientSentAtTimestampMS,
|
||||
currentServerTimestampMS,
|
||||
ok: true,
|
||||
sequence: payload?.sequence,
|
||||
serverProcessingDurationMS:
|
||||
Math.round((performance.now() - receivedAtMonotonicMS) * 10) / 10,
|
||||
});
|
||||
} catch (error) {
|
||||
const errorPayload = this.resolveErrorPayload(error);
|
||||
ack?.({
|
||||
...errorPayload,
|
||||
clientSentAtTimestampMS: payload?.clientSentAtTimestampMS,
|
||||
rejected: true,
|
||||
sequence: payload?.sequence,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeMessage('open-bidding')
|
||||
public async handleOpenBidding(
|
||||
@ConnectedSocket() socket: Socket,
|
||||
@@ -208,13 +266,12 @@ export class AuctionGateway
|
||||
try {
|
||||
const auction = await this.auctionService.openBidding(
|
||||
new mongoose.Types.ObjectId(matchId),
|
||||
this.toAuctionActionRequest(payload),
|
||||
this.toSocketAuctionActionRequest(payload),
|
||||
);
|
||||
this.broadcastState(matchId, auction);
|
||||
ack?.({
|
||||
auctionActionRequestId: payload?.auctionActionRequestId,
|
||||
ok: true,
|
||||
state: this.serializeAuction(auction),
|
||||
});
|
||||
} catch (error) {
|
||||
this.emitKnownError(socket, error);
|
||||
@@ -239,13 +296,12 @@ export class AuctionGateway
|
||||
const auction = await this.auctionService.markSold({
|
||||
matchId: new mongoose.Types.ObjectId(matchId),
|
||||
assignedPosition: payload?.assignedPosition,
|
||||
...this.toAuctionActionRequest(payload),
|
||||
...this.toSocketAuctionActionRequest(payload),
|
||||
});
|
||||
this.broadcastState(matchId, auction);
|
||||
ack?.({
|
||||
auctionActionRequestId: payload?.auctionActionRequestId,
|
||||
ok: true,
|
||||
state: this.serializeAuction(auction),
|
||||
});
|
||||
} catch (error) {
|
||||
this.emitKnownError(socket, error);
|
||||
@@ -269,13 +325,12 @@ export class AuctionGateway
|
||||
try {
|
||||
const auction = await this.auctionService.next(
|
||||
new mongoose.Types.ObjectId(matchId),
|
||||
this.toAuctionActionRequest(payload),
|
||||
this.toSocketAuctionActionRequest(payload),
|
||||
);
|
||||
this.broadcastState(matchId, auction);
|
||||
ack?.({
|
||||
auctionActionRequestId: payload?.auctionActionRequestId,
|
||||
ok: true,
|
||||
state: this.serializeAuction(auction),
|
||||
});
|
||||
} catch (error) {
|
||||
this.emitKnownError(socket, error);
|
||||
@@ -299,13 +354,12 @@ export class AuctionGateway
|
||||
try {
|
||||
const auction = await this.auctionService.markPassed(
|
||||
new mongoose.Types.ObjectId(matchId),
|
||||
this.toAuctionActionRequest(payload),
|
||||
this.toSocketAuctionActionRequest(payload),
|
||||
);
|
||||
this.broadcastState(matchId, auction);
|
||||
ack?.({
|
||||
auctionActionRequestId: payload?.auctionActionRequestId,
|
||||
ok: true,
|
||||
state: this.serializeAuction(auction),
|
||||
});
|
||||
} catch (error) {
|
||||
this.emitKnownError(socket, error);
|
||||
@@ -395,6 +449,13 @@ export class AuctionGateway
|
||||
};
|
||||
}
|
||||
|
||||
private toSocketAuctionActionRequest(payload?: AuctionActionPayload) {
|
||||
return {
|
||||
...this.toAuctionActionRequest(payload),
|
||||
shouldBroadcastStateAfterDurability: false,
|
||||
};
|
||||
}
|
||||
|
||||
private readHandshakeUserId(socket: Socket): string | undefined {
|
||||
const authUserId = socket.handshake.auth['x-auth-user-id'];
|
||||
if (typeof authUserId === 'string') return authUserId;
|
||||
@@ -509,7 +570,7 @@ export class AuctionGateway
|
||||
}
|
||||
|
||||
public broadcastState(matchId: string, auction: AuctionStateResponse) {
|
||||
this.server.to(matchId).emit('state', this.serializeAuction(auction));
|
||||
this.server.to(matchId).emit('state', serializeRealtimeAuction(auction));
|
||||
}
|
||||
|
||||
public broadcastBid(matchId: string, delta: Record<string, unknown>) {
|
||||
@@ -536,9 +597,7 @@ export class AuctionGateway
|
||||
}
|
||||
|
||||
private emitKnownError(socket: Socket, error: unknown) {
|
||||
const message =
|
||||
error instanceof Error ? error.message : 'Unexpected auction gateway error.';
|
||||
this.emitError(socket, message);
|
||||
this.emitError(socket, this.resolveErrorPayload(error).message);
|
||||
}
|
||||
|
||||
private emitError(socket: Socket, message: string) {
|
||||
@@ -549,6 +608,68 @@ export class AuctionGateway
|
||||
return JSON.parse(JSON.stringify(auction));
|
||||
}
|
||||
|
||||
private resolveErrorPayload(error: unknown): Record<string, unknown> & {
|
||||
message: string;
|
||||
} {
|
||||
const response =
|
||||
typeof (error as { getResponse?: unknown })?.getResponse === 'function'
|
||||
? (error as { getResponse: () => unknown }).getResponse()
|
||||
: undefined;
|
||||
if (typeof response === 'object' && response !== null) {
|
||||
const record = response as Record<string, unknown>;
|
||||
const message = Array.isArray(record.message)
|
||||
? record.message.join(', ')
|
||||
: typeof record.message === 'string'
|
||||
? record.message
|
||||
: error instanceof Error
|
||||
? error.message
|
||||
: 'Unexpected auction gateway error.';
|
||||
return {
|
||||
...record,
|
||||
code:
|
||||
typeof record.code === 'string'
|
||||
? record.code
|
||||
: error instanceof Error
|
||||
? error.message
|
||||
: 'UNKNOWN',
|
||||
message,
|
||||
};
|
||||
}
|
||||
return {
|
||||
code: error instanceof Error ? error.message : 'UNKNOWN',
|
||||
message:
|
||||
error instanceof Error ? error.message : 'Unexpected auction gateway error.',
|
||||
};
|
||||
}
|
||||
|
||||
private buildGatewayBidTiming(
|
||||
gatewayBidStartedAtMS: number,
|
||||
bidServerTiming?: Record<string, unknown>,
|
||||
): Record<string, unknown> {
|
||||
return {
|
||||
...(bidServerTiming ?? {}),
|
||||
gatewayTotalDurationMS:
|
||||
Math.round((performance.now() - gatewayBidStartedAtMS) * 10) / 10,
|
||||
};
|
||||
}
|
||||
|
||||
private extractBidServerTiming(
|
||||
bidDelta: Record<string, unknown> | null,
|
||||
): Record<string, unknown> | undefined {
|
||||
const timing = bidDelta?.bidServerTiming;
|
||||
return typeof timing === 'object' && timing !== null
|
||||
? (timing as Record<string, unknown>)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
private stripBidServerTiming(
|
||||
bidDelta: Record<string, unknown> | null,
|
||||
): Record<string, unknown> | null {
|
||||
if (!bidDelta || !('bidServerTiming' in bidDelta)) return bidDelta;
|
||||
const { bidServerTiming: _bidServerTiming, ...publicBidDelta } = bidDelta;
|
||||
return publicBidDelta;
|
||||
}
|
||||
|
||||
private buildBidDeltaFromAuctionState(
|
||||
auction: AuctionStateResponse,
|
||||
bidRequestId?: string,
|
||||
@@ -604,6 +725,19 @@ export class AuctionGateway
|
||||
};
|
||||
}
|
||||
|
||||
private isBidDeltaResponse(
|
||||
value: unknown,
|
||||
): value is AuctionBidDeltaResponse {
|
||||
return (
|
||||
typeof value === 'object' &&
|
||||
value !== null &&
|
||||
'auctionBidHistoryEntry' in value &&
|
||||
'currentHighestBidPointAmount' in value &&
|
||||
'currentHighestBidderTeamIndex' in value &&
|
||||
'revision' in value
|
||||
);
|
||||
}
|
||||
|
||||
private convertLegacyBidToRedisBidHistoryEntry(
|
||||
bid: unknown,
|
||||
): Record<string, unknown> | null {
|
||||
|
||||
@@ -91,6 +91,7 @@ describe('AuctionService', () => {
|
||||
auctionLifecycleId: 'life-1',
|
||||
revision: 1,
|
||||
}),
|
||||
readBidContext: jest.fn().mockResolvedValue(null),
|
||||
readAuctionStateView: jest.fn().mockResolvedValue(null),
|
||||
};
|
||||
|
||||
@@ -1006,6 +1007,123 @@ describe('AuctionService', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('returns bid deltas without re-reading the full Redis state', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const captainUserId = new mongoose.Types.ObjectId();
|
||||
const playerUserId = new mongoose.Types.ObjectId();
|
||||
const biddingContext = {
|
||||
auctionLifecycleId: 'life-1',
|
||||
bidderTeamCaptainUserId: captainUserId.toString(),
|
||||
currentBidRoundPlayerUserId: playerUserId.toString(),
|
||||
phase: 'bidding',
|
||||
};
|
||||
const auctionBidHistoryEntry = {
|
||||
bidderTeamIndex: 1,
|
||||
bidderUserId: captainUserId.toString(),
|
||||
bidPlacedAtTimestampMS: 1780000000000,
|
||||
bidPointAmount: 120,
|
||||
};
|
||||
const {
|
||||
connectionService,
|
||||
service,
|
||||
auctionRedisCommandService,
|
||||
auctionRedisStateReaderService,
|
||||
} = createService({});
|
||||
auctionRedisStateReaderService.readBidContext.mockResolvedValueOnce(
|
||||
biddingContext,
|
||||
);
|
||||
auctionRedisCommandService.placeBid.mockResolvedValueOnce({
|
||||
auctionBidHistoryEntry,
|
||||
bidRequestId: '00000000-0000-4000-8000-000000000050',
|
||||
currentBidRoundDeadlineTimestampMS: 1780000030000,
|
||||
currentHighestBidderTeamIndex: 1,
|
||||
currentHighestBidPointAmount: 120,
|
||||
currentServerTimestampMS: 1780000000000,
|
||||
ok: true,
|
||||
revision: 3,
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.placeBidDelta({
|
||||
amount: 120,
|
||||
bidRequestId: '00000000-0000-4000-8000-000000000050',
|
||||
matchId,
|
||||
teamIndex: 1,
|
||||
}),
|
||||
).resolves.toEqual(
|
||||
expect.objectContaining({
|
||||
auctionBidHistoryEntry,
|
||||
auctionLifecycleId: 'life-1',
|
||||
bidRequestId: '00000000-0000-4000-8000-000000000050',
|
||||
bidServerTiming: expect.objectContaining({
|
||||
redisBidCommandDurationMS: expect.any(Number),
|
||||
redisBidContextReadDurationMS: expect.any(Number),
|
||||
serviceTotalDurationMS: expect.any(Number),
|
||||
}),
|
||||
currentBidRoundDeadlineTimestampMS: 1780000030000,
|
||||
currentHighestBidderTeamIndex: 1,
|
||||
currentHighestBidPointAmount: 120,
|
||||
currentServerTimestampMS: 1780000000000,
|
||||
revision: 3,
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
auctionRedisStateReaderService.readAuctionStateView,
|
||||
).not.toHaveBeenCalled();
|
||||
expect(connectionService.getModel).not.toHaveBeenCalledWith('auction');
|
||||
});
|
||||
|
||||
it('includes redis bid diagnostics and timing on realtime bid rejection', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const captainUserId = new mongoose.Types.ObjectId();
|
||||
const playerUserId = new mongoose.Types.ObjectId();
|
||||
const {
|
||||
service,
|
||||
auctionRedisCommandService,
|
||||
auctionRedisStateReaderService,
|
||||
} = createService({});
|
||||
auctionRedisStateReaderService.readBidContext.mockResolvedValueOnce({
|
||||
auctionLifecycleId: 'life-1',
|
||||
bidderTeamCaptainUserId: captainUserId.toString(),
|
||||
currentBidRoundPlayerUserId: playerUserId.toString(),
|
||||
phase: 'bidding',
|
||||
});
|
||||
auctionRedisCommandService.placeBid.mockResolvedValueOnce({
|
||||
bidRequestId: 'bid-1',
|
||||
code: 'EXPIRED',
|
||||
currentBidRoundDeadlineTimestampMS: 1780000002500,
|
||||
currentServerTimestampMS: 1780000003000,
|
||||
rejected: true,
|
||||
});
|
||||
|
||||
try {
|
||||
await service.placeBidDelta({
|
||||
amount: 120,
|
||||
bidRequestId: 'bid-1',
|
||||
matchId,
|
||||
teamIndex: 1,
|
||||
});
|
||||
throw new Error('Expected bid rejection.');
|
||||
} catch (error) {
|
||||
const response = (error as { getResponse: () => unknown }).getResponse();
|
||||
expect(response).toEqual(
|
||||
expect.objectContaining({
|
||||
bidDiagnostics: {
|
||||
currentBidRoundDeadlineTimestampMS: 1780000002500,
|
||||
currentServerTimestampMS: 1780000003000,
|
||||
},
|
||||
bidServerTiming: expect.objectContaining({
|
||||
redisBidCommandDurationMS: expect.any(Number),
|
||||
redisBidContextReadDurationMS: expect.any(Number),
|
||||
serviceTotalDurationMS: expect.any(Number),
|
||||
}),
|
||||
code: 'EXPIRED',
|
||||
message: 'Bid deadline has already expired.',
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('syncs match teams when a redis-v1 auction completes', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const captainUserId = new mongoose.Types.ObjectId();
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { performance } from 'perf_hooks';
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import {
|
||||
@@ -25,7 +26,10 @@ import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.se
|
||||
import type { RiotPlatformRoute, RiotRegionalRoute } from '../riot/riot.types';
|
||||
import { TournamentCodeService } from '../tournament-code/tournament-code.service';
|
||||
import { TournamentResultService } from '../tournament-result/tournament-result.service';
|
||||
import { AuctionRedisCommandService } from './redis/auction-redis-command.service';
|
||||
import {
|
||||
AuctionRedisCommandService,
|
||||
type AuctionBidCommandResult,
|
||||
} from './redis/auction-redis-command.service';
|
||||
import { buildAuctionRedisKeys } from './redis/auction-redis.keys';
|
||||
import {
|
||||
buildAuctionRedisLiveStatePatchFromStructure,
|
||||
@@ -87,6 +91,7 @@ interface AuctionStructureActionRequestParams {
|
||||
clientObservedCurrentBidRoundPlayerUserId?: string;
|
||||
clientObservedPhase?: string;
|
||||
clientObservedRevision?: number;
|
||||
shouldBroadcastStateAfterDurability?: boolean;
|
||||
}
|
||||
|
||||
interface MarkSoldParams extends AuctionStructureActionRequestParams {
|
||||
@@ -136,6 +141,30 @@ export interface AuctionHistoryView {
|
||||
|
||||
export type AuctionStateResponse = AuctionDocument | Record<string, unknown>;
|
||||
|
||||
export interface AuctionBidDeltaResponse {
|
||||
auctionBidHistoryEntry: Record<string, unknown>;
|
||||
auctionLifecycleId?: string;
|
||||
bidServerTiming?: AuctionBidServerTiming;
|
||||
bidRequestId: string;
|
||||
currentBidRoundDeadlineTimestampMS: number;
|
||||
currentHighestBidderTeamIndex: number;
|
||||
currentHighestBidPointAmount: number;
|
||||
currentServerTimestampMS: number;
|
||||
revision: number;
|
||||
}
|
||||
|
||||
export interface AuctionBidServerTiming {
|
||||
fallbackFullStatePath?: boolean;
|
||||
redisBidCommandDurationMS?: number;
|
||||
redisBidContextReadDurationMS?: number;
|
||||
serviceTotalDurationMS?: number;
|
||||
}
|
||||
|
||||
export interface AuctionBidRejectDiagnostics {
|
||||
currentBidRoundDeadlineTimestampMS?: number;
|
||||
currentServerTimestampMS?: number;
|
||||
}
|
||||
|
||||
interface AuctionEnrichmentTarget {
|
||||
userId: mongoose.Types.ObjectId;
|
||||
puuid: string;
|
||||
@@ -591,6 +620,23 @@ export class AuctionService {
|
||||
return auction;
|
||||
}
|
||||
|
||||
public async placeBidDelta(
|
||||
params: PlaceBidParams,
|
||||
): Promise<AuctionBidDeltaResponse | AuctionStateResponse> {
|
||||
this.assertValidBidPointAmount(params.amount);
|
||||
const redisBidDelta = await this.tryPlaceRedisBidDeltaFromRealtimeState(
|
||||
params,
|
||||
);
|
||||
if (redisBidDelta) return redisBidDelta;
|
||||
|
||||
const auction = await this.getByMatchId(params.matchId);
|
||||
this.assertLiveAuctionOperationSupported(auction);
|
||||
if (this.isRedisV1Auction(auction)) {
|
||||
return this.placeRedisBidDelta(auction, params);
|
||||
}
|
||||
return this.placeBid(params);
|
||||
}
|
||||
|
||||
private async openRedisBidding(
|
||||
auction: AuctionDocument,
|
||||
actionRequestParams: AuctionStructureActionRequestParams,
|
||||
@@ -627,6 +673,8 @@ export class AuctionService {
|
||||
},
|
||||
expectedPhase: 'presenting',
|
||||
liveStatePatch,
|
||||
shouldBroadcastStateAfterDurability:
|
||||
actionRequestParams.shouldBroadcastStateAfterDurability,
|
||||
state,
|
||||
structureInput,
|
||||
});
|
||||
@@ -636,6 +684,110 @@ export class AuctionService {
|
||||
auction: AuctionDocument,
|
||||
params: PlaceBidParams,
|
||||
): Promise<AuctionStateResponse> {
|
||||
const matchId = auction.matchId.toString();
|
||||
await this.executeRedisBid(auction, params);
|
||||
return this.requireRedisAuctionState(matchId);
|
||||
}
|
||||
|
||||
private async placeRedisBidDelta(
|
||||
auction: AuctionDocument,
|
||||
params: PlaceBidParams,
|
||||
): Promise<AuctionBidDeltaResponse> {
|
||||
const serviceStartedAtMS = performance.now();
|
||||
const { redisBidCommandDurationMS, result, state } =
|
||||
await this.executeRedisBid(auction, params);
|
||||
const bidDelta = this.buildBidDeltaFromRedisBidResult(state, result);
|
||||
bidDelta.bidServerTiming = this.roundBidServerTiming({
|
||||
fallbackFullStatePath: true,
|
||||
redisBidCommandDurationMS,
|
||||
serviceTotalDurationMS: performance.now() - serviceStartedAtMS,
|
||||
});
|
||||
this.logSlowBidTiming(auction.matchId.toString(), bidDelta.bidServerTiming);
|
||||
return bidDelta;
|
||||
}
|
||||
|
||||
private async tryPlaceRedisBidDeltaFromRealtimeState(
|
||||
params: PlaceBidParams,
|
||||
): Promise<AuctionBidDeltaResponse | null> {
|
||||
const serviceStartedAtMS = performance.now();
|
||||
const matchId = params.matchId.toString();
|
||||
const bidContextReadStartedAtMS = performance.now();
|
||||
const bidContext =
|
||||
await this.auctionRedisStateReaderService.readBidContext(
|
||||
matchId,
|
||||
params.teamIndex,
|
||||
);
|
||||
const redisBidContextReadDurationMS =
|
||||
performance.now() - bidContextReadStartedAtMS;
|
||||
if (!bidContext) return null;
|
||||
if (bidContext.phase !== 'bidding') {
|
||||
throw new BadRequestException('Auction is not in bidding phase.');
|
||||
}
|
||||
if (!bidContext.bidderTeamCaptainUserId) {
|
||||
throw new BadRequestException('Unknown team.');
|
||||
}
|
||||
|
||||
const auctionLifecycleId =
|
||||
params.clientObservedAuctionLifecycleId ?? bidContext.auctionLifecycleId;
|
||||
const currentBidRoundPlayerUserId =
|
||||
params.clientObservedCurrentBidRoundPlayerUserId ??
|
||||
bidContext.currentBidRoundPlayerUserId;
|
||||
if (!auctionLifecycleId || !currentBidRoundPlayerUserId) {
|
||||
throw new BadRequestException('Current bid round is not available.');
|
||||
}
|
||||
|
||||
const redisBidCommandStartedAtMS = performance.now();
|
||||
const result = await this.auctionRedisCommandService.placeBid(matchId, {
|
||||
bidPointAmount: params.amount,
|
||||
bidderTeamIndex: params.teamIndex,
|
||||
bidderUserId: bidContext.bidderTeamCaptainUserId,
|
||||
bidRequestId: params.bidRequestId ?? randomUUID(),
|
||||
clientObservedAuctionLifecycleId: auctionLifecycleId,
|
||||
clientObservedCurrentBidRoundPlayerUserId: currentBidRoundPlayerUserId,
|
||||
matchId,
|
||||
maximumAuctionTeamMemberCount: AUCTION_MAX_TEAM_SIZE,
|
||||
maximumStoredAuctionBidHistoryCount: AUCTION_MAX_STORED_BID_HISTORY_COUNT,
|
||||
maximumStoredBidRequestResultCount:
|
||||
AUCTION_MAX_STORED_BID_REQUEST_RESULT_COUNT,
|
||||
minimumBidPointReservePerRemainingAuctionTeamMemberSlot:
|
||||
AUCTION_MIN_BID_POINTS,
|
||||
minimumBidRequestResultReplayWindowMS:
|
||||
AUCTION_BID_REQUEST_REPLAY_WINDOW_MS,
|
||||
});
|
||||
const redisBidCommandDurationMS =
|
||||
performance.now() - redisBidCommandStartedAtMS;
|
||||
if ('rejected' in result) {
|
||||
const bidServerTiming = this.roundBidServerTiming({
|
||||
redisBidCommandDurationMS,
|
||||
redisBidContextReadDurationMS,
|
||||
serviceTotalDurationMS: performance.now() - serviceStartedAtMS,
|
||||
});
|
||||
this.logSlowBidTiming(matchId, bidServerTiming);
|
||||
throw this.createRedisBidRejectedException(result, bidServerTiming);
|
||||
}
|
||||
|
||||
const bidDelta = this.buildBidDeltaFromRedisBidResult(
|
||||
{ auctionLifecycleId: bidContext.auctionLifecycleId },
|
||||
result,
|
||||
);
|
||||
bidDelta.bidServerTiming = this.roundBidServerTiming({
|
||||
redisBidCommandDurationMS,
|
||||
redisBidContextReadDurationMS,
|
||||
serviceTotalDurationMS: performance.now() - serviceStartedAtMS,
|
||||
});
|
||||
this.logSlowBidTiming(matchId, bidDelta.bidServerTiming);
|
||||
return bidDelta;
|
||||
}
|
||||
|
||||
private async executeRedisBid(
|
||||
auction: AuctionDocument,
|
||||
params: PlaceBidParams,
|
||||
): Promise<{
|
||||
redisBidCommandDurationMS: number;
|
||||
result: Extract<AuctionBidCommandResult, { ok: true }>;
|
||||
state: Record<string, unknown>;
|
||||
}> {
|
||||
const serviceStartedAtMS = performance.now();
|
||||
const matchId = auction.matchId.toString();
|
||||
const state = await this.requireRedisAuctionState(matchId);
|
||||
if (state.phase !== 'bidding') {
|
||||
@@ -660,6 +812,7 @@ export class AuctionService {
|
||||
throw new BadRequestException('Current bid round is not available.');
|
||||
}
|
||||
|
||||
const redisBidCommandStartedAtMS = performance.now();
|
||||
const result = await this.auctionRedisCommandService.placeBid(matchId, {
|
||||
bidPointAmount: params.amount,
|
||||
bidderTeamIndex: params.teamIndex,
|
||||
@@ -677,11 +830,36 @@ export class AuctionService {
|
||||
minimumBidRequestResultReplayWindowMS:
|
||||
AUCTION_BID_REQUEST_REPLAY_WINDOW_MS,
|
||||
});
|
||||
const redisBidCommandDurationMS =
|
||||
performance.now() - redisBidCommandStartedAtMS;
|
||||
if ('rejected' in result) {
|
||||
throw new BadRequestException(this.formatRedisBidRejectCode(result.code));
|
||||
const bidServerTiming = this.roundBidServerTiming({
|
||||
fallbackFullStatePath: true,
|
||||
redisBidCommandDurationMS,
|
||||
serviceTotalDurationMS: performance.now() - serviceStartedAtMS,
|
||||
});
|
||||
this.logSlowBidTiming(matchId, bidServerTiming);
|
||||
throw this.createRedisBidRejectedException(result, bidServerTiming);
|
||||
}
|
||||
|
||||
return this.requireRedisAuctionState(matchId);
|
||||
return { redisBidCommandDurationMS, result, state };
|
||||
}
|
||||
|
||||
private buildBidDeltaFromRedisBidResult(
|
||||
state: Record<string, unknown>,
|
||||
result: Extract<AuctionBidCommandResult, { ok: true }>,
|
||||
): AuctionBidDeltaResponse {
|
||||
return {
|
||||
auctionBidHistoryEntry: result.auctionBidHistoryEntry,
|
||||
auctionLifecycleId: this.stringFromState(state.auctionLifecycleId),
|
||||
bidRequestId: result.bidRequestId,
|
||||
currentBidRoundDeadlineTimestampMS:
|
||||
result.currentBidRoundDeadlineTimestampMS,
|
||||
currentHighestBidderTeamIndex: result.currentHighestBidderTeamIndex,
|
||||
currentHighestBidPointAmount: result.currentHighestBidPointAmount,
|
||||
currentServerTimestampMS: result.currentServerTimestampMS,
|
||||
revision: result.revision,
|
||||
};
|
||||
}
|
||||
|
||||
private async markRedisSold(
|
||||
@@ -749,6 +927,8 @@ export class AuctionService {
|
||||
...buildAuctionRedisLiveStatePatchFromStructure(structureInput),
|
||||
phase: 'sold',
|
||||
},
|
||||
shouldBroadcastStateAfterDurability:
|
||||
params.shouldBroadcastStateAfterDurability,
|
||||
state,
|
||||
structureInput,
|
||||
});
|
||||
@@ -806,6 +986,8 @@ export class AuctionService {
|
||||
...buildAuctionRedisLiveStatePatchFromStructure(structureInput),
|
||||
phase: 'passed',
|
||||
},
|
||||
shouldBroadcastStateAfterDurability:
|
||||
actionRequestParams.shouldBroadcastStateAfterDurability,
|
||||
state,
|
||||
structureInput,
|
||||
});
|
||||
@@ -972,6 +1154,8 @@ export class AuctionService {
|
||||
currentHighestBidderTeamIndex: -1,
|
||||
phase: nextPhase,
|
||||
},
|
||||
shouldBroadcastStateAfterDurability:
|
||||
actionRequestParams.shouldBroadcastStateAfterDurability,
|
||||
state,
|
||||
structureInput,
|
||||
});
|
||||
@@ -1445,6 +1629,7 @@ export class AuctionService {
|
||||
historyMutation?: Record<string, unknown>;
|
||||
liveStatePatch: Record<string, string | number | boolean | null | undefined>;
|
||||
matchSideEffectMutation?: Record<string, unknown>;
|
||||
shouldBroadcastStateAfterDurability?: boolean;
|
||||
shouldResetBidRuntime?: boolean;
|
||||
state: Record<string, unknown>;
|
||||
structureInput: Parameters<typeof stringifyAuctionRedisStructureState>[0];
|
||||
@@ -1528,7 +1713,8 @@ export class AuctionService {
|
||||
expectedRevision,
|
||||
liveStatePatch: params.liveStatePatch,
|
||||
matchId,
|
||||
shouldBroadcastState: true,
|
||||
shouldBroadcastState:
|
||||
params.shouldBroadcastStateAfterDurability ?? true,
|
||||
shouldResetBidRuntime: params.shouldResetBidRuntime,
|
||||
actionRequest: params.actionRequest?.actionRequest,
|
||||
},
|
||||
@@ -1945,6 +2131,46 @@ export class AuctionService {
|
||||
}
|
||||
}
|
||||
|
||||
private createRedisBidRejectedException(
|
||||
result: Extract<AuctionBidCommandResult, { rejected: true }>,
|
||||
bidServerTiming?: AuctionBidServerTiming,
|
||||
): BadRequestException {
|
||||
const message = this.formatRedisBidRejectCode(result.code);
|
||||
const bidDiagnostics: AuctionBidRejectDiagnostics = {
|
||||
currentBidRoundDeadlineTimestampMS:
|
||||
result.currentBidRoundDeadlineTimestampMS,
|
||||
currentServerTimestampMS: result.currentServerTimestampMS,
|
||||
};
|
||||
return new BadRequestException({
|
||||
bidDiagnostics,
|
||||
...(bidServerTiming ? { bidServerTiming } : {}),
|
||||
code: result.code,
|
||||
message,
|
||||
});
|
||||
}
|
||||
|
||||
private roundBidServerTiming(
|
||||
timing: AuctionBidServerTiming,
|
||||
): AuctionBidServerTiming {
|
||||
return Object.fromEntries(
|
||||
Object.entries(timing).map(([key, value]) => [
|
||||
key,
|
||||
typeof value === 'number' ? Math.round(value * 10) / 10 : value,
|
||||
]),
|
||||
) as AuctionBidServerTiming;
|
||||
}
|
||||
|
||||
private logSlowBidTiming(
|
||||
matchId: string,
|
||||
timing: AuctionBidServerTiming,
|
||||
): void {
|
||||
const serviceTotalDurationMS = timing.serviceTotalDurationMS ?? 0;
|
||||
if (serviceTotalDurationMS < 250) return;
|
||||
this.logger.warn(
|
||||
`Auction bid latency match=${matchId} service=${serviceTotalDurationMS}ms context=${timing.redisBidContextReadDurationMS ?? 0}ms redisBid=${timing.redisBidCommandDurationMS ?? 0}ms fallback=${timing.fallbackFullStatePath ? '1' : '0'}`,
|
||||
);
|
||||
}
|
||||
|
||||
private applyTopTierPriority(
|
||||
order: AuctionPlayerSnapshot[],
|
||||
threshold: AuctionTopTierThreshold,
|
||||
|
||||
@@ -67,6 +67,7 @@ describe('AuctionRedisCommandService', () => {
|
||||
'TOO_LOW',
|
||||
'bid-1',
|
||||
'1000',
|
||||
'31000',
|
||||
]);
|
||||
|
||||
await expect(
|
||||
@@ -87,6 +88,7 @@ describe('AuctionRedisCommandService', () => {
|
||||
).resolves.toEqual({
|
||||
bidRequestId: 'bid-1',
|
||||
code: 'TOO_LOW',
|
||||
currentBidRoundDeadlineTimestampMS: 31_000,
|
||||
currentServerTimestampMS: 1000,
|
||||
rejected: true,
|
||||
});
|
||||
|
||||
@@ -37,6 +37,7 @@ export type AuctionBidCommandResult =
|
||||
| {
|
||||
bidRequestId: string;
|
||||
code: string;
|
||||
currentBidRoundDeadlineTimestampMS?: number;
|
||||
currentServerTimestampMS: number;
|
||||
isReplay?: boolean;
|
||||
rejected: true;
|
||||
@@ -244,6 +245,7 @@ function parseBidCommandReply(reply: unknown[]): AuctionBidCommandResult {
|
||||
return {
|
||||
bidRequestId: values[2],
|
||||
code: values[4] || status,
|
||||
currentBidRoundDeadlineTimestampMS: optionalNumberValue(values[7]),
|
||||
currentServerTimestampMS: numberValue(values[9]),
|
||||
isReplay: true,
|
||||
rejected: true,
|
||||
@@ -252,6 +254,7 @@ function parseBidCommandReply(reply: unknown[]): AuctionBidCommandResult {
|
||||
return {
|
||||
bidRequestId: values[2] ?? '',
|
||||
code: values[1] ?? 'UNKNOWN',
|
||||
currentBidRoundDeadlineTimestampMS: optionalNumberValue(values[4]),
|
||||
currentServerTimestampMS: numberValue(values[3]),
|
||||
rejected: true,
|
||||
};
|
||||
@@ -373,3 +376,9 @@ function numberValue(value: string | undefined): number {
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : 0;
|
||||
}
|
||||
|
||||
function optionalNumberValue(value: string | undefined): number | undefined {
|
||||
if (value === undefined || value === '') return undefined;
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : undefined;
|
||||
}
|
||||
@@ -146,6 +146,7 @@ describe('auction redis projection helpers', () => {
|
||||
currentBidRoundPlayerUserId: playerUserId.toString(),
|
||||
maximumBidRoundDurationSeconds: 30,
|
||||
'team:2:assignedAuctionTeamMemberCount': 2,
|
||||
'team:2:captainUserId': captainUserId.toString(),
|
||||
'team:2:remainingBidPointAmount': 970,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -68,6 +68,8 @@ export function buildAuctionRedisLiveStatePatchFromStructure(
|
||||
}
|
||||
|
||||
for (const team of input.auctionTeams) {
|
||||
patch[`team:${team.teamIndex}:captainUserId`] =
|
||||
team.captainUserId.toString();
|
||||
patch[`team:${team.teamIndex}:remainingBidPointAmount`] =
|
||||
team.remainingBidPointAmount;
|
||||
patch[`team:${team.teamIndex}:assignedAuctionTeamMemberCount`] =
|
||||
|
||||
@@ -41,6 +41,46 @@ describe('AuctionRedisStateReaderService', () => {
|
||||
await expect(service.readLiveStateIdentity('match-1')).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('reads bid context from the live state hot path fields', async () => {
|
||||
const { service, sendCommand } = makeService([
|
||||
['bidding', 'life-1', 'player-1', 'captain-2'],
|
||||
]);
|
||||
|
||||
await expect(service.readBidContext('match-1', 2)).resolves.toEqual({
|
||||
auctionLifecycleId: 'life-1',
|
||||
bidderTeamCaptainUserId: 'captain-2',
|
||||
currentBidRoundPlayerUserId: 'player-1',
|
||||
phase: 'bidding',
|
||||
});
|
||||
expect(sendCommand).toHaveBeenCalledTimes(1);
|
||||
expect(sendCommand).toHaveBeenCalledWith([
|
||||
'HMGET',
|
||||
'auction:match-1:liveAuctionState',
|
||||
'phase',
|
||||
'auctionLifecycleId',
|
||||
'currentBidRoundPlayerUserId',
|
||||
'team:2:captainUserId',
|
||||
]);
|
||||
});
|
||||
|
||||
it('falls back to structure state when bid context has no live captain field', async () => {
|
||||
const { service, sendCommand } = makeService([
|
||||
['bidding', 'life-1', 'player-1', null],
|
||||
'{"auctionTeams":[{"teamIndex":2,"captainUserId":"captain-2"}]}',
|
||||
]);
|
||||
|
||||
await expect(service.readBidContext('match-1', 2)).resolves.toEqual({
|
||||
auctionLifecycleId: 'life-1',
|
||||
bidderTeamCaptainUserId: 'captain-2',
|
||||
currentBidRoundPlayerUserId: 'player-1',
|
||||
phase: 'bidding',
|
||||
});
|
||||
expect(sendCommand).toHaveBeenNthCalledWith(2, [
|
||||
'GET',
|
||||
'auction:match-1:auctionStructureState',
|
||||
]);
|
||||
});
|
||||
|
||||
it('assembles a public auction view from Redis state', async () => {
|
||||
const { service, sendCommand } = makeService([
|
||||
[
|
||||
|
||||
@@ -22,6 +22,13 @@ export interface AuctionRedisLiveStateIdentity {
|
||||
revision?: number;
|
||||
}
|
||||
|
||||
export interface AuctionRedisBidContext {
|
||||
auctionLifecycleId: string;
|
||||
bidderTeamCaptainUserId?: string;
|
||||
currentBidRoundPlayerUserId?: string;
|
||||
phase: string;
|
||||
}
|
||||
|
||||
export interface AuctionRedisStateViewReadOptions {
|
||||
includeInternalLiveStateFields?: boolean;
|
||||
shouldForceAuctionStateResync?: boolean;
|
||||
@@ -55,6 +62,41 @@ export class AuctionRedisStateReaderService {
|
||||
};
|
||||
}
|
||||
|
||||
public async readBidContext(
|
||||
matchId: string,
|
||||
bidderTeamIndex: number,
|
||||
): Promise<AuctionRedisBidContext | null> {
|
||||
const keys = buildAuctionRedisKeys(matchId);
|
||||
const bidderTeamCaptainUserIdField = `team:${bidderTeamIndex}:captainUserId`;
|
||||
const liveReply = await this.auctionRedisService.raw().sendCommand([
|
||||
'HMGET',
|
||||
keys.liveStateKey,
|
||||
'phase',
|
||||
'auctionLifecycleId',
|
||||
'currentBidRoundPlayerUserId',
|
||||
bidderTeamCaptainUserIdField,
|
||||
]);
|
||||
if (!Array.isArray(liveReply)) return null;
|
||||
|
||||
const phase = stringValue(liveReply[0]);
|
||||
const auctionLifecycleId = stringValue(liveReply[1]);
|
||||
const currentBidRoundPlayerUserId = stringValue(liveReply[2]);
|
||||
const liveCaptainUserId = stringValue(liveReply[3]);
|
||||
if (!phase || !auctionLifecycleId) return null;
|
||||
|
||||
return {
|
||||
auctionLifecycleId,
|
||||
bidderTeamCaptainUserId:
|
||||
liveCaptainUserId ??
|
||||
(await this.readBidderTeamCaptainUserIdFromStructure(
|
||||
keys.structureStateKey,
|
||||
bidderTeamIndex,
|
||||
)),
|
||||
currentBidRoundPlayerUserId,
|
||||
phase,
|
||||
};
|
||||
}
|
||||
|
||||
public async readAuctionStateView(
|
||||
matchId: string,
|
||||
options: AuctionRedisStateViewReadOptions = {},
|
||||
@@ -102,11 +144,43 @@ export class AuctionRedisStateReaderService {
|
||||
shouldForceAuctionStateResync: options.shouldForceAuctionStateResync,
|
||||
structureState: JSON.parse(structureStateJson) as Record<string, unknown>,
|
||||
});
|
||||
view.matchId = matchId;
|
||||
if (options.includeInternalLiveStateFields) {
|
||||
view.redisInternalPhase = liveState.phase;
|
||||
}
|
||||
return view;
|
||||
}
|
||||
|
||||
private async readBidderTeamCaptainUserIdFromStructure(
|
||||
structureStateKey: string,
|
||||
bidderTeamIndex: number,
|
||||
): Promise<string | undefined> {
|
||||
const structureStateJson = await this.auctionRedisService
|
||||
.raw()
|
||||
.sendCommand(['GET', structureStateKey]);
|
||||
if (typeof structureStateJson !== 'string' || !structureStateJson) {
|
||||
return undefined;
|
||||
}
|
||||
const structureState = JSON.parse(structureStateJson) as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
const auctionTeams = Array.isArray(structureState.auctionTeams)
|
||||
? structureState.auctionTeams
|
||||
: [];
|
||||
const bidderTeam = auctionTeams.find((entry) => {
|
||||
if (!entry || typeof entry !== 'object') return false;
|
||||
return (
|
||||
Number((entry as Record<string, unknown>).teamIndex) === bidderTeamIndex
|
||||
);
|
||||
});
|
||||
if (!bidderTeam || typeof bidderTeam !== 'object') return undefined;
|
||||
return stringValue((bidderTeam as Record<string, unknown>).captainUserId);
|
||||
}
|
||||
}
|
||||
|
||||
function stringValue(value: unknown): string | undefined {
|
||||
return typeof value === 'string' && value ? value : undefined;
|
||||
}
|
||||
|
||||
function parseHashReply(
|
||||
|
||||
@@ -174,6 +174,7 @@ if redis.call('LLEN', bidRequestResultOrderKey) >= maximumStoredBidRequestResult
|
||||
end
|
||||
|
||||
local function storeRejectedRequest(rejectCode)
|
||||
local rejectedCurrentBidRoundDeadlineTimestampMS = redis.call('HGET', liveAuctionStateKey, 'currentBidRoundDeadlineTimestampMS') or ''
|
||||
redis.call(
|
||||
'HSET',
|
||||
bidRequestResultsKey,
|
||||
@@ -183,13 +184,15 @@ local function storeRejectedRequest(rejectCode)
|
||||
'rejected',
|
||||
requestField('rejectCode'),
|
||||
rejectCode,
|
||||
requestField('currentBidRoundDeadlineTimestampMS'),
|
||||
rejectedCurrentBidRoundDeadlineTimestampMS,
|
||||
requestField('responseServerTimestampMS'),
|
||||
tostring(currentRedisTimestampMS),
|
||||
requestField('createdAtTimestampMS'),
|
||||
tostring(currentRedisTimestampMS)
|
||||
)
|
||||
redis.call('RPUSH', bidRequestResultOrderKey, bidRequestId)
|
||||
return {'REJECTED', rejectCode, bidRequestId, tostring(currentRedisTimestampMS)}
|
||||
return {'REJECTED', rejectCode, bidRequestId, tostring(currentRedisTimestampMS), rejectedCurrentBidRoundDeadlineTimestampMS}
|
||||
end
|
||||
|
||||
local phase = redis.call('HGET', liveAuctionStateKey, 'phase')
|
||||
|
||||
Reference in new issue
Block a user