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
@@ -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 {
|
||||
|
||||
Reference in new issue
Block a user