release/87 #3

Merged
dahyeon merged 3 commits from release/87 into main 2026-07-25 04:59:34 +00:00
42 changed files with 307 additions and 199 deletions
Showing only changes of commit fd1fa2366c - Show all commits

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-floating-promises': '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;
}
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;
}
+85 -51
View File
@@ -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,
+2 -3
View File
@@ -26,8 +26,7 @@ export class JwtAuthGuard implements CanActivate {
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
[context.getHandler(), context.getClass()],
);
const authz = request.headers?.authorization;
const authzHeader = Array.isArray(authz) ? authz[0] : authz;
const authzHeader = request.get('authorization');
if (!authzHeader) {
const fallback =
@@ -74,7 +73,7 @@ export class JwtAuthGuard implements CanActivate {
private pickIdPFromToken(token: string): IdentityProviderName {
try {
const { iss } = decodeJwt(token) as { iss?: string };
const { iss } = decodeJwt(token);
if (!iss) {
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');
}
if (identityProvider !== 'MICROSOFT_ENTRAID') {
throw new Error(`Identity provider not configured: ${identityProvider}`);
const provider =
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, {
issuer: provider.issuer,
audience: provider.audience,
@@ -48,14 +50,22 @@ export class JwtService {
});
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}`);
}
if (payload.ver && payload.ver !== '2.0') {
throw new Error(`Unsupported Entra token version: ${payload.ver}`);
if (
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) {
throw new Error(`Unexpected tenant: ${payload.tid}`);
if (
payload.tid !== undefined &&
(typeof payload.tid !== 'string' || payload.tid !== provider.tenantId)
) {
throw new Error(`Unexpected tenant: ${formatClaimValue(payload.tid)}`);
}
return result;
@@ -98,3 +108,16 @@ export class JwtService {
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';
import { Reflector } from '@nestjs/core';
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 './auth-request';
@@ -23,7 +23,7 @@ export class RolesGuard implements CanActivate {
if (!requiredRoles || requiredRoles.length === 0) return true;
const req = context.switchToHttp().getRequest<Request>();
const user = req.user as UserDocument | undefined;
const user = req.user;
if (!user && req.identity) {
throw new ForbiddenException('No membership in this community.');
}
@@ -34,16 +34,29 @@ export class CommunityStatsCacheService {
let deleted = 0;
do {
const reply = (await client.sendCommand([
const reply = await client.sendCommand([
'SCAN',
cursor,
'MATCH',
match,
'COUNT',
'100',
])) as [string, string[]];
cursor = reply[0];
const keys = reply[1] ?? [];
]);
if (!Array.isArray(reply)) {
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) {
deleted += await client.del(keys);
}
@@ -125,8 +125,8 @@ describe('MatchStatsRepository', () => {
if (
stored &&
stored.sourceCompetitionId?.equals(fragment.sourceCompetitionId!) &&
stored.sourceRevision! <= fragment.sourceRevision!
stored.sourceCompetitionId?.equals(fragment.sourceCompetitionId) &&
stored.sourceRevision <= fragment.sourceRevision
) {
stored = fragment;
return { matchedCount: 1, upsertedCount: 0 };
@@ -485,11 +485,7 @@ function createHarness(
let competitionCall = 0;
const competitionModel = {
findOneAndUpdate: jest.fn(
(
_filter: unknown,
update: { $setOnInsert: InsertPayload },
_queryOptions: unknown,
) => {
(_filter: unknown, update: { $setOnInsert: InsertPayload }) => {
insertedPayloads.push(update.$setOnInsert);
const selected = options.competitionResults?.[competitionCall++];
if (selected instanceof Error) return rejectedQuery(selected);
@@ -105,7 +105,7 @@ describe('DakaoUserService', () => {
tagLine: 'KR2',
isPrimary: false,
});
expect((result.user.riotAccounts as RiotAccount[])[0]).toMatchObject({
expect(result.user.riotAccounts[0]).toMatchObject({
puuid: 'puuid-1',
isPrimary: true,
});
@@ -87,7 +87,7 @@ export class DakaoUserService {
if (!community) {
throw new DakaoUserError('community_not_found', dakaoProjectId);
}
return community._id as mongoose.Types.ObjectId;
return community._id;
}
public async upsertUser(params: {
@@ -301,7 +301,7 @@ export class DakaoSubscriber implements OnModuleInit {
text:
index === this.usageCommands.length - 1
? ` ${command}`
: ` ${command} \n`,
: ` ${command}\u3000\n`,
} as const,
]);
}
@@ -20,8 +20,8 @@ export class IdempotencyCache {
public remember(key: string): void {
this.evictExpired();
if (this.entries.size >= MAX_ENTRIES) {
const oldestKey = this.entries.keys().next().value;
if (oldestKey !== undefined) this.entries.delete(oldestKey);
const oldestKey: unknown = this.entries.keys().next().value;
if (typeof oldestKey === 'string') this.entries.delete(oldestKey);
}
this.entries.set(key, Date.now() + TTL_MS);
}
@@ -144,7 +144,7 @@ export function buildDoubleEliminationBracket(
teamIndex,
}));
const bracket: DoubleEliminationBracket = {
teamCount: seededTeamIndexes.length as 4 | 8,
teamCount: seededTeamIndexes.length,
resetFinalEnabled: options.resetFinalEnabled,
resetFinalCreated: false,
seeds,
@@ -1,4 +1,4 @@
import { DynamicModule, Module } from '@nestjs/common';
import { Module } from '@nestjs/common';
import { ConnectionService } from './connection.service';
@Module({
@@ -330,6 +330,9 @@ function legacyAuctionLifecycleId(value: unknown): string {
function stringifyId(value: unknown): string | 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);
}
@@ -1,11 +1,4 @@
type TournamentCodeState =
| 'available'
| 'reserved'
| 'used'
| 'released'
| 'expired'
| 'voided'
| string;
type TournamentCodeState = string;
type AnyDoc = Record<string, unknown> & { _id: unknown };
type IndexKey = Record<string, 1 | -1>;
@@ -36,7 +29,7 @@ interface MigrationCollection {
$unset?: Record<string, ''>;
},
options?: { ordered?: boolean },
): Promise<{ matchedCount?: number; modifiedCount?: number } | unknown>;
): Promise<unknown>;
indexes?(): Promise<MigrationIndex[]>;
dropIndex?(name: string): Promise<unknown>;
createIndex?(
@@ -516,15 +509,17 @@ function summarizeGroups(
function summarizeCode(doc: TournamentCodeDoc): TournamentCodeDuplicateSummary {
return {
bracketMatchId:
doc.bracketMatchId === undefined ? undefined : String(doc.bracketMatchId),
code: doc.code === undefined ? undefined : String(doc.code),
doc.bracketMatchId === undefined
? undefined
: stringifyId(doc.bracketMatchId),
code: doc.code === undefined ? undefined : stringifyId(doc.code),
gameNumber:
doc.gameNumber === undefined ? undefined : String(doc.gameNumber),
doc.gameNumber === undefined ? undefined : stringifyId(doc.gameNumber),
id: stringifyId(doc._id) ?? '',
matchId: doc.matchId === undefined ? undefined : stringifyId(doc.matchId),
riotMatchId:
doc.riotMatchId === undefined ? undefined : String(doc.riotMatchId),
state: doc.state === undefined ? undefined : String(doc.state),
doc.riotMatchId === undefined ? undefined : stringifyId(doc.riotMatchId),
state: doc.state,
};
}
@@ -749,16 +744,19 @@ function readModifiedCount(result: unknown): number {
}
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 {
if (value === null) return '<null>';
if (value === undefined) return '<undefined>';
return stringifyId(value) ?? String(value);
return stringifyId(value) ?? '<unknown>';
}
function stringifyId(value: unknown): string | 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);
}
@@ -1,5 +1,4 @@
import { Module } from '@nestjs/common';
import fs from 'fs/promises';
import { connect } from 'nats';
import type { NatsConnection } from 'nats';
import { SecretModule } from '../secret/secret.module';
@@ -38,27 +38,24 @@ export function applyMongoosePerformancePlugin(schema: mongoose.Schema): void {
const markedSchema = schema as SchemaWithPerformanceMarker;
if (markedSchema[PERFORMANCE_PLUGIN_APPLIED]) return;
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;
query[QUERY_PERFORMANCE_START] = process.hrtime.bigint();
query[QUERY_PERFORMANCE_RECORDED] = false;
});
hookableSchema.post(QUERY_OPERATION_REGEX, function (result: unknown) {
recordQueryPerformance(
this as unknown as QueryWithPerformanceState,
result,
);
schema.post(QUERY_OPERATION_REGEX, function (result: unknown) {
recordQueryPerformance(this as QueryWithPerformanceState, result);
});
hookableSchema.post(
schema.post(
QUERY_OPERATION_REGEX,
{ errorHandler: true },
function (
error: unknown,
error: Error,
_result: unknown,
next: (error: unknown) => void,
next: (error?: mongoose.CallbackError) => void,
) {
recordQueryPerformance(
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;
aggregate[QUERY_PERFORMANCE_START] = process.hrtime.bigint();
aggregate[QUERY_PERFORMANCE_RECORDED] = false;
});
hookableSchema.post('aggregate', function (result: unknown) {
schema.post('aggregate', function (result: unknown) {
recordAggregatePerformance(this as AggregateWithPerformanceState, result);
});
hookableSchema.post(
schema.post(
'aggregate',
{ errorHandler: true },
function (
error: unknown,
error: Error,
_result: unknown,
next: (error: unknown) => void,
next: (error?: mongoose.CallbackError) => void,
) {
recordAggregatePerformance(
this as AggregateWithPerformanceState,
@@ -56,16 +56,11 @@ export class DistributedLockService {
const lockOwnershipToken = options.lockOwnershipToken ?? randomUUID();
const result = await this.redisService
.raw()
.sendCommand([
'SET',
options.lockKey,
lockOwnershipToken,
'NX',
'PX',
String(options.lockExpirationDurationMilliseconds),
]);
.sendCommand<
string | null
>(['SET', options.lockKey, lockOwnershipToken, 'NX', 'PX', String(options.lockExpirationDurationMilliseconds)]);
if (String(result) !== 'OK') return null;
if (result !== 'OK') return null;
return {
lockKey: options.lockKey,
lockOwnershipToken,
@@ -124,7 +119,7 @@ export class DistributedLockService {
await this.releaseLockIfOwned(lockOwnership).catch((error: unknown) => {
this.logger.warn(
`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);
if (!lockOwnership) return null;
let lockRenewalTimer: NodeJS.Timeout | undefined;
lockRenewalTimer = setInterval(() => {
const lockRenewalTimer = setInterval(() => {
void this.extendLockIfOwned(lockOwnership).then((wasExtended) => {
if (wasExtended) return;
this.logger.warn(
@@ -157,11 +151,11 @@ export class DistributedLockService {
try {
return await operation(lockOwnership);
} finally {
if (lockRenewalTimer) clearInterval(lockRenewalTimer);
clearInterval(lockRenewalTimer);
await this.releaseLockIfOwned(lockOwnership).catch((error: unknown) => {
this.logger.warn(
`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) => {
logger.error(`Redis client error: ${error?.message ?? error}`);
client.on('error', (error: unknown) => {
logger.error(
`Redis client error: ${
error instanceof Error ? error.message : String(error)
}`,
);
});
await client.connect();
@@ -35,11 +35,14 @@ interface RawStreamReadResult {
function normalizeStreamFields(fields: unknown): Record<string, string> {
if (Array.isArray(fields)) {
const values = fields as unknown[];
const normalized: Record<string, string> = {};
for (let index = 0; index < fields.length; index += 2) {
const key = fields[index];
for (let index = 0; index < values.length; index += 2) {
const key = values[index];
if (key === undefined) continue;
normalized[String(key)] = String(fields[index + 1] ?? '');
normalized[redisValueToString(key)] = redisValueToString(
values[index + 1],
);
}
return normalized;
}
@@ -260,10 +263,10 @@ export class RedisService implements OnModuleDestroy {
rawMessage: unknown,
): StreamEntry | null {
if (Array.isArray(rawMessage)) {
const [id, fields] = rawMessage;
const [id, fields] = rawMessage as unknown[];
if (id === undefined) return null;
return {
id: String(id),
id: redisValueToString(id),
message: normalizeStreamFields(fields),
};
}
@@ -291,3 +294,17 @@ export class RedisService implements OnModuleDestroy {
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 mongoose from 'mongoose';
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', () => {
// Metadata must be read from the unbound prototype method itself.
// eslint-disable-next-line @typescript-eslint/unbound-method
const handler = MatchController.prototype.joinMatch;
const roles = Reflect.getMetadata(ROLES_KEY, handler) as
| string[]
@@ -73,7 +73,7 @@ export class BackgroundRefreshScheduler
.catch((err: unknown) => {
this.logger.warn(
`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> {
const client = this.redisService.raw();
const raw = (await client.sendCommand([
const entries = await client.sendCommand<string[]>([
'ZRANGEBYSCORE',
RIOT_JOB_SCHEDULED_ZSET,
'-inf',
@@ -223,16 +223,15 @@ export class RiotJobQueueService {
'LIMIT',
'0',
String(limit),
])) as string[] | null;
const entries = raw ?? [];
]);
let promoted = 0;
for (const entry of entries) {
const removed = (await client.sendCommand([
const removed = await client.sendCommand<number>([
'ZREM',
RIOT_JOB_SCHEDULED_ZSET,
entry,
])) as number;
]);
if (removed !== 1) continue;
const job = this.parseScheduledJob(entry);
if (!job) continue;
@@ -67,7 +67,7 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
.catch((error: unknown) => {
this.logger.warn(
`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);
@SubscribeMessage('subscribe')
public async handleSubscribe(
public handleSubscribe(
@ConnectedSocket() socket: Socket,
@MessageBody() payload: SubscribePayload,
) {
): void {
const rooms = this.resolveRooms(payload);
if (rooms.length === 0) {
socket.emit('error', { message: 'Invalid riot refresh subscription.' });
@@ -47,7 +47,7 @@ export class RiotRefreshGateway {
return;
}
await Promise.all(rooms.map((room) => socket.join(room)));
void socket.join(rooms);
socket.emit('subscribed', { rooms });
}
@@ -100,7 +100,7 @@ export class RiotRecentMatchesService {
} catch (error: unknown) {
this.logger.warn(
`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) {
const receivedAt = new Date().toISOString();
const rawBodyText = req.rawBody?.toString('utf8') ?? null;
const body: unknown = req.body;
const logPayload = {
receivedAt,
method: req.method,
@@ -25,7 +26,7 @@ export class RiotWebhookController {
headers: req.headers,
query: req.query,
params: req.params,
body: req.body,
body,
rawBodyLength: req.rawBody?.length ?? null,
rawBodyText,
};
@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import mongoose from 'mongoose';
import type { CompetitionResultSnapshot } from './competition-result.adapter';
import { CompetitionAssignmentProvisioner } from './competition-assignment.provisioner';
@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import mongoose from 'mongoose';
import { Logger } from '@nestjs/common';
import { CommunityStatsService } from '../community-stats/community-stats.service';
@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import mongoose from 'mongoose';
import type { MatchDocument } from '../global/database/schema';
import type { RiotMatchDto } from '../riot/riot.types';
@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import mongoose from 'mongoose';
import type { MatchDocument } from '../global/database/schema';
import type { RiotMatchDto } from '../riot/riot.types';
@@ -485,7 +485,9 @@ function newRelicTransactionResultToRow(
hydratedDocsReturnedP95Budget: number;
},
): 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;
const row: EndpointReportRow = {
+13 -12
View File
@@ -419,15 +419,15 @@ async function main(): Promise<void> {
auctionRedisService,
);
const dummyTournamentCodeService = {
releaseFromMatch: async () => undefined,
reserveForMatch: async () => undefined,
releaseFromMatch: () => Promise.resolve(undefined),
reserveForMatch: () => Promise.resolve(undefined),
};
const dummyTournamentResultService = {
cancelPolling: async () => undefined,
scheduleInitialPoll: async () => undefined,
cancelPolling: () => Promise.resolve(undefined),
scheduleInitialPoll: () => Promise.resolve(undefined),
};
const dummySideEffectService = {
mirrorMatchSideEffectStatus: async () => true,
mirrorMatchSideEffectStatus: () => Promise.resolve(true),
};
const dummyEventBus = {
broadcastMatchSideEffect: () => undefined,
@@ -436,13 +436,14 @@ async function main(): Promise<void> {
const auctionService = new AuctionService(
connectionService,
{
enrichRiotAccount: async () => ({
account: null,
league: 'fresh',
masteries: 'fresh',
recentMatches: 'fresh',
summoner: 'fresh',
}),
enrichRiotAccount: () =>
Promise.resolve({
account: null,
league: 'fresh',
masteries: 'fresh',
recentMatches: 'fresh',
summoner: 'fresh',
}),
} as never,
dummyTournamentCodeService as never,
dummyTournamentResultService as never,
-1
View File
@@ -9,7 +9,6 @@ import { ConnectionService } from './modules/global/database/connection.service'
import type {
ChampionMasteryEntry,
MatchParticipant,
MatchTeam,
Position,
PositionPreference,
RiotLane,