fix(api): resolve lint errors

This commit is contained in:
dahyeon committed 2026-07-24 21:52:35 -07:00
1 parent 96fede9fe5
commit fd1fa2366c
42 files changed
+297 -189

No files matched your search

+22 -1
View File
@@ -29,7 +29,28 @@ export default tseslint.config(
'@typescript-eslint/no-explicit-any': 'off', '@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-floating-promises': 'warn', '@typescript-eslint/no-floating-promises': 'warn',
'@typescript-eslint/no-unsafe-argument': 'warn', '@typescript-eslint/no-unsafe-argument': 'warn',
"prettier/prettier": ["error", { endOfLine: "auto" }], 'prettier/prettier': ['error', { endOfLine: 'auto' }],
},
},
{
files: ['**/*.spec.ts', 'test/**/*.ts'],
rules: {
'@typescript-eslint/no-unsafe-assignment': 'off',
'@typescript-eslint/no-unsafe-call': 'off',
'@typescript-eslint/no-unsafe-member-access': 'off',
'@typescript-eslint/no-unsafe-return': 'off',
'@typescript-eslint/no-this-alias': 'off',
'@typescript-eslint/require-await': 'off',
'@typescript-eslint/unbound-method': 'off',
},
},
{
files: ['src/modules/global/database/migrations/**/*.ts'],
rules: {
'@typescript-eslint/no-unsafe-assignment': 'off',
'@typescript-eslint/no-unsafe-call': 'off',
'@typescript-eslint/no-unsafe-member-access': 'off',
'@typescript-eslint/no-unsafe-return': 'off',
}, },
}, },
); );
@@ -74,13 +74,11 @@ function serializeRealtimeAuctionPlayer(
return player; return player;
} }
const { const lightweightPlayer = { ...player };
masteries: _masteries, delete lightweightPlayer.masteries;
puuid: _puuid, delete lightweightPlayer.puuid;
recentStatsSummary: _recentStatsSummary, delete lightweightPlayer.recentStatsSummary;
tierHistory: _tierHistory, delete lightweightPlayer.tierHistory;
...lightweightPlayer
} = player;
return lightweightPlayer; return lightweightPlayer;
} }
+85 -51
View File
@@ -13,7 +13,7 @@ import {
} from '@nestjs/websockets'; } from '@nestjs/websockets';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import type { JWTPayload } from 'jose'; 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 { AuthService } from '../auth/auth.service';
import { IdentityService } from '../auth/identity.service'; import { IdentityService } from '../auth/identity.service';
import { JwtService } from '../auth/jwt.service'; import { JwtService } from '../auth/jwt.service';
@@ -78,6 +78,20 @@ interface BidRateLimitState {
windowStartedAtTimestampMS: number; 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_WINDOW_MS = 1000;
const BID_RATE_LIMIT_MAX_REQUESTS_PER_WINDOW = 8; const BID_RATE_LIMIT_MAX_REQUESTS_PER_WINDOW = 8;
const BID_RATE_LIMIT_REJECTION_CODE = 'BID_RATE_LIMITED'; const BID_RATE_LIMIT_REJECTION_CODE = 'BID_RATE_LIMITED';
@@ -112,14 +126,14 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
this.auctionEventBusService.attachAuctionNamespace(server); this.auctionEventBusService.attachAuctionNamespace(server);
} }
public async handleConnection(socket: Socket) { public async handleConnection(socket: AuctionSocket) {
try { try {
await this.authenticateSocket(socket); await this.authenticateSocket(socket);
this.logger.debug(`Auction client connected: ${socket.id}`); this.logger.debug(`Auction client connected: ${socket.id}`);
} catch (err) { } catch (err) {
this.logger.warn( this.logger.warn(
`Auction client authentication failed: ${ `Auction client authentication failed: ${
err instanceof Error ? err.message : err err instanceof Error ? err.message : String(err)
}`, }`,
); );
socket.disconnect(true); socket.disconnect(true);
@@ -128,7 +142,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
@SubscribeMessage('join') @SubscribeMessage('join')
public async handleJoin( public async handleJoin(
@ConnectedSocket() socket: Socket, @ConnectedSocket() socket: AuctionSocket,
@MessageBody() payload: JoinAuctionPayload, @MessageBody() payload: JoinAuctionPayload,
) { ) {
if (!payload?.matchId || !mongoose.isValidObjectId(payload.matchId)) { if (!payload?.matchId || !mongoose.isValidObjectId(payload.matchId)) {
@@ -156,7 +170,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
@SubscribeMessage('bid') @SubscribeMessage('bid')
public async handleBid( public async handleBid(
@ConnectedSocket() socket: Socket, @ConnectedSocket() socket: AuctionSocket,
@MessageBody() payload: BidPayload, @MessageBody() payload: BidPayload,
@Ack() ack?: (response: Record<string, unknown>) => void, @Ack() ack?: (response: Record<string, unknown>) => void,
) { ) {
@@ -220,7 +234,12 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
error, error,
); );
const bidServerTiming = this.extractBidServerTiming(rejectionAckFields); const bidServerTiming = this.extractBidServerTiming(rejectionAckFields);
this.emitError(socket, String(rejectionAckFields.message ?? '')); this.emitError(
socket,
typeof rejectionAckFields.message === 'string'
? rejectionAckFields.message
: '',
);
ack?.({ ack?.({
...rejectionAckFields, ...rejectionAckFields,
bidRequestId, bidRequestId,
@@ -263,7 +282,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
@SubscribeMessage('open-bidding') @SubscribeMessage('open-bidding')
public async handleOpenBidding( public async handleOpenBidding(
@ConnectedSocket() socket: Socket, @ConnectedSocket() socket: AuctionSocket,
@MessageBody() payload: AuctionActionPayload, @MessageBody() payload: AuctionActionPayload,
@Ack() ack?: (response: Record<string, unknown>) => void, @Ack() ack?: (response: Record<string, unknown>) => void,
) { ) {
@@ -292,7 +311,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
@SubscribeMessage('sold') @SubscribeMessage('sold')
public async handleSold( public async handleSold(
@ConnectedSocket() socket: Socket, @ConnectedSocket() socket: AuctionSocket,
@MessageBody() payload: SoldPayload, @MessageBody() payload: SoldPayload,
@Ack() ack?: (response: Record<string, unknown>) => void, @Ack() ack?: (response: Record<string, unknown>) => void,
) { ) {
@@ -322,7 +341,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
@SubscribeMessage('next') @SubscribeMessage('next')
public async handleNext( public async handleNext(
@ConnectedSocket() socket: Socket, @ConnectedSocket() socket: AuctionSocket,
@MessageBody() payload: AuctionActionPayload, @MessageBody() payload: AuctionActionPayload,
@Ack() ack?: (response: Record<string, unknown>) => void, @Ack() ack?: (response: Record<string, unknown>) => void,
) { ) {
@@ -351,7 +370,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
@SubscribeMessage('passed') @SubscribeMessage('passed')
public async handlePassed( public async handlePassed(
@ConnectedSocket() socket: Socket, @ConnectedSocket() socket: AuctionSocket,
@MessageBody() payload: AuctionActionPayload, @MessageBody() payload: AuctionActionPayload,
@Ack() ack?: (response: Record<string, unknown>) => void, @Ack() ack?: (response: Record<string, unknown>) => void,
) { ) {
@@ -380,7 +399,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
@SubscribeMessage('chat-message') @SubscribeMessage('chat-message')
public async handleChatMessage( public async handleChatMessage(
@ConnectedSocket() socket: Socket, @ConnectedSocket() socket: AuctionSocket,
@MessageBody() payload: ChatMessagePayload, @MessageBody() payload: ChatMessagePayload,
) { ) {
const matchId = this.requireJoinedMatchId(socket); 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); const matchId = this.getSocketMatchId(socket);
if (!matchId) { if (!matchId) {
this.emitError(socket, 'Join a match room before sending events.'); this.emitError(socket, 'Join a match room before sending events.');
@@ -415,11 +434,9 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
return matchId; return matchId;
} }
private consumeBidRateLimit(socket: Socket): boolean { private consumeBidRateLimit(socket: AuctionSocket): boolean {
const currentTimestampMS = Date.now(); const currentTimestampMS = Date.now();
const previousState = socket.data.auctionBidRateLimit as const previousState = socket.data.auctionBidRateLimit;
| BidRateLimitState
| undefined;
if ( if (
!previousState || !previousState ||
currentTimestampMS - previousState.windowStartedAtTimestampMS >= currentTimestampMS - previousState.windowStartedAtTimestampMS >=
@@ -437,10 +454,8 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
return previousState.count <= BID_RATE_LIMIT_MAX_REQUESTS_PER_WINDOW; return previousState.count <= BID_RATE_LIMIT_MAX_REQUESTS_PER_WINDOW;
} }
private getSocketMatchId(socket: Socket): string | undefined { private getSocketMatchId(socket: AuctionSocket): string | undefined {
return typeof socket.data.matchId === 'string' return socket.data.matchId;
? socket.data.matchId
: undefined;
} }
private toAuctionActionRequest(payload?: AuctionActionPayload) { private toAuctionActionRequest(payload?: AuctionActionPayload) {
@@ -464,8 +479,9 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
}; };
} }
private readHandshakeUserId(socket: Socket): string | undefined { private readHandshakeUserId(socket: AuctionSocket): string | undefined {
const authUserId = socket.handshake.auth['x-auth-user-id']; const handshakeAuth = socket.handshake.auth as Record<string, unknown>;
const authUserId = handshakeAuth['x-auth-user-id'];
if (typeof authUserId === 'string') return authUserId; if (typeof authUserId === 'string') return authUserId;
const header = socket.handshake.headers['x-auth-user-id']; const header = socket.handshake.headers['x-auth-user-id'];
@@ -473,16 +489,16 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
} }
private resolveSocketUserId( private resolveSocketUserId(
socket: Socket, socket: AuctionSocket,
): mongoose.Types.ObjectId | undefined { ): mongoose.Types.ObjectId | undefined {
return (socket.data.user as UserDocument | undefined)?._id; return socket.data.user?._id;
} }
private resolveChatDisplayName( private resolveChatDisplayName(
socket: Socket, socket: AuctionSocket,
fallbackDisplayName?: string, fallbackDisplayName?: string,
): string { ): string {
const user = socket.data.user as UserDocument | undefined; const user = socket.data.user;
const primaryRiotAccount = const primaryRiotAccount =
user?.riotAccounts.find((entry) => entry.isPrimary) ?? user?.riotAccounts.find((entry) => entry.isPrimary) ??
user?.riotAccounts[0]; user?.riotAccounts[0];
@@ -495,14 +511,14 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
if (user?.kakaoTalkNickname) return user.kakaoTalkNickname; if (user?.kakaoTalkNickname) return user.kakaoTalkNickname;
if (user?.discordNickname) return user.discordNickname; 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?.displayName) return identity.displayName;
if (identity?.email) return identity.email; if (identity?.email) return identity.email;
return fallbackDisplayName ?? '관전자'; return fallbackDisplayName ?? '관전자';
} }
private async authenticateSocket(socket: Socket): Promise<void> { private async authenticateSocket(socket: AuctionSocket): Promise<void> {
const fallback = await this.authService.resolveDevUserById( const fallback = await this.authService.resolveDevUserById(
this.readHandshakeUserId(socket), this.readHandshakeUserId(socket),
); );
@@ -532,14 +548,20 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
}); });
} }
private readHandshakeToken(socket: Socket): string | undefined { private readHandshakeToken(socket: AuctionSocket): string | undefined {
const authToken = socket.handshake.auth.token; const handshakeAuth = socket.handshake.auth as Record<string, unknown>;
const authToken = handshakeAuth.token;
if (typeof authToken === 'string' && authToken.trim()) { if (typeof authToken === 'string' && authToken.trim()) {
return authToken.trim().replace(/^Bearer\s+/i, ''); return authToken.trim().replace(/^Bearer\s+/i, '');
} }
const header = socket.handshake.headers.authorization; const header: unknown = socket.handshake.headers.authorization;
const authorization = Array.isArray(header) ? header[0] : header; const authorization =
typeof header === 'string'
? header
: Array.isArray(header) && typeof header[0] === 'string'
? header[0]
: undefined;
if (authorization?.startsWith('Bearer ')) { if (authorization?.startsWith('Bearer ')) {
return authorization.slice('Bearer '.length).trim(); return authorization.slice('Bearer '.length).trim();
} }
@@ -547,10 +569,11 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
} }
private async resolveSocketUserForMatch( private async resolveSocketUserForMatch(
socket: Socket, socket: AuctionSocket,
matchId: string, matchId: string,
): Promise<void> { ): Promise<void> {
if (socket.data.user || !socket.data.identity) return; if (socket.data.user || !socket.data.identity) return;
const identity = socket.data.identity;
const MatchModel = await this.connectionService.getModel('match'); const MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findById(matchId).select({ const match = await MatchModel.findById(matchId).select({
@@ -559,10 +582,11 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
if (!match) return; if (!match) return;
const UserModel = await this.connectionService.getModel('user'); const UserModel = await this.connectionService.getModel('user');
socket.data.user = await UserModel.findOne({ const user = await UserModel.findOne({
communityId: match.communityId, communityId: match.communityId,
identityId: (socket.data.identity as IdentityDocument)._id, identityId: identity._id,
}).exec(); }).exec();
socket.data.user = user ?? undefined;
} }
private requireStringClaim(payload: JWTPayload, key: string): string { 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); 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', { socket.emit('chat-history', {
messages: (auction.chatMessages ?? []).map((message) => messages: (auction.chatMessages ?? []).map((message) =>
this.serializeChatMessage(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); this.emitError(socket, this.resolveErrorPayload(error).message);
} }
private emitError(socket: Socket, message: string) { private emitError(socket: AuctionSocket, message: string) {
socket.emit('error', { message }); socket.emit('error', { message });
} }
private serializeAuction(auction: AuctionStateResponse) { private serializeAuction(
return JSON.parse(JSON.stringify(auction)); 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, bidDelta: Record<string, unknown> | null,
): Record<string, unknown> | null { ): Record<string, unknown> | null {
if (!bidDelta || !('bidServerTiming' in bidDelta)) return bidDelta; if (!bidDelta || !('bidServerTiming' in bidDelta)) return bidDelta;
const { bidServerTiming: _bidServerTiming, ...publicBidDelta } = bidDelta; const publicBidDelta = { ...bidDelta };
delete publicBidDelta.bidServerTiming;
return publicBidDelta; return publicBidDelta;
} }
@@ -729,10 +759,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
auction: AuctionStateResponse, auction: AuctionStateResponse,
bidRequestId?: string, bidRequestId?: string,
): Record<string, unknown> | null { ): Record<string, unknown> | null {
const serialized = this.serializeAuction(auction) as Record< const serialized = this.serializeAuction(auction);
string,
unknown
>;
const revision = Number(serialized.revision); const revision = Number(serialized.revision);
const currentHighestBidPointAmount = Number( const currentHighestBidPointAmount = Number(
serialized.currentHighestBidPointAmount ?? serialized.currentBid, serialized.currentHighestBidPointAmount ?? serialized.currentBid,
@@ -747,11 +774,13 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
? Date.parse(serialized.currentDeadline) ? Date.parse(serialized.currentDeadline)
: 0), : 0),
); );
const redisBidHistory = Array.isArray(serialized.auctionBidHistory) const redisBidHistory: unknown[] = Array.isArray(
? serialized.auctionBidHistory serialized.auctionBidHistory,
)
? (serialized.auctionBidHistory as unknown[])
: []; : [];
const legacyBidHistory = Array.isArray(serialized.bids) const legacyBidHistory: unknown[] = Array.isArray(serialized.bids)
? serialized.bids ? (serialized.bids as unknown[])
: []; : [];
const auctionBidHistoryEntry = const auctionBidHistoryEntry =
redisBidHistory[redisBidHistory.length - 1] ?? redisBidHistory[redisBidHistory.length - 1] ??
@@ -810,7 +839,12 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
}; };
} }
private serializeChatMessage(message: AuctionChatMessage) { private serializeChatMessage(
return JSON.parse(JSON.stringify(message)); 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,8 +158,7 @@ describe('AuctionService', () => {
it('rejects non-positive or fractional bid amounts before loading auction state', async () => { it('rejects non-positive or fractional bid amounts before loading auction state', async () => {
const matchId = new mongoose.Types.ObjectId(); const matchId = new mongoose.Types.ObjectId();
const auctionFindOne = jest.fn(); const auctionFindOne = jest.fn();
const { service, auctionRedisCommandService, auctionRedisService } = const { service, auctionRedisCommandService } = createService({
createService({
auction: { auction: {
findOne: auctionFindOne, findOne: auctionFindOne,
}, },
@@ -151,7 +151,7 @@ export class AuctionRedisStateReaderService {
revision: number; revision: number;
}, },
shouldForceAuctionStateResync: options.shouldForceAuctionStateResync, shouldForceAuctionStateResync: options.shouldForceAuctionStateResync,
structureState: JSON.parse(structureStateJson) as Record<string, unknown>, structureState: parseJsonRecord(structureStateJson),
}); });
view.matchId = matchId; view.matchId = matchId;
if (options.includeInternalLiveStateFields) { if (options.includeInternalLiveStateFields) {
@@ -170,12 +170,9 @@ export class AuctionRedisStateReaderService {
if (typeof structureStateJson !== 'string' || !structureStateJson) { if (typeof structureStateJson !== 'string' || !structureStateJson) {
return undefined; return undefined;
} }
const structureState = JSON.parse(structureStateJson) as Record< const structureState = parseJsonRecord(structureStateJson);
string, const auctionTeams: unknown[] = Array.isArray(structureState.auctionTeams)
unknown ? (structureState.auctionTeams as unknown[])
>;
const auctionTeams = Array.isArray(structureState.auctionTeams)
? structureState.auctionTeams
: []; : [];
const bidderTeam = auctionTeams.find((entry) => { const bidderTeam = auctionTeams.find((entry) => {
if (!entry || typeof entry !== 'object') return false; if (!entry || typeof entry !== 'object') return false;
@@ -192,6 +189,13 @@ function stringValue(value: unknown): string | undefined {
return typeof value === 'string' && value ? value : 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( function parseHashReply(
reply: unknown, reply: unknown,
options: { includeInternalLiveStateFields?: boolean } = {}, options: { includeInternalLiveStateFields?: boolean } = {},
@@ -74,9 +74,11 @@ async function readFirstSecret(
const logger = new Logger('AuctionRedisClient'); const logger = new Logger('AuctionRedisClient');
const client = createClient(auctionRedisOptions); const client = createClient(auctionRedisOptions);
client.on('error', (error) => { client.on('error', (error: unknown) => {
logger.error( 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; if (!isNoscriptError(error)) throw error;
} }
const loadedSha = String( const loadedShaReply = await this.client.sendCommand([
await this.client.sendCommand(['SCRIPT', 'LOAD', params.script]), '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( return (await this.client.sendCommand(
buildEvalShaCommand(loadedSha, params.keys, params.values), buildEvalShaCommand(loadedSha, params.keys, params.values),
)) as T; )) as T;
@@ -111,7 +117,7 @@ export class AuctionRedisService implements OnModuleDestroy {
token: string, token: string,
ttlMS: number, ttlMS: number,
): Promise<boolean> { ): Promise<boolean> {
const result = await this.client.sendCommand([ const result = await this.client.sendCommand<string | null>([
'SET', 'SET',
key, key,
token, token,
@@ -119,7 +125,7 @@ export class AuctionRedisService implements OnModuleDestroy {
String(ttlMS), String(ttlMS),
'NX', 'NX',
]); ]);
return String(result) === 'OK'; return result === 'OK';
} }
public async releaseTokenLock(key: string, token: string): Promise<boolean> { public async releaseTokenLock(key: string, token: string): Promise<boolean> {
@@ -78,9 +78,7 @@ export function assembleAuctionViewFromRedisState(
return { return {
...params.structureState, ...params.structureState,
...params.liveState, ...params.liveState,
auctionBidHistory: params.auctionBidHistoryEntries.map((entry) => auctionBidHistory: params.auctionBidHistoryEntries.map(parseJsonValue),
JSON.parse(entry),
),
canPlaceBidInCurrentBidRound: !isExpiring, canPlaceBidInCurrentBidRound: !isExpiring,
currentServerTimestampMS: params.currentServerTimestampMS, currentServerTimestampMS: params.currentServerTimestampMS,
isAuctionStateTransitionInProgress: isExpiring, 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( export function buildHydrateAuctionStateScriptInvocation(
keys: AuctionRedisKeys, keys: AuctionRedisKeys,
input: HydrateAuctionStateScriptInput, input: HydrateAuctionStateScriptInput,
+2 -3
View File
@@ -26,8 +26,7 @@ export class JwtAuthGuard implements CanActivate {
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED, METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
[context.getHandler(), context.getClass()], [context.getHandler(), context.getClass()],
); );
const authz = request.headers?.authorization; const authzHeader = request.get('authorization');
const authzHeader = Array.isArray(authz) ? authz[0] : authz;
if (!authzHeader) { if (!authzHeader) {
const fallback = const fallback =
@@ -74,7 +73,7 @@ export class JwtAuthGuard implements CanActivate {
private pickIdPFromToken(token: string): IdentityProviderName { private pickIdPFromToken(token: string): IdentityProviderName {
try { try {
const { iss } = decodeJwt(token) as { iss?: string }; const { iss } = decodeJwt(token);
if (!iss) { if (!iss) {
throw new Error('Token has no issuer (iss) claim'); throw new Error('Token has no issuer (iss) claim');
} }
+32 -9
View File
@@ -35,11 +35,13 @@ export class JwtService {
throw new Error('Empty token'); throw new Error('Empty token');
} }
if (identityProvider !== 'MICROSOFT_ENTRAID') { const provider =
throw new Error(`Identity provider not configured: ${identityProvider}`); identityProvider === 'MICROSOFT_ENTRAID'
? await this.getEntraConfig()
: undefined;
if (!provider) {
throw new Error('Identity provider not configured.');
} }
const provider = await this.getEntraConfig();
const result = await jwtVerify(token, provider.jwks, { const result = await jwtVerify(token, provider.jwks, {
issuer: provider.issuer, issuer: provider.issuer,
audience: provider.audience, audience: provider.audience,
@@ -48,14 +50,22 @@ export class JwtService {
}); });
const { payload, protectedHeader } = result; const { payload, protectedHeader } = result;
if (!provider.allowedAlgs.includes(protectedHeader.alg as string)) { if (!provider.allowedAlgs.includes(protectedHeader.alg)) {
throw new Error(`Unexpected alg: ${protectedHeader.alg}`); throw new Error(`Unexpected alg: ${protectedHeader.alg}`);
} }
if (payload.ver && payload.ver !== '2.0') { if (
throw new Error(`Unsupported Entra token version: ${payload.ver}`); payload.ver !== undefined &&
(typeof payload.ver !== 'string' || payload.ver !== '2.0')
) {
throw new Error(
`Unsupported Entra token version: ${formatClaimValue(payload.ver)}`,
);
} }
if (payload.tid && payload.tid !== provider.tenantId) { if (
throw new Error(`Unexpected tenant: ${payload.tid}`); payload.tid !== undefined &&
(typeof payload.tid !== 'string' || payload.tid !== provider.tenantId)
) {
throw new Error(`Unexpected tenant: ${formatClaimValue(payload.tid)}`);
} }
return result; return result;
@@ -98,3 +108,16 @@ export class JwtService {
return this.entraConfig; return this.entraConfig;
} }
} }
function formatClaimValue(value: unknown): string {
if (
typeof value === 'string' ||
typeof value === 'number' ||
typeof value === 'boolean' ||
typeof value === 'bigint'
) {
return String(value);
}
if (value === null) return 'null';
return JSON.stringify(value) ?? typeof value;
}
+2 -2
View File
@@ -7,7 +7,7 @@ import {
} from '@nestjs/common'; } from '@nestjs/common';
import { Reflector } from '@nestjs/core'; import { Reflector } from '@nestjs/core';
import type { Request } from 'express'; import type { Request } from 'express';
import { CommunityRole, UserDocument } from '../global/database/schema'; import type { CommunityRole } from '../global/database/schema';
import { ROLES_KEY } from './roles.decorator'; import { ROLES_KEY } from './roles.decorator';
import './auth-request'; import './auth-request';
@@ -23,7 +23,7 @@ export class RolesGuard implements CanActivate {
if (!requiredRoles || requiredRoles.length === 0) return true; if (!requiredRoles || requiredRoles.length === 0) return true;
const req = context.switchToHttp().getRequest<Request>(); const req = context.switchToHttp().getRequest<Request>();
const user = req.user as UserDocument | undefined; const user = req.user;
if (!user && req.identity) { if (!user && req.identity) {
throw new ForbiddenException('No membership in this community.'); throw new ForbiddenException('No membership in this community.');
} }
@@ -34,16 +34,29 @@ export class CommunityStatsCacheService {
let deleted = 0; let deleted = 0;
do { do {
const reply = (await client.sendCommand([ const reply = await client.sendCommand([
'SCAN', 'SCAN',
cursor, cursor,
'MATCH', 'MATCH',
match, match,
'COUNT', 'COUNT',
'100', '100',
])) as [string, string[]]; ]);
cursor = reply[0]; if (!Array.isArray(reply)) {
const keys = reply[1] ?? []; throw new Error('Redis SCAN returned an invalid response.');
}
const values = reply as unknown[];
const nextCursor = values[0];
const rawKeys = values[1];
if (typeof nextCursor !== 'string') {
throw new Error('Redis SCAN returned an invalid cursor.');
}
cursor = nextCursor;
const keys = Array.isArray(rawKeys)
? (rawKeys as unknown[]).filter(
(key): key is string => typeof key === 'string',
)
: [];
if (keys.length > 0) { if (keys.length > 0) {
deleted += await client.del(keys); deleted += await client.del(keys);
} }
@@ -125,8 +125,8 @@ describe('MatchStatsRepository', () => {
if ( if (
stored && stored &&
stored.sourceCompetitionId?.equals(fragment.sourceCompetitionId!) && stored.sourceCompetitionId?.equals(fragment.sourceCompetitionId) &&
stored.sourceRevision! <= fragment.sourceRevision! stored.sourceRevision <= fragment.sourceRevision
) { ) {
stored = fragment; stored = fragment;
return { matchedCount: 1, upsertedCount: 0 }; return { matchedCount: 1, upsertedCount: 0 };
@@ -485,11 +485,7 @@ function createHarness(
let competitionCall = 0; let competitionCall = 0;
const competitionModel = { const competitionModel = {
findOneAndUpdate: jest.fn( findOneAndUpdate: jest.fn(
( (_filter: unknown, update: { $setOnInsert: InsertPayload }) => {
_filter: unknown,
update: { $setOnInsert: InsertPayload },
_queryOptions: unknown,
) => {
insertedPayloads.push(update.$setOnInsert); insertedPayloads.push(update.$setOnInsert);
const selected = options.competitionResults?.[competitionCall++]; const selected = options.competitionResults?.[competitionCall++];
if (selected instanceof Error) return rejectedQuery(selected); if (selected instanceof Error) return rejectedQuery(selected);
@@ -105,7 +105,7 @@ describe('DakaoUserService', () => {
tagLine: 'KR2', tagLine: 'KR2',
isPrimary: false, isPrimary: false,
}); });
expect((result.user.riotAccounts as RiotAccount[])[0]).toMatchObject({ expect(result.user.riotAccounts[0]).toMatchObject({
puuid: 'puuid-1', puuid: 'puuid-1',
isPrimary: true, isPrimary: true,
}); });
@@ -87,7 +87,7 @@ export class DakaoUserService {
if (!community) { if (!community) {
throw new DakaoUserError('community_not_found', dakaoProjectId); throw new DakaoUserError('community_not_found', dakaoProjectId);
} }
return community._id as mongoose.Types.ObjectId; return community._id;
} }
public async upsertUser(params: { public async upsertUser(params: {
@@ -301,7 +301,7 @@ export class DakaoSubscriber implements OnModuleInit {
text: text:
index === this.usageCommands.length - 1 index === this.usageCommands.length - 1
? ` ${command}` ? ` ${command}`
: ` ${command} \n`, : ` ${command}\u3000\n`,
} as const, } as const,
]); ]);
} }
@@ -20,8 +20,8 @@ export class IdempotencyCache {
public remember(key: string): void { public remember(key: string): void {
this.evictExpired(); this.evictExpired();
if (this.entries.size >= MAX_ENTRIES) { if (this.entries.size >= MAX_ENTRIES) {
const oldestKey = this.entries.keys().next().value; const oldestKey: unknown = this.entries.keys().next().value;
if (oldestKey !== undefined) this.entries.delete(oldestKey); if (typeof oldestKey === 'string') this.entries.delete(oldestKey);
} }
this.entries.set(key, Date.now() + TTL_MS); this.entries.set(key, Date.now() + TTL_MS);
} }
@@ -144,7 +144,7 @@ export function buildDoubleEliminationBracket(
teamIndex, teamIndex,
})); }));
const bracket: DoubleEliminationBracket = { const bracket: DoubleEliminationBracket = {
teamCount: seededTeamIndexes.length as 4 | 8, teamCount: seededTeamIndexes.length,
resetFinalEnabled: options.resetFinalEnabled, resetFinalEnabled: options.resetFinalEnabled,
resetFinalCreated: false, resetFinalCreated: false,
seeds, seeds,
@@ -1,4 +1,4 @@
import { DynamicModule, Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { ConnectionService } from './connection.service'; import { ConnectionService } from './connection.service';
@Module({ @Module({
@@ -330,6 +330,9 @@ function legacyAuctionLifecycleId(value: unknown): string {
function stringifyId(value: unknown): string | undefined { function stringifyId(value: unknown): string | undefined {
if (value === undefined || value === null) return undefined; if (value === undefined || value === null) return undefined;
// MongoDB ObjectId and migration fixture IDs intentionally rely on their
// stable string representation.
// eslint-disable-next-line @typescript-eslint/no-base-to-string
return typeof value === 'string' ? value : String(value); return typeof value === 'string' ? value : String(value);
} }
@@ -1,11 +1,4 @@
type TournamentCodeState = type TournamentCodeState = string;
| 'available'
| 'reserved'
| 'used'
| 'released'
| 'expired'
| 'voided'
| string;
type AnyDoc = Record<string, unknown> & { _id: unknown }; type AnyDoc = Record<string, unknown> & { _id: unknown };
type IndexKey = Record<string, 1 | -1>; type IndexKey = Record<string, 1 | -1>;
@@ -36,7 +29,7 @@ interface MigrationCollection {
$unset?: Record<string, ''>; $unset?: Record<string, ''>;
}, },
options?: { ordered?: boolean }, options?: { ordered?: boolean },
): Promise<{ matchedCount?: number; modifiedCount?: number } | unknown>; ): Promise<unknown>;
indexes?(): Promise<MigrationIndex[]>; indexes?(): Promise<MigrationIndex[]>;
dropIndex?(name: string): Promise<unknown>; dropIndex?(name: string): Promise<unknown>;
createIndex?( createIndex?(
@@ -516,15 +509,17 @@ function summarizeGroups(
function summarizeCode(doc: TournamentCodeDoc): TournamentCodeDuplicateSummary { function summarizeCode(doc: TournamentCodeDoc): TournamentCodeDuplicateSummary {
return { return {
bracketMatchId: bracketMatchId:
doc.bracketMatchId === undefined ? undefined : String(doc.bracketMatchId), doc.bracketMatchId === undefined
code: doc.code === undefined ? undefined : String(doc.code), ? undefined
: stringifyId(doc.bracketMatchId),
code: doc.code === undefined ? undefined : stringifyId(doc.code),
gameNumber: gameNumber:
doc.gameNumber === undefined ? undefined : String(doc.gameNumber), doc.gameNumber === undefined ? undefined : stringifyId(doc.gameNumber),
id: stringifyId(doc._id) ?? '', id: stringifyId(doc._id) ?? '',
matchId: doc.matchId === undefined ? undefined : stringifyId(doc.matchId), matchId: doc.matchId === undefined ? undefined : stringifyId(doc.matchId),
riotMatchId: riotMatchId:
doc.riotMatchId === undefined ? undefined : String(doc.riotMatchId), doc.riotMatchId === undefined ? undefined : stringifyId(doc.riotMatchId),
state: doc.state === undefined ? undefined : String(doc.state), state: doc.state,
}; };
} }
@@ -749,16 +744,19 @@ function readModifiedCount(result: unknown): number {
} }
function hasField(doc: Record<string, unknown>, key: string): boolean { function hasField(doc: Record<string, unknown>, key: string): boolean {
return Object.prototype.hasOwnProperty.call(doc, key); return Object.hasOwn(doc, key);
} }
function stringifyKeyPart(value: unknown): string { function stringifyKeyPart(value: unknown): string {
if (value === null) return '<null>'; if (value === null) return '<null>';
if (value === undefined) return '<undefined>'; if (value === undefined) return '<undefined>';
return stringifyId(value) ?? String(value); return stringifyId(value) ?? '<unknown>';
} }
function stringifyId(value: unknown): string | undefined { function stringifyId(value: unknown): string | undefined {
if (value === undefined || value === null) return undefined; if (value === undefined || value === null) return undefined;
// MongoDB ObjectId and migration fixture IDs intentionally rely on their
// stable string representation.
// eslint-disable-next-line @typescript-eslint/no-base-to-string
return typeof value === 'string' ? value : String(value); return typeof value === 'string' ? value : String(value);
} }
@@ -1,5 +1,4 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import fs from 'fs/promises';
import { connect } from 'nats'; import { connect } from 'nats';
import type { NatsConnection } from 'nats'; import type { NatsConnection } from 'nats';
import { SecretModule } from '../secret/secret.module'; import { SecretModule } from '../secret/secret.module';
@@ -38,27 +38,24 @@ export function applyMongoosePerformancePlugin(schema: mongoose.Schema): void {
const markedSchema = schema as SchemaWithPerformanceMarker; const markedSchema = schema as SchemaWithPerformanceMarker;
if (markedSchema[PERFORMANCE_PLUGIN_APPLIED]) return; if (markedSchema[PERFORMANCE_PLUGIN_APPLIED]) return;
markedSchema[PERFORMANCE_PLUGIN_APPLIED] = true; markedSchema[PERFORMANCE_PLUGIN_APPLIED] = true;
const hookableSchema = schema as any;
hookableSchema.pre(QUERY_OPERATION_REGEX, function () { schema.pre(QUERY_OPERATION_REGEX, function () {
const query = this as QueryWithPerformanceState; const query = this as QueryWithPerformanceState;
query[QUERY_PERFORMANCE_START] = process.hrtime.bigint(); query[QUERY_PERFORMANCE_START] = process.hrtime.bigint();
query[QUERY_PERFORMANCE_RECORDED] = false; query[QUERY_PERFORMANCE_RECORDED] = false;
}); });
hookableSchema.post(QUERY_OPERATION_REGEX, function (result: unknown) { schema.post(QUERY_OPERATION_REGEX, function (result: unknown) {
recordQueryPerformance( recordQueryPerformance(this as QueryWithPerformanceState, result);
this as unknown as QueryWithPerformanceState,
result,
);
}); });
hookableSchema.post( schema.post(
QUERY_OPERATION_REGEX, QUERY_OPERATION_REGEX,
{ errorHandler: true },
function ( function (
error: unknown, error: Error,
_result: unknown, _result: unknown,
next: (error: unknown) => void, next: (error?: mongoose.CallbackError) => void,
) { ) {
recordQueryPerformance( recordQueryPerformance(
this as unknown as QueryWithPerformanceState, this as unknown as QueryWithPerformanceState,
@@ -69,22 +66,23 @@ export function applyMongoosePerformancePlugin(schema: mongoose.Schema): void {
}, },
); );
hookableSchema.pre('aggregate', function () { schema.pre('aggregate', function () {
const aggregate = this as AggregateWithPerformanceState; const aggregate = this as AggregateWithPerformanceState;
aggregate[QUERY_PERFORMANCE_START] = process.hrtime.bigint(); aggregate[QUERY_PERFORMANCE_START] = process.hrtime.bigint();
aggregate[QUERY_PERFORMANCE_RECORDED] = false; aggregate[QUERY_PERFORMANCE_RECORDED] = false;
}); });
hookableSchema.post('aggregate', function (result: unknown) { schema.post('aggregate', function (result: unknown) {
recordAggregatePerformance(this as AggregateWithPerformanceState, result); recordAggregatePerformance(this as AggregateWithPerformanceState, result);
}); });
hookableSchema.post( schema.post(
'aggregate', 'aggregate',
{ errorHandler: true },
function ( function (
error: unknown, error: Error,
_result: unknown, _result: unknown,
next: (error: unknown) => void, next: (error?: mongoose.CallbackError) => void,
) { ) {
recordAggregatePerformance( recordAggregatePerformance(
this as AggregateWithPerformanceState, this as AggregateWithPerformanceState,
@@ -56,16 +56,11 @@ export class DistributedLockService {
const lockOwnershipToken = options.lockOwnershipToken ?? randomUUID(); const lockOwnershipToken = options.lockOwnershipToken ?? randomUUID();
const result = await this.redisService const result = await this.redisService
.raw() .raw()
.sendCommand([ .sendCommand<
'SET', string | null
options.lockKey, >(['SET', options.lockKey, lockOwnershipToken, 'NX', 'PX', String(options.lockExpirationDurationMilliseconds)]);
lockOwnershipToken,
'NX',
'PX',
String(options.lockExpirationDurationMilliseconds),
]);
if (String(result) !== 'OK') return null; if (result !== 'OK') return null;
return { return {
lockKey: options.lockKey, lockKey: options.lockKey,
lockOwnershipToken, lockOwnershipToken,
@@ -124,7 +119,7 @@ export class DistributedLockService {
await this.releaseLockIfOwned(lockOwnership).catch((error: unknown) => { await this.releaseLockIfOwned(lockOwnership).catch((error: unknown) => {
this.logger.warn( this.logger.warn(
`Failed to release distributed lock ${lockOwnership.lockKey}: ${ `Failed to release distributed lock ${lockOwnership.lockKey}: ${
error instanceof Error ? error.message : error error instanceof Error ? error.message : String(error)
}`, }`,
); );
}); });
@@ -143,8 +138,7 @@ export class DistributedLockService {
const lockOwnership = await this.acquireLockWithRetry(options); const lockOwnership = await this.acquireLockWithRetry(options);
if (!lockOwnership) return null; if (!lockOwnership) return null;
let lockRenewalTimer: NodeJS.Timeout | undefined; const lockRenewalTimer = setInterval(() => {
lockRenewalTimer = setInterval(() => {
void this.extendLockIfOwned(lockOwnership).then((wasExtended) => { void this.extendLockIfOwned(lockOwnership).then((wasExtended) => {
if (wasExtended) return; if (wasExtended) return;
this.logger.warn( this.logger.warn(
@@ -157,11 +151,11 @@ export class DistributedLockService {
try { try {
return await operation(lockOwnership); return await operation(lockOwnership);
} finally { } finally {
if (lockRenewalTimer) clearInterval(lockRenewalTimer); clearInterval(lockRenewalTimer);
await this.releaseLockIfOwned(lockOwnership).catch((error: unknown) => { await this.releaseLockIfOwned(lockOwnership).catch((error: unknown) => {
this.logger.warn( this.logger.warn(
`Failed to release distributed lock ${lockOwnership.lockKey}: ${ `Failed to release distributed lock ${lockOwnership.lockKey}: ${
error instanceof Error ? error.message : error error instanceof Error ? error.message : String(error)
}`, }`,
); );
}); });
@@ -54,8 +54,12 @@ async function readFirstSecret(
}), }),
); );
client.on('error', (error) => { client.on('error', (error: unknown) => {
logger.error(`Redis client error: ${error?.message ?? error}`); logger.error(
`Redis client error: ${
error instanceof Error ? error.message : String(error)
}`,
);
}); });
await client.connect(); await client.connect();
@@ -35,11 +35,14 @@ interface RawStreamReadResult {
function normalizeStreamFields(fields: unknown): Record<string, string> { function normalizeStreamFields(fields: unknown): Record<string, string> {
if (Array.isArray(fields)) { if (Array.isArray(fields)) {
const values = fields as unknown[];
const normalized: Record<string, string> = {}; const normalized: Record<string, string> = {};
for (let index = 0; index < fields.length; index += 2) { for (let index = 0; index < values.length; index += 2) {
const key = fields[index]; const key = values[index];
if (key === undefined) continue; if (key === undefined) continue;
normalized[String(key)] = String(fields[index + 1] ?? ''); normalized[redisValueToString(key)] = redisValueToString(
values[index + 1],
);
} }
return normalized; return normalized;
} }
@@ -260,10 +263,10 @@ export class RedisService implements OnModuleDestroy {
rawMessage: unknown, rawMessage: unknown,
): StreamEntry | null { ): StreamEntry | null {
if (Array.isArray(rawMessage)) { if (Array.isArray(rawMessage)) {
const [id, fields] = rawMessage; const [id, fields] = rawMessage as unknown[];
if (id === undefined) return null; if (id === undefined) return null;
return { return {
id: String(id), id: redisValueToString(id),
message: normalizeStreamFields(fields), message: normalizeStreamFields(fields),
}; };
} }
@@ -291,3 +294,17 @@ export class RedisService implements OnModuleDestroy {
return null; return null;
} }
} }
function redisValueToString(value: unknown): string {
if (typeof value === 'string') return value;
if (
typeof value === 'number' ||
typeof value === 'boolean' ||
typeof value === 'bigint'
) {
return String(value);
}
if (Buffer.isBuffer(value)) return value.toString('utf8');
if (value === undefined || value === null) return '';
return JSON.stringify(value) ?? '';
}
@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/require-await, @typescript-eslint/unbound-method */
import { readFileSync } from 'node:fs'; import { readFileSync } from 'node:fs';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import type { CompetitionBootstrapService } from '../competition/competition-bootstrap.service'; import type { CompetitionBootstrapService } from '../competition/competition-bootstrap.service';
@@ -34,7 +34,7 @@ describe('MatchController participant access', () => {
it('requires an authenticated community member for the self-join route', () => { it('requires an authenticated community member for the self-join route', () => {
// Metadata must be read from the unbound prototype method itself. // Metadata must be read from the unbound prototype method itself.
// eslint-disable-next-line @typescript-eslint/unbound-method
const handler = MatchController.prototype.joinMatch; const handler = MatchController.prototype.joinMatch;
const roles = Reflect.getMetadata(ROLES_KEY, handler) as const roles = Reflect.getMetadata(ROLES_KEY, handler) as
| string[] | string[]
@@ -73,7 +73,7 @@ export class BackgroundRefreshScheduler
.catch((err: unknown) => { .catch((err: unknown) => {
this.logger.warn( this.logger.warn(
`Background refresh leader release failed: ${ `Background refresh leader release failed: ${
err instanceof Error ? err.message : err err instanceof Error ? err.message : String(err)
}`, }`,
); );
}); });
@@ -215,7 +215,7 @@ export class RiotJobQueueService {
public async promoteDueScheduledJobs(limit = 100): Promise<number> { public async promoteDueScheduledJobs(limit = 100): Promise<number> {
const client = this.redisService.raw(); const client = this.redisService.raw();
const raw = (await client.sendCommand([ const entries = await client.sendCommand<string[]>([
'ZRANGEBYSCORE', 'ZRANGEBYSCORE',
RIOT_JOB_SCHEDULED_ZSET, RIOT_JOB_SCHEDULED_ZSET,
'-inf', '-inf',
@@ -223,16 +223,15 @@ export class RiotJobQueueService {
'LIMIT', 'LIMIT',
'0', '0',
String(limit), String(limit),
])) as string[] | null; ]);
const entries = raw ?? [];
let promoted = 0; let promoted = 0;
for (const entry of entries) { for (const entry of entries) {
const removed = (await client.sendCommand([ const removed = await client.sendCommand<number>([
'ZREM', 'ZREM',
RIOT_JOB_SCHEDULED_ZSET, RIOT_JOB_SCHEDULED_ZSET,
entry, entry,
])) as number; ]);
if (removed !== 1) continue; if (removed !== 1) continue;
const job = this.parseScheduledJob(entry); const job = this.parseScheduledJob(entry);
if (!job) continue; if (!job) continue;
@@ -67,7 +67,7 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
.catch((error: unknown) => { .catch((error: unknown) => {
this.logger.warn( this.logger.warn(
`Failed to release Riot job worker leader lock: ${ `Failed to release Riot job worker leader lock: ${
error instanceof Error ? error.message : error error instanceof Error ? error.message : String(error)
}`, }`,
); );
}); });
@@ -31,10 +31,10 @@ export class RiotRefreshGateway {
private readonly logger = new Logger(RiotRefreshGateway.name); private readonly logger = new Logger(RiotRefreshGateway.name);
@SubscribeMessage('subscribe') @SubscribeMessage('subscribe')
public async handleSubscribe( public handleSubscribe(
@ConnectedSocket() socket: Socket, @ConnectedSocket() socket: Socket,
@MessageBody() payload: SubscribePayload, @MessageBody() payload: SubscribePayload,
) { ): void {
const rooms = this.resolveRooms(payload); const rooms = this.resolveRooms(payload);
if (rooms.length === 0) { if (rooms.length === 0) {
socket.emit('error', { message: 'Invalid riot refresh subscription.' }); socket.emit('error', { message: 'Invalid riot refresh subscription.' });
@@ -47,7 +47,7 @@ export class RiotRefreshGateway {
return; return;
} }
await Promise.all(rooms.map((room) => socket.join(room))); void socket.join(rooms);
socket.emit('subscribed', { rooms }); socket.emit('subscribed', { rooms });
} }
@@ -100,7 +100,7 @@ export class RiotRecentMatchesService {
} catch (error: unknown) { } catch (error: unknown) {
this.logger.warn( this.logger.warn(
`Skipping Riot match ${matchId} while syncing ${params.puuid}: ${ `Skipping Riot match ${matchId} while syncing ${params.puuid}: ${
error instanceof Error ? error.message : error error instanceof Error ? error.message : String(error)
}`, }`,
); );
} }
@@ -14,6 +14,7 @@ export class RiotWebhookController {
public captureTournamentWebhook(@Req() req: RiotWebhookRequest) { public captureTournamentWebhook(@Req() req: RiotWebhookRequest) {
const receivedAt = new Date().toISOString(); const receivedAt = new Date().toISOString();
const rawBodyText = req.rawBody?.toString('utf8') ?? null; const rawBodyText = req.rawBody?.toString('utf8') ?? null;
const body: unknown = req.body;
const logPayload = { const logPayload = {
receivedAt, receivedAt,
method: req.method, method: req.method,
@@ -25,7 +26,7 @@ export class RiotWebhookController {
headers: req.headers, headers: req.headers,
query: req.query, query: req.query,
params: req.params, params: req.params,
body: req.body, body,
rawBodyLength: req.rawBody?.length ?? null, rawBodyLength: req.rawBody?.length ?? null,
rawBodyText, rawBodyText,
}; };
@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import type { CompetitionResultSnapshot } from './competition-result.adapter'; import type { CompetitionResultSnapshot } from './competition-result.adapter';
import { CompetitionAssignmentProvisioner } from './competition-assignment.provisioner'; import { CompetitionAssignmentProvisioner } from './competition-assignment.provisioner';
@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import { Logger } from '@nestjs/common'; import { Logger } from '@nestjs/common';
import { CommunityStatsService } from '../community-stats/community-stats.service'; import { CommunityStatsService } from '../community-stats/community-stats.service';
@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import type { MatchDocument } from '../global/database/schema'; import type { MatchDocument } from '../global/database/schema';
import type { RiotMatchDto } from '../riot/riot.types'; import type { RiotMatchDto } from '../riot/riot.types';
@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import type { MatchDocument } from '../global/database/schema'; import type { MatchDocument } from '../global/database/schema';
import type { RiotMatchDto } from '../riot/riot.types'; import type { RiotMatchDto } from '../riot/riot.types';
@@ -485,7 +485,9 @@ function newRelicTransactionResultToRow(
hydratedDocsReturnedP95Budget: number; hydratedDocsReturnedP95Budget: number;
}, },
): EndpointReportRow | null { ): EndpointReportRow | null {
const parsed = parseTransactionName(String(result.facet ?? '')); const facet = result.facet;
if (typeof facet !== 'string') return null;
const parsed = parseTransactionName(facet);
if (!parsed) return null; if (!parsed) return null;
const row: EndpointReportRow = { const row: EndpointReportRow = {
@@ -419,15 +419,15 @@ async function main(): Promise<void> {
auctionRedisService, auctionRedisService,
); );
const dummyTournamentCodeService = { const dummyTournamentCodeService = {
releaseFromMatch: async () => undefined, releaseFromMatch: () => Promise.resolve(undefined),
reserveForMatch: async () => undefined, reserveForMatch: () => Promise.resolve(undefined),
}; };
const dummyTournamentResultService = { const dummyTournamentResultService = {
cancelPolling: async () => undefined, cancelPolling: () => Promise.resolve(undefined),
scheduleInitialPoll: async () => undefined, scheduleInitialPoll: () => Promise.resolve(undefined),
}; };
const dummySideEffectService = { const dummySideEffectService = {
mirrorMatchSideEffectStatus: async () => true, mirrorMatchSideEffectStatus: () => Promise.resolve(true),
}; };
const dummyEventBus = { const dummyEventBus = {
broadcastMatchSideEffect: () => undefined, broadcastMatchSideEffect: () => undefined,
@@ -436,7 +436,8 @@ async function main(): Promise<void> {
const auctionService = new AuctionService( const auctionService = new AuctionService(
connectionService, connectionService,
{ {
enrichRiotAccount: async () => ({ enrichRiotAccount: () =>
Promise.resolve({
account: null, account: null,
league: 'fresh', league: 'fresh',
masteries: 'fresh', masteries: 'fresh',
-1
View File
@@ -9,7 +9,6 @@ import { ConnectionService } from './modules/global/database/connection.service'
import type { import type {
ChampionMasteryEntry, ChampionMasteryEntry,
MatchParticipant, MatchParticipant,
MatchTeam,
Position, Position,
PositionPreference, PositionPreference,
RiotLane, RiotLane,