fix(api): resolve lint errors
This commit is contained in:
1 parent
96fede9fe5
commit
fd1fa2366c
42 files changed
+307
-199
No files matched your search
@@ -74,13 +74,11 @@ function serializeRealtimeAuctionPlayer(
|
||||
return player;
|
||||
}
|
||||
|
||||
const {
|
||||
masteries: _masteries,
|
||||
puuid: _puuid,
|
||||
recentStatsSummary: _recentStatsSummary,
|
||||
tierHistory: _tierHistory,
|
||||
...lightweightPlayer
|
||||
} = player;
|
||||
const lightweightPlayer = { ...player };
|
||||
delete lightweightPlayer.masteries;
|
||||
delete lightweightPlayer.puuid;
|
||||
delete lightweightPlayer.recentStatsSummary;
|
||||
delete lightweightPlayer.tierHistory;
|
||||
|
||||
return lightweightPlayer;
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
} from '@nestjs/websockets';
|
||||
import mongoose from 'mongoose';
|
||||
import type { JWTPayload } from 'jose';
|
||||
import { Namespace, Socket } from 'socket.io';
|
||||
import type { DefaultEventsMap, Namespace, Socket } from 'socket.io';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
import { IdentityService } from '../auth/identity.service';
|
||||
import { JwtService } from '../auth/jwt.service';
|
||||
@@ -78,6 +78,20 @@ interface BidRateLimitState {
|
||||
windowStartedAtTimestampMS: number;
|
||||
}
|
||||
|
||||
interface AuctionSocketData {
|
||||
auctionBidRateLimit?: BidRateLimitState;
|
||||
identity?: IdentityDocument;
|
||||
matchId?: string;
|
||||
user?: UserDocument;
|
||||
}
|
||||
|
||||
type AuctionSocket = Socket<
|
||||
DefaultEventsMap,
|
||||
DefaultEventsMap,
|
||||
DefaultEventsMap,
|
||||
AuctionSocketData
|
||||
>;
|
||||
|
||||
const BID_RATE_LIMIT_WINDOW_MS = 1000;
|
||||
const BID_RATE_LIMIT_MAX_REQUESTS_PER_WINDOW = 8;
|
||||
const BID_RATE_LIMIT_REJECTION_CODE = 'BID_RATE_LIMITED';
|
||||
@@ -112,14 +126,14 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
this.auctionEventBusService.attachAuctionNamespace(server);
|
||||
}
|
||||
|
||||
public async handleConnection(socket: Socket) {
|
||||
public async handleConnection(socket: AuctionSocket) {
|
||||
try {
|
||||
await this.authenticateSocket(socket);
|
||||
this.logger.debug(`Auction client connected: ${socket.id}`);
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`Auction client authentication failed: ${
|
||||
err instanceof Error ? err.message : err
|
||||
err instanceof Error ? err.message : String(err)
|
||||
}`,
|
||||
);
|
||||
socket.disconnect(true);
|
||||
@@ -128,7 +142,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
|
||||
@SubscribeMessage('join')
|
||||
public async handleJoin(
|
||||
@ConnectedSocket() socket: Socket,
|
||||
@ConnectedSocket() socket: AuctionSocket,
|
||||
@MessageBody() payload: JoinAuctionPayload,
|
||||
) {
|
||||
if (!payload?.matchId || !mongoose.isValidObjectId(payload.matchId)) {
|
||||
@@ -156,7 +170,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
|
||||
@SubscribeMessage('bid')
|
||||
public async handleBid(
|
||||
@ConnectedSocket() socket: Socket,
|
||||
@ConnectedSocket() socket: AuctionSocket,
|
||||
@MessageBody() payload: BidPayload,
|
||||
@Ack() ack?: (response: Record<string, unknown>) => void,
|
||||
) {
|
||||
@@ -220,7 +234,12 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
error,
|
||||
);
|
||||
const bidServerTiming = this.extractBidServerTiming(rejectionAckFields);
|
||||
this.emitError(socket, String(rejectionAckFields.message ?? ''));
|
||||
this.emitError(
|
||||
socket,
|
||||
typeof rejectionAckFields.message === 'string'
|
||||
? rejectionAckFields.message
|
||||
: '',
|
||||
);
|
||||
ack?.({
|
||||
...rejectionAckFields,
|
||||
bidRequestId,
|
||||
@@ -263,7 +282,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
|
||||
@SubscribeMessage('open-bidding')
|
||||
public async handleOpenBidding(
|
||||
@ConnectedSocket() socket: Socket,
|
||||
@ConnectedSocket() socket: AuctionSocket,
|
||||
@MessageBody() payload: AuctionActionPayload,
|
||||
@Ack() ack?: (response: Record<string, unknown>) => void,
|
||||
) {
|
||||
@@ -292,7 +311,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
|
||||
@SubscribeMessage('sold')
|
||||
public async handleSold(
|
||||
@ConnectedSocket() socket: Socket,
|
||||
@ConnectedSocket() socket: AuctionSocket,
|
||||
@MessageBody() payload: SoldPayload,
|
||||
@Ack() ack?: (response: Record<string, unknown>) => void,
|
||||
) {
|
||||
@@ -322,7 +341,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
|
||||
@SubscribeMessage('next')
|
||||
public async handleNext(
|
||||
@ConnectedSocket() socket: Socket,
|
||||
@ConnectedSocket() socket: AuctionSocket,
|
||||
@MessageBody() payload: AuctionActionPayload,
|
||||
@Ack() ack?: (response: Record<string, unknown>) => void,
|
||||
) {
|
||||
@@ -351,7 +370,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
|
||||
@SubscribeMessage('passed')
|
||||
public async handlePassed(
|
||||
@ConnectedSocket() socket: Socket,
|
||||
@ConnectedSocket() socket: AuctionSocket,
|
||||
@MessageBody() payload: AuctionActionPayload,
|
||||
@Ack() ack?: (response: Record<string, unknown>) => void,
|
||||
) {
|
||||
@@ -380,7 +399,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
|
||||
@SubscribeMessage('chat-message')
|
||||
public async handleChatMessage(
|
||||
@ConnectedSocket() socket: Socket,
|
||||
@ConnectedSocket() socket: AuctionSocket,
|
||||
@MessageBody() payload: ChatMessagePayload,
|
||||
) {
|
||||
const matchId = this.requireJoinedMatchId(socket);
|
||||
@@ -406,7 +425,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
}
|
||||
}
|
||||
|
||||
private requireJoinedMatchId(socket: Socket): string | null {
|
||||
private requireJoinedMatchId(socket: AuctionSocket): string | null {
|
||||
const matchId = this.getSocketMatchId(socket);
|
||||
if (!matchId) {
|
||||
this.emitError(socket, 'Join a match room before sending events.');
|
||||
@@ -415,11 +434,9 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
return matchId;
|
||||
}
|
||||
|
||||
private consumeBidRateLimit(socket: Socket): boolean {
|
||||
private consumeBidRateLimit(socket: AuctionSocket): boolean {
|
||||
const currentTimestampMS = Date.now();
|
||||
const previousState = socket.data.auctionBidRateLimit as
|
||||
| BidRateLimitState
|
||||
| undefined;
|
||||
const previousState = socket.data.auctionBidRateLimit;
|
||||
if (
|
||||
!previousState ||
|
||||
currentTimestampMS - previousState.windowStartedAtTimestampMS >=
|
||||
@@ -437,10 +454,8 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
return previousState.count <= BID_RATE_LIMIT_MAX_REQUESTS_PER_WINDOW;
|
||||
}
|
||||
|
||||
private getSocketMatchId(socket: Socket): string | undefined {
|
||||
return typeof socket.data.matchId === 'string'
|
||||
? socket.data.matchId
|
||||
: undefined;
|
||||
private getSocketMatchId(socket: AuctionSocket): string | undefined {
|
||||
return socket.data.matchId;
|
||||
}
|
||||
|
||||
private toAuctionActionRequest(payload?: AuctionActionPayload) {
|
||||
@@ -464,8 +479,9 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
};
|
||||
}
|
||||
|
||||
private readHandshakeUserId(socket: Socket): string | undefined {
|
||||
const authUserId = socket.handshake.auth['x-auth-user-id'];
|
||||
private readHandshakeUserId(socket: AuctionSocket): string | undefined {
|
||||
const handshakeAuth = socket.handshake.auth as Record<string, unknown>;
|
||||
const authUserId = handshakeAuth['x-auth-user-id'];
|
||||
if (typeof authUserId === 'string') return authUserId;
|
||||
|
||||
const header = socket.handshake.headers['x-auth-user-id'];
|
||||
@@ -473,16 +489,16 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
}
|
||||
|
||||
private resolveSocketUserId(
|
||||
socket: Socket,
|
||||
socket: AuctionSocket,
|
||||
): mongoose.Types.ObjectId | undefined {
|
||||
return (socket.data.user as UserDocument | undefined)?._id;
|
||||
return socket.data.user?._id;
|
||||
}
|
||||
|
||||
private resolveChatDisplayName(
|
||||
socket: Socket,
|
||||
socket: AuctionSocket,
|
||||
fallbackDisplayName?: string,
|
||||
): string {
|
||||
const user = socket.data.user as UserDocument | undefined;
|
||||
const user = socket.data.user;
|
||||
const primaryRiotAccount =
|
||||
user?.riotAccounts.find((entry) => entry.isPrimary) ??
|
||||
user?.riotAccounts[0];
|
||||
@@ -495,14 +511,14 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
if (user?.kakaoTalkNickname) return user.kakaoTalkNickname;
|
||||
if (user?.discordNickname) return user.discordNickname;
|
||||
|
||||
const identity = socket.data.identity as IdentityDocument | undefined;
|
||||
const identity = socket.data.identity;
|
||||
if (identity?.displayName) return identity.displayName;
|
||||
if (identity?.email) return identity.email;
|
||||
|
||||
return fallbackDisplayName ?? '관전자';
|
||||
}
|
||||
|
||||
private async authenticateSocket(socket: Socket): Promise<void> {
|
||||
private async authenticateSocket(socket: AuctionSocket): Promise<void> {
|
||||
const fallback = await this.authService.resolveDevUserById(
|
||||
this.readHandshakeUserId(socket),
|
||||
);
|
||||
@@ -532,14 +548,20 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
});
|
||||
}
|
||||
|
||||
private readHandshakeToken(socket: Socket): string | undefined {
|
||||
const authToken = socket.handshake.auth.token;
|
||||
private readHandshakeToken(socket: AuctionSocket): string | undefined {
|
||||
const handshakeAuth = socket.handshake.auth as Record<string, unknown>;
|
||||
const authToken = handshakeAuth.token;
|
||||
if (typeof authToken === 'string' && authToken.trim()) {
|
||||
return authToken.trim().replace(/^Bearer\s+/i, '');
|
||||
}
|
||||
|
||||
const header = socket.handshake.headers.authorization;
|
||||
const authorization = Array.isArray(header) ? header[0] : header;
|
||||
const header: unknown = socket.handshake.headers.authorization;
|
||||
const authorization =
|
||||
typeof header === 'string'
|
||||
? header
|
||||
: Array.isArray(header) && typeof header[0] === 'string'
|
||||
? header[0]
|
||||
: undefined;
|
||||
if (authorization?.startsWith('Bearer ')) {
|
||||
return authorization.slice('Bearer '.length).trim();
|
||||
}
|
||||
@@ -547,10 +569,11 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
}
|
||||
|
||||
private async resolveSocketUserForMatch(
|
||||
socket: Socket,
|
||||
socket: AuctionSocket,
|
||||
matchId: string,
|
||||
): Promise<void> {
|
||||
if (socket.data.user || !socket.data.identity) return;
|
||||
const identity = socket.data.identity;
|
||||
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const match = await MatchModel.findById(matchId).select({
|
||||
@@ -559,10 +582,11 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
if (!match) return;
|
||||
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
socket.data.user = await UserModel.findOne({
|
||||
const user = await UserModel.findOne({
|
||||
communityId: match.communityId,
|
||||
identityId: (socket.data.identity as IdentityDocument)._id,
|
||||
identityId: identity._id,
|
||||
}).exec();
|
||||
socket.data.user = user ?? undefined;
|
||||
}
|
||||
|
||||
private requireStringClaim(payload: JWTPayload, key: string): string {
|
||||
@@ -596,7 +620,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
this.server.to(matchId).emit('match-side-effect', delta);
|
||||
}
|
||||
|
||||
private emitChatHistory(socket: Socket, auction: AuctionDocument) {
|
||||
private emitChatHistory(socket: AuctionSocket, auction: AuctionDocument) {
|
||||
socket.emit('chat-history', {
|
||||
messages: (auction.chatMessages ?? []).map((message) =>
|
||||
this.serializeChatMessage(message),
|
||||
@@ -604,16 +628,21 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
});
|
||||
}
|
||||
|
||||
private emitKnownError(socket: Socket, error: unknown) {
|
||||
private emitKnownError(socket: AuctionSocket, error: unknown) {
|
||||
this.emitError(socket, this.resolveErrorPayload(error).message);
|
||||
}
|
||||
|
||||
private emitError(socket: Socket, message: string) {
|
||||
private emitError(socket: AuctionSocket, message: string) {
|
||||
socket.emit('error', { message });
|
||||
}
|
||||
|
||||
private serializeAuction(auction: AuctionStateResponse) {
|
||||
return JSON.parse(JSON.stringify(auction));
|
||||
private serializeAuction(
|
||||
auction: AuctionStateResponse,
|
||||
): Record<string, unknown> {
|
||||
const serialized: unknown = JSON.parse(JSON.stringify(auction));
|
||||
return typeof serialized === 'object' && serialized !== null
|
||||
? (serialized as Record<string, unknown>)
|
||||
: {};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -721,7 +750,8 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
bidDelta: Record<string, unknown> | null,
|
||||
): Record<string, unknown> | null {
|
||||
if (!bidDelta || !('bidServerTiming' in bidDelta)) return bidDelta;
|
||||
const { bidServerTiming: _bidServerTiming, ...publicBidDelta } = bidDelta;
|
||||
const publicBidDelta = { ...bidDelta };
|
||||
delete publicBidDelta.bidServerTiming;
|
||||
return publicBidDelta;
|
||||
}
|
||||
|
||||
@@ -729,10 +759,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
auction: AuctionStateResponse,
|
||||
bidRequestId?: string,
|
||||
): Record<string, unknown> | null {
|
||||
const serialized = this.serializeAuction(auction) as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
const serialized = this.serializeAuction(auction);
|
||||
const revision = Number(serialized.revision);
|
||||
const currentHighestBidPointAmount = Number(
|
||||
serialized.currentHighestBidPointAmount ?? serialized.currentBid,
|
||||
@@ -747,11 +774,13 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
? Date.parse(serialized.currentDeadline)
|
||||
: 0),
|
||||
);
|
||||
const redisBidHistory = Array.isArray(serialized.auctionBidHistory)
|
||||
? serialized.auctionBidHistory
|
||||
const redisBidHistory: unknown[] = Array.isArray(
|
||||
serialized.auctionBidHistory,
|
||||
)
|
||||
? (serialized.auctionBidHistory as unknown[])
|
||||
: [];
|
||||
const legacyBidHistory = Array.isArray(serialized.bids)
|
||||
? serialized.bids
|
||||
const legacyBidHistory: unknown[] = Array.isArray(serialized.bids)
|
||||
? (serialized.bids as unknown[])
|
||||
: [];
|
||||
const auctionBidHistoryEntry =
|
||||
redisBidHistory[redisBidHistory.length - 1] ??
|
||||
@@ -810,7 +839,12 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
};
|
||||
}
|
||||
|
||||
private serializeChatMessage(message: AuctionChatMessage) {
|
||||
return JSON.parse(JSON.stringify(message));
|
||||
private serializeChatMessage(
|
||||
message: AuctionChatMessage,
|
||||
): Record<string, unknown> {
|
||||
const serialized: unknown = JSON.parse(JSON.stringify(message));
|
||||
return typeof serialized === 'object' && serialized !== null
|
||||
? (serialized as Record<string, unknown>)
|
||||
: {};
|
||||
}
|
||||
}
|
||||
@@ -158,12 +158,11 @@ describe('AuctionService', () => {
|
||||
it('rejects non-positive or fractional bid amounts before loading auction state', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const auctionFindOne = jest.fn();
|
||||
const { service, auctionRedisCommandService, auctionRedisService } =
|
||||
createService({
|
||||
auction: {
|
||||
findOne: auctionFindOne,
|
||||
},
|
||||
});
|
||||
const { service, auctionRedisCommandService } = createService({
|
||||
auction: {
|
||||
findOne: auctionFindOne,
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.placeBid({
|
||||
|
||||
@@ -151,7 +151,7 @@ export class AuctionRedisStateReaderService {
|
||||
revision: number;
|
||||
},
|
||||
shouldForceAuctionStateResync: options.shouldForceAuctionStateResync,
|
||||
structureState: JSON.parse(structureStateJson) as Record<string, unknown>,
|
||||
structureState: parseJsonRecord(structureStateJson),
|
||||
});
|
||||
view.matchId = matchId;
|
||||
if (options.includeInternalLiveStateFields) {
|
||||
@@ -170,12 +170,9 @@ export class AuctionRedisStateReaderService {
|
||||
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 structureState = parseJsonRecord(structureStateJson);
|
||||
const auctionTeams: unknown[] = Array.isArray(structureState.auctionTeams)
|
||||
? (structureState.auctionTeams as unknown[])
|
||||
: [];
|
||||
const bidderTeam = auctionTeams.find((entry) => {
|
||||
if (!entry || typeof entry !== 'object') return false;
|
||||
@@ -192,6 +189,13 @@ function stringValue(value: unknown): string | undefined {
|
||||
return typeof value === 'string' && value ? value : undefined;
|
||||
}
|
||||
|
||||
function parseJsonRecord(json: string): Record<string, unknown> {
|
||||
const value: unknown = JSON.parse(json);
|
||||
return typeof value === 'object' && value !== null
|
||||
? (value as Record<string, unknown>)
|
||||
: {};
|
||||
}
|
||||
|
||||
function parseHashReply(
|
||||
reply: unknown,
|
||||
options: { includeInternalLiveStateFields?: boolean } = {},
|
||||
|
||||
@@ -74,9 +74,11 @@ async function readFirstSecret(
|
||||
|
||||
const logger = new Logger('AuctionRedisClient');
|
||||
const client = createClient(auctionRedisOptions);
|
||||
client.on('error', (error) => {
|
||||
client.on('error', (error: unknown) => {
|
||||
logger.error(
|
||||
`Auction Redis client error: ${error?.message ?? error}`,
|
||||
`Auction Redis client error: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`,
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -85,9 +85,15 @@ export class AuctionRedisService implements OnModuleDestroy {
|
||||
if (!isNoscriptError(error)) throw error;
|
||||
}
|
||||
|
||||
const loadedSha = String(
|
||||
await this.client.sendCommand(['SCRIPT', 'LOAD', params.script]),
|
||||
);
|
||||
const loadedShaReply = await this.client.sendCommand([
|
||||
'SCRIPT',
|
||||
'LOAD',
|
||||
params.script,
|
||||
]);
|
||||
if (typeof loadedShaReply !== 'string') {
|
||||
throw new Error('Redis SCRIPT LOAD returned a non-string SHA.');
|
||||
}
|
||||
const loadedSha = loadedShaReply;
|
||||
return (await this.client.sendCommand(
|
||||
buildEvalShaCommand(loadedSha, params.keys, params.values),
|
||||
)) as T;
|
||||
@@ -111,7 +117,7 @@ export class AuctionRedisService implements OnModuleDestroy {
|
||||
token: string,
|
||||
ttlMS: number,
|
||||
): Promise<boolean> {
|
||||
const result = await this.client.sendCommand([
|
||||
const result = await this.client.sendCommand<string | null>([
|
||||
'SET',
|
||||
key,
|
||||
token,
|
||||
@@ -119,7 +125,7 @@ export class AuctionRedisService implements OnModuleDestroy {
|
||||
String(ttlMS),
|
||||
'NX',
|
||||
]);
|
||||
return String(result) === 'OK';
|
||||
return result === 'OK';
|
||||
}
|
||||
|
||||
public async releaseTokenLock(key: string, token: string): Promise<boolean> {
|
||||
|
||||
@@ -78,9 +78,7 @@ export function assembleAuctionViewFromRedisState(
|
||||
return {
|
||||
...params.structureState,
|
||||
...params.liveState,
|
||||
auctionBidHistory: params.auctionBidHistoryEntries.map((entry) =>
|
||||
JSON.parse(entry),
|
||||
),
|
||||
auctionBidHistory: params.auctionBidHistoryEntries.map(parseJsonValue),
|
||||
canPlaceBidInCurrentBidRound: !isExpiring,
|
||||
currentServerTimestampMS: params.currentServerTimestampMS,
|
||||
isAuctionStateTransitionInProgress: isExpiring,
|
||||
@@ -90,6 +88,11 @@ export function assembleAuctionViewFromRedisState(
|
||||
};
|
||||
}
|
||||
|
||||
function parseJsonValue(json: string): unknown {
|
||||
const value: unknown = JSON.parse(json);
|
||||
return value;
|
||||
}
|
||||
|
||||
export function buildHydrateAuctionStateScriptInvocation(
|
||||
keys: AuctionRedisKeys,
|
||||
input: HydrateAuctionStateScriptInput,
|
||||
|
||||
Reference in new issue
Block a user