Compare commits

..
Author SHA1 Message Date
dahyeon 03be85d07b refactor(web): remove redundant history result column 2026-07-25 07:37:32 -07:00
dahyeon d269bdd92b Merge pull request 'chore(deps): resolve high audit findings' (#7) from release/87 into main
Reviewed-on: #7
2026-07-25 08:52:22 +00:00
dahyeon 2bac89d3dc chore(deps): resolve high audit findings
Upgrade direct dependencies and pin patched transitive versions so the high-severity pnpm audit gate passes. Document the dev-only brace-expansion exception and the separate Mongoose type-migration follow-up.
2026-07-25 01:51:00 -07:00
dahyeon 760da1cbea Merge pull request 'fix(dakao): hide started matches from schedule' (#6) from release/87 into main
Reviewed-on: #6
2026-07-25 08:07:42 +00:00
dahyeon ca786fd80a fix(dakao): hide started matches from schedule 2026-07-25 01:01:57 -07:00
dahyeon ac0d2b53f0 Merge pull request 'fix(web): satisfy React hook lint rules' (#5) from release/87 into main
Reviewed-on: #5
2026-07-25 06:40:40 +00:00
dahyeon a4215f86fb fix(web): satisfy React hook lint rules 2026-07-24 22:36:53 -07:00
dahyeon a24726d7da Merge pull request 'fix(api): eliminate unsafe lint warnings' (#4) from release/87 into main
Reviewed-on: #4
2026-07-25 05:23:15 +00:00
dahyeon bb68be14fa fix(api): eliminate unsafe lint warnings 2026-07-24 22:16:53 -07:00
dahyeon 9e2f2c61e7 Merge pull request 'release/87' (#3) from release/87 into main
Reviewed-on: #3
2026-07-25 04:59:34 +00:00
dahyeon fd1fa2366c fix(api): resolve lint errors 2026-07-24 21:52:35 -07:00
dahyeon 96fede9fe5 style(api): apply prettier formatting 2026-07-24 21:42:28 -07:00
dahyeon 1f75c6318a Merge pull request 'release/86' (#2) from release/86 into main
Reviewed-on: #2
2026-07-15 08:56:05 +00:00
dahyeon 8ec9edc35f feat(web): align double-elimination winner connector rails 2026-07-15 01:41:52 -07:00
dahyeon 61f1db0e6a fix(web): align bracket score-card row geometry 2026-07-15 01:06:26 -07:00
dahyeon c155f26272 Merge pull request 'Release 77' (#1) from release/77 into main
Reviewed-on: #1
2026-06-09 13:36:48 +00:00
134 changed files with 4639 additions and 2942 deletions

No files matched your search

+2
View File
@@ -28,6 +28,8 @@ website/LICENSE
!AGENTS.md
!docs/specs/internal-match-game-analysis.md
!docs/plans/internal-match-game-analysis-p0-p1.md
!docs/specs/double-elimination-connector-routing.md
!docs/plans/double-elimination-connector-routing.md
!agents/**/*.md
!skills/**/*.md
/tmp/
+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',
},
},
);
+8 -8
View File
@@ -29,20 +29,20 @@
},
"dependencies": {
"@lolympus/contracts": "workspace:*",
"@nestjs/common": "^11.0.1",
"@nestjs/common": "^11.1.28",
"@nestjs/config": "^4.0.4",
"@nestjs/core": "^11.0.1",
"@nestjs/platform-express": "^11.0.1",
"@nestjs/platform-socket.io": "^11.1.19",
"@nestjs/swagger": "^11.2.7",
"@nestjs/websockets": "^11.1.19",
"@nestjs/core": "^11.1.28",
"@nestjs/platform-express": "^11.1.28",
"@nestjs/platform-socket.io": "^11.1.28",
"@nestjs/swagger": "^11.4.6",
"@nestjs/websockets": "^11.1.28",
"@socket.io/redis-adapter": "^8.3.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.15.1",
"jose": "^6.2.2",
"mongoose": "^9.4.1",
"mongoose": "9.4.1",
"nats": "^2.29.3",
"newrelic": "^14.3.0",
"newrelic": "^14.3.3",
"redis": "^5.12.1",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
@@ -79,7 +79,9 @@ describe('AuctionDeadlineScheduler', () => {
.spyOn(scheduler, 'processDueBidRoundDeadlines')
.mockResolvedValue({ completed: 0, prepared: 0, skipped: 0 });
await (scheduler as unknown as { safeTick: () => Promise<void> }).safeTick();
await (
scheduler as unknown as { safeTick: () => Promise<void> }
).safeTick();
const leaderLockToken = redis.acquireTokenLock.mock.calls[0]?.[1];
expect(redis.acquireTokenLock).toHaveBeenCalledWith(
@@ -100,7 +102,9 @@ describe('AuctionDeadlineScheduler', () => {
.spyOn(scheduler, 'processDueBidRoundDeadlines')
.mockResolvedValue({ completed: 0, prepared: 0, skipped: 0 });
await (scheduler as unknown as { safeTick: () => Promise<void> }).safeTick();
await (
scheduler as unknown as { safeTick: () => Promise<void> }
).safeTick();
expect(processDueBidRoundDeadlinesSpy).not.toHaveBeenCalled();
expect(redis.releaseTokenLock).not.toHaveBeenCalled();
@@ -129,10 +133,12 @@ describe('AuctionDeadlineScheduler', () => {
it('prepares and completes due auction deadlines', async () => {
const matchId = '665f2f01f1f1f1f1f1f1f1f1';
const completedState = { phase: 'passed', revision: 3 };
const { auctionService, eventBus, redisCommand, scheduler } = makeScheduler({
dueReply: [matchId],
completedState,
});
const { auctionService, eventBus, redisCommand, scheduler } = makeScheduler(
{
dueReply: [matchId],
completedState,
},
);
await expect(scheduler.processDueBidRoundDeadlines(10)).resolves.toEqual({
completed: 1,
@@ -149,7 +155,10 @@ describe('AuctionDeadlineScheduler', () => {
expect(auctionService.completePreparedExpiry).toHaveBeenCalledTimes(1);
// 만료 확정 결과는 즉시 1차 broadcast돼야 한다(클라가 입찰 라운드에 멈춰
// 후속 액션에서 CONFLICT가 반복되는 것을 막는 핵심 동작).
expect(eventBus.broadcastState).toHaveBeenCalledWith(matchId, completedState);
expect(eventBus.broadcastState).toHaveBeenCalledWith(
matchId,
completedState,
);
});
it('skips noop expiry preparations', async () => {
@@ -189,10 +198,7 @@ describe('AuctionDeadlineScheduler', () => {
});
it('continues processing later deadline items after one item fails', async () => {
const matchIds = [
'665f2f01f1f1f1f1f1f1f1f1',
'665f2f02f1f1f1f1f1f1f1f1',
];
const matchIds = ['665f2f01f1f1f1f1f1f1f1f1', '665f2f02f1f1f1f1f1f1f1f1'];
const { auctionService, redisCommand, scheduler } = makeScheduler({
dueReply: matchIds,
});
@@ -101,15 +101,17 @@ export class AuctionDeadlineScheduler implements OnModuleInit, OnModuleDestroy {
currentRedisTimestampMS: number,
batchLimit: number,
): Promise<string[]> {
const reply = await this.auctionRedisService.raw().sendCommand([
'ZRANGEBYSCORE',
BID_ROUND_DEADLINE_QUEUE_KEY,
'-inf',
String(currentRedisTimestampMS),
'LIMIT',
'0',
String(batchLimit),
]);
const reply = await this.auctionRedisService
.raw()
.sendCommand([
'ZRANGEBYSCORE',
BID_ROUND_DEADLINE_QUEUE_KEY,
'-inf',
String(currentRedisTimestampMS),
'LIMIT',
'0',
String(batchLimit),
]);
return Array.isArray(reply) ? reply.map(String) : [];
}
@@ -177,11 +179,11 @@ export class AuctionDeadlineScheduler implements OnModuleInit, OnModuleDestroy {
return { completed, prepared, skipped };
}
private async removeBidRoundDeadlineQueueEntry(matchId: string): Promise<void> {
await this.auctionRedisService.raw().sendCommand([
'ZREM',
BID_ROUND_DEADLINE_QUEUE_KEY,
matchId,
]);
private async removeBidRoundDeadlineQueueEntry(
matchId: string,
): Promise<void> {
await this.auctionRedisService
.raw()
.sendCommand(['ZREM', BID_ROUND_DEADLINE_QUEUE_KEY, matchId]);
}
}
@@ -20,9 +20,8 @@ export class AuctionEventBusService {
}
public broadcastState(matchId: string, state: AuctionStateResponse): void {
this.auctionNamespace?.to(matchId).emit(
'state',
serializeRealtimeAuction(state),
);
this.auctionNamespace
?.to(matchId)
.emit('state', serializeRealtimeAuction(state));
}
}
@@ -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;
}
@@ -22,7 +22,10 @@ describe('resolveAuctionRejectionReason', () => {
it('maps known BadRequest messages without a structured code', () => {
expect(
resolveAuctionRejectionReason(undefined, 'Cannot advance from current phase.'),
resolveAuctionRejectionReason(
undefined,
'Cannot advance from current phase.',
),
).toBe(
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_PHASE_DOES_NOT_ALLOW_ADVANCE,
);
@@ -41,22 +41,24 @@ export class AuctionSideEffectService {
matchSideEffectStatus: AuctionMatchSideEffectStatus;
}): Promise<boolean> {
const keys = buildAuctionRedisKeys(params.matchId);
const result = await this.auctionRedisService.raw().sendCommand([
'EVAL',
[
"if redis.call('HGET', KEYS[1], 'auctionLifecycleId') ~= ARGV[1] then return 0 end",
"local currentRevision = tonumber(redis.call('HGET', KEYS[1], 'matchSideEffectRevision') or '-1')",
'local nextRevision = tonumber(ARGV[2])',
'if currentRevision >= nextRevision then return 0 end',
"redis.call('HSET', KEYS[1], 'matchSideEffectRevision', ARGV[2], 'matchSideEffectStatus', ARGV[3])",
'return 1',
].join('\n'),
'1',
keys.liveStateKey,
params.auctionLifecycleId,
String(params.matchSideEffectRevision),
params.matchSideEffectStatus,
]);
const result = await this.auctionRedisService
.raw()
.sendCommand([
'EVAL',
[
"if redis.call('HGET', KEYS[1], 'auctionLifecycleId') ~= ARGV[1] then return 0 end",
"local currentRevision = tonumber(redis.call('HGET', KEYS[1], 'matchSideEffectRevision') or '-1')",
'local nextRevision = tonumber(ARGV[2])',
'if currentRevision >= nextRevision then return 0 end',
"redis.call('HSET', KEYS[1], 'matchSideEffectRevision', ARGV[2], 'matchSideEffectStatus', ARGV[3])",
'return 1',
].join('\n'),
'1',
keys.liveStateKey,
params.auctionLifecycleId,
String(params.matchSideEffectRevision),
params.matchSideEffectStatus,
]);
return Number(result) === 1;
}
}
@@ -78,8 +80,7 @@ export function canAcquireSideEffectLease(
if (state.state === 'pending' || state.state === 'failed') return true;
if (state.state !== 'processing') return false;
return (
(state.processingLeaseExpiresAtTimestampMS ?? 0) <=
currentRedisTimestampMS
(state.processingLeaseExpiresAtTimestampMS ?? 0) <= currentRedisTimestampMS
);
}
@@ -59,8 +59,7 @@ export class AuctionController {
initialTeamBidPointAmount: c.initialTeamBidPointAmount,
})),
initialTeamBidPointAmount: body.initialTeamBidPointAmount ?? 1000,
maximumBidRoundDurationSeconds:
body.maximumBidRoundDurationSeconds ?? 30,
maximumBidRoundDurationSeconds: body.maximumBidRoundDurationSeconds ?? 30,
bidRoundExtensionSeconds: body.bidRoundExtensionSeconds ?? 5,
topTierAuctionPriorityThreshold:
body.topTierAuctionPriorityThreshold ?? 'NONE',
+96 -56
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';
@@ -92,9 +106,7 @@ const BID_RATE_LIMIT_REJECTION_MESSAGE =
allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'],
},
})
export class AuctionGateway
implements OnGatewayConnection, OnGatewayInit
{
export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
@WebSocketServer()
private server!: Namespace;
@@ -114,14 +126,14 @@ export class AuctionGateway
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);
@@ -130,7 +142,7 @@ export class AuctionGateway
@SubscribeMessage('join')
public async handleJoin(
@ConnectedSocket() socket: Socket,
@ConnectedSocket() socket: AuctionSocket,
@MessageBody() payload: JoinAuctionPayload,
) {
if (!payload?.matchId || !mongoose.isValidObjectId(payload.matchId)) {
@@ -158,7 +170,7 @@ export class AuctionGateway
@SubscribeMessage('bid')
public async handleBid(
@ConnectedSocket() socket: Socket,
@ConnectedSocket() socket: AuctionSocket,
@MessageBody() payload: BidPayload,
@Ack() ack?: (response: Record<string, unknown>) => void,
) {
@@ -205,7 +217,9 @@ export class AuctionGateway
ack?.({
...(bidDelta
? {}
: { state: this.serializeAuction(bidResult as AuctionStateResponse) }),
: {
state: this.serializeAuction(bidResult as AuctionStateResponse),
}),
ok: true,
bidRequestId,
bidDelta: broadcastBidDelta,
@@ -220,7 +234,12 @@ export class AuctionGateway
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
@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
@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
@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
@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
@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
}
}
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,10 +434,9 @@ export class AuctionGateway
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 >=
@@ -436,10 +454,8 @@ export class AuctionGateway
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) {
@@ -463,8 +479,9 @@ export class AuctionGateway
};
}
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'];
@@ -472,16 +489,16 @@ export class AuctionGateway
}
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];
@@ -494,14 +511,14 @@ export class AuctionGateway
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),
);
@@ -531,14 +548,20 @@ export class AuctionGateway
});
}
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();
}
@@ -546,10 +569,11 @@ export class AuctionGateway
}
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({
@@ -558,10 +582,11 @@ export class AuctionGateway
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 {
@@ -595,7 +620,7 @@ export class AuctionGateway
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),
@@ -603,16 +628,21 @@ export class AuctionGateway
});
}
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>)
: {};
}
/**
@@ -633,7 +663,9 @@ export class AuctionGateway
typeof errorPayload.code === 'string' ? errorPayload.code : undefined,
errorPayload.message,
);
const resyncRecommended = isAuctionResyncRecommended(auctionRejectionReason);
const resyncRecommended = isAuctionResyncRecommended(
auctionRejectionReason,
);
const state = resyncRecommended
? await this.fetchSerializedAuctionState(matchId)
: undefined;
@@ -688,7 +720,9 @@ export class AuctionGateway
return {
code: error instanceof Error ? error.message : 'UNKNOWN',
message:
error instanceof Error ? error.message : 'Unexpected auction gateway error.',
error instanceof Error
? error.message
: 'Unexpected auction gateway error.',
};
}
@@ -716,7 +750,8 @@ export class AuctionGateway
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;
}
@@ -724,7 +759,7 @@ export class AuctionGateway
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,
@@ -739,11 +774,13 @@ export class AuctionGateway
? 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] ??
@@ -775,9 +812,7 @@ export class AuctionGateway
};
}
private isBidDeltaResponse(
value: unknown,
): value is AuctionBidDeltaResponse {
private isBidDeltaResponse(value: unknown): value is AuctionBidDeltaResponse {
return (
typeof value === 'object' &&
value !== null &&
@@ -804,7 +839,12 @@ export class AuctionGateway
};
}
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>)
: {};
}
}
@@ -2,6 +2,30 @@ import mongoose from 'mongoose';
import { AuctionService } from './auction.service';
describe('AuctionService', () => {
function requireRecord(
value: unknown,
label: string,
): Record<string, unknown> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new Error(`${label} must be an object.`);
}
return value as Record<string, unknown>;
}
function requireArray(value: unknown, label: string): unknown[] {
if (!Array.isArray(value)) {
throw new Error(`${label} must be an array.`);
}
return value as unknown[];
}
function parseJsonRecord(value: unknown, label: string) {
if (typeof value !== 'string') {
throw new Error(`${label} must be a JSON string.`);
}
return requireRecord(JSON.parse(value) as unknown, label);
}
function createService(models: Record<string, unknown>) {
const auctionHistoryModel = {
findOne: jest.fn().mockReturnValue({
@@ -158,12 +182,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({
@@ -1008,7 +1031,12 @@ describe('AuctionService', () => {
);
const transitionInput =
auctionRedisCommandService.applyTransition.mock.calls[0][1];
expect(JSON.parse(transitionInput.durabilityPayloadJson)).toMatchObject({
expect(
parseJsonRecord(
transitionInput.durabilityPayloadJson,
'durabilityPayloadJson',
),
).toMatchObject({
afterAuctionMongoProjection: expect.objectContaining({
phase: 'bidding',
revision: 2,
@@ -1179,17 +1207,40 @@ describe('AuctionService', () => {
const transitionInput =
auctionRedisCommandService.applyTransition.mock.calls[0][1];
const durabilityPayload = JSON.parse(transitionInput.durabilityPayloadJson);
expect(durabilityPayload.snapshotBefore).toMatchObject({
const durabilityPayload = parseJsonRecord(
transitionInput.durabilityPayloadJson,
'durabilityPayloadJson',
);
const snapshotBefore = requireRecord(
durabilityPayload.snapshotBefore,
'snapshotBefore',
);
const snapshotBeforeTeams = requireArray(
snapshotBefore.auctionTeams,
'snapshotBefore.auctionTeams',
);
const snapshotBeforeTeam = requireRecord(
snapshotBeforeTeams[0],
'snapshotBefore.auctionTeams[0]',
);
const afterAuctionMongoProjection = requireRecord(
durabilityPayload.afterAuctionMongoProjection,
'afterAuctionMongoProjection',
);
const projectedTeams = requireArray(
afterAuctionMongoProjection.auctionTeams,
'afterAuctionMongoProjection.auctionTeams',
);
const projectedTeam = requireRecord(
projectedTeams[0],
'afterAuctionMongoProjection.auctionTeams[0]',
);
expect(snapshotBefore).toMatchObject({
phase: 'bidding',
revision: 4,
});
expect(durabilityPayload.snapshotBefore.auctionTeams[0].members).toEqual(
[],
);
expect(
durabilityPayload.afterAuctionMongoProjection.auctionTeams[0].members,
).toEqual([
expect(snapshotBeforeTeam.members).toEqual([]);
expect(projectedTeam.members).toEqual([
expect.objectContaining({
memberAcquisitionBidPointAmount: 120,
userId: playerUserId.toString(),
@@ -1397,7 +1448,12 @@ describe('AuctionService', () => {
});
const [, transitionInput] =
auctionRedisCommandService.applyTransition.mock.calls.at(-1) ?? [];
expect(JSON.parse(transitionInput.durabilityPayloadJson)).toMatchObject({
expect(
parseJsonRecord(
transitionInput.durabilityPayloadJson,
'durabilityPayloadJson',
),
).toMatchObject({
afterAuctionMongoProjection: {
matchSideEffectStatus: 'pending',
phase: 'complete',
@@ -2568,7 +2624,10 @@ describe('AuctionService', () => {
durationSeconds: 30,
mode: 'set-relative',
});
const durabilityPayload = JSON.parse(transitionInput.durabilityPayloadJson);
const durabilityPayload = parseJsonRecord(
transitionInput.durabilityPayloadJson,
'durabilityPayloadJson',
);
expect(durabilityPayload).toMatchObject({
auctionActionType: 'undo',
historyMutation: {
@@ -210,21 +210,25 @@ describe('AuctionRedisCommandService', () => {
it('parses apply transition replay and rejected replies', async () => {
await expect(
makeService(['REPLAY', 'APPLIED', 'transition-1', '2100'])
.service.applyTransition('match-1', {
afterAuctionStructureStateJson: '{}',
auctionHistorySequence: 5,
auctionLifecycleId: 'life-1',
auctionStateTransitionId: 'transition-1',
broadcastStateRevision: 11,
deadline: { mode: 'none' },
durabilityPayloadJson: '{}',
expectedPhase: 'sold',
expectedRevision: 10,
liveStatePatch: {},
matchId: 'match-1',
shouldBroadcastState: false,
}),
makeService([
'REPLAY',
'APPLIED',
'transition-1',
'2100',
]).service.applyTransition('match-1', {
afterAuctionStructureStateJson: '{}',
auctionHistorySequence: 5,
auctionLifecycleId: 'life-1',
auctionStateTransitionId: 'transition-1',
broadcastStateRevision: 11,
deadline: { mode: 'none' },
durabilityPayloadJson: '{}',
expectedPhase: 'sold',
expectedRevision: 10,
liveStatePatch: {},
matchId: 'match-1',
shouldBroadcastState: false,
}),
).resolves.toEqual({
auctionStateTransitionId: 'transition-1',
currentServerTimestampMS: 2100,
@@ -233,21 +237,25 @@ describe('AuctionRedisCommandService', () => {
});
await expect(
makeService(['REJECTED', 'CONFLICT', 'transition-1', '2200'])
.service.applyTransition('match-1', {
afterAuctionStructureStateJson: '{}',
auctionHistorySequence: 5,
auctionLifecycleId: 'life-1',
auctionStateTransitionId: 'transition-1',
broadcastStateRevision: 11,
deadline: { mode: 'none' },
durabilityPayloadJson: '{}',
expectedPhase: 'sold',
expectedRevision: 10,
liveStatePatch: {},
matchId: 'match-1',
shouldBroadcastState: false,
}),
makeService([
'REJECTED',
'CONFLICT',
'transition-1',
'2200',
]).service.applyTransition('match-1', {
afterAuctionStructureStateJson: '{}',
auctionHistorySequence: 5,
auctionLifecycleId: 'life-1',
auctionStateTransitionId: 'transition-1',
broadcastStateRevision: 11,
deadline: { mode: 'none' },
durabilityPayloadJson: '{}',
expectedPhase: 'sold',
expectedRevision: 10,
liveStatePatch: {},
matchId: 'match-1',
shouldBroadcastState: false,
}),
).resolves.toEqual({
auctionStateTransitionId: 'transition-1',
code: 'CONFLICT',
@@ -288,12 +296,17 @@ describe('AuctionRedisCommandService', () => {
it('parses expire prepare replay and noop replies', async () => {
await expect(
makeService(['REPLAY', 'passed', 'expire-1', '12', '3100'])
.service.expirePrepare('match-1', {
auctionStateTransitionId: 'expire-1',
bidRoundExpiryRetryDelayMS: 3000,
matchId: 'match-1',
}),
makeService([
'REPLAY',
'passed',
'expire-1',
'12',
'3100',
]).service.expirePrepare('match-1', {
auctionStateTransitionId: 'expire-1',
bidRoundExpiryRetryDelayMS: 3000,
matchId: 'match-1',
}),
).resolves.toMatchObject({
auctionStateTransitionId: 'expire-1',
bidRoundExpiryDecision: 'passed',
@@ -360,16 +373,19 @@ describe('AuctionRedisCommandService', () => {
});
await expect(
makeService(['REJECTED', 'INVALID_PATCH_ARITY', '4200'])
.service.hydrateState('match-1', {
auctionHistorySequence: 3,
auctionLifecycleId: 'life-1',
maximumBidRoundDurationSeconds: 30,
matchId: 'match-1',
phase: 'presenting',
revision: 6,
structureStateJson: '{}',
}),
makeService([
'REJECTED',
'INVALID_PATCH_ARITY',
'4200',
]).service.hydrateState('match-1', {
auctionHistorySequence: 3,
auctionLifecycleId: 'life-1',
maximumBidRoundDurationSeconds: 30,
matchId: 'match-1',
phase: 'presenting',
revision: 6,
structureStateJson: '{}',
}),
).resolves.toEqual({
code: 'INVALID_PATCH_ARITY',
currentServerTimestampMS: 4200,
@@ -85,7 +85,9 @@ export function stringifyAuctionRedisStructureState(
return JSON.stringify(buildAuctionRedisStructureState(input));
}
function countAuctionTeamMembersIncludingCaptain(team: RedisAuctionTeam): number {
function countAuctionTeamMembersIncludingCaptain(
team: RedisAuctionTeam,
): number {
const userIds = new Set<string>([team.captainUserId.toString()]);
for (const member of team.members) {
userIds.add(member.userId.toString());
@@ -1,7 +1,10 @@
import { AuctionRedisService } from './auction-redis.service';
import { AuctionRedisStateReaderService } from './auction-redis-state-reader.service';
function makeService(commandReplies: unknown[], currentServerTimestampMS = 1000) {
function makeService(
commandReplies: unknown[],
currentServerTimestampMS = 1000,
) {
const sendCommand = jest
.fn()
.mockImplementation(() => Promise.resolve(commandReplies.shift()));
@@ -149,7 +152,9 @@ describe('AuctionRedisStateReaderService', () => {
[],
]);
await expect(service.readAuctionStateView('match-1')).resolves.toMatchObject({
await expect(
service.readAuctionStateView('match-1'),
).resolves.toMatchObject({
auctionLifecycleId: 'life-1',
auctionTeams: [],
phase: 'presenting',
@@ -181,7 +186,6 @@ describe('AuctionRedisStateReaderService', () => {
});
});
it('returns null when live or structure state is absent', async () => {
await expect(
makeService([[], '{"auctionTeams":[]}', []]).service.readAuctionStateView(
@@ -42,12 +42,14 @@ export class AuctionRedisStateReaderService {
matchId: string,
): Promise<AuctionRedisLiveStateIdentity | null> {
const keys = buildAuctionRedisKeys(matchId);
const reply = await this.auctionRedisService.raw().sendCommand([
'HMGET',
keys.liveStateKey,
'auctionLifecycleId',
'revision',
]);
const reply = await this.auctionRedisService
.raw()
.sendCommand([
'HMGET',
keys.liveStateKey,
'auctionLifecycleId',
'revision',
]);
if (!Array.isArray(reply)) return null;
const auctionLifecycleId =
typeof reply[0] === 'string' && reply[0] ? reply[0] : undefined;
@@ -68,14 +70,16 @@ export class AuctionRedisStateReaderService {
): Promise<AuctionRedisBidContext | null> {
const keys = buildAuctionRedisKeys(matchId);
const bidderTeamCaptainUserIdField = `team:${bidderTeamIndex}:captainUserId`;
const liveReply = await this.auctionRedisService.raw().sendCommand([
'HMGET',
keys.liveStateKey,
'phase',
'auctionLifecycleId',
'currentBidRoundPlayerUserId',
bidderTeamCaptainUserIdField,
]);
const liveReply = await this.auctionRedisService
.raw()
.sendCommand([
'HMGET',
keys.liveStateKey,
'phase',
'auctionLifecycleId',
'currentBidRoundPlayerUserId',
bidderTeamCaptainUserIdField,
]);
if (!Array.isArray(liveReply)) return null;
const phase = stringValue(liveReply[0]);
@@ -102,18 +106,23 @@ export class AuctionRedisStateReaderService {
options: AuctionRedisStateViewReadOptions = {},
): Promise<Record<string, unknown> | null> {
const keys = buildAuctionRedisKeys(matchId);
const [currentServerTimestampMS, liveReply, structureStateJson, bidEntries] =
await Promise.all([
this.auctionRedisService.getCurrentRedisTimestampMS(),
this.auctionRedisService.raw().sendCommand(['HGETALL', keys.liveStateKey]),
this.auctionRedisService.raw().sendCommand(['GET', keys.structureStateKey]),
this.auctionRedisService.raw().sendCommand([
'LRANGE',
keys.bidHistoryKey,
'0',
'-1',
]),
]);
const [
currentServerTimestampMS,
liveReply,
structureStateJson,
bidEntries,
] = await Promise.all([
this.auctionRedisService.getCurrentRedisTimestampMS(),
this.auctionRedisService
.raw()
.sendCommand(['HGETALL', keys.liveStateKey]),
this.auctionRedisService
.raw()
.sendCommand(['GET', keys.structureStateKey]),
this.auctionRedisService
.raw()
.sendCommand(['LRANGE', keys.bidHistoryKey, '0', '-1']),
]);
const liveState = parseHashReply(liveReply, {
includeInternalLiveStateFields:
@@ -142,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) {
@@ -161,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;
@@ -183,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 } = {},
@@ -210,7 +223,10 @@ function parseHashEntries(
): Record<string, unknown> {
const result: Record<string, unknown> = {};
for (const [field, rawValue] of entries) {
if (!options.includeInternalLiveStateFields && isInternalLiveStateField(field)) {
if (
!options.includeInternalLiveStateFields &&
isInternalLiveStateField(field)
) {
continue;
}
const value = String(rawValue);
@@ -91,9 +91,7 @@ describe('auction apply transition redis script contract', () => {
expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain(
'shouldBroadcastState',
);
expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain(
"redis.call('SADD'",
);
expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain("redis.call('SADD'");
expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain(
"redis.call('HINCRBY'",
);
@@ -64,9 +64,7 @@ describe('auction bid redis script contract', () => {
expect(AUCTION_BID_SCRIPT.lua).toContain("redis.call('TIME')");
expect(AUCTION_BID_SCRIPT.lua).toContain("redis.call('HINCRBY'");
expect(AUCTION_BID_SCRIPT.lua).toContain('BID_REQUEST_RESULT_LIMIT');
expect(AUCTION_BID_SCRIPT.lua).toContain(
'currentHighestBidPointAmount',
);
expect(AUCTION_BID_SCRIPT.lua).toContain('currentHighestBidPointAmount');
expect(AUCTION_BID_SCRIPT.lua).not.toContain('cjson.decode');
});
});
@@ -3,9 +3,11 @@ import { buildAuctionRedisKeys } from './auction-redis.keys';
describe('auction redis keys', () => {
it('builds lifecycle-safe key names from match id', () => {
expect(buildAuctionRedisKeys('match-1')).toMatchObject({
actionRequestResultOrderKey: 'auction:match-1:auctionActionRequestResultOrder',
actionRequestResultOrderKey:
'auction:match-1:auctionActionRequestResultOrder',
actionRequestResultsKey: 'auction:match-1:auctionActionRequestResults',
appliedTransitionIdsKey: 'auction:match-1:appliedAuctionStateTransitionIds',
appliedTransitionIdsKey:
'auction:match-1:appliedAuctionStateTransitionIds',
bidHistoryKey: 'auction:match-1:auctionBidHistory',
bidRequestResultOrderKey: 'auction:match-1:bidRequestResultOrder',
bidRequestResultsKey: 'auction:match-1:bidRequestResults',
@@ -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)
}`,
);
});
@@ -15,7 +15,9 @@ function makeService(sendCommand: jest.Mock) {
describe('AuctionRedisService', () => {
it('uses Redis TIME as the timestamp source', async () => {
const service = makeService(jest.fn().mockResolvedValue(['1781700000', '123000']));
const service = makeService(
jest.fn().mockResolvedValue(['1781700000', '123000']),
);
await expect(service.getCurrentRedisTimestampMS()).resolves.toBe(
1_781_700_000_123,
@@ -22,7 +22,11 @@ export class AuctionRedisNoscriptError extends Error {
function isNoscriptError(error: unknown): boolean {
if (error instanceof AuctionRedisNoscriptError) return true;
const message =
error instanceof Error ? error.message : typeof error === 'string' ? error : '';
error instanceof Error
? error.message
: typeof error === 'string'
? error
: '';
return /\bNOSCRIPT\b/iu.test(message);
}
@@ -81,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;
@@ -107,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,
@@ -115,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> {
@@ -100,9 +100,7 @@ describe('auction redis state assembly', () => {
'1000',
]);
expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain("redis.call('TIME')");
expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain(
'INVALID_PATCH_ARITY',
);
expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain('INVALID_PATCH_ARITY');
expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain(
'mongoRevision > redisRevision',
);
@@ -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,
+1 -4
View File
@@ -1,8 +1,5 @@
import type { JWTHeaderParameters, JWTPayload } from 'jose';
import type {
IdentityDocument,
UserDocument,
} from '../global/database/schema';
import type { IdentityDocument, UserDocument } from '../global/database/schema';
import type { IdentityProviderName } from './jwt.service';
declare module 'express' {
+1 -4
View File
@@ -2,10 +2,7 @@ import { Injectable } from '@nestjs/common';
import type { Request } from 'express';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import {
IdentityDocument,
UserDocument,
} from '../global/database/schema';
import { IdentityDocument, UserDocument } from '../global/database/schema';
import { SecretService } from '../global/secret/secret.service';
import './auth-request';
+4 -4
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');
}
@@ -84,7 +83,8 @@ export class JwtAuthGuard implements CanActivate {
}
throw new Error(`Unknown issuer: ${iss}`);
} catch (err) {
const message = err instanceof Error ? err.message : 'Unable to decode token';
const message =
err instanceof Error ? err.message : 'Unable to decode token';
throw new UnauthorizedException(message);
}
}
+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.');
}
@@ -7,9 +7,10 @@ import {
import mongoose from 'mongoose';
@Injectable()
export class ParseObjectIdPipe
implements PipeTransform<string, mongoose.Types.ObjectId>
{
export class ParseObjectIdPipe implements PipeTransform<
string,
mongoose.Types.ObjectId
> {
public transform(
value: string,
metadata: ArgumentMetadata,
@@ -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);
}
@@ -23,7 +23,14 @@ export class CommunityStatsController {
) {
return this.communityStatsService.getMatches({
communityId,
filters: this.toFilters({ seasonId, from, to, championId, cursor, limit }),
filters: this.toFilters({
seasonId,
from,
to,
championId,
cursor,
limit,
}),
});
}
@@ -85,7 +92,14 @@ export class CommunityStatsController {
return this.communityStatsService.getUserInternalHistory({
communityId,
userId,
filters: this.toFilters({ seasonId, from, to, championId, cursor, limit }),
filters: this.toFilters({
seasonId,
from,
to,
championId,
cursor,
limit,
}),
});
}
@@ -7,7 +7,10 @@ import type {
RiotLane,
TeamSide,
} from '../global/database/schema';
import type { RecentMatchView, HistorySeasonDto } from '../match-history/match-history.types';
import type {
RecentMatchView,
HistorySeasonDto,
} from '../match-history/match-history.types';
export interface CommunityStatsFilters {
seasonId?: string;
@@ -80,7 +83,9 @@ export interface LeaderboardRow {
avgCsPerMin: number;
avgDamageShare: number;
avgVisionScore: number;
byLane: Partial<Record<RiotLane, { games: number; wins: number; kda: number }>>;
byLane: Partial<
Record<RiotLane, { games: number; wins: number; kda: number }>
>;
topChampions: Array<{ championId: number; games: number; winRate: number }>;
}
@@ -227,9 +227,7 @@ export class MatchStatsFragmentBuilder {
participant,
rawParticipant,
buildEvents: rawParticipant
? buildEventsByParticipantId.get(
rawParticipant.participantId,
)
? buildEventsByParticipantId.get(rawParticipant.participantId)
: undefined,
checkpoints: rawParticipant
? checkpointsByParticipantId.get(rawParticipant.participantId)
@@ -420,7 +418,10 @@ export class MatchStatsFragmentBuilder {
private toBuildEventsByParticipantId(
timeline?: RiotMatchTimelineDto,
): Map<number, ParticipantBuildEvents> {
const buildEventsByParticipantId = new Map<number, ParticipantBuildEvents>();
const buildEventsByParticipantId = new Map<
number,
ParticipantBuildEvents
>();
if (!timeline?.info.frames.length) return buildEventsByParticipantId;
const getEvents = (participantId: number): ParticipantBuildEvents => {
@@ -796,15 +797,18 @@ export class MatchStatsFragmentBuilder {
? timelineDragon
: (rawObjectives?.dragon?.kills ?? 0),
inhibitor: rawObjectives?.inhibitor?.kills ?? 0,
baron: (timelineObjectives?.baron ?? 0) > 0
? (timelineObjectives?.baron ?? 0)
: (rawObjectives?.baron?.kills ?? 0),
riftHerald: (timelineObjectives?.riftHerald ?? 0) > 0
? (timelineObjectives?.riftHerald ?? 0)
: (rawObjectives?.riftHerald?.kills ?? 0),
voidGrub: (timelineObjectives?.voidGrub ?? 0) > 0
? (timelineObjectives?.voidGrub ?? 0)
: (rawObjectives?.horde?.kills ?? 0),
baron:
(timelineObjectives?.baron ?? 0) > 0
? (timelineObjectives?.baron ?? 0)
: (rawObjectives?.baron?.kills ?? 0),
riftHerald:
(timelineObjectives?.riftHerald ?? 0) > 0
? (timelineObjectives?.riftHerald ?? 0)
: (rawObjectives?.riftHerald?.kills ?? 0),
voidGrub:
(timelineObjectives?.voidGrub ?? 0) > 0
? (timelineObjectives?.voidGrub ?? 0)
: (rawObjectives?.horde?.kills ?? 0),
elderDragon: hasProjectedDragon ? timelineElder : 0,
};
}
@@ -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 };
@@ -6,10 +6,7 @@ import {
} from '@nestjs/common';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import {
CommunityDocument,
UserDocument,
} from '../global/database/schema';
import { CommunityDocument, UserDocument } from '../global/database/schema';
export interface CreateCommunityInput {
name: string;
@@ -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);
@@ -429,8 +429,14 @@ export function applyCompetitionDomainInvariantIndexes(
}
}
export type CompetitionModelName =
| 'competition'
| 'competitionFact'
| 'competitionOutbox'
| 'tournamentCodeAssignment';
export const competitionModelDefinitions: Array<{
name: string;
name: CompetitionModelName;
schema: mongoose.Schema;
schemaName: string;
}> = [
@@ -1,4 +1,8 @@
import { projectCompetition } from './competition-projector';
import {
CompetitionDomainError,
type CompetitionDomainErrorCode,
} from './domain-error';
import { generateSeriesGraph } from './series-graph';
describe('projectCompetition', () => {
@@ -323,20 +327,18 @@ describe('projectCompetition', () => {
'team-1',
);
expect(() =>
projectCompetition({
competitionId,
revision: 1,
projectorVersion: 1,
teams,
format,
seriesGraph,
facts: [{ ...accepted, seriesId: 'series-does-not-exist' }],
}),
).toThrow(
expect.objectContaining({
code: 'GAME_SERIES_MISMATCH',
}),
expectCompetitionDomainError(
() =>
projectCompetition({
competitionId,
revision: 1,
projectorVersion: 1,
teams,
format,
seriesGraph,
facts: [{ ...accepted, seriesId: 'series-does-not-exist' }],
}),
'GAME_SERIES_MISMATCH',
);
});
@@ -356,20 +358,18 @@ describe('projectCompetition', () => {
'team-1',
);
expect(() =>
projectCompetition({
competitionId,
revision: 1,
projectorVersion: 1,
teams,
format,
seriesGraph,
facts: [{ ...accepted, gameSlotId: 'slot-does-not-exist' }],
}),
).toThrow(
expect.objectContaining({
code: 'GAME_SLOT_INVALID',
}),
expectCompetitionDomainError(
() =>
projectCompetition({
competitionId,
revision: 1,
projectorVersion: 1,
teams,
format,
seriesGraph,
facts: [{ ...accepted, gameSlotId: 'slot-does-not-exist' }],
}),
'GAME_SLOT_INVALID',
);
});
@@ -382,36 +382,34 @@ describe('projectCompetition', () => {
};
const seriesGraph = generateSeriesGraph({ competitionId, teams, format });
expect(() =>
projectCompetition({
competitionId,
revision: 1,
projectorVersion: 1,
teams,
format,
seriesGraph,
facts: [
{
id: 'fact-unknown-adjudication-series',
type: 'series-adjudicated',
competitionId,
revision: 1,
ordinalWithinRevision: 1,
commandId: 'command-unknown-adjudication-series',
schemaVersion: 1,
actor: { type: 'user' },
occurredAt: new Date('2026-07-12T00:00:01.000Z'),
recordedAt: new Date('2026-07-12T00:00:02.000Z'),
seriesId: 'series-does-not-exist',
decision: { type: 'administrative', winnerTeamId: 'team-1' },
reason: 'Manual correction',
},
],
}),
).toThrow(
expect.objectContaining({
code: 'ADJUDICATION_INVALID',
}),
expectCompetitionDomainError(
() =>
projectCompetition({
competitionId,
revision: 1,
projectorVersion: 1,
teams,
format,
seriesGraph,
facts: [
{
id: 'fact-unknown-adjudication-series',
type: 'series-adjudicated',
competitionId,
revision: 1,
ordinalWithinRevision: 1,
commandId: 'command-unknown-adjudication-series',
schemaVersion: 1,
actor: { type: 'user' },
occurredAt: new Date('2026-07-12T00:00:01.000Z'),
recordedAt: new Date('2026-07-12T00:00:02.000Z'),
seriesId: 'series-does-not-exist',
decision: { type: 'administrative', winnerTeamId: 'team-1' },
reason: 'Manual correction',
},
],
}),
'ADJUDICATION_INVALID',
);
});
@@ -617,3 +615,23 @@ interface GameSlotLike {
id: string;
ordinal: number;
}
function expectCompetitionDomainError(
action: () => unknown,
expectedCode: CompetitionDomainErrorCode,
): void {
let thrown: unknown;
try {
action();
} catch (error: unknown) {
thrown = error;
}
expect(thrown).toBeInstanceOf(CompetitionDomainError);
if (!(thrown instanceof CompetitionDomainError)) {
throw new Error(
`Expected CompetitionDomainError, received ${String(thrown)}`,
);
}
expect(thrown.code).toBe(expectedCode);
}
@@ -1,6 +1,7 @@
import {
assertReversalPreview,
buildReversalFacts,
CompetitionReversalError,
previewSeriesReversal,
} from './competition-reversal';
@@ -19,18 +20,18 @@ describe('Competition reversal planning', () => {
];
it('rejects strict reversal when a descendant has result activity', () => {
expect(() =>
previewSeriesReversal({
competitionId: 'competition-1',
revision: 2,
seriesId: 'series-parent',
mode: 'strict',
graph,
facts,
assignments,
}),
).toThrow(
expect.objectContaining({ code: 'REVERSAL_DESCENDANT_ACTIVITY' }),
expectCompetitionReversalError(
() =>
previewSeriesReversal({
competitionId: 'competition-1',
revision: 2,
seriesId: 'series-parent',
mode: 'strict',
graph,
facts,
assignments,
}),
'REVERSAL_DESCENDANT_ACTIVITY',
);
});
@@ -105,20 +106,22 @@ describe('Competition reversal planning', () => {
assignments,
});
expect(() =>
assertReversalPreview(
{
competitionId: 'competition-1',
revision: 3,
seriesId: 'series-parent',
mode: 'cascade',
graph,
facts,
assignments,
},
preview.impactHash,
),
).toThrow(expect.objectContaining({ code: 'REVERSAL_PREVIEW_STALE' }));
expectCompetitionReversalError(
() =>
assertReversalPreview(
{
competitionId: 'competition-1',
revision: 3,
seriesId: 'series-parent',
mode: 'cascade',
graph,
facts,
assignments,
},
preview.impactHash,
),
'REVERSAL_PREVIEW_STALE',
);
});
it('emits one append-only reversal fact for every active result fact', () => {
@@ -160,6 +163,26 @@ describe('Competition reversal planning', () => {
});
});
function expectCompetitionReversalError(
action: () => unknown,
expectedCode: CompetitionReversalError['code'],
): void {
let thrown: unknown;
try {
action();
} catch (error: unknown) {
thrown = error;
}
expect(thrown).toBeInstanceOf(CompetitionReversalError);
if (!(thrown instanceof CompetitionReversalError)) {
throw new Error(
`Expected CompetitionReversalError, received ${String(thrown)}`,
);
}
expect(thrown.code).toBe(expectedCode);
}
function series(id: string, sources: Array<Record<string, unknown>>) {
return {
id,
@@ -9,7 +9,8 @@ import { DakaoOutboxService } from './dakao-outbox.service';
const SWEEP_INTERVAL_MS = 60 * 1000;
const STALE_OUTBOX_MS = 5 * 60 * 1000;
const SWEEP_LOCK_KEY = 'distributed-lock:dakao-outbox:sweep-stale-publish-leases';
const SWEEP_LOCK_KEY =
'distributed-lock:dakao-outbox:sweep-stale-publish-leases';
const SWEEP_LOCK_EXPIRATION_DURATION_MILLISECONDS = 55_000;
@Injectable()
@@ -78,35 +78,29 @@ export class DakaoOutboxService {
await this.natsService.publishJetStream(params.subject, params.envelope, {
messageId: params.eventId,
});
await OutboxModel.updateOne(
updateFilter,
{
$set: {
state: 'published',
publishedAt: new Date(),
},
$inc: { publishAttempts: 1 },
$unset: {
lastPublishError: '',
publishLeaseOwnerIdentifier: '',
publishLeaseExpiresAt: '',
},
await OutboxModel.updateOne(updateFilter, {
$set: {
state: 'published',
publishedAt: new Date(),
},
).exec();
$inc: { publishAttempts: 1 },
$unset: {
lastPublishError: '',
publishLeaseOwnerIdentifier: '',
publishLeaseExpiresAt: '',
},
}).exec();
} catch (err) {
await OutboxModel.updateOne(
updateFilter,
{
$inc: { publishAttempts: 1 },
$set: {
lastPublishError: (err as Error)?.message ?? String(err),
},
$unset: {
publishLeaseOwnerIdentifier: '',
publishLeaseExpiresAt: '',
},
await OutboxModel.updateOne(updateFilter, {
$inc: { publishAttempts: 1 },
$set: {
lastPublishError: (err as Error)?.message ?? String(err),
},
).exec();
$unset: {
publishLeaseOwnerIdentifier: '',
publishLeaseExpiresAt: '',
},
}).exec();
this.logger.error(
`Failed to publish Dakao outbox eventId=${params.eventId}: ${
(err as Error)?.stack ?? err
@@ -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,
]);
}
@@ -104,9 +104,11 @@ describe('MatchCancelHandler', () => {
const handler = makeHandler({
matchService: {
cancelJoin,
list: jest.fn().mockResolvedValue([
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
]),
list: jest
.fn()
.mockResolvedValue([
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
]),
} as Partial<MatchService>,
dakaoUserService: {
findUserByKakaoTalkId,
@@ -230,9 +230,11 @@ describe('MatchJoinHandler', () => {
const resolveRiotAccount = jest.fn();
const handler = makeHandler({
matchService: {
list: jest.fn().mockResolvedValue([
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
]),
list: jest
.fn()
.mockResolvedValue([
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
]),
join,
} as Partial<MatchService>,
dakaoUserService: {
@@ -282,9 +284,11 @@ describe('MatchJoinHandler', () => {
const join = jest.fn();
const handler = makeHandler({
matchService: {
list: jest.fn().mockResolvedValue([
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
]),
list: jest
.fn()
.mockResolvedValue([
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
]),
join,
} as Partial<MatchService>,
dakaoUserService: {
@@ -44,9 +44,7 @@ export class MatchJoinHandler {
return this.errorReply(params, joinTarget);
}
let resolved:
| { user: UserDocument; riotAccount: RiotAccount }
| string;
let resolved: { user: UserDocument; riotAccount: RiotAccount } | string;
try {
resolved =
joinTarget.gameName && joinTarget.tagLine
@@ -243,10 +241,7 @@ export class MatchJoinHandler {
const gameName = normalizeRiotIdPart(value.slice(splitAt + 1));
if (!matchTitlePrefix || !gameName) continue;
const result = resolveRecruitingMatchReference(
matchTitlePrefix,
matches,
);
const result = resolveRecruitingMatchReference(matchTitlePrefix, matches);
if (result.kind === 'matched') {
return { kind: 'matched', match: result.match, gameName };
}
@@ -22,6 +22,33 @@ function makeHandler(params: {
}
describe('MatchListHandler', () => {
afterEach(() => {
jest.useRealTimers();
});
it('queries only matches scheduled at or after command processing time', async () => {
const now = new Date('2026-07-25T07:30:00.000Z');
jest.useFakeTimers().setSystemTime(now);
const communityId = objectId('111111111111111111111111');
const list = jest.fn().mockResolvedValue([]);
const handler = makeHandler({
matchService: { list },
});
await handler.handle({
communityId,
senderUserId: 'kakao-user-1',
senderNickname: '프리리',
});
expect(list).toHaveBeenCalledWith({
communityId,
status: 'recruiting',
scheduledFrom: now,
limit: 10,
});
});
it('prints short codes, compact KST dates, and short links', async () => {
const match = {
_id: objectId('333333333333333333333333'),
@@ -19,9 +19,11 @@ export class MatchListHandler {
senderUserId: string;
senderNickname: string;
}): Promise<DakaoSegment[]> {
const scheduledFrom = new Date();
const matches = await this.matchService.list({
communityId: params.communityId,
status: 'recruiting',
scheduledFrom,
limit: 10,
});
@@ -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,
@@ -19,7 +19,9 @@ describe('auction Redis schema foundation', () => {
expect(AuctionSchema.path('revision')).toBeDefined();
expect(AuctionSchema.path('auctionEngineVersion')).toBeDefined();
expect(AuctionSchema.path('auctionLifecycleId')).toBeDefined();
expect(AuctionSchema.path('lastAppliedAuctionStateTransitionId')).toBeDefined();
expect(
AuctionSchema.path('lastAppliedAuctionStateTransitionId'),
).toBeDefined();
expect(AuctionSchema.path('currentAuctionHistorySequence')).toBeDefined();
expect(AuctionSchema.path('startAuctionRequestId')).toBeDefined();
expect(AuctionSchema.path('startAuctionStateTransitionId')).toBeDefined();
@@ -36,46 +38,75 @@ describe('auction Redis schema foundation', () => {
expect(AuctionSchema.path('auctionBidHistory')).toBeDefined();
expect(AuctionSchema.path('currentHighestBidPointAmount')).toBeDefined();
expect(AuctionSchema.path('currentHighestBidderTeamIndex')).toBeDefined();
expect(AuctionSchema.path('currentBidRoundDeadlineTimestampMS')).toBeDefined();
expect(
AuctionSchema.path('currentBidRoundDeadlineTimestampMS'),
).toBeDefined();
expect(AuctionSchema.path('maximumBidRoundDurationSeconds')).toBeDefined();
expect(AuctionSchema.path('bidRoundExtensionSeconds')).toBeDefined();
expect(AuctionSchema.path('initialTeamBidPointAmount')).toBeDefined();
expect(AuctionSchema.path('topTierAuctionPriorityThreshold')).toBeDefined();
expect(AuctionSchema.path('manualTopTierAuctionPriorityUserIds')).toBeDefined();
expect(
AuctionSchema.path('manualTopTierAuctionPriorityUserIds'),
).toBeDefined();
expect(AuctionSchema.path('auctionStartedAtTimestampMS')).toBeDefined();
expect(AuctionSchema.path('auctionCompletedAtTimestampMS')).toBeDefined();
});
it('adds history transition fields and reset/undo action enum values', () => {
expect(AuctionHistoryEntrySchema.path('auctionStateTransitionId')).toBeDefined();
expect(
AuctionHistoryEntrySchema.path('auctionStateTransitionId'),
).toBeDefined();
expect(AuctionHistoryEntrySchema.path('auctionLifecycleId')).toBeDefined();
expect(AuctionHistoryEntrySchema.path('revision')).toBeDefined();
expect(AuctionHistoryEntrySchema.path('historyMutation')).toBeDefined();
expect(AuctionHistoryEntrySchema.path('matchSideEffectMutation')).toBeDefined();
expect(
AuctionHistoryEntrySchema.path('matchSideEffectMutation'),
).toBeDefined();
expect(
AuctionHistoryEntrySchema.path<string>('action').options.enum,
).toEqual(
expect.arrayContaining(['start', 'open-bidding', 'bid', 'sold', 'passed', 'next', 'complete', 'reset', 'undo']),
expect.arrayContaining([
'start',
'open-bidding',
'bid',
'sold',
'passed',
'next',
'complete',
'reset',
'undo',
]),
);
});
it('adds unique history indexes for sequence and transition idempotency', () => {
const indexes = AuctionHistoryEntrySchema.indexes();
expect(indexWithKeys(indexes, { auctionId: 1, sequence: 1 })?.[1]).toMatchObject({
expect(
indexWithKeys(indexes, { auctionId: 1, sequence: 1 })?.[1],
).toMatchObject({
unique: true,
});
expect(
indexWithKeys(indexes, { auctionId: 1, auctionStateTransitionId: 1 })?.[1],
indexWithKeys(indexes, {
auctionId: 1,
auctionStateTransitionId: 1,
})?.[1],
).toMatchObject({ unique: true, sparse: true });
});
it('registers auction side effect application model with lease fields and unique idempotency index', () => {
expect(AuctionSideEffectApplicationSchema.path('processingOwnerToken')).toBeDefined();
expect(
AuctionSideEffectApplicationSchema.path('processingLeaseExpiresAtTimestampMS'),
AuctionSideEffectApplicationSchema.path('processingOwnerToken'),
).toBeDefined();
expect(
AuctionSideEffectApplicationSchema.path(
'processingLeaseExpiresAtTimestampMS',
),
).toBeDefined();
expect(
AuctionSideEffectApplicationSchema.path('payloadChecksum'),
).toBeDefined();
expect(AuctionSideEffectApplicationSchema.path('payloadChecksum')).toBeDefined();
const indexes = AuctionSideEffectApplicationSchema.indexes();
expect(
@@ -2,7 +2,10 @@ import { Injectable, Logger, Scope, OnModuleInit } from '@nestjs/common';
import mongoose from 'mongoose';
import { applyMongoosePerformancePlugin } from '../observability/mongoose-performance.plugin';
import { SecretService } from '../secret/secret.service';
import { tournamentModelDefinitions, TournamentModelTypes } from './schema';
import {
tournamentModelDefinitions,
type TournamentModelTypes,
} from './schema';
export function resolveMongoDbName(nodeEnv = process.env.NODE_ENV): string {
if (nodeEnv === 'prod') return 'lolympus';
@@ -42,7 +45,8 @@ export class ConnectionService implements OnModuleInit {
private connectionPromise: Promise<mongoose.Connection> | null = null;
constructor(private readonly secretService: SecretService) {}
private tournamentModels: Map<string, mongoose.Model<any>> | null = null;
private tournamentModels: Map<keyof TournamentModelTypes, unknown> | null =
null;
public async getConnection(): Promise<mongoose.Connection> {
if (
@@ -89,14 +93,18 @@ export class ConnectionService implements OnModuleInit {
modelKey: K,
): Promise<mongoose.Model<TournamentModelTypes[K]>> {
const connection = await this.getConnection();
if (this.tournamentModels)
return this.tournamentModels.get(modelKey) as mongoose.Model<
TournamentModelTypes[K]
>;
if (this.tournamentModels) {
return this.requireTournamentModel(this.tournamentModels, modelKey);
}
const models = new Map<K, mongoose.Model<TournamentModelTypes[K]>>();
const models = new Map<keyof TournamentModelTypes, unknown>();
tournamentModelDefinitions.forEach((modelDefinition) => {
if (!(modelDefinition.schema instanceof mongoose.Schema)) {
throw new Error(
`Invalid Mongoose schema for model ${modelDefinition.name}.`,
);
}
applyMongoosePerformancePlugin(modelDefinition.schema);
// 이미 생성된 경우 컴파일 스킵.
if (
@@ -106,14 +114,14 @@ export class ConnectionService implements OnModuleInit {
)
) {
models.set(
modelDefinition.name as K,
modelDefinition.name,
connection.models[modelDefinition.name],
);
return;
} else {
models.set(
modelDefinition.name as K,
connection.model<TournamentModelTypes[K]>(
modelDefinition.name,
connection.model(
modelDefinition.name,
modelDefinition.schema,
modelDefinition.schemaName,
@@ -123,7 +131,18 @@ export class ConnectionService implements OnModuleInit {
});
this.tournamentModels = models;
return models.get(modelKey) as mongoose.Model<TournamentModelTypes[K]>;
return this.requireTournamentModel(models, modelKey);
}
private requireTournamentModel<K extends keyof TournamentModelTypes>(
models: ReadonlyMap<keyof TournamentModelTypes, unknown>,
modelKey: K,
): mongoose.Model<TournamentModelTypes[K]> {
const model = models.get(modelKey);
if (model === undefined) {
throw new Error(`Mongoose model ${modelKey} is not registered.`);
}
return model as mongoose.Model<TournamentModelTypes[K]>;
}
public async createSession(
@@ -1,4 +1,4 @@
import { DynamicModule, Module } from '@nestjs/common';
import { Module } from '@nestjs/common';
import { ConnectionService } from './connection.service';
@Module({
@@ -45,7 +45,10 @@ export async function migrateAuctionPassHistory(
};
}> = [];
for await (const doc of db.collection('auction').find({}).limit(options.limit ?? 0)) {
for await (const doc of db
.collection('auction')
.find({})
.limit(options.limit ?? 0)) {
stats.scannedAuctions += 1;
const set: Record<string, unknown> = {};
let changed = false;
@@ -27,17 +27,21 @@ function createDb(params: {
},
};
},
async bulkWrite(writes: Array<{
updateOne: {
filter: { _id: unknown };
update: {
$set: Record<string, unknown>;
$unset: Record<string, ''>;
async bulkWrite(
writes: Array<{
updateOne: {
filter: { _id: unknown };
update: {
$set: Record<string, unknown>;
$unset: Record<string, ''>;
};
};
};
}>) {
}>,
) {
for (const write of writes) {
const doc = docs.find((item) => item._id === write.updateOne.filter._id);
const doc = docs.find(
(item) => item._id === write.updateOne.filter._id,
);
if (!doc) continue;
Object.assign(doc, write.updateOne.update.$set);
for (const key of Object.keys(write.updateOne.update.$unset)) {
@@ -57,7 +61,10 @@ describe('migrateTeamIndex', () => {
auctions: [
{
_id: 'auction-1',
teams: [{ side: 'blue', groupIndex: 1 }, { side: 'red', groupIndex: 1 }],
teams: [
{ side: 'blue', groupIndex: 1 },
{ side: 'red', groupIndex: 1 },
],
bids: [{ side: 'red', groupIndex: 1, amount: 100 }],
currentBidder: 'red',
currentBidderGroupIndex: 1,
@@ -66,7 +73,10 @@ describe('migrateTeamIndex', () => {
matches: [
{
_id: 'match-1',
teams: [{ side: 'blue', groupIndex: 1 }, { side: 'red', groupIndex: 1 }],
teams: [
{ side: 'blue', groupIndex: 1 },
{ side: 'red', groupIndex: 1 },
],
result: {
winnerSide: 'blue',
blueScore: 1,
@@ -112,7 +122,10 @@ describe('migrateTeamIndex', () => {
currentBidderTeamIndex: 2,
});
expect(collections.match[0]).toMatchObject({
teams: [{ teamIndex: 1, name: '1팀' }, { teamIndex: 2, name: '2팀' }],
teams: [
{ teamIndex: 1, name: '1팀' },
{ teamIndex: 2, name: '2팀' },
],
result: {
winnerTeamIndex: 1,
games: [
@@ -45,8 +45,20 @@ export async function migrateTeamIndex(
changedMatches: 0,
};
await migrateCollection(db.collection('auction'), options.limit, dryRun, stats, 'auction');
await migrateCollection(db.collection('match'), options.limit, dryRun, stats, 'match');
await migrateCollection(
db.collection('auction'),
options.limit,
dryRun,
stats,
'auction',
);
await migrateCollection(
db.collection('match'),
options.limit,
dryRun,
stats,
'match',
);
return stats;
}
@@ -60,7 +72,7 @@ async function migrateCollection(
) {
const cursor = collection.find({}).limit(limit ?? 0);
const writes: Array<{
updateOne: {
updateOne: {
filter: { _id: unknown };
update: { $set: Record<string, unknown>; $unset: Record<string, ''> };
};
@@ -143,7 +155,8 @@ function migrateMatch(doc: AnyDoc) {
const migrated = { ...team };
const teamIndex = readTeamIndex(migrated);
if (teamIndex !== undefined) migrated.teamIndex = teamIndex;
if (!migrated.name && typeof teamIndex === 'number') migrated.name = `${teamIndex}팀`;
if (!migrated.name && typeof teamIndex === 'number')
migrated.name = `${teamIndex}팀`;
if ('side' in migrated || 'groupIndex' in migrated) changed = true;
delete migrated.side;
delete migrated.groupIndex;
@@ -200,7 +213,10 @@ function migrateResult(result: Record<string, unknown>) {
migrated.games = games;
const seriesResults = asArray(result.seriesResults).map((series) => {
if (typeof series.teamAIndex === 'number' && typeof series.teamBIndex === 'number') {
if (
typeof series.teamAIndex === 'number' &&
typeof series.teamBIndex === 'number'
) {
return series;
}
changed = true;
@@ -216,7 +232,9 @@ function migrateResult(result: Record<string, unknown>) {
const teamBIndex = Math.max(legacyBlueTeamIndex, legacyRedTeamIndex);
const blueScore = numberOrDefault(series.blueScore, 0);
const redScore = numberOrDefault(series.redScore, 0);
const winnerSide = isSide(series.winnerSide) ? series.winnerSide : undefined;
const winnerSide = isSide(series.winnerSide)
? series.winnerSide
: undefined;
const winnerTeamIndex =
winnerSide === 'blue'
? legacyBlueTeamIndex
@@ -231,12 +249,11 @@ function migrateResult(result: Record<string, unknown>) {
winnerTeamIndex,
};
});
migrated.seriesResults = seriesResults.length > 0 ? seriesResults : buildSeries(games);
migrated.seriesResults =
seriesResults.length > 0 ? seriesResults : buildSeries(games);
if (typeof migrated.winnerTeamIndex !== 'number') {
const migratedSeriesResults = Array.isArray(migrated.seriesResults)
? migrated.seriesResults
: [];
const migratedSeriesResults = asArray(migrated.seriesResults);
migrated.winnerTeamIndex =
resolveWinnerTeamIndex(migratedSeriesResults) ??
(isSide(migrated.winnerSide)
@@ -244,7 +261,11 @@ function migrateResult(result: Record<string, unknown>) {
: undefined);
}
if ('winnerSide' in migrated || 'blueScore' in migrated || 'redScore' in migrated) {
if (
'winnerSide' in migrated ||
'blueScore' in migrated ||
'redScore' in migrated
) {
changed = true;
}
delete migrated.winnerSide;
@@ -272,8 +293,12 @@ function buildSeries(games: Record<string, unknown>[]) {
const teamAIndex = Math.min(blueTeamIndex, redTeamIndex);
const teamBIndex = Math.max(blueTeamIndex, redTeamIndex);
const key = `${teamAIndex}:${teamBIndex}`;
const current =
bySeries.get(key) ?? { teamAIndex, teamBIndex, teamAWins: 0, teamBWins: 0 };
const current = bySeries.get(key) ?? {
teamAIndex,
teamBIndex,
teamAWins: 0,
teamBWins: 0,
};
if (winnerTeamIndex === teamAIndex) current.teamAWins += 1;
if (winnerTeamIndex === teamBIndex) current.teamBWins += 1;
current.winnerTeamIndex =
@@ -331,5 +356,7 @@ function numberOrDefault(value: unknown, fallback: number) {
}
function numberOrUndefined(value: unknown) {
return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
return typeof value === 'number' && Number.isFinite(value)
? value
: undefined;
}
@@ -30,20 +30,26 @@ function createDb(params: { auctions?: Doc[]; history?: Doc[] }) {
},
};
},
async bulkWrite(writes: Array<{
updateOne: {
filter: { _id: unknown };
update: {
$set?: Record<string, unknown>;
$unset?: Record<string, ''>;
async bulkWrite(
writes: Array<{
updateOne: {
filter: { _id: unknown };
update: {
$set?: Record<string, unknown>;
$unset?: Record<string, ''>;
};
};
};
}>) {
}>,
) {
for (const write of writes) {
const doc = docs.find((item) => item._id === write.updateOne.filter._id);
const doc = docs.find(
(item) => item._id === write.updateOne.filter._id,
);
if (!doc) continue;
Object.assign(doc, write.updateOne.update.$set ?? {});
for (const key of Object.keys(write.updateOne.update.$unset ?? {})) {
for (const key of Object.keys(
write.updateOne.update.$unset ?? {},
)) {
delete doc[key];
}
}
@@ -31,7 +31,10 @@ interface MigrationStats {
}
type AnyDoc = Record<string, unknown> & { _id: unknown };
type UpdateDoc = { $set?: Record<string, unknown>; $unset?: Record<string, ''> };
type UpdateDoc = {
$set?: Record<string, unknown>;
$unset?: Record<string, ''>;
};
const AUCTION_FIELD_RENAMES: Array<{
from: string;
@@ -43,7 +46,11 @@ const AUCTION_FIELD_RENAMES: Array<{
{ from: 'passedQueue', to: 'passedAuctionPlayerQueue' },
{ from: 'auctionRound', to: 'currentAuctionRound' },
{ from: 'currentIndex', to: 'currentAuctionPlayerOrderIndex' },
{ from: 'bids', to: 'auctionBidHistory', transform: transformAuctionBidHistory },
{
from: 'bids',
to: 'auctionBidHistory',
transform: transformAuctionBidHistory,
},
{ from: 'currentBid', to: 'currentHighestBidPointAmount' },
{ from: 'currentBidderTeamIndex', to: 'currentHighestBidderTeamIndex' },
{
@@ -157,7 +164,8 @@ async function countDuplicateHistorySequences(
const duplicates = new Set<string>();
for await (const doc of collection.find({}).limit(limit ?? 0)) {
const auctionId = stringifyId(doc.auctionId);
const sequence = typeof doc.sequence === 'number' ? doc.sequence : undefined;
const sequence =
typeof doc.sequence === 'number' ? doc.sequence : undefined;
if (!auctionId || sequence === undefined) continue;
const key = `${auctionId}:${sequence}`;
@@ -322,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);
}
@@ -117,7 +117,9 @@ function createDb(params: {
function matchesFilter(doc: Doc, filter: Record<string, unknown>): boolean {
const clauses = filter.$or;
if (Array.isArray(clauses)) {
return clauses.some((clause) => matchesFilter(doc, clause));
return (clauses as unknown[]).some(
(clause) => isRecord(clause) && matchesFilter(doc, clause),
);
}
return Object.entries(filter).every(([key, 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);
}
@@ -11,7 +11,11 @@ import {
} from '../../../double-elimination/double-elimination.util';
import { TOURNAMENT_CODE_EXPIRY_MARGIN_MS } from '../../../tournament-code/tournament-code.constants';
import { ConnectionService } from '../connection.service';
import type { MatchDocument, TournamentCodeDocument } from '../schema';
import type {
MatchDocument,
TournamentCode,
TournamentCodeDocument,
} from '../schema';
import { SecretModule } from '../../secret/secret.module';
interface CliOptions {
@@ -334,7 +338,7 @@ function printPlan(plan: MatchRepairPlan) {
async function applyPlan(
match: MatchDocument,
plan: MatchRepairPlan,
TournamentCodeModel: mongoose.Model<any>,
TournamentCodeModel: mongoose.Model<TournamentCode>,
session: mongoose.ClientSession,
) {
if (plan.skippedReason) return;
@@ -5,10 +5,7 @@ import { NestFactory } from '@nestjs/core';
import mongoose from 'mongoose';
import { readFile } from 'node:fs/promises';
import { resolve } from 'node:path';
import {
ConnectionService,
resolveMongoDbName,
} from '../connection.service';
import { ConnectionService, resolveMongoDbName } from '../connection.service';
import type {
MatchDocument,
MatchGameAssignment,
@@ -214,12 +211,16 @@ async function main() {
printPlan(options, match, codes, plan);
if (options.dryRun) {
console.log('No writes were made. Re-run with --apply to update MongoDB.');
console.log(
'No writes were made. Re-run with --apply to update MongoDB.',
);
return;
}
const now = new Date();
const session = await (await connectionService.getConnection()).startSession();
const session = await (
await connectionService.getConnection()
).startSession();
try {
await session.withTransaction(async () => {
await applyTournamentCodeUpdates(plan, now, session);
@@ -230,9 +231,9 @@ async function main() {
status: 'finished',
roundRobinMaxRounds: options.maxRounds,
gameSchedule: plan.schedule,
tournamentCodeIds: [
...plan.usedCodeByOldGameNumber.values(),
].map((code) => code._id),
tournamentCodeIds: [...plan.usedCodeByOldGameNumber.values()].map(
(code) => code._id,
),
resultPollState: {
startedAt: match.resultPollState?.startedAt ?? now,
lastPolledAt: now,
@@ -423,7 +424,9 @@ function partitionIntoRounds(
}
if (!fillRound(0)) {
throw new Error('Could not partition result games into simultaneous rounds.');
throw new Error(
'Could not partition result games into simultaneous rounds.',
);
}
return rounds;
@@ -586,8 +589,7 @@ function buildSeriesResults(games: MatchGameResult[]): MatchSeriesResult[] {
}
return [...bySeries.values()].sort(
(left, right) =>
left.teamAIndex - right.teamAIndex ||
left.teamBIndex - right.teamBIndex,
left.teamAIndex - right.teamAIndex || left.teamBIndex - right.teamBIndex,
);
}
@@ -219,9 +219,9 @@ async function listDuplicateHistorySequences(
.toArray();
}
function printDuplicateHistorySequences(groups: Awaited<
ReturnType<typeof listDuplicateHistorySequences>
>) {
function printDuplicateHistorySequences(
groups: Awaited<ReturnType<typeof listDuplicateHistorySequences>>,
) {
if (groups.length === 0) {
console.log('No duplicate auctionHistory auctionId+sequence groups found.');
return;
@@ -248,7 +248,8 @@ async function repairDuplicateHistorySequences(
): Promise<DuplicateSequenceRepairStats> {
const historyCollection = db.collection('auctionHistory');
const auctionCollection = db.collection('auction');
const affectedAuctionIds = await findAuctionIdsWithDuplicateHistorySequences(db);
const affectedAuctionIds =
await findAuctionIdsWithDuplicateHistorySequences(db);
const stats: DuplicateSequenceRepairStats = {
affectedAuctions: affectedAuctionIds.length,
changedAuctionSequenceFields: 0,
@@ -177,7 +177,9 @@ function parseArgs(argv: string[]): CliOptions {
function parseCommitQuorum(value: string | undefined, label: string) {
if (!value) {
throw new Error(`${label} requires a positive integer, majority, or votingMembers.`);
throw new Error(
`${label} requires a positive integer, majority, or votingMembers.`,
);
}
if (value === 'majority' || value === 'votingMembers') return value;
return parsePositiveInteger(value, label);
@@ -230,9 +232,7 @@ function printDuplicateGroups(groups: TournamentCodeDuplicateGroupSummary[]) {
kind: group.kind,
loserCodes: group.losers.map((loser) => loser.code ?? '').join(', '),
loserIds: group.losers.map((loser) => loser.id).join(', '),
loserStates: group.losers
.map((loser) => loser.state ?? '')
.join(', '),
loserStates: group.losers.map((loser) => loser.state ?? '').join(', '),
})),
);
}
@@ -2485,7 +2485,9 @@ MatchStatsSchema.index({ communityId: 1, userIds: 1 });
MatchStatsSchema.index({ communityId: 1, userIds: 1, scheduledAt: -1 });
MatchStatsSchema.index({ communityId: 1, championIds: 1 });
export const tournamentModelDefinitions: ModelDefinition[] = [
export const tournamentModelDefinitions: Array<
ModelDefinition & { name: keyof TournamentModelTypes }
> = [
...competitionModelDefinitions,
{ name: 'identity', schema: IdentitySchema, schemaName: 'identity' },
{ name: 'community', schema: CommunitySchema, schemaName: 'community' },
+1 -1
View File
@@ -1,5 +1,5 @@
export interface ModelDefinition {
name: string;
schema: mongoose.Schema<any>;
schema: unknown;
schemaName?: string;
}
@@ -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';
@@ -34,31 +34,32 @@ type SchemaWithPerformanceMarker = mongoose.Schema & {
[PERFORMANCE_PLUGIN_APPLIED]?: boolean;
};
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;
export function applyMongoosePerformancePlugin(schemaValue: unknown): void {
if (!(schemaValue instanceof mongoose.Schema)) {
throw new TypeError('Mongoose performance plugin requires a Schema.');
}
const schema = schemaValue as SchemaWithPerformanceMarker;
if (schema[PERFORMANCE_PLUGIN_APPLIED]) return;
schema[PERFORMANCE_PLUGIN_APPLIED] = true;
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,
function (error: unknown, _result: unknown, next: (error: unknown) => void) {
{ errorHandler: true },
function (
error: Error,
_result: unknown,
next: (error?: mongoose.CallbackError) => void,
) {
recordQueryPerformance(
this as unknown as QueryWithPerformanceState,
undefined,
@@ -68,19 +69,24 @@ 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',
function (error: unknown, _result: unknown, next: (error: unknown) => void) {
{ errorHandler: true },
function (
error: Error,
_result: unknown,
next: (error?: mongoose.CallbackError) => void,
) {
recordAggregatePerformance(
this as AggregateWithPerformanceState,
undefined,
@@ -164,8 +170,8 @@ export function countHydratedDocuments(result: unknown): number {
function isHydratedDocument(value: unknown): boolean {
return Boolean(
value &&
typeof value === 'object' &&
'$__' in (value as Record<string, unknown>),
typeof value === 'object' &&
'$__' in (value as Record<string, unknown>),
);
}
@@ -11,9 +11,7 @@ interface NewRelicCustomEventApi {
eventType: string,
attributes: Record<string, NewRelicAttributeValue>,
): void;
addCustomAttributes(
attributes: Record<string, NewRelicAttributeValue>,
): void;
addCustomAttributes(attributes: Record<string, NewRelicAttributeValue>): void;
setTransactionName(name: string): void;
}
const agent = newrelicAgent as unknown as NewRelicCustomEventApi;
@@ -52,8 +52,7 @@ export interface ApiRequestPerformanceEvent {
leanQueryCount: number;
}
export interface MongooseQueryPerformanceEvent
extends MongooseQueryPerformance {
export interface MongooseQueryPerformanceEvent extends MongooseQueryPerformance {
type: 'mongoose-query';
timestamp: string;
requestId?: string;
@@ -92,10 +91,7 @@ export function resolveApiPerformanceConfig(
const enabled = readBoolean(env.API_PERF_OBSERVABILITY_ENABLED, false);
return {
enabled,
localEventsEnabled: readBoolean(
env.API_PERF_LOCAL_EVENTS_ENABLED,
enabled,
),
localEventsEnabled: readBoolean(env.API_PERF_LOCAL_EVENTS_ENABLED, enabled),
localEventFile:
env.API_PERF_LOCAL_EVENT_FILE || '/tmp/lolympus-api-performance.ndjson',
newRelicRequestEventsEnabled: readBoolean(
@@ -35,8 +35,7 @@ export interface RunWithDistributedLockOptions {
lockRetryDelayMilliseconds?: number;
}
export interface RunWithRenewedDistributedLockOptions
extends RunWithDistributedLockOptions {
export interface RunWithRenewedDistributedLockOptions extends RunWithDistributedLockOptions {
lockRenewalIntervalMilliseconds: number;
}
@@ -55,16 +54,13 @@ export class DistributedLockService {
);
const lockOwnershipToken = options.lockOwnershipToken ?? randomUUID();
const result = await this.redisService.raw().sendCommand([
'SET',
options.lockKey,
lockOwnershipToken,
'NX',
'PX',
String(options.lockExpirationDurationMilliseconds),
]);
const result = await this.redisService
.raw()
.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,
@@ -76,34 +72,37 @@ export class DistributedLockService {
public async releaseLockIfOwned(
lockOwnership: DistributedLockOwnership,
): Promise<boolean> {
const result = await this.redisService.raw().sendCommand([
'EVAL',
RELEASE_LOCK_IF_OWNED_SCRIPT,
'1',
lockOwnership.lockKey,
lockOwnership.lockOwnershipToken,
]);
const result = await this.redisService
.raw()
.sendCommand([
'EVAL',
RELEASE_LOCK_IF_OWNED_SCRIPT,
'1',
lockOwnership.lockKey,
lockOwnership.lockOwnershipToken,
]);
return Number(result) === 1;
}
public async extendLockIfOwned(
lockOwnership: DistributedLockOwnership,
lockExpirationDurationMilliseconds =
lockOwnership.lockExpirationDurationMilliseconds,
lockExpirationDurationMilliseconds = lockOwnership.lockExpirationDurationMilliseconds,
): Promise<boolean> {
this.assertPositiveDuration(
lockExpirationDurationMilliseconds,
'lockExpirationDurationMilliseconds',
);
const result = await this.redisService.raw().sendCommand([
'EVAL',
EXTEND_LOCK_IF_OWNED_SCRIPT,
'1',
lockOwnership.lockKey,
lockOwnership.lockOwnershipToken,
String(lockExpirationDurationMilliseconds),
]);
const result = await this.redisService
.raw()
.sendCommand([
'EVAL',
EXTEND_LOCK_IF_OWNED_SCRIPT,
'1',
lockOwnership.lockKey,
lockOwnership.lockOwnershipToken,
String(lockExpirationDurationMilliseconds),
]);
return Number(result) === 1;
}
@@ -120,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)
}`,
);
});
@@ -139,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(
@@ -153,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)
}`,
);
});
@@ -25,7 +25,9 @@ async function readFirstSecret(
{
provide: REDIS_CLIENT,
inject: [SecretService],
useFactory: async (secretService: SecretService): Promise<RedisClient> => {
useFactory: async (
secretService: SecretService,
): Promise<RedisClient> => {
await secretService.ready();
const [url, endpoint, username, password] = await Promise.all([
@@ -52,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();
@@ -6,15 +6,17 @@ function createRedisService(client: Record<string, unknown>) {
describe('RedisService stream pending recovery', () => {
it('normalizes XAUTOCLAIM array replies into stream entries', async () => {
const sendCommand = jest.fn().mockResolvedValue([
'0-0',
[
const sendCommand = jest
.fn()
.mockResolvedValue([
'0-0',
[
'1700000000000-0',
['job', '{"kind":"poll-tournament-result"}', 'source', 'test'],
[
'1700000000000-0',
['job', '{"kind":"poll-tournament-result"}', 'source', 'test'],
],
],
],
]);
]);
const service = createRedisService({ sendCommand });
await expect(
@@ -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;
}
@@ -223,9 +226,7 @@ export class RedisService implements OnModuleDestroy {
])) as unknown;
const responseItems = Array.isArray(response) ? response : [];
const rawMessages = Array.isArray(responseItems[1])
? responseItems[1]
: [];
const rawMessages = Array.isArray(responseItems[1]) ? responseItems[1] : [];
return {
nextStartId: String(responseItems[0] ?? '0-0'),
@@ -258,12 +259,14 @@ export class RedisService implements OnModuleDestroy {
return this.client.publish(channel, message);
}
private normalizeClaimedStreamMessage(rawMessage: unknown): StreamEntry | null {
private normalizeClaimedStreamMessage(
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';
@@ -46,11 +46,13 @@ export function countKnownParticipants(
): { team100: number; team200: number; total: number } {
const team100 = detail.info.participants.filter(
(participant) =>
participant.teamId === RIOT_BLUE_TEAM_ID && userByPuuid.has(participant.puuid),
participant.teamId === RIOT_BLUE_TEAM_ID &&
userByPuuid.has(participant.puuid),
).length;
const team200 = detail.info.participants.filter(
(participant) =>
participant.teamId === RIOT_RED_TEAM_ID && userByPuuid.has(participant.puuid),
participant.teamId === RIOT_RED_TEAM_ID &&
userByPuuid.has(participant.puuid),
).length;
return { team100, team200, total: team100 + team200 };
}
@@ -78,13 +80,16 @@ export function buildParticipantsSnapshot(
tagLine: user.account.tagLine || participant.riotIdTagLine,
profileIconId: user.account.profileIconId,
tier:
user.account.tiers.find((tier) => tier.queueType === 'RANKED_SOLO_5x5') ??
user.account.tiers[0],
user.account.tiers.find(
(tier) => tier.queueType === 'RANKED_SOLO_5x5',
) ?? user.account.tiers[0],
preferredPositions: user.preferredPositions,
joinedAt: new Date(detail.info.gameCreation),
};
})
.filter((participant): participant is MatchParticipant => Boolean(participant));
.filter((participant): participant is MatchParticipant =>
Boolean(participant),
);
}
export function buildTeams(
@@ -105,7 +110,9 @@ export function buildTeams(
assignedPosition: resolveAssignedPosition(participant, user),
};
})
.filter((member): member is NonNullable<typeof member> => Boolean(member));
.filter((member): member is NonNullable<typeof member> =>
Boolean(member),
);
return {
teamIndex,
name: `${teamIndex}팀`,
@@ -3,9 +3,7 @@ import mongoose from 'mongoose';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
import { RiotJobQueueService } from '../riot-job-queue/riot-job-queue.service';
import type {
RiotJobPriority,
} from '../riot-job-queue/riot-job-queue.types';
import type { RiotJobPriority } from '../riot-job-queue/riot-job-queue.types';
import { MatchHistoryService } from './match-history.service';
interface RefreshBody {
@@ -1,4 +1,8 @@
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import {
BadRequestException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import type {
@@ -16,10 +20,7 @@ import {
type RiotQueueGroup,
type RiotRankFilter,
} from '../riot/riot-queue.constants';
import type {
RiotMatchDto,
RiotMatchParticipantDto,
} from '../riot/riot.types';
import type { RiotMatchDto, RiotMatchParticipantDto } from '../riot/riot.types';
import type {
ChampionStatsResponse,
ChampionStatsRow,
@@ -104,7 +105,10 @@ export class MatchHistoryService {
fetchedAt: tier.fetchedAt.toISOString(),
})),
tierHistory: [...context.account.tierHistory]
.sort((left, right) => left.recordedAt.getTime() - right.recordedAt.getTime())
.sort(
(left, right) =>
left.recordedAt.getTime() - right.recordedAt.getTime(),
)
.map((entry) => ({
queueType: entry.queueType,
tier: entry.tier,
@@ -170,7 +174,11 @@ export class MatchHistoryService {
seasonId: params.filters.seasonId,
});
const { queueIds } = this.resolveQueueFilters(params.filters);
const limit = this.clampLimit(params.filters.limit, DEFAULT_SUMMARY_LIMIT, 50);
const limit = this.clampLimit(
params.filters.limit,
DEFAULT_SUMMARY_LIMIT,
50,
);
const docs = await this.findStoredMatches({
context,
queueIds,
@@ -196,7 +204,11 @@ export class MatchHistoryService {
seasonId: params.filters.seasonId,
});
const { queueIds } = this.resolveQueueFilters(params.filters);
const limit = this.clampLimit(params.filters.limit, DEFAULT_RECENT_LIMIT, 30);
const limit = this.clampLimit(
params.filters.limit,
DEFAULT_RECENT_LIMIT,
30,
);
const docs = await this.findStoredMatches({
context,
queueIds,
@@ -212,7 +224,10 @@ export class MatchHistoryService {
return {
matches: page,
nextCursor: views.length > limit ? page[page.length - 1]?.gameCreation ?? null : null,
nextCursor:
views.length > limit
? (page[page.length - 1]?.gameCreation ?? null)
: null,
lastFetchedAt: this.resolveLastFetchedAt(docs, context),
season: context.season,
};
@@ -455,8 +470,9 @@ export class MatchHistoryService {
puuid: string,
): RiotMatchParticipantDto | null {
return (
match.info.participants.find((participant) => participant.puuid === puuid) ??
null
match.info.participants.find(
(participant) => participant.puuid === puuid,
) ?? null
);
}
@@ -570,7 +586,8 @@ export class MatchHistoryService {
return {
matchId: dto.metadata.matchId,
queueId: dto.info.queueId,
queueLabel: RIOT_QUEUE_LABELS[dto.info.queueId] ?? `큐 ${dto.info.queueId}`,
queueLabel:
RIOT_QUEUE_LABELS[dto.info.queueId] ?? `큐 ${dto.info.queueId}`,
gameCreation: dto.info.gameCreation,
gameDuration: dto.info.gameDuration,
win: participant.win,
@@ -684,11 +701,15 @@ export class MatchHistoryService {
return {
puuid: participant.puuid,
gameName: participant.riotIdGameName || participant.summonerName || 'Unknown',
gameName:
participant.riotIdGameName ||
participant.summonerName ||
'Unknown',
tagLine: participant.riotIdTagLine || '',
championId: participant.championId,
championLevel: participant.champLevel,
teamPosition: participant.teamPosition || participant.individualPosition,
teamPosition:
participant.teamPosition || participant.individualPosition,
kills: participant.kills,
deaths: participant.deaths,
assists: participant.assists,
@@ -720,7 +741,9 @@ export class MatchHistoryService {
}));
}
private resolvePerks(participant: RiotMatchParticipantDto): RecentMatchView['perks'] {
private resolvePerks(
participant: RiotMatchParticipantDto,
): RecentMatchView['perks'] {
const primary = participant.perks.styles.find(
(style) => style.description === 'primaryStyle',
);
@@ -750,11 +773,19 @@ export class MatchHistoryService {
) as Partial<Record<RiotLane, number>>;
}
private resolveTopChampions(views: RecentMatchView[]): RecentSummaryResponse['topChampions'] {
const byChampion = new Map<number, { games: number; wins: number; rating: number }>();
private resolveTopChampions(
views: RecentMatchView[],
): RecentSummaryResponse['topChampions'] {
const byChampion = new Map<
number,
{ games: number; wins: number; rating: number }
>();
for (const view of views) {
const stat =
byChampion.get(view.championId) ?? { games: 0, wins: 0, rating: 0 };
const stat = byChampion.get(view.championId) ?? {
games: 0,
wins: 0,
rating: 0,
};
stat.games += 1;
stat.wins += view.win ? 1 : 0;
stat.rating += view.rating;
@@ -797,7 +828,8 @@ export class MatchHistoryService {
participant.deaths,
participant.assists,
);
const kp = teamKills > 0 ? (participant.kills + participant.assists) / teamKills : 0;
const kp =
teamKills > 0 ? (participant.kills + participant.assists) / teamKills : 0;
const csPerMin = this.resolveTotalCs(participant) / Math.max(minutes, 1);
const visionPerMin = participant.visionScore / Math.max(minutes, 1);
const score =
@@ -815,8 +847,13 @@ export class MatchHistoryService {
): number {
const teamDamage = match.info.participants
.filter((candidate) => candidate.teamId === participant.teamId)
.reduce((sum, candidate) => sum + candidate.totalDamageDealtToChampions, 0);
return teamDamage > 0 ? participant.totalDamageDealtToChampions / teamDamage : 0;
.reduce(
(sum, candidate) => sum + candidate.totalDamageDealtToChampions,
0,
);
return teamDamage > 0
? participant.totalDamageDealtToChampions / teamDamage
: 0;
}
private resolveTotalCs(participant: RiotMatchParticipantDto): number {
@@ -827,11 +864,16 @@ export class MatchHistoryService {
match: RiotMatchDto,
participant: RiotMatchParticipantDto,
): number {
return Math.max((participant.timePlayed || match.info.gameDuration) / 60, 1);
return Math.max(
(participant.timePlayed || match.info.gameDuration) / 60,
1,
);
}
private resolveKda(kills: number, deaths: number, assists: number): number {
return deaths === 0 ? kills + assists : this.round((kills + assists) / deaths);
return deaths === 0
? kills + assists
: this.round((kills + assists) / deaths);
}
private resolveLastFetchedAt(
@@ -841,9 +883,11 @@ export class MatchHistoryService {
if (docs.length === 0) {
return context.account.recentStatsFetchedAt?.toISOString() ?? null;
}
const oldest = docs.reduce((acc, doc) =>
doc.fetchedAt.getTime() < acc.getTime() ? doc.fetchedAt : acc,
docs[0].fetchedAt);
const oldest = docs.reduce(
(acc, doc) =>
doc.fetchedAt.getTime() < acc.getTime() ? doc.fetchedAt : acc,
docs[0].fetchedAt,
);
return oldest.toISOString();
}
@@ -858,14 +902,17 @@ export class MatchHistoryService {
.map((row) => row.lastFetchedAt)
.filter((value): value is Date => value instanceof Date)
.reduce<Date | null>(
(acc, value) =>
!acc || value.getTime() < acc.getTime() ? value : acc,
(acc, value) => (!acc || value.getTime() < acc.getTime() ? value : acc),
null,
);
return oldest?.toISOString() ?? null;
}
private clampLimit(value: number | undefined, fallback: number, max: number): number {
private clampLimit(
value: number | undefined,
fallback: number,
max: number,
): number {
if (!value || !Number.isFinite(value)) return fallback;
return Math.max(1, Math.min(Math.floor(value), max));
}
@@ -882,18 +929,12 @@ export class MatchHistoryService {
return Math.round(value * 10) / 10;
}
private numberField(
value: RiotMatchParticipantDto,
key: string,
): number {
private numberField(value: RiotMatchParticipantDto, key: string): number {
const field = value[key];
return typeof field === 'number' && Number.isFinite(field) ? field : 0;
}
private booleanField(
value: RiotMatchParticipantDto,
key: string,
): boolean {
private booleanField(value: RiotMatchParticipantDto, key: string): boolean {
return value[key] === true;
}
}
@@ -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[]
@@ -5,10 +5,12 @@ describe('MatchService', () => {
function createServiceWithCreateModels() {
const createdPayloads: Record<string, unknown>[] = [];
const MatchModel = {
create: jest.fn().mockImplementation(async (payload) => {
createdPayloads.push(payload);
return payload;
}),
create: jest
.fn()
.mockImplementation(async (payload: Record<string, unknown>) => {
createdPayloads.push(payload);
return payload;
}),
exists: jest.fn().mockResolvedValue(null),
};
const CommunityModel = {
@@ -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)
}`,
);
});
@@ -8,7 +8,11 @@ import { RiotJobWorkerService } from './riot-job-worker.service';
import { RiotRefreshGateway } from './riot-refresh.gateway';
@Module({
imports: [RiotModule, LegacyImportModule, forwardRef(() => TournamentResultModule)],
imports: [
RiotModule,
LegacyImportModule,
forwardRef(() => TournamentResultModule),
],
controllers: [RiotJobQueueController],
providers: [RiotJobQueueService, RiotJobWorkerService, RiotRefreshGateway],
exports: [RiotJobQueueService],
@@ -95,7 +95,8 @@ export class RiotJobQueueService {
jobId: existingJobId,
queueGroup,
alreadyQueued: true,
etaSeconds: existingStatus?.etaSeconds ?? queuePosition * RIOT_JOB_AVG_SECONDS,
etaSeconds:
existingStatus?.etaSeconds ?? queuePosition * RIOT_JOB_AVG_SECONDS,
queuePosition: existingStatus?.queuePosition ?? queuePosition,
});
continue;
@@ -127,7 +128,8 @@ export class RiotJobQueueService {
jobId,
queueGroup,
alreadyQueued: true,
etaSeconds: status?.etaSeconds ?? queuePosition * RIOT_JOB_AVG_SECONDS,
etaSeconds:
status?.etaSeconds ?? queuePosition * RIOT_JOB_AVG_SECONDS,
queuePosition: status?.queuePosition ?? queuePosition,
});
continue;
@@ -164,7 +166,10 @@ export class RiotJobQueueService {
});
}
await this.setParent(parentJobId, subJobs.map((job) => job.jobId));
await this.setParent(
parentJobId,
subJobs.map((job) => job.jobId),
);
if (params.priority === 'high' && needsNewJob) {
await this.markRefreshRequested(context.user._id, context.account.puuid);
}
@@ -210,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',
@@ -218,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;
@@ -253,8 +257,8 @@ export class RiotJobQueueService {
const subJobs = (
await Promise.all(jobIds.map((jobId) => this.getStatus(jobId)))
).filter((status): status is RiotJobStatus => Boolean(status));
const done = subJobs.filter((job) =>
job.state === 'completed' || job.state === 'failed',
const done = subJobs.filter(
(job) => job.state === 'completed' || job.state === 'failed',
).length;
const state = this.resolveParentState(subJobs);
@@ -411,12 +415,14 @@ export class RiotJobQueueService {
job: PollTournamentResultJob,
deferUntilMs: number,
): Promise<void> {
await this.redisService.raw().sendCommand([
'ZADD',
RIOT_JOB_SCHEDULED_ZSET,
String(deferUntilMs),
JSON.stringify(job),
]);
await this.redisService
.raw()
.sendCommand([
'ZADD',
RIOT_JOB_SCHEDULED_ZSET,
String(deferUntilMs),
JSON.stringify(job),
]);
}
private parseScheduledJob(value: string): PollTournamentResultJob | null {
@@ -449,7 +455,10 @@ export class RiotJobQueueService {
);
}
private async setParent(parentJobId: string, jobIds: string[]): Promise<void> {
private async setParent(
parentJobId: string,
jobIds: string[],
): Promise<void> {
await this.redisService.setJson(
this.parentKey(parentJobId),
jobIds,
@@ -1,7 +1,4 @@
import type {
RiotPlatformRoute,
RiotRegionalRoute,
} from '../riot/riot.types';
import type { RiotPlatformRoute, RiotRegionalRoute } from '../riot/riot.types';
import type { RiotQueueGroup } from '../riot/riot-queue.constants';
import type { PollTournamentResultJob } from '../tournament-result/tournament-result.types';
import type { LegacyImportMemberJob } from '../legacy-import/legacy-import.types';
@@ -21,14 +21,16 @@ function makeWorker() {
deleteStreamEntries: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<RedisService>;
const distributedLockService = {
runWithRenewedLock: jest.fn().mockImplementation(async (options, operation) =>
operation({
lockKey: options.lockKey,
lockOwnershipToken: 'lock-owner',
lockExpirationDurationMilliseconds:
options.lockExpirationDurationMilliseconds,
}),
),
runWithRenewedLock: jest
.fn()
.mockImplementation(async (options, operation) =>
operation({
lockKey: options.lockKey,
lockOwnershipToken: 'lock-owner',
lockExpirationDurationMilliseconds:
options.lockExpirationDurationMilliseconds,
}),
),
} as unknown as jest.Mocked<DistributedLockService>;
const jobQueueService = {
markProcessing: jest.fn().mockResolvedValue(undefined),
@@ -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)
}`,
);
});
@@ -275,10 +275,10 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
): Promise<{ stream: string; message: StreamEntry } | null> {
const result = await this.redisService.readGroup(
stream,
RIOT_JOB_GROUP,
this.consumerIdentifier,
'>',
{ count: 1, blockMs },
RIOT_JOB_GROUP,
this.consumerIdentifier,
'>',
{ count: 1, blockMs },
);
const message = result?.[0]?.messages[0];
return message ? { stream, message } : null;
@@ -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 });
}
@@ -70,7 +70,10 @@ export class RiotRefreshGateway {
if (typeof payload?.puuid === 'string' && payload.puuid.trim()) {
rooms.push(`puuid:${payload.puuid.trim()}`);
}
if (typeof payload?.parentJobId === 'string' && payload.parentJobId.trim()) {
if (
typeof payload?.parentJobId === 'string' &&
payload.parentJobId.trim()
) {
rooms.push(`parent:${payload.parentJobId.trim()}`);
}
return rooms;
@@ -101,7 +101,7 @@ function makeService(overrides?: {
Promise.resolve({
riotPlatform: 'kr',
riotRegion: 'asia',
}),
}),
}),
}),
});
@@ -198,65 +198,64 @@ describe('RiotAccountEnrichmentService', () => {
masteryService,
recentMatchesService,
recentStatsService,
} =
makeService({
user,
summoner: {
getByPuuid: jest.fn().mockResolvedValue({
} = makeService({
user,
summoner: {
getByPuuid: jest.fn().mockResolvedValue({
puuid: 'puuid-1',
profileIconId: 588,
revisionDate: 1776977597000,
summonerLevel: 529,
}),
} as Partial<RiotSummonerService>,
league: {
getEntriesByPuuid: jest.fn().mockResolvedValue([
{
leagueId: 'L1',
queueType: 'RANKED_SOLO_5x5',
tier: 'EMERALD',
rank: 'I',
puuid: 'puuid-1',
profileIconId: 588,
revisionDate: 1776977597000,
summonerLevel: 529,
}),
} as Partial<RiotSummonerService>,
league: {
getEntriesByPuuid: jest.fn().mockResolvedValue([
{
leagueId: 'L1',
queueType: 'RANKED_SOLO_5x5',
tier: 'EMERALD',
rank: 'I',
puuid: 'puuid-1',
leaguePoints: 75,
wins: 160,
losses: 148,
},
]),
} as Partial<RiotLeagueService>,
mastery: {
getTopByPuuid: jest.fn().mockResolvedValue([
{
puuid: 'puuid-1',
championId: 7,
championLevel: 70,
championPoints: 742560,
},
]),
} as Partial<RiotChampionMasteryService>,
recentMatches: {
syncRecentMatches: jest.fn().mockResolvedValue([]),
loadFromDb: jest.fn().mockResolvedValue([
{ matchId: 'KR_1', raw: {} },
{ matchId: 'KR_2', raw: {} },
]),
} as Partial<RiotRecentMatchesService>,
recentStats: {
computeSummary: jest.fn().mockReturnValue({
overall: {
games: 2,
wins: 1,
losses: 1,
avgKills: 5.5,
avgDeaths: 2.5,
avgAssists: 7,
avgCs: 175,
avgCsPerMin: 6.4,
mostPlayedChampionIds: [7, 103],
},
byLane: {},
}),
} as Partial<RiotRecentStatsService>,
});
leaguePoints: 75,
wins: 160,
losses: 148,
},
]),
} as Partial<RiotLeagueService>,
mastery: {
getTopByPuuid: jest.fn().mockResolvedValue([
{
puuid: 'puuid-1',
championId: 7,
championLevel: 70,
championPoints: 742560,
},
]),
} as Partial<RiotChampionMasteryService>,
recentMatches: {
syncRecentMatches: jest.fn().mockResolvedValue([]),
loadFromDb: jest.fn().mockResolvedValue([
{ matchId: 'KR_1', raw: {} },
{ matchId: 'KR_2', raw: {} },
]),
} as Partial<RiotRecentMatchesService>,
recentStats: {
computeSummary: jest.fn().mockReturnValue({
overall: {
games: 2,
wins: 1,
losses: 1,
avgKills: 5.5,
avgDeaths: 2.5,
avgAssists: 7,
avgCs: 175,
avgCsPerMin: 6.4,
mostPlayedChampionIds: [7, 103],
},
byLane: {},
}),
} as Partial<RiotRecentStatsService>,
});
const result = await service.enrichRiotAccount({
userId: user._id,
@@ -148,14 +148,18 @@ describe('RiotDdragonService', () => {
'ddragon:manifest:v5:ko_KR',
expect.objectContaining({
summonerSpells: expect.objectContaining({
'4': expect.objectContaining({ description: '커서 방향으로 순간이동합니다.' }),
'4': expect.objectContaining({
description: '커서 방향으로 순간이동합니다.',
}),
}),
runesReforged: expect.arrayContaining([
expect.objectContaining({
slots: expect.arrayContaining([
expect.objectContaining({
runes: expect.arrayContaining([
expect.objectContaining({ longDesc: expect.stringContaining('기본 공격') }),
expect.objectContaining({
longDesc: expect.stringContaining('기본 공격'),
}),
]),
}),
]),
@@ -114,7 +114,9 @@ export class RiotDdragonService {
constructor(private readonly redisService: RedisService) {}
public async getManifest(locale: string = DEFAULT_LOCALE): Promise<DdragonManifest> {
public async getManifest(
locale: string = DEFAULT_LOCALE,
): Promise<DdragonManifest> {
const normalizedLocale = normalizeLocale(locale);
const cacheKey = manifestCacheKey(normalizedLocale);
@@ -139,12 +141,14 @@ export class RiotDdragonService {
private async buildManifest(locale: string): Promise<DdragonManifest> {
const version = await this.fetchLatestVersion();
const [champions, summonerSpells, runesReforged, items] = await Promise.all([
this.fetchChampionMap(version, locale),
this.fetchSummonerSpellMap(version, locale),
this.fetchRuneStyles(version, locale),
this.fetchItemMap(version, locale),
]);
const [champions, summonerSpells, runesReforged, items] = await Promise.all(
[
this.fetchChampionMap(version, locale),
this.fetchSummonerSpellMap(version, locale),
this.fetchRuneStyles(version, locale),
this.fetchItemMap(version, locale),
],
);
return {
version,
cdn: DDRAGON_CDN,
@@ -158,7 +162,9 @@ export class RiotDdragonService {
}
private async fetchLatestVersion(): Promise<string> {
const versions = await this.fetchJson<unknown>(`${DDRAGON_BASE}/api/versions.json`);
const versions = await this.fetchJson<unknown>(
`${DDRAGON_BASE}/api/versions.json`,
);
if (!Array.isArray(versions) || typeof versions[0] !== 'string') {
throw new Error('ddragon versions.json response is malformed.');
}
@@ -219,7 +225,9 @@ export class RiotDdragonService {
const url = `${DDRAGON_CDN}/${version}/data/${locale}/runesReforged.json`;
const payload = await this.fetchJson<unknown>(url);
if (!Array.isArray(payload)) {
throw new Error(`ddragon runesReforged.json response is malformed (${url}).`);
throw new Error(
`ddragon runesReforged.json response is malformed (${url}).`,
);
}
return payload
@@ -229,8 +237,7 @@ export class RiotDdragonService {
key: style.key,
icon: style.icon,
name: style.name,
shortDesc:
typeof style.shortDesc === 'string' ? style.shortDesc : '',
shortDesc: typeof style.shortDesc === 'string' ? style.shortDesc : '',
longDesc: typeof style.longDesc === 'string' ? style.longDesc : '',
slots: (style.slots ?? []).map((slot) => ({
runes: (slot.runes ?? [])
@@ -290,9 +297,7 @@ export class RiotDdragonService {
signal: controller.signal,
});
if (!response.ok) {
throw new Error(
`ddragon request failed (${response.status}): ${url}`,
);
throw new Error(`ddragon request failed (${response.status}): ${url}`);
}
return (await response.json()) as T;
} catch (err) {
@@ -1,9 +1,6 @@
import { Injectable } from '@nestjs/common';
import { RiotClientService } from './riot.client.service';
import {
RiotLeagueEntryDto,
RiotPlatformLookupOptions,
} from './riot.types';
import { RiotLeagueEntryDto, RiotPlatformLookupOptions } from './riot.types';
@Injectable()
export class RiotLeagueService {
@@ -98,9 +98,7 @@ function validateMatchIdsLookupOptions(
assertOptionalNonNegativeInteger(options.endTime, 'endTime');
if (options.type !== undefined && !RIOT_MATCH_TYPES.includes(options.type)) {
throw new RangeError(
`type must be one of: ${RIOT_MATCH_TYPES.join(', ')}`,
);
throw new RangeError(`type must be one of: ${RIOT_MATCH_TYPES.join(', ')}`);
}
if (
@@ -278,7 +276,9 @@ function parseTimelineParticipant(
index: number,
): RiotMatchTimelineParticipantDto {
if (!isRecord(value)) {
throw new TypeError(`timeline.info.participants[${index}] must be an object.`);
throw new TypeError(
`timeline.info.participants[${index}] must be an object.`,
);
}
return {
@@ -287,7 +287,10 @@ function parseTimelineParticipant(
value.participantId,
`timeline.info.participants[${index}].participantId`,
),
puuid: requireString(value.puuid, `timeline.info.participants[${index}].puuid`),
puuid: requireString(
value.puuid,
`timeline.info.participants[${index}].puuid`,
),
};
}
@@ -589,7 +592,10 @@ function parseParticipant(
};
}
function parsePerks(value: unknown, participantIndex: number): RiotMatchPerksDto {
function parsePerks(
value: unknown,
participantIndex: number,
): RiotMatchPerksDto {
if (!isRecord(value)) {
throw new TypeError(
`participants[${participantIndex}].perks must be an object.`,
@@ -732,7 +738,9 @@ function parseBan(
banIndex: number,
): RiotMatchBanDto {
if (!isRecord(value)) {
throw new TypeError(`teams[${teamIndex}].bans[${banIndex}] must be an object.`);
throw new TypeError(
`teams[${teamIndex}].bans[${banIndex}] must be an object.`,
);
}
return {
@@ -781,7 +789,9 @@ function parseObjective(
key: keyof RiotMatchObjectivesDto,
): RiotMatchObjectiveDto {
if (!isRecord(value)) {
throw new TypeError(`teams[${teamIndex}].objectives.${key} must be an object.`);
throw new TypeError(
`teams[${teamIndex}].objectives.${key} must be an object.`,
);
}
return {
@@ -84,5 +84,10 @@ export function isRiotQueueGroup(value: string): value is RiotQueueGroup {
}
export function isRiotRankFilter(value: string): value is RiotRankFilter {
return value === 'all' || value === 'solo' || value === 'flex' || value === 'normal';
return (
value === 'all' ||
value === 'solo' ||
value === 'flex' ||
value === 'normal'
);
}
@@ -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)
}`,
);
}
@@ -150,13 +150,16 @@ async function runWithConcurrency<T>(
if (items.length === 0) return;
const queue = [...items];
const runners = Array.from({ length: Math.min(concurrency, queue.length) }, async () => {
while (queue.length > 0) {
const item = queue.shift();
if (item === undefined) return;
await worker(item);
}
});
const runners = Array.from(
{ length: Math.min(concurrency, queue.length) },
async () => {
while (queue.length > 0) {
const item = queue.shift();
if (item === undefined) return;
await worker(item);
}
},
);
await Promise.all(runners);
}
@@ -44,17 +44,29 @@ export class RiotRecentStatsService {
);
for (const match of filteredMatches) {
const participant = match.info.participants.find((entry) => entry.puuid === puuid);
const participant = match.info.participants.find(
(entry) => entry.puuid === puuid,
);
if (!participant) continue;
accumulateAggregate(overall, participant, match.info.gameCreation, match.info.gameDuration);
accumulateAggregate(
overall,
participant,
match.info.gameCreation,
match.info.gameDuration,
);
const lane = resolveLane(participant);
if (!lane) continue;
const aggregate = laneAggregates.get(lane);
if (!aggregate) continue;
accumulateAggregate(aggregate, participant, match.info.gameCreation, match.info.gameDuration);
accumulateAggregate(
aggregate,
participant,
match.info.gameCreation,
match.info.gameDuration,
);
}
if (overall.games === 0) {
@@ -133,7 +145,8 @@ function finalizeAggregate(aggregate: Aggregate): RiotLaneStats {
const mostPlayedChampionIds = [...aggregate.championCounts.entries()]
.sort((left, right) => {
if (right[1] !== left[1]) return right[1] - left[1];
const rightLastPlayed = aggregate.lastPlayedAtByChampion.get(right[0]) ?? 0;
const rightLastPlayed =
aggregate.lastPlayedAtByChampion.get(right[0]) ?? 0;
const leftLastPlayed = aggregate.lastPlayedAtByChampion.get(left[0]) ?? 0;
if (rightLastPlayed !== leftLastPlayed) {
return rightLastPlayed - leftLastPlayed;
@@ -1,9 +1,6 @@
import { Injectable } from '@nestjs/common';
import { RiotClientService } from './riot.client.service';
import {
RiotPlatformLookupOptions,
RiotSummonerDto,
} from './riot.types';
import { RiotPlatformLookupOptions, RiotSummonerDto } from './riot.types';
@Injectable()
export class RiotSummonerService {
@@ -17,8 +17,12 @@ describe('RiotWebhookController', () => {
});
it('logs the incoming webhook payload and returns an acknowledgement', () => {
const logSpy = jest.spyOn(console, 'log').mockImplementation(() => undefined);
const dirSpy = jest.spyOn(console, 'dir').mockImplementation(() => undefined);
const logSpy = jest
.spyOn(console, 'log')
.mockImplementation(() => undefined);
const dirSpy = jest
.spyOn(console, 'dir')
.mockImplementation(() => undefined);
const request = {
method: 'POST',
originalUrl: '/riot/webhooks/tournament',
@@ -1,10 +1,4 @@
import {
All,
Controller,
HttpCode,
HttpStatus,
Req,
} from '@nestjs/common';
import { All, Controller, HttpCode, HttpStatus, Req } from '@nestjs/common';
import type { Request } from 'express';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
@@ -20,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,
@@ -31,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,
};
Loaded 100 of 134 files, more files were not shown because too many files have changed in this diff. Show more