Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2004ea03fe | ||
|
|
8ec9edc35f | ||
|
|
61f1db0e6a |
No files matched your search
@@ -28,6 +28,8 @@ website/LICENSE
|
|||||||
!AGENTS.md
|
!AGENTS.md
|
||||||
!docs/specs/internal-match-game-analysis.md
|
!docs/specs/internal-match-game-analysis.md
|
||||||
!docs/plans/internal-match-game-analysis-p0-p1.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
|
!agents/**/*.md
|
||||||
!skills/**/*.md
|
!skills/**/*.md
|
||||||
/tmp/
|
/tmp/
|
||||||
|
|||||||
+2
-2
@@ -1,11 +1,11 @@
|
|||||||
# syntax=docker/dockerfile:1.7
|
# syntax=docker/dockerfile:1.7
|
||||||
|
|
||||||
FROM node:26-bookworm-slim AS pnpm-base
|
FROM node:24-bookworm-slim AS pnpm-base
|
||||||
|
|
||||||
ENV PNPM_HOME=/pnpm
|
ENV PNPM_HOME=/pnpm
|
||||||
ENV PATH="${PNPM_HOME}:${PATH}"
|
ENV PATH="${PNPM_HOME}:${PATH}"
|
||||||
|
|
||||||
RUN npm install --global pnpm@10.4.1
|
RUN corepack enable
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
|
|||||||
@@ -29,28 +29,7 @@ export default tseslint.config(
|
|||||||
'@typescript-eslint/no-explicit-any': 'off',
|
'@typescript-eslint/no-explicit-any': 'off',
|
||||||
'@typescript-eslint/no-floating-promises': 'warn',
|
'@typescript-eslint/no-floating-promises': 'warn',
|
||||||
'@typescript-eslint/no-unsafe-argument': 'warn',
|
'@typescript-eslint/no-unsafe-argument': 'warn',
|
||||||
'prettier/prettier': ['error', { endOfLine: 'auto' }],
|
"prettier/prettier": ["error", { endOfLine: "auto" }],
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
files: ['**/*.spec.ts', 'test/**/*.ts'],
|
|
||||||
rules: {
|
|
||||||
'@typescript-eslint/no-unsafe-assignment': 'off',
|
|
||||||
'@typescript-eslint/no-unsafe-call': 'off',
|
|
||||||
'@typescript-eslint/no-unsafe-member-access': 'off',
|
|
||||||
'@typescript-eslint/no-unsafe-return': 'off',
|
|
||||||
'@typescript-eslint/no-this-alias': 'off',
|
|
||||||
'@typescript-eslint/require-await': 'off',
|
|
||||||
'@typescript-eslint/unbound-method': 'off',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
files: ['src/modules/global/database/migrations/**/*.ts'],
|
|
||||||
rules: {
|
|
||||||
'@typescript-eslint/no-unsafe-assignment': 'off',
|
|
||||||
'@typescript-eslint/no-unsafe-call': 'off',
|
|
||||||
'@typescript-eslint/no-unsafe-member-access': 'off',
|
|
||||||
'@typescript-eslint/no-unsafe-return': 'off',
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -29,20 +29,20 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@lolympus/contracts": "workspace:*",
|
"@lolympus/contracts": "workspace:*",
|
||||||
"@nestjs/common": "^11.1.28",
|
"@nestjs/common": "^11.0.1",
|
||||||
"@nestjs/config": "^4.0.4",
|
"@nestjs/config": "^4.0.4",
|
||||||
"@nestjs/core": "^11.1.28",
|
"@nestjs/core": "^11.0.1",
|
||||||
"@nestjs/platform-express": "^11.1.28",
|
"@nestjs/platform-express": "^11.0.1",
|
||||||
"@nestjs/platform-socket.io": "^11.1.28",
|
"@nestjs/platform-socket.io": "^11.1.19",
|
||||||
"@nestjs/swagger": "^11.4.6",
|
"@nestjs/swagger": "^11.2.7",
|
||||||
"@nestjs/websockets": "^11.1.28",
|
"@nestjs/websockets": "^11.1.19",
|
||||||
"@socket.io/redis-adapter": "^8.3.0",
|
"@socket.io/redis-adapter": "^8.3.0",
|
||||||
"class-transformer": "^0.5.1",
|
"class-transformer": "^0.5.1",
|
||||||
"class-validator": "^0.15.1",
|
"class-validator": "^0.15.1",
|
||||||
"jose": "^6.2.2",
|
"jose": "^6.2.2",
|
||||||
"mongoose": "9.4.1",
|
"mongoose": "^9.4.1",
|
||||||
"nats": "^2.29.3",
|
"nats": "^2.29.3",
|
||||||
"newrelic": "^14.3.3",
|
"newrelic": "^14.1.2",
|
||||||
"redis": "^5.12.1",
|
"redis": "^5.12.1",
|
||||||
"reflect-metadata": "^0.2.2",
|
"reflect-metadata": "^0.2.2",
|
||||||
"rxjs": "^7.8.1",
|
"rxjs": "^7.8.1",
|
||||||
@@ -57,7 +57,7 @@
|
|||||||
"@nestjs/testing": "^11.0.1",
|
"@nestjs/testing": "^11.0.1",
|
||||||
"@types/express": "^5.0.0",
|
"@types/express": "^5.0.0",
|
||||||
"@types/jest": "^30.0.0",
|
"@types/jest": "^30.0.0",
|
||||||
"@types/node": "^26.1.1",
|
"@types/node": "^24.0.0",
|
||||||
"@types/supertest": "^7.0.0",
|
"@types/supertest": "^7.0.0",
|
||||||
"eslint": "^9.18.0",
|
"eslint": "^9.18.0",
|
||||||
"eslint-config-prettier": "^10.0.1",
|
"eslint-config-prettier": "^10.0.1",
|
||||||
|
|||||||
@@ -79,9 +79,7 @@ describe('AuctionDeadlineScheduler', () => {
|
|||||||
.spyOn(scheduler, 'processDueBidRoundDeadlines')
|
.spyOn(scheduler, 'processDueBidRoundDeadlines')
|
||||||
.mockResolvedValue({ completed: 0, prepared: 0, skipped: 0 });
|
.mockResolvedValue({ completed: 0, prepared: 0, skipped: 0 });
|
||||||
|
|
||||||
await (
|
await (scheduler as unknown as { safeTick: () => Promise<void> }).safeTick();
|
||||||
scheduler as unknown as { safeTick: () => Promise<void> }
|
|
||||||
).safeTick();
|
|
||||||
|
|
||||||
const leaderLockToken = redis.acquireTokenLock.mock.calls[0]?.[1];
|
const leaderLockToken = redis.acquireTokenLock.mock.calls[0]?.[1];
|
||||||
expect(redis.acquireTokenLock).toHaveBeenCalledWith(
|
expect(redis.acquireTokenLock).toHaveBeenCalledWith(
|
||||||
@@ -102,9 +100,7 @@ describe('AuctionDeadlineScheduler', () => {
|
|||||||
.spyOn(scheduler, 'processDueBidRoundDeadlines')
|
.spyOn(scheduler, 'processDueBidRoundDeadlines')
|
||||||
.mockResolvedValue({ completed: 0, prepared: 0, skipped: 0 });
|
.mockResolvedValue({ completed: 0, prepared: 0, skipped: 0 });
|
||||||
|
|
||||||
await (
|
await (scheduler as unknown as { safeTick: () => Promise<void> }).safeTick();
|
||||||
scheduler as unknown as { safeTick: () => Promise<void> }
|
|
||||||
).safeTick();
|
|
||||||
|
|
||||||
expect(processDueBidRoundDeadlinesSpy).not.toHaveBeenCalled();
|
expect(processDueBidRoundDeadlinesSpy).not.toHaveBeenCalled();
|
||||||
expect(redis.releaseTokenLock).not.toHaveBeenCalled();
|
expect(redis.releaseTokenLock).not.toHaveBeenCalled();
|
||||||
@@ -133,12 +129,10 @@ describe('AuctionDeadlineScheduler', () => {
|
|||||||
it('prepares and completes due auction deadlines', async () => {
|
it('prepares and completes due auction deadlines', async () => {
|
||||||
const matchId = '665f2f01f1f1f1f1f1f1f1f1';
|
const matchId = '665f2f01f1f1f1f1f1f1f1f1';
|
||||||
const completedState = { phase: 'passed', revision: 3 };
|
const completedState = { phase: 'passed', revision: 3 };
|
||||||
const { auctionService, eventBus, redisCommand, scheduler } = makeScheduler(
|
const { auctionService, eventBus, redisCommand, scheduler } = makeScheduler({
|
||||||
{
|
|
||||||
dueReply: [matchId],
|
dueReply: [matchId],
|
||||||
completedState,
|
completedState,
|
||||||
},
|
});
|
||||||
);
|
|
||||||
|
|
||||||
await expect(scheduler.processDueBidRoundDeadlines(10)).resolves.toEqual({
|
await expect(scheduler.processDueBidRoundDeadlines(10)).resolves.toEqual({
|
||||||
completed: 1,
|
completed: 1,
|
||||||
@@ -155,10 +149,7 @@ describe('AuctionDeadlineScheduler', () => {
|
|||||||
expect(auctionService.completePreparedExpiry).toHaveBeenCalledTimes(1);
|
expect(auctionService.completePreparedExpiry).toHaveBeenCalledTimes(1);
|
||||||
// 만료 확정 결과는 즉시 1차 broadcast돼야 한다(클라가 입찰 라운드에 멈춰
|
// 만료 확정 결과는 즉시 1차 broadcast돼야 한다(클라가 입찰 라운드에 멈춰
|
||||||
// 후속 액션에서 CONFLICT가 반복되는 것을 막는 핵심 동작).
|
// 후속 액션에서 CONFLICT가 반복되는 것을 막는 핵심 동작).
|
||||||
expect(eventBus.broadcastState).toHaveBeenCalledWith(
|
expect(eventBus.broadcastState).toHaveBeenCalledWith(matchId, completedState);
|
||||||
matchId,
|
|
||||||
completedState,
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('skips noop expiry preparations', async () => {
|
it('skips noop expiry preparations', async () => {
|
||||||
@@ -198,7 +189,10 @@ describe('AuctionDeadlineScheduler', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('continues processing later deadline items after one item fails', async () => {
|
it('continues processing later deadline items after one item fails', async () => {
|
||||||
const matchIds = ['665f2f01f1f1f1f1f1f1f1f1', '665f2f02f1f1f1f1f1f1f1f1'];
|
const matchIds = [
|
||||||
|
'665f2f01f1f1f1f1f1f1f1f1',
|
||||||
|
'665f2f02f1f1f1f1f1f1f1f1',
|
||||||
|
];
|
||||||
const { auctionService, redisCommand, scheduler } = makeScheduler({
|
const { auctionService, redisCommand, scheduler } = makeScheduler({
|
||||||
dueReply: matchIds,
|
dueReply: matchIds,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -101,9 +101,7 @@ export class AuctionDeadlineScheduler implements OnModuleInit, OnModuleDestroy {
|
|||||||
currentRedisTimestampMS: number,
|
currentRedisTimestampMS: number,
|
||||||
batchLimit: number,
|
batchLimit: number,
|
||||||
): Promise<string[]> {
|
): Promise<string[]> {
|
||||||
const reply = await this.auctionRedisService
|
const reply = await this.auctionRedisService.raw().sendCommand([
|
||||||
.raw()
|
|
||||||
.sendCommand([
|
|
||||||
'ZRANGEBYSCORE',
|
'ZRANGEBYSCORE',
|
||||||
BID_ROUND_DEADLINE_QUEUE_KEY,
|
BID_ROUND_DEADLINE_QUEUE_KEY,
|
||||||
'-inf',
|
'-inf',
|
||||||
@@ -179,11 +177,11 @@ export class AuctionDeadlineScheduler implements OnModuleInit, OnModuleDestroy {
|
|||||||
return { completed, prepared, skipped };
|
return { completed, prepared, skipped };
|
||||||
}
|
}
|
||||||
|
|
||||||
private async removeBidRoundDeadlineQueueEntry(
|
private async removeBidRoundDeadlineQueueEntry(matchId: string): Promise<void> {
|
||||||
matchId: string,
|
await this.auctionRedisService.raw().sendCommand([
|
||||||
): Promise<void> {
|
'ZREM',
|
||||||
await this.auctionRedisService
|
BID_ROUND_DEADLINE_QUEUE_KEY,
|
||||||
.raw()
|
matchId,
|
||||||
.sendCommand(['ZREM', BID_ROUND_DEADLINE_QUEUE_KEY, matchId]);
|
]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -20,8 +20,9 @@ export class AuctionEventBusService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public broadcastState(matchId: string, state: AuctionStateResponse): void {
|
public broadcastState(matchId: string, state: AuctionStateResponse): void {
|
||||||
this.auctionNamespace
|
this.auctionNamespace?.to(matchId).emit(
|
||||||
?.to(matchId)
|
'state',
|
||||||
.emit('state', serializeRealtimeAuction(state));
|
serializeRealtimeAuction(state),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -74,11 +74,13 @@ function serializeRealtimeAuctionPlayer(
|
|||||||
return player;
|
return player;
|
||||||
}
|
}
|
||||||
|
|
||||||
const lightweightPlayer = { ...player };
|
const {
|
||||||
delete lightweightPlayer.masteries;
|
masteries: _masteries,
|
||||||
delete lightweightPlayer.puuid;
|
puuid: _puuid,
|
||||||
delete lightweightPlayer.recentStatsSummary;
|
recentStatsSummary: _recentStatsSummary,
|
||||||
delete lightweightPlayer.tierHistory;
|
tierHistory: _tierHistory,
|
||||||
|
...lightweightPlayer
|
||||||
|
} = player;
|
||||||
|
|
||||||
return lightweightPlayer;
|
return lightweightPlayer;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,10 +22,7 @@ describe('resolveAuctionRejectionReason', () => {
|
|||||||
|
|
||||||
it('maps known BadRequest messages without a structured code', () => {
|
it('maps known BadRequest messages without a structured code', () => {
|
||||||
expect(
|
expect(
|
||||||
resolveAuctionRejectionReason(
|
resolveAuctionRejectionReason(undefined, 'Cannot advance from current phase.'),
|
||||||
undefined,
|
|
||||||
'Cannot advance from current phase.',
|
|
||||||
),
|
|
||||||
).toBe(
|
).toBe(
|
||||||
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_PHASE_DOES_NOT_ALLOW_ADVANCE,
|
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_PHASE_DOES_NOT_ALLOW_ADVANCE,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -41,9 +41,7 @@ export class AuctionSideEffectService {
|
|||||||
matchSideEffectStatus: AuctionMatchSideEffectStatus;
|
matchSideEffectStatus: AuctionMatchSideEffectStatus;
|
||||||
}): Promise<boolean> {
|
}): Promise<boolean> {
|
||||||
const keys = buildAuctionRedisKeys(params.matchId);
|
const keys = buildAuctionRedisKeys(params.matchId);
|
||||||
const result = await this.auctionRedisService
|
const result = await this.auctionRedisService.raw().sendCommand([
|
||||||
.raw()
|
|
||||||
.sendCommand([
|
|
||||||
'EVAL',
|
'EVAL',
|
||||||
[
|
[
|
||||||
"if redis.call('HGET', KEYS[1], 'auctionLifecycleId') ~= ARGV[1] then return 0 end",
|
"if redis.call('HGET', KEYS[1], 'auctionLifecycleId') ~= ARGV[1] then return 0 end",
|
||||||
@@ -80,7 +78,8 @@ export function canAcquireSideEffectLease(
|
|||||||
if (state.state === 'pending' || state.state === 'failed') return true;
|
if (state.state === 'pending' || state.state === 'failed') return true;
|
||||||
if (state.state !== 'processing') return false;
|
if (state.state !== 'processing') return false;
|
||||||
return (
|
return (
|
||||||
(state.processingLeaseExpiresAtTimestampMS ?? 0) <= currentRedisTimestampMS
|
(state.processingLeaseExpiresAtTimestampMS ?? 0) <=
|
||||||
|
currentRedisTimestampMS
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -59,7 +59,8 @@ export class AuctionController {
|
|||||||
initialTeamBidPointAmount: c.initialTeamBidPointAmount,
|
initialTeamBidPointAmount: c.initialTeamBidPointAmount,
|
||||||
})),
|
})),
|
||||||
initialTeamBidPointAmount: body.initialTeamBidPointAmount ?? 1000,
|
initialTeamBidPointAmount: body.initialTeamBidPointAmount ?? 1000,
|
||||||
maximumBidRoundDurationSeconds: body.maximumBidRoundDurationSeconds ?? 30,
|
maximumBidRoundDurationSeconds:
|
||||||
|
body.maximumBidRoundDurationSeconds ?? 30,
|
||||||
bidRoundExtensionSeconds: body.bidRoundExtensionSeconds ?? 5,
|
bidRoundExtensionSeconds: body.bidRoundExtensionSeconds ?? 5,
|
||||||
topTierAuctionPriorityThreshold:
|
topTierAuctionPriorityThreshold:
|
||||||
body.topTierAuctionPriorityThreshold ?? 'NONE',
|
body.topTierAuctionPriorityThreshold ?? 'NONE',
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import {
|
|||||||
} from '@nestjs/websockets';
|
} from '@nestjs/websockets';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
import type { JWTPayload } from 'jose';
|
import type { JWTPayload } from 'jose';
|
||||||
import type { DefaultEventsMap, Namespace, Socket } from 'socket.io';
|
import { Namespace, Socket } from 'socket.io';
|
||||||
import { AuthService } from '../auth/auth.service';
|
import { AuthService } from '../auth/auth.service';
|
||||||
import { IdentityService } from '../auth/identity.service';
|
import { IdentityService } from '../auth/identity.service';
|
||||||
import { JwtService } from '../auth/jwt.service';
|
import { JwtService } from '../auth/jwt.service';
|
||||||
@@ -78,20 +78,6 @@ interface BidRateLimitState {
|
|||||||
windowStartedAtTimestampMS: number;
|
windowStartedAtTimestampMS: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface AuctionSocketData {
|
|
||||||
auctionBidRateLimit?: BidRateLimitState;
|
|
||||||
identity?: IdentityDocument;
|
|
||||||
matchId?: string;
|
|
||||||
user?: UserDocument;
|
|
||||||
}
|
|
||||||
|
|
||||||
type AuctionSocket = Socket<
|
|
||||||
DefaultEventsMap,
|
|
||||||
DefaultEventsMap,
|
|
||||||
DefaultEventsMap,
|
|
||||||
AuctionSocketData
|
|
||||||
>;
|
|
||||||
|
|
||||||
const BID_RATE_LIMIT_WINDOW_MS = 1000;
|
const BID_RATE_LIMIT_WINDOW_MS = 1000;
|
||||||
const BID_RATE_LIMIT_MAX_REQUESTS_PER_WINDOW = 8;
|
const BID_RATE_LIMIT_MAX_REQUESTS_PER_WINDOW = 8;
|
||||||
const BID_RATE_LIMIT_REJECTION_CODE = 'BID_RATE_LIMITED';
|
const BID_RATE_LIMIT_REJECTION_CODE = 'BID_RATE_LIMITED';
|
||||||
@@ -106,7 +92,9 @@ const BID_RATE_LIMIT_REJECTION_MESSAGE =
|
|||||||
allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'],
|
allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'],
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
export class AuctionGateway
|
||||||
|
implements OnGatewayConnection, OnGatewayInit
|
||||||
|
{
|
||||||
@WebSocketServer()
|
@WebSocketServer()
|
||||||
private server!: Namespace;
|
private server!: Namespace;
|
||||||
|
|
||||||
@@ -126,14 +114,14 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
this.auctionEventBusService.attachAuctionNamespace(server);
|
this.auctionEventBusService.attachAuctionNamespace(server);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async handleConnection(socket: AuctionSocket) {
|
public async handleConnection(socket: Socket) {
|
||||||
try {
|
try {
|
||||||
await this.authenticateSocket(socket);
|
await this.authenticateSocket(socket);
|
||||||
this.logger.debug(`Auction client connected: ${socket.id}`);
|
this.logger.debug(`Auction client connected: ${socket.id}`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.logger.warn(
|
this.logger.warn(
|
||||||
`Auction client authentication failed: ${
|
`Auction client authentication failed: ${
|
||||||
err instanceof Error ? err.message : String(err)
|
err instanceof Error ? err.message : err
|
||||||
}`,
|
}`,
|
||||||
);
|
);
|
||||||
socket.disconnect(true);
|
socket.disconnect(true);
|
||||||
@@ -142,7 +130,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
|
|
||||||
@SubscribeMessage('join')
|
@SubscribeMessage('join')
|
||||||
public async handleJoin(
|
public async handleJoin(
|
||||||
@ConnectedSocket() socket: AuctionSocket,
|
@ConnectedSocket() socket: Socket,
|
||||||
@MessageBody() payload: JoinAuctionPayload,
|
@MessageBody() payload: JoinAuctionPayload,
|
||||||
) {
|
) {
|
||||||
if (!payload?.matchId || !mongoose.isValidObjectId(payload.matchId)) {
|
if (!payload?.matchId || !mongoose.isValidObjectId(payload.matchId)) {
|
||||||
@@ -170,7 +158,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
|
|
||||||
@SubscribeMessage('bid')
|
@SubscribeMessage('bid')
|
||||||
public async handleBid(
|
public async handleBid(
|
||||||
@ConnectedSocket() socket: AuctionSocket,
|
@ConnectedSocket() socket: Socket,
|
||||||
@MessageBody() payload: BidPayload,
|
@MessageBody() payload: BidPayload,
|
||||||
@Ack() ack?: (response: Record<string, unknown>) => void,
|
@Ack() ack?: (response: Record<string, unknown>) => void,
|
||||||
) {
|
) {
|
||||||
@@ -217,9 +205,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
ack?.({
|
ack?.({
|
||||||
...(bidDelta
|
...(bidDelta
|
||||||
? {}
|
? {}
|
||||||
: {
|
: { state: this.serializeAuction(bidResult as AuctionStateResponse) }),
|
||||||
state: this.serializeAuction(bidResult as AuctionStateResponse),
|
|
||||||
}),
|
|
||||||
ok: true,
|
ok: true,
|
||||||
bidRequestId,
|
bidRequestId,
|
||||||
bidDelta: broadcastBidDelta,
|
bidDelta: broadcastBidDelta,
|
||||||
@@ -234,12 +220,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
error,
|
error,
|
||||||
);
|
);
|
||||||
const bidServerTiming = this.extractBidServerTiming(rejectionAckFields);
|
const bidServerTiming = this.extractBidServerTiming(rejectionAckFields);
|
||||||
this.emitError(
|
this.emitError(socket, String(rejectionAckFields.message ?? ''));
|
||||||
socket,
|
|
||||||
typeof rejectionAckFields.message === 'string'
|
|
||||||
? rejectionAckFields.message
|
|
||||||
: '',
|
|
||||||
);
|
|
||||||
ack?.({
|
ack?.({
|
||||||
...rejectionAckFields,
|
...rejectionAckFields,
|
||||||
bidRequestId,
|
bidRequestId,
|
||||||
@@ -282,7 +263,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
|
|
||||||
@SubscribeMessage('open-bidding')
|
@SubscribeMessage('open-bidding')
|
||||||
public async handleOpenBidding(
|
public async handleOpenBidding(
|
||||||
@ConnectedSocket() socket: AuctionSocket,
|
@ConnectedSocket() socket: Socket,
|
||||||
@MessageBody() payload: AuctionActionPayload,
|
@MessageBody() payload: AuctionActionPayload,
|
||||||
@Ack() ack?: (response: Record<string, unknown>) => void,
|
@Ack() ack?: (response: Record<string, unknown>) => void,
|
||||||
) {
|
) {
|
||||||
@@ -311,7 +292,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
|
|
||||||
@SubscribeMessage('sold')
|
@SubscribeMessage('sold')
|
||||||
public async handleSold(
|
public async handleSold(
|
||||||
@ConnectedSocket() socket: AuctionSocket,
|
@ConnectedSocket() socket: Socket,
|
||||||
@MessageBody() payload: SoldPayload,
|
@MessageBody() payload: SoldPayload,
|
||||||
@Ack() ack?: (response: Record<string, unknown>) => void,
|
@Ack() ack?: (response: Record<string, unknown>) => void,
|
||||||
) {
|
) {
|
||||||
@@ -341,7 +322,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
|
|
||||||
@SubscribeMessage('next')
|
@SubscribeMessage('next')
|
||||||
public async handleNext(
|
public async handleNext(
|
||||||
@ConnectedSocket() socket: AuctionSocket,
|
@ConnectedSocket() socket: Socket,
|
||||||
@MessageBody() payload: AuctionActionPayload,
|
@MessageBody() payload: AuctionActionPayload,
|
||||||
@Ack() ack?: (response: Record<string, unknown>) => void,
|
@Ack() ack?: (response: Record<string, unknown>) => void,
|
||||||
) {
|
) {
|
||||||
@@ -370,7 +351,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
|
|
||||||
@SubscribeMessage('passed')
|
@SubscribeMessage('passed')
|
||||||
public async handlePassed(
|
public async handlePassed(
|
||||||
@ConnectedSocket() socket: AuctionSocket,
|
@ConnectedSocket() socket: Socket,
|
||||||
@MessageBody() payload: AuctionActionPayload,
|
@MessageBody() payload: AuctionActionPayload,
|
||||||
@Ack() ack?: (response: Record<string, unknown>) => void,
|
@Ack() ack?: (response: Record<string, unknown>) => void,
|
||||||
) {
|
) {
|
||||||
@@ -399,7 +380,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
|
|
||||||
@SubscribeMessage('chat-message')
|
@SubscribeMessage('chat-message')
|
||||||
public async handleChatMessage(
|
public async handleChatMessage(
|
||||||
@ConnectedSocket() socket: AuctionSocket,
|
@ConnectedSocket() socket: Socket,
|
||||||
@MessageBody() payload: ChatMessagePayload,
|
@MessageBody() payload: ChatMessagePayload,
|
||||||
) {
|
) {
|
||||||
const matchId = this.requireJoinedMatchId(socket);
|
const matchId = this.requireJoinedMatchId(socket);
|
||||||
@@ -425,7 +406,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private requireJoinedMatchId(socket: AuctionSocket): string | null {
|
private requireJoinedMatchId(socket: Socket): string | null {
|
||||||
const matchId = this.getSocketMatchId(socket);
|
const matchId = this.getSocketMatchId(socket);
|
||||||
if (!matchId) {
|
if (!matchId) {
|
||||||
this.emitError(socket, 'Join a match room before sending events.');
|
this.emitError(socket, 'Join a match room before sending events.');
|
||||||
@@ -434,9 +415,10 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
return matchId;
|
return matchId;
|
||||||
}
|
}
|
||||||
|
|
||||||
private consumeBidRateLimit(socket: AuctionSocket): boolean {
|
private consumeBidRateLimit(socket: Socket): boolean {
|
||||||
const currentTimestampMS = Date.now();
|
const currentTimestampMS = Date.now();
|
||||||
const previousState = socket.data.auctionBidRateLimit;
|
const previousState = socket.data
|
||||||
|
.auctionBidRateLimit as BidRateLimitState | undefined;
|
||||||
if (
|
if (
|
||||||
!previousState ||
|
!previousState ||
|
||||||
currentTimestampMS - previousState.windowStartedAtTimestampMS >=
|
currentTimestampMS - previousState.windowStartedAtTimestampMS >=
|
||||||
@@ -454,8 +436,10 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
return previousState.count <= BID_RATE_LIMIT_MAX_REQUESTS_PER_WINDOW;
|
return previousState.count <= BID_RATE_LIMIT_MAX_REQUESTS_PER_WINDOW;
|
||||||
}
|
}
|
||||||
|
|
||||||
private getSocketMatchId(socket: AuctionSocket): string | undefined {
|
private getSocketMatchId(socket: Socket): string | undefined {
|
||||||
return socket.data.matchId;
|
return typeof socket.data.matchId === 'string'
|
||||||
|
? socket.data.matchId
|
||||||
|
: undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
private toAuctionActionRequest(payload?: AuctionActionPayload) {
|
private toAuctionActionRequest(payload?: AuctionActionPayload) {
|
||||||
@@ -479,9 +463,8 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private readHandshakeUserId(socket: AuctionSocket): string | undefined {
|
private readHandshakeUserId(socket: Socket): string | undefined {
|
||||||
const handshakeAuth = socket.handshake.auth as Record<string, unknown>;
|
const authUserId = socket.handshake.auth['x-auth-user-id'];
|
||||||
const authUserId = handshakeAuth['x-auth-user-id'];
|
|
||||||
if (typeof authUserId === 'string') return authUserId;
|
if (typeof authUserId === 'string') return authUserId;
|
||||||
|
|
||||||
const header = socket.handshake.headers['x-auth-user-id'];
|
const header = socket.handshake.headers['x-auth-user-id'];
|
||||||
@@ -489,16 +472,16 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private resolveSocketUserId(
|
private resolveSocketUserId(
|
||||||
socket: AuctionSocket,
|
socket: Socket,
|
||||||
): mongoose.Types.ObjectId | undefined {
|
): mongoose.Types.ObjectId | undefined {
|
||||||
return socket.data.user?._id;
|
return (socket.data.user as UserDocument | undefined)?._id;
|
||||||
}
|
}
|
||||||
|
|
||||||
private resolveChatDisplayName(
|
private resolveChatDisplayName(
|
||||||
socket: AuctionSocket,
|
socket: Socket,
|
||||||
fallbackDisplayName?: string,
|
fallbackDisplayName?: string,
|
||||||
): string {
|
): string {
|
||||||
const user = socket.data.user;
|
const user = socket.data.user as UserDocument | undefined;
|
||||||
const primaryRiotAccount =
|
const primaryRiotAccount =
|
||||||
user?.riotAccounts.find((entry) => entry.isPrimary) ??
|
user?.riotAccounts.find((entry) => entry.isPrimary) ??
|
||||||
user?.riotAccounts[0];
|
user?.riotAccounts[0];
|
||||||
@@ -511,14 +494,14 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
if (user?.kakaoTalkNickname) return user.kakaoTalkNickname;
|
if (user?.kakaoTalkNickname) return user.kakaoTalkNickname;
|
||||||
if (user?.discordNickname) return user.discordNickname;
|
if (user?.discordNickname) return user.discordNickname;
|
||||||
|
|
||||||
const identity = socket.data.identity;
|
const identity = socket.data.identity as IdentityDocument | undefined;
|
||||||
if (identity?.displayName) return identity.displayName;
|
if (identity?.displayName) return identity.displayName;
|
||||||
if (identity?.email) return identity.email;
|
if (identity?.email) return identity.email;
|
||||||
|
|
||||||
return fallbackDisplayName ?? '관전자';
|
return fallbackDisplayName ?? '관전자';
|
||||||
}
|
}
|
||||||
|
|
||||||
private async authenticateSocket(socket: AuctionSocket): Promise<void> {
|
private async authenticateSocket(socket: Socket): Promise<void> {
|
||||||
const fallback = await this.authService.resolveDevUserById(
|
const fallback = await this.authService.resolveDevUserById(
|
||||||
this.readHandshakeUserId(socket),
|
this.readHandshakeUserId(socket),
|
||||||
);
|
);
|
||||||
@@ -548,20 +531,14 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private readHandshakeToken(socket: AuctionSocket): string | undefined {
|
private readHandshakeToken(socket: Socket): string | undefined {
|
||||||
const handshakeAuth = socket.handshake.auth as Record<string, unknown>;
|
const authToken = socket.handshake.auth.token;
|
||||||
const authToken = handshakeAuth.token;
|
|
||||||
if (typeof authToken === 'string' && authToken.trim()) {
|
if (typeof authToken === 'string' && authToken.trim()) {
|
||||||
return authToken.trim().replace(/^Bearer\s+/i, '');
|
return authToken.trim().replace(/^Bearer\s+/i, '');
|
||||||
}
|
}
|
||||||
|
|
||||||
const header: unknown = socket.handshake.headers.authorization;
|
const header = socket.handshake.headers.authorization;
|
||||||
const authorization =
|
const authorization = Array.isArray(header) ? header[0] : header;
|
||||||
typeof header === 'string'
|
|
||||||
? header
|
|
||||||
: Array.isArray(header) && typeof header[0] === 'string'
|
|
||||||
? header[0]
|
|
||||||
: undefined;
|
|
||||||
if (authorization?.startsWith('Bearer ')) {
|
if (authorization?.startsWith('Bearer ')) {
|
||||||
return authorization.slice('Bearer '.length).trim();
|
return authorization.slice('Bearer '.length).trim();
|
||||||
}
|
}
|
||||||
@@ -569,11 +546,10 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async resolveSocketUserForMatch(
|
private async resolveSocketUserForMatch(
|
||||||
socket: AuctionSocket,
|
socket: Socket,
|
||||||
matchId: string,
|
matchId: string,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
if (socket.data.user || !socket.data.identity) return;
|
if (socket.data.user || !socket.data.identity) return;
|
||||||
const identity = socket.data.identity;
|
|
||||||
|
|
||||||
const MatchModel = await this.connectionService.getModel('match');
|
const MatchModel = await this.connectionService.getModel('match');
|
||||||
const match = await MatchModel.findById(matchId).select({
|
const match = await MatchModel.findById(matchId).select({
|
||||||
@@ -582,11 +558,10 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
if (!match) return;
|
if (!match) return;
|
||||||
|
|
||||||
const UserModel = await this.connectionService.getModel('user');
|
const UserModel = await this.connectionService.getModel('user');
|
||||||
const user = await UserModel.findOne({
|
socket.data.user = await UserModel.findOne({
|
||||||
communityId: match.communityId,
|
communityId: match.communityId,
|
||||||
identityId: identity._id,
|
identityId: (socket.data.identity as IdentityDocument)._id,
|
||||||
}).exec();
|
}).exec();
|
||||||
socket.data.user = user ?? undefined;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private requireStringClaim(payload: JWTPayload, key: string): string {
|
private requireStringClaim(payload: JWTPayload, key: string): string {
|
||||||
@@ -620,7 +595,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
this.server.to(matchId).emit('match-side-effect', delta);
|
this.server.to(matchId).emit('match-side-effect', delta);
|
||||||
}
|
}
|
||||||
|
|
||||||
private emitChatHistory(socket: AuctionSocket, auction: AuctionDocument) {
|
private emitChatHistory(socket: Socket, auction: AuctionDocument) {
|
||||||
socket.emit('chat-history', {
|
socket.emit('chat-history', {
|
||||||
messages: (auction.chatMessages ?? []).map((message) =>
|
messages: (auction.chatMessages ?? []).map((message) =>
|
||||||
this.serializeChatMessage(message),
|
this.serializeChatMessage(message),
|
||||||
@@ -628,21 +603,16 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private emitKnownError(socket: AuctionSocket, error: unknown) {
|
private emitKnownError(socket: Socket, error: unknown) {
|
||||||
this.emitError(socket, this.resolveErrorPayload(error).message);
|
this.emitError(socket, this.resolveErrorPayload(error).message);
|
||||||
}
|
}
|
||||||
|
|
||||||
private emitError(socket: AuctionSocket, message: string) {
|
private emitError(socket: Socket, message: string) {
|
||||||
socket.emit('error', { message });
|
socket.emit('error', { message });
|
||||||
}
|
}
|
||||||
|
|
||||||
private serializeAuction(
|
private serializeAuction(auction: AuctionStateResponse) {
|
||||||
auction: AuctionStateResponse,
|
return JSON.parse(JSON.stringify(auction));
|
||||||
): Record<string, unknown> {
|
|
||||||
const serialized: unknown = JSON.parse(JSON.stringify(auction));
|
|
||||||
return typeof serialized === 'object' && serialized !== null
|
|
||||||
? (serialized as Record<string, unknown>)
|
|
||||||
: {};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -663,9 +633,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
typeof errorPayload.code === 'string' ? errorPayload.code : undefined,
|
typeof errorPayload.code === 'string' ? errorPayload.code : undefined,
|
||||||
errorPayload.message,
|
errorPayload.message,
|
||||||
);
|
);
|
||||||
const resyncRecommended = isAuctionResyncRecommended(
|
const resyncRecommended = isAuctionResyncRecommended(auctionRejectionReason);
|
||||||
auctionRejectionReason,
|
|
||||||
);
|
|
||||||
const state = resyncRecommended
|
const state = resyncRecommended
|
||||||
? await this.fetchSerializedAuctionState(matchId)
|
? await this.fetchSerializedAuctionState(matchId)
|
||||||
: undefined;
|
: undefined;
|
||||||
@@ -720,9 +688,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
return {
|
return {
|
||||||
code: error instanceof Error ? error.message : 'UNKNOWN',
|
code: error instanceof Error ? error.message : 'UNKNOWN',
|
||||||
message:
|
message:
|
||||||
error instanceof Error
|
error instanceof Error ? error.message : 'Unexpected auction gateway error.',
|
||||||
? error.message
|
|
||||||
: 'Unexpected auction gateway error.',
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -750,8 +716,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
bidDelta: Record<string, unknown> | null,
|
bidDelta: Record<string, unknown> | null,
|
||||||
): Record<string, unknown> | null {
|
): Record<string, unknown> | null {
|
||||||
if (!bidDelta || !('bidServerTiming' in bidDelta)) return bidDelta;
|
if (!bidDelta || !('bidServerTiming' in bidDelta)) return bidDelta;
|
||||||
const publicBidDelta = { ...bidDelta };
|
const { bidServerTiming: _bidServerTiming, ...publicBidDelta } = bidDelta;
|
||||||
delete publicBidDelta.bidServerTiming;
|
|
||||||
return publicBidDelta;
|
return publicBidDelta;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -759,7 +724,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
auction: AuctionStateResponse,
|
auction: AuctionStateResponse,
|
||||||
bidRequestId?: string,
|
bidRequestId?: string,
|
||||||
): Record<string, unknown> | null {
|
): Record<string, unknown> | null {
|
||||||
const serialized = this.serializeAuction(auction);
|
const serialized = this.serializeAuction(auction) as Record<string, unknown>;
|
||||||
const revision = Number(serialized.revision);
|
const revision = Number(serialized.revision);
|
||||||
const currentHighestBidPointAmount = Number(
|
const currentHighestBidPointAmount = Number(
|
||||||
serialized.currentHighestBidPointAmount ?? serialized.currentBid,
|
serialized.currentHighestBidPointAmount ?? serialized.currentBid,
|
||||||
@@ -774,13 +739,11 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
? Date.parse(serialized.currentDeadline)
|
? Date.parse(serialized.currentDeadline)
|
||||||
: 0),
|
: 0),
|
||||||
);
|
);
|
||||||
const redisBidHistory: unknown[] = Array.isArray(
|
const redisBidHistory = Array.isArray(serialized.auctionBidHistory)
|
||||||
serialized.auctionBidHistory,
|
? serialized.auctionBidHistory
|
||||||
)
|
|
||||||
? (serialized.auctionBidHistory as unknown[])
|
|
||||||
: [];
|
: [];
|
||||||
const legacyBidHistory: unknown[] = Array.isArray(serialized.bids)
|
const legacyBidHistory = Array.isArray(serialized.bids)
|
||||||
? (serialized.bids as unknown[])
|
? serialized.bids
|
||||||
: [];
|
: [];
|
||||||
const auctionBidHistoryEntry =
|
const auctionBidHistoryEntry =
|
||||||
redisBidHistory[redisBidHistory.length - 1] ??
|
redisBidHistory[redisBidHistory.length - 1] ??
|
||||||
@@ -812,7 +775,9 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private isBidDeltaResponse(value: unknown): value is AuctionBidDeltaResponse {
|
private isBidDeltaResponse(
|
||||||
|
value: unknown,
|
||||||
|
): value is AuctionBidDeltaResponse {
|
||||||
return (
|
return (
|
||||||
typeof value === 'object' &&
|
typeof value === 'object' &&
|
||||||
value !== null &&
|
value !== null &&
|
||||||
@@ -839,12 +804,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private serializeChatMessage(
|
private serializeChatMessage(message: AuctionChatMessage) {
|
||||||
message: AuctionChatMessage,
|
return JSON.parse(JSON.stringify(message));
|
||||||
): Record<string, unknown> {
|
|
||||||
const serialized: unknown = JSON.parse(JSON.stringify(message));
|
|
||||||
return typeof serialized === 'object' && serialized !== null
|
|
||||||
? (serialized as Record<string, unknown>)
|
|
||||||
: {};
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,30 +2,6 @@ import mongoose from 'mongoose';
|
|||||||
import { AuctionService } from './auction.service';
|
import { AuctionService } from './auction.service';
|
||||||
|
|
||||||
describe('AuctionService', () => {
|
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>) {
|
function createService(models: Record<string, unknown>) {
|
||||||
const auctionHistoryModel = {
|
const auctionHistoryModel = {
|
||||||
findOne: jest.fn().mockReturnValue({
|
findOne: jest.fn().mockReturnValue({
|
||||||
@@ -182,7 +158,8 @@ describe('AuctionService', () => {
|
|||||||
it('rejects non-positive or fractional bid amounts before loading auction state', async () => {
|
it('rejects non-positive or fractional bid amounts before loading auction state', async () => {
|
||||||
const matchId = new mongoose.Types.ObjectId();
|
const matchId = new mongoose.Types.ObjectId();
|
||||||
const auctionFindOne = jest.fn();
|
const auctionFindOne = jest.fn();
|
||||||
const { service, auctionRedisCommandService } = createService({
|
const { service, auctionRedisCommandService, auctionRedisService } =
|
||||||
|
createService({
|
||||||
auction: {
|
auction: {
|
||||||
findOne: auctionFindOne,
|
findOne: auctionFindOne,
|
||||||
},
|
},
|
||||||
@@ -1031,12 +1008,7 @@ describe('AuctionService', () => {
|
|||||||
);
|
);
|
||||||
const transitionInput =
|
const transitionInput =
|
||||||
auctionRedisCommandService.applyTransition.mock.calls[0][1];
|
auctionRedisCommandService.applyTransition.mock.calls[0][1];
|
||||||
expect(
|
expect(JSON.parse(transitionInput.durabilityPayloadJson)).toMatchObject({
|
||||||
parseJsonRecord(
|
|
||||||
transitionInput.durabilityPayloadJson,
|
|
||||||
'durabilityPayloadJson',
|
|
||||||
),
|
|
||||||
).toMatchObject({
|
|
||||||
afterAuctionMongoProjection: expect.objectContaining({
|
afterAuctionMongoProjection: expect.objectContaining({
|
||||||
phase: 'bidding',
|
phase: 'bidding',
|
||||||
revision: 2,
|
revision: 2,
|
||||||
@@ -1207,40 +1179,17 @@ describe('AuctionService', () => {
|
|||||||
|
|
||||||
const transitionInput =
|
const transitionInput =
|
||||||
auctionRedisCommandService.applyTransition.mock.calls[0][1];
|
auctionRedisCommandService.applyTransition.mock.calls[0][1];
|
||||||
const durabilityPayload = parseJsonRecord(
|
const durabilityPayload = JSON.parse(transitionInput.durabilityPayloadJson);
|
||||||
transitionInput.durabilityPayloadJson,
|
expect(durabilityPayload.snapshotBefore).toMatchObject({
|
||||||
'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',
|
phase: 'bidding',
|
||||||
revision: 4,
|
revision: 4,
|
||||||
});
|
});
|
||||||
expect(snapshotBeforeTeam.members).toEqual([]);
|
expect(durabilityPayload.snapshotBefore.auctionTeams[0].members).toEqual(
|
||||||
expect(projectedTeam.members).toEqual([
|
[],
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
durabilityPayload.afterAuctionMongoProjection.auctionTeams[0].members,
|
||||||
|
).toEqual([
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
memberAcquisitionBidPointAmount: 120,
|
memberAcquisitionBidPointAmount: 120,
|
||||||
userId: playerUserId.toString(),
|
userId: playerUserId.toString(),
|
||||||
@@ -1448,12 +1397,7 @@ describe('AuctionService', () => {
|
|||||||
});
|
});
|
||||||
const [, transitionInput] =
|
const [, transitionInput] =
|
||||||
auctionRedisCommandService.applyTransition.mock.calls.at(-1) ?? [];
|
auctionRedisCommandService.applyTransition.mock.calls.at(-1) ?? [];
|
||||||
expect(
|
expect(JSON.parse(transitionInput.durabilityPayloadJson)).toMatchObject({
|
||||||
parseJsonRecord(
|
|
||||||
transitionInput.durabilityPayloadJson,
|
|
||||||
'durabilityPayloadJson',
|
|
||||||
),
|
|
||||||
).toMatchObject({
|
|
||||||
afterAuctionMongoProjection: {
|
afterAuctionMongoProjection: {
|
||||||
matchSideEffectStatus: 'pending',
|
matchSideEffectStatus: 'pending',
|
||||||
phase: 'complete',
|
phase: 'complete',
|
||||||
@@ -2624,10 +2568,7 @@ describe('AuctionService', () => {
|
|||||||
durationSeconds: 30,
|
durationSeconds: 30,
|
||||||
mode: 'set-relative',
|
mode: 'set-relative',
|
||||||
});
|
});
|
||||||
const durabilityPayload = parseJsonRecord(
|
const durabilityPayload = JSON.parse(transitionInput.durabilityPayloadJson);
|
||||||
transitionInput.durabilityPayloadJson,
|
|
||||||
'durabilityPayloadJson',
|
|
||||||
);
|
|
||||||
expect(durabilityPayload).toMatchObject({
|
expect(durabilityPayload).toMatchObject({
|
||||||
auctionActionType: 'undo',
|
auctionActionType: 'undo',
|
||||||
historyMutation: {
|
historyMutation: {
|
||||||
|
|||||||
@@ -210,12 +210,8 @@ describe('AuctionRedisCommandService', () => {
|
|||||||
|
|
||||||
it('parses apply transition replay and rejected replies', async () => {
|
it('parses apply transition replay and rejected replies', async () => {
|
||||||
await expect(
|
await expect(
|
||||||
makeService([
|
makeService(['REPLAY', 'APPLIED', 'transition-1', '2100'])
|
||||||
'REPLAY',
|
.service.applyTransition('match-1', {
|
||||||
'APPLIED',
|
|
||||||
'transition-1',
|
|
||||||
'2100',
|
|
||||||
]).service.applyTransition('match-1', {
|
|
||||||
afterAuctionStructureStateJson: '{}',
|
afterAuctionStructureStateJson: '{}',
|
||||||
auctionHistorySequence: 5,
|
auctionHistorySequence: 5,
|
||||||
auctionLifecycleId: 'life-1',
|
auctionLifecycleId: 'life-1',
|
||||||
@@ -237,12 +233,8 @@ describe('AuctionRedisCommandService', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
await expect(
|
await expect(
|
||||||
makeService([
|
makeService(['REJECTED', 'CONFLICT', 'transition-1', '2200'])
|
||||||
'REJECTED',
|
.service.applyTransition('match-1', {
|
||||||
'CONFLICT',
|
|
||||||
'transition-1',
|
|
||||||
'2200',
|
|
||||||
]).service.applyTransition('match-1', {
|
|
||||||
afterAuctionStructureStateJson: '{}',
|
afterAuctionStructureStateJson: '{}',
|
||||||
auctionHistorySequence: 5,
|
auctionHistorySequence: 5,
|
||||||
auctionLifecycleId: 'life-1',
|
auctionLifecycleId: 'life-1',
|
||||||
@@ -296,13 +288,8 @@ describe('AuctionRedisCommandService', () => {
|
|||||||
|
|
||||||
it('parses expire prepare replay and noop replies', async () => {
|
it('parses expire prepare replay and noop replies', async () => {
|
||||||
await expect(
|
await expect(
|
||||||
makeService([
|
makeService(['REPLAY', 'passed', 'expire-1', '12', '3100'])
|
||||||
'REPLAY',
|
.service.expirePrepare('match-1', {
|
||||||
'passed',
|
|
||||||
'expire-1',
|
|
||||||
'12',
|
|
||||||
'3100',
|
|
||||||
]).service.expirePrepare('match-1', {
|
|
||||||
auctionStateTransitionId: 'expire-1',
|
auctionStateTransitionId: 'expire-1',
|
||||||
bidRoundExpiryRetryDelayMS: 3000,
|
bidRoundExpiryRetryDelayMS: 3000,
|
||||||
matchId: 'match-1',
|
matchId: 'match-1',
|
||||||
@@ -373,11 +360,8 @@ describe('AuctionRedisCommandService', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
await expect(
|
await expect(
|
||||||
makeService([
|
makeService(['REJECTED', 'INVALID_PATCH_ARITY', '4200'])
|
||||||
'REJECTED',
|
.service.hydrateState('match-1', {
|
||||||
'INVALID_PATCH_ARITY',
|
|
||||||
'4200',
|
|
||||||
]).service.hydrateState('match-1', {
|
|
||||||
auctionHistorySequence: 3,
|
auctionHistorySequence: 3,
|
||||||
auctionLifecycleId: 'life-1',
|
auctionLifecycleId: 'life-1',
|
||||||
maximumBidRoundDurationSeconds: 30,
|
maximumBidRoundDurationSeconds: 30,
|
||||||
|
|||||||
@@ -85,9 +85,7 @@ export function stringifyAuctionRedisStructureState(
|
|||||||
return JSON.stringify(buildAuctionRedisStructureState(input));
|
return JSON.stringify(buildAuctionRedisStructureState(input));
|
||||||
}
|
}
|
||||||
|
|
||||||
function countAuctionTeamMembersIncludingCaptain(
|
function countAuctionTeamMembersIncludingCaptain(team: RedisAuctionTeam): number {
|
||||||
team: RedisAuctionTeam,
|
|
||||||
): number {
|
|
||||||
const userIds = new Set<string>([team.captainUserId.toString()]);
|
const userIds = new Set<string>([team.captainUserId.toString()]);
|
||||||
for (const member of team.members) {
|
for (const member of team.members) {
|
||||||
userIds.add(member.userId.toString());
|
userIds.add(member.userId.toString());
|
||||||
|
|||||||
@@ -1,10 +1,7 @@
|
|||||||
import { AuctionRedisService } from './auction-redis.service';
|
import { AuctionRedisService } from './auction-redis.service';
|
||||||
import { AuctionRedisStateReaderService } from './auction-redis-state-reader.service';
|
import { AuctionRedisStateReaderService } from './auction-redis-state-reader.service';
|
||||||
|
|
||||||
function makeService(
|
function makeService(commandReplies: unknown[], currentServerTimestampMS = 1000) {
|
||||||
commandReplies: unknown[],
|
|
||||||
currentServerTimestampMS = 1000,
|
|
||||||
) {
|
|
||||||
const sendCommand = jest
|
const sendCommand = jest
|
||||||
.fn()
|
.fn()
|
||||||
.mockImplementation(() => Promise.resolve(commandReplies.shift()));
|
.mockImplementation(() => Promise.resolve(commandReplies.shift()));
|
||||||
@@ -152,9 +149,7 @@ describe('AuctionRedisStateReaderService', () => {
|
|||||||
[],
|
[],
|
||||||
]);
|
]);
|
||||||
|
|
||||||
await expect(
|
await expect(service.readAuctionStateView('match-1')).resolves.toMatchObject({
|
||||||
service.readAuctionStateView('match-1'),
|
|
||||||
).resolves.toMatchObject({
|
|
||||||
auctionLifecycleId: 'life-1',
|
auctionLifecycleId: 'life-1',
|
||||||
auctionTeams: [],
|
auctionTeams: [],
|
||||||
phase: 'presenting',
|
phase: 'presenting',
|
||||||
@@ -186,6 +181,7 @@ describe('AuctionRedisStateReaderService', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
it('returns null when live or structure state is absent', async () => {
|
it('returns null when live or structure state is absent', async () => {
|
||||||
await expect(
|
await expect(
|
||||||
makeService([[], '{"auctionTeams":[]}', []]).service.readAuctionStateView(
|
makeService([[], '{"auctionTeams":[]}', []]).service.readAuctionStateView(
|
||||||
|
|||||||
@@ -42,9 +42,7 @@ export class AuctionRedisStateReaderService {
|
|||||||
matchId: string,
|
matchId: string,
|
||||||
): Promise<AuctionRedisLiveStateIdentity | null> {
|
): Promise<AuctionRedisLiveStateIdentity | null> {
|
||||||
const keys = buildAuctionRedisKeys(matchId);
|
const keys = buildAuctionRedisKeys(matchId);
|
||||||
const reply = await this.auctionRedisService
|
const reply = await this.auctionRedisService.raw().sendCommand([
|
||||||
.raw()
|
|
||||||
.sendCommand([
|
|
||||||
'HMGET',
|
'HMGET',
|
||||||
keys.liveStateKey,
|
keys.liveStateKey,
|
||||||
'auctionLifecycleId',
|
'auctionLifecycleId',
|
||||||
@@ -70,9 +68,7 @@ export class AuctionRedisStateReaderService {
|
|||||||
): Promise<AuctionRedisBidContext | null> {
|
): Promise<AuctionRedisBidContext | null> {
|
||||||
const keys = buildAuctionRedisKeys(matchId);
|
const keys = buildAuctionRedisKeys(matchId);
|
||||||
const bidderTeamCaptainUserIdField = `team:${bidderTeamIndex}:captainUserId`;
|
const bidderTeamCaptainUserIdField = `team:${bidderTeamIndex}:captainUserId`;
|
||||||
const liveReply = await this.auctionRedisService
|
const liveReply = await this.auctionRedisService.raw().sendCommand([
|
||||||
.raw()
|
|
||||||
.sendCommand([
|
|
||||||
'HMGET',
|
'HMGET',
|
||||||
keys.liveStateKey,
|
keys.liveStateKey,
|
||||||
'phase',
|
'phase',
|
||||||
@@ -106,22 +102,17 @@ export class AuctionRedisStateReaderService {
|
|||||||
options: AuctionRedisStateViewReadOptions = {},
|
options: AuctionRedisStateViewReadOptions = {},
|
||||||
): Promise<Record<string, unknown> | null> {
|
): Promise<Record<string, unknown> | null> {
|
||||||
const keys = buildAuctionRedisKeys(matchId);
|
const keys = buildAuctionRedisKeys(matchId);
|
||||||
const [
|
const [currentServerTimestampMS, liveReply, structureStateJson, bidEntries] =
|
||||||
currentServerTimestampMS,
|
await Promise.all([
|
||||||
liveReply,
|
|
||||||
structureStateJson,
|
|
||||||
bidEntries,
|
|
||||||
] = await Promise.all([
|
|
||||||
this.auctionRedisService.getCurrentRedisTimestampMS(),
|
this.auctionRedisService.getCurrentRedisTimestampMS(),
|
||||||
this.auctionRedisService
|
this.auctionRedisService.raw().sendCommand(['HGETALL', keys.liveStateKey]),
|
||||||
.raw()
|
this.auctionRedisService.raw().sendCommand(['GET', keys.structureStateKey]),
|
||||||
.sendCommand(['HGETALL', keys.liveStateKey]),
|
this.auctionRedisService.raw().sendCommand([
|
||||||
this.auctionRedisService
|
'LRANGE',
|
||||||
.raw()
|
keys.bidHistoryKey,
|
||||||
.sendCommand(['GET', keys.structureStateKey]),
|
'0',
|
||||||
this.auctionRedisService
|
'-1',
|
||||||
.raw()
|
]),
|
||||||
.sendCommand(['LRANGE', keys.bidHistoryKey, '0', '-1']),
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const liveState = parseHashReply(liveReply, {
|
const liveState = parseHashReply(liveReply, {
|
||||||
@@ -151,7 +142,7 @@ export class AuctionRedisStateReaderService {
|
|||||||
revision: number;
|
revision: number;
|
||||||
},
|
},
|
||||||
shouldForceAuctionStateResync: options.shouldForceAuctionStateResync,
|
shouldForceAuctionStateResync: options.shouldForceAuctionStateResync,
|
||||||
structureState: parseJsonRecord(structureStateJson),
|
structureState: JSON.parse(structureStateJson) as Record<string, unknown>,
|
||||||
});
|
});
|
||||||
view.matchId = matchId;
|
view.matchId = matchId;
|
||||||
if (options.includeInternalLiveStateFields) {
|
if (options.includeInternalLiveStateFields) {
|
||||||
@@ -170,9 +161,12 @@ export class AuctionRedisStateReaderService {
|
|||||||
if (typeof structureStateJson !== 'string' || !structureStateJson) {
|
if (typeof structureStateJson !== 'string' || !structureStateJson) {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
const structureState = parseJsonRecord(structureStateJson);
|
const structureState = JSON.parse(structureStateJson) as Record<
|
||||||
const auctionTeams: unknown[] = Array.isArray(structureState.auctionTeams)
|
string,
|
||||||
? (structureState.auctionTeams as unknown[])
|
unknown
|
||||||
|
>;
|
||||||
|
const auctionTeams = Array.isArray(structureState.auctionTeams)
|
||||||
|
? structureState.auctionTeams
|
||||||
: [];
|
: [];
|
||||||
const bidderTeam = auctionTeams.find((entry) => {
|
const bidderTeam = auctionTeams.find((entry) => {
|
||||||
if (!entry || typeof entry !== 'object') return false;
|
if (!entry || typeof entry !== 'object') return false;
|
||||||
@@ -189,13 +183,6 @@ function stringValue(value: unknown): string | undefined {
|
|||||||
return typeof value === 'string' && value ? value : undefined;
|
return typeof value === 'string' && value ? value : undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseJsonRecord(json: string): Record<string, unknown> {
|
|
||||||
const value: unknown = JSON.parse(json);
|
|
||||||
return typeof value === 'object' && value !== null
|
|
||||||
? (value as Record<string, unknown>)
|
|
||||||
: {};
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseHashReply(
|
function parseHashReply(
|
||||||
reply: unknown,
|
reply: unknown,
|
||||||
options: { includeInternalLiveStateFields?: boolean } = {},
|
options: { includeInternalLiveStateFields?: boolean } = {},
|
||||||
@@ -223,10 +210,7 @@ function parseHashEntries(
|
|||||||
): Record<string, unknown> {
|
): Record<string, unknown> {
|
||||||
const result: Record<string, unknown> = {};
|
const result: Record<string, unknown> = {};
|
||||||
for (const [field, rawValue] of entries) {
|
for (const [field, rawValue] of entries) {
|
||||||
if (
|
if (!options.includeInternalLiveStateFields && isInternalLiveStateField(field)) {
|
||||||
!options.includeInternalLiveStateFields &&
|
|
||||||
isInternalLiveStateField(field)
|
|
||||||
) {
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const value = String(rawValue);
|
const value = String(rawValue);
|
||||||
|
|||||||
@@ -91,7 +91,9 @@ describe('auction apply transition redis script contract', () => {
|
|||||||
expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain(
|
expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain(
|
||||||
'shouldBroadcastState',
|
'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(
|
expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain(
|
||||||
"redis.call('HINCRBY'",
|
"redis.call('HINCRBY'",
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -64,7 +64,9 @@ describe('auction bid redis script contract', () => {
|
|||||||
expect(AUCTION_BID_SCRIPT.lua).toContain("redis.call('TIME')");
|
expect(AUCTION_BID_SCRIPT.lua).toContain("redis.call('TIME')");
|
||||||
expect(AUCTION_BID_SCRIPT.lua).toContain("redis.call('HINCRBY'");
|
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('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');
|
expect(AUCTION_BID_SCRIPT.lua).not.toContain('cjson.decode');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -3,11 +3,9 @@ import { buildAuctionRedisKeys } from './auction-redis.keys';
|
|||||||
describe('auction redis keys', () => {
|
describe('auction redis keys', () => {
|
||||||
it('builds lifecycle-safe key names from match id', () => {
|
it('builds lifecycle-safe key names from match id', () => {
|
||||||
expect(buildAuctionRedisKeys('match-1')).toMatchObject({
|
expect(buildAuctionRedisKeys('match-1')).toMatchObject({
|
||||||
actionRequestResultOrderKey:
|
actionRequestResultOrderKey: 'auction:match-1:auctionActionRequestResultOrder',
|
||||||
'auction:match-1:auctionActionRequestResultOrder',
|
|
||||||
actionRequestResultsKey: 'auction:match-1:auctionActionRequestResults',
|
actionRequestResultsKey: 'auction:match-1:auctionActionRequestResults',
|
||||||
appliedTransitionIdsKey:
|
appliedTransitionIdsKey: 'auction:match-1:appliedAuctionStateTransitionIds',
|
||||||
'auction:match-1:appliedAuctionStateTransitionIds',
|
|
||||||
bidHistoryKey: 'auction:match-1:auctionBidHistory',
|
bidHistoryKey: 'auction:match-1:auctionBidHistory',
|
||||||
bidRequestResultOrderKey: 'auction:match-1:bidRequestResultOrder',
|
bidRequestResultOrderKey: 'auction:match-1:bidRequestResultOrder',
|
||||||
bidRequestResultsKey: 'auction:match-1:bidRequestResults',
|
bidRequestResultsKey: 'auction:match-1:bidRequestResults',
|
||||||
|
|||||||
@@ -74,11 +74,9 @@ async function readFirstSecret(
|
|||||||
|
|
||||||
const logger = new Logger('AuctionRedisClient');
|
const logger = new Logger('AuctionRedisClient');
|
||||||
const client = createClient(auctionRedisOptions);
|
const client = createClient(auctionRedisOptions);
|
||||||
client.on('error', (error: unknown) => {
|
client.on('error', (error) => {
|
||||||
logger.error(
|
logger.error(
|
||||||
`Auction Redis client error: ${
|
`Auction Redis client error: ${error?.message ?? error}`,
|
||||||
error instanceof Error ? error.message : String(error)
|
|
||||||
}`,
|
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -15,9 +15,7 @@ function makeService(sendCommand: jest.Mock) {
|
|||||||
|
|
||||||
describe('AuctionRedisService', () => {
|
describe('AuctionRedisService', () => {
|
||||||
it('uses Redis TIME as the timestamp source', async () => {
|
it('uses Redis TIME as the timestamp source', async () => {
|
||||||
const service = makeService(
|
const service = makeService(jest.fn().mockResolvedValue(['1781700000', '123000']));
|
||||||
jest.fn().mockResolvedValue(['1781700000', '123000']),
|
|
||||||
);
|
|
||||||
|
|
||||||
await expect(service.getCurrentRedisTimestampMS()).resolves.toBe(
|
await expect(service.getCurrentRedisTimestampMS()).resolves.toBe(
|
||||||
1_781_700_000_123,
|
1_781_700_000_123,
|
||||||
|
|||||||
@@ -22,11 +22,7 @@ export class AuctionRedisNoscriptError extends Error {
|
|||||||
function isNoscriptError(error: unknown): boolean {
|
function isNoscriptError(error: unknown): boolean {
|
||||||
if (error instanceof AuctionRedisNoscriptError) return true;
|
if (error instanceof AuctionRedisNoscriptError) return true;
|
||||||
const message =
|
const message =
|
||||||
error instanceof Error
|
error instanceof Error ? error.message : typeof error === 'string' ? error : '';
|
||||||
? error.message
|
|
||||||
: typeof error === 'string'
|
|
||||||
? error
|
|
||||||
: '';
|
|
||||||
return /\bNOSCRIPT\b/iu.test(message);
|
return /\bNOSCRIPT\b/iu.test(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -85,15 +81,9 @@ export class AuctionRedisService implements OnModuleDestroy {
|
|||||||
if (!isNoscriptError(error)) throw error;
|
if (!isNoscriptError(error)) throw error;
|
||||||
}
|
}
|
||||||
|
|
||||||
const loadedShaReply = await this.client.sendCommand([
|
const loadedSha = String(
|
||||||
'SCRIPT',
|
await this.client.sendCommand(['SCRIPT', 'LOAD', params.script]),
|
||||||
'LOAD',
|
);
|
||||||
params.script,
|
|
||||||
]);
|
|
||||||
if (typeof loadedShaReply !== 'string') {
|
|
||||||
throw new Error('Redis SCRIPT LOAD returned a non-string SHA.');
|
|
||||||
}
|
|
||||||
const loadedSha = loadedShaReply;
|
|
||||||
return (await this.client.sendCommand(
|
return (await this.client.sendCommand(
|
||||||
buildEvalShaCommand(loadedSha, params.keys, params.values),
|
buildEvalShaCommand(loadedSha, params.keys, params.values),
|
||||||
)) as T;
|
)) as T;
|
||||||
@@ -117,7 +107,7 @@ export class AuctionRedisService implements OnModuleDestroy {
|
|||||||
token: string,
|
token: string,
|
||||||
ttlMS: number,
|
ttlMS: number,
|
||||||
): Promise<boolean> {
|
): Promise<boolean> {
|
||||||
const result = await this.client.sendCommand<string | null>([
|
const result = await this.client.sendCommand([
|
||||||
'SET',
|
'SET',
|
||||||
key,
|
key,
|
||||||
token,
|
token,
|
||||||
@@ -125,7 +115,7 @@ export class AuctionRedisService implements OnModuleDestroy {
|
|||||||
String(ttlMS),
|
String(ttlMS),
|
||||||
'NX',
|
'NX',
|
||||||
]);
|
]);
|
||||||
return result === 'OK';
|
return String(result) === 'OK';
|
||||||
}
|
}
|
||||||
|
|
||||||
public async releaseTokenLock(key: string, token: string): Promise<boolean> {
|
public async releaseTokenLock(key: string, token: string): Promise<boolean> {
|
||||||
|
|||||||
@@ -100,7 +100,9 @@ describe('auction redis state assembly', () => {
|
|||||||
'1000',
|
'1000',
|
||||||
]);
|
]);
|
||||||
expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain("redis.call('TIME')");
|
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(
|
expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain(
|
||||||
'mongoRevision > redisRevision',
|
'mongoRevision > redisRevision',
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -78,7 +78,9 @@ export function assembleAuctionViewFromRedisState(
|
|||||||
return {
|
return {
|
||||||
...params.structureState,
|
...params.structureState,
|
||||||
...params.liveState,
|
...params.liveState,
|
||||||
auctionBidHistory: params.auctionBidHistoryEntries.map(parseJsonValue),
|
auctionBidHistory: params.auctionBidHistoryEntries.map((entry) =>
|
||||||
|
JSON.parse(entry),
|
||||||
|
),
|
||||||
canPlaceBidInCurrentBidRound: !isExpiring,
|
canPlaceBidInCurrentBidRound: !isExpiring,
|
||||||
currentServerTimestampMS: params.currentServerTimestampMS,
|
currentServerTimestampMS: params.currentServerTimestampMS,
|
||||||
isAuctionStateTransitionInProgress: isExpiring,
|
isAuctionStateTransitionInProgress: isExpiring,
|
||||||
@@ -88,11 +90,6 @@ export function assembleAuctionViewFromRedisState(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseJsonValue(json: string): unknown {
|
|
||||||
const value: unknown = JSON.parse(json);
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function buildHydrateAuctionStateScriptInvocation(
|
export function buildHydrateAuctionStateScriptInvocation(
|
||||||
keys: AuctionRedisKeys,
|
keys: AuctionRedisKeys,
|
||||||
input: HydrateAuctionStateScriptInput,
|
input: HydrateAuctionStateScriptInput,
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
import type { JWTHeaderParameters, JWTPayload } from 'jose';
|
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';
|
import type { IdentityProviderName } from './jwt.service';
|
||||||
|
|
||||||
declare module 'express' {
|
declare module 'express' {
|
||||||
|
|||||||
@@ -2,7 +2,10 @@ import { Injectable } from '@nestjs/common';
|
|||||||
import type { Request } from 'express';
|
import type { Request } from 'express';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
import { ConnectionService } from '../global/database/connection.service';
|
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 { SecretService } from '../global/secret/secret.service';
|
||||||
import './auth-request';
|
import './auth-request';
|
||||||
|
|
||||||
|
|||||||
@@ -26,7 +26,8 @@ export class JwtAuthGuard implements CanActivate {
|
|||||||
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
|
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
|
||||||
[context.getHandler(), context.getClass()],
|
[context.getHandler(), context.getClass()],
|
||||||
);
|
);
|
||||||
const authzHeader = request.get('authorization');
|
const authz = request.headers?.authorization;
|
||||||
|
const authzHeader = Array.isArray(authz) ? authz[0] : authz;
|
||||||
|
|
||||||
if (!authzHeader) {
|
if (!authzHeader) {
|
||||||
const fallback =
|
const fallback =
|
||||||
@@ -73,7 +74,7 @@ export class JwtAuthGuard implements CanActivate {
|
|||||||
|
|
||||||
private pickIdPFromToken(token: string): IdentityProviderName {
|
private pickIdPFromToken(token: string): IdentityProviderName {
|
||||||
try {
|
try {
|
||||||
const { iss } = decodeJwt(token);
|
const { iss } = decodeJwt(token) as { iss?: string };
|
||||||
if (!iss) {
|
if (!iss) {
|
||||||
throw new Error('Token has no issuer (iss) claim');
|
throw new Error('Token has no issuer (iss) claim');
|
||||||
}
|
}
|
||||||
@@ -83,8 +84,7 @@ export class JwtAuthGuard implements CanActivate {
|
|||||||
}
|
}
|
||||||
throw new Error(`Unknown issuer: ${iss}`);
|
throw new Error(`Unknown issuer: ${iss}`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const message =
|
const message = err instanceof Error ? err.message : 'Unable to decode token';
|
||||||
err instanceof Error ? err.message : 'Unable to decode token';
|
|
||||||
throw new UnauthorizedException(message);
|
throw new UnauthorizedException(message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,13 +35,11 @@ export class JwtService {
|
|||||||
throw new Error('Empty token');
|
throw new Error('Empty token');
|
||||||
}
|
}
|
||||||
|
|
||||||
const provider =
|
if (identityProvider !== 'MICROSOFT_ENTRAID') {
|
||||||
identityProvider === 'MICROSOFT_ENTRAID'
|
throw new Error(`Identity provider not configured: ${identityProvider}`);
|
||||||
? await this.getEntraConfig()
|
|
||||||
: undefined;
|
|
||||||
if (!provider) {
|
|
||||||
throw new Error('Identity provider not configured.');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const provider = await this.getEntraConfig();
|
||||||
const result = await jwtVerify(token, provider.jwks, {
|
const result = await jwtVerify(token, provider.jwks, {
|
||||||
issuer: provider.issuer,
|
issuer: provider.issuer,
|
||||||
audience: provider.audience,
|
audience: provider.audience,
|
||||||
@@ -50,22 +48,14 @@ export class JwtService {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const { payload, protectedHeader } = result;
|
const { payload, protectedHeader } = result;
|
||||||
if (!provider.allowedAlgs.includes(protectedHeader.alg)) {
|
if (!provider.allowedAlgs.includes(protectedHeader.alg as string)) {
|
||||||
throw new Error(`Unexpected alg: ${protectedHeader.alg}`);
|
throw new Error(`Unexpected alg: ${protectedHeader.alg}`);
|
||||||
}
|
}
|
||||||
if (
|
if (payload.ver && payload.ver !== '2.0') {
|
||||||
payload.ver !== undefined &&
|
throw new Error(`Unsupported Entra token version: ${payload.ver}`);
|
||||||
(typeof payload.ver !== 'string' || payload.ver !== '2.0')
|
|
||||||
) {
|
|
||||||
throw new Error(
|
|
||||||
`Unsupported Entra token version: ${formatClaimValue(payload.ver)}`,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
if (
|
if (payload.tid && payload.tid !== provider.tenantId) {
|
||||||
payload.tid !== undefined &&
|
throw new Error(`Unexpected tenant: ${payload.tid}`);
|
||||||
(typeof payload.tid !== 'string' || payload.tid !== provider.tenantId)
|
|
||||||
) {
|
|
||||||
throw new Error(`Unexpected tenant: ${formatClaimValue(payload.tid)}`);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
@@ -108,16 +98,3 @@ export class JwtService {
|
|||||||
return this.entraConfig;
|
return this.entraConfig;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatClaimValue(value: unknown): string {
|
|
||||||
if (
|
|
||||||
typeof value === 'string' ||
|
|
||||||
typeof value === 'number' ||
|
|
||||||
typeof value === 'boolean' ||
|
|
||||||
typeof value === 'bigint'
|
|
||||||
) {
|
|
||||||
return String(value);
|
|
||||||
}
|
|
||||||
if (value === null) return 'null';
|
|
||||||
return JSON.stringify(value) ?? typeof value;
|
|
||||||
}
|
|
||||||
@@ -7,7 +7,7 @@ import {
|
|||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { Reflector } from '@nestjs/core';
|
import { Reflector } from '@nestjs/core';
|
||||||
import type { Request } from 'express';
|
import type { Request } from 'express';
|
||||||
import type { CommunityRole } from '../global/database/schema';
|
import { CommunityRole, UserDocument } from '../global/database/schema';
|
||||||
import { ROLES_KEY } from './roles.decorator';
|
import { ROLES_KEY } from './roles.decorator';
|
||||||
import './auth-request';
|
import './auth-request';
|
||||||
|
|
||||||
@@ -23,7 +23,7 @@ export class RolesGuard implements CanActivate {
|
|||||||
if (!requiredRoles || requiredRoles.length === 0) return true;
|
if (!requiredRoles || requiredRoles.length === 0) return true;
|
||||||
|
|
||||||
const req = context.switchToHttp().getRequest<Request>();
|
const req = context.switchToHttp().getRequest<Request>();
|
||||||
const user = req.user;
|
const user = req.user as UserDocument | undefined;
|
||||||
if (!user && req.identity) {
|
if (!user && req.identity) {
|
||||||
throw new ForbiddenException('No membership in this community.');
|
throw new ForbiddenException('No membership in this community.');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,10 +7,9 @@ import {
|
|||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class ParseObjectIdPipe implements PipeTransform<
|
export class ParseObjectIdPipe
|
||||||
string,
|
implements PipeTransform<string, mongoose.Types.ObjectId>
|
||||||
mongoose.Types.ObjectId
|
{
|
||||||
> {
|
|
||||||
public transform(
|
public transform(
|
||||||
value: string,
|
value: string,
|
||||||
metadata: ArgumentMetadata,
|
metadata: ArgumentMetadata,
|
||||||
|
|||||||
@@ -34,29 +34,16 @@ export class CommunityStatsCacheService {
|
|||||||
let deleted = 0;
|
let deleted = 0;
|
||||||
|
|
||||||
do {
|
do {
|
||||||
const reply = await client.sendCommand([
|
const reply = (await client.sendCommand([
|
||||||
'SCAN',
|
'SCAN',
|
||||||
cursor,
|
cursor,
|
||||||
'MATCH',
|
'MATCH',
|
||||||
match,
|
match,
|
||||||
'COUNT',
|
'COUNT',
|
||||||
'100',
|
'100',
|
||||||
]);
|
])) as [string, string[]];
|
||||||
if (!Array.isArray(reply)) {
|
cursor = reply[0];
|
||||||
throw new Error('Redis SCAN returned an invalid response.');
|
const keys = reply[1] ?? [];
|
||||||
}
|
|
||||||
const values = reply as unknown[];
|
|
||||||
const nextCursor = values[0];
|
|
||||||
const rawKeys = values[1];
|
|
||||||
if (typeof nextCursor !== 'string') {
|
|
||||||
throw new Error('Redis SCAN returned an invalid cursor.');
|
|
||||||
}
|
|
||||||
cursor = nextCursor;
|
|
||||||
const keys = Array.isArray(rawKeys)
|
|
||||||
? (rawKeys as unknown[]).filter(
|
|
||||||
(key): key is string => typeof key === 'string',
|
|
||||||
)
|
|
||||||
: [];
|
|
||||||
if (keys.length > 0) {
|
if (keys.length > 0) {
|
||||||
deleted += await client.del(keys);
|
deleted += await client.del(keys);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,14 +23,7 @@ export class CommunityStatsController {
|
|||||||
) {
|
) {
|
||||||
return this.communityStatsService.getMatches({
|
return this.communityStatsService.getMatches({
|
||||||
communityId,
|
communityId,
|
||||||
filters: this.toFilters({
|
filters: this.toFilters({ seasonId, from, to, championId, cursor, limit }),
|
||||||
seasonId,
|
|
||||||
from,
|
|
||||||
to,
|
|
||||||
championId,
|
|
||||||
cursor,
|
|
||||||
limit,
|
|
||||||
}),
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -92,14 +85,7 @@ export class CommunityStatsController {
|
|||||||
return this.communityStatsService.getUserInternalHistory({
|
return this.communityStatsService.getUserInternalHistory({
|
||||||
communityId,
|
communityId,
|
||||||
userId,
|
userId,
|
||||||
filters: this.toFilters({
|
filters: this.toFilters({ seasonId, from, to, championId, cursor, limit }),
|
||||||
seasonId,
|
|
||||||
from,
|
|
||||||
to,
|
|
||||||
championId,
|
|
||||||
cursor,
|
|
||||||
limit,
|
|
||||||
}),
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -7,10 +7,7 @@ import type {
|
|||||||
RiotLane,
|
RiotLane,
|
||||||
TeamSide,
|
TeamSide,
|
||||||
} from '../global/database/schema';
|
} from '../global/database/schema';
|
||||||
import type {
|
import type { RecentMatchView, HistorySeasonDto } from '../match-history/match-history.types';
|
||||||
RecentMatchView,
|
|
||||||
HistorySeasonDto,
|
|
||||||
} from '../match-history/match-history.types';
|
|
||||||
|
|
||||||
export interface CommunityStatsFilters {
|
export interface CommunityStatsFilters {
|
||||||
seasonId?: string;
|
seasonId?: string;
|
||||||
@@ -83,9 +80,7 @@ export interface LeaderboardRow {
|
|||||||
avgCsPerMin: number;
|
avgCsPerMin: number;
|
||||||
avgDamageShare: number;
|
avgDamageShare: number;
|
||||||
avgVisionScore: number;
|
avgVisionScore: number;
|
||||||
byLane: Partial<
|
byLane: Partial<Record<RiotLane, { games: number; wins: number; kda: number }>>;
|
||||||
Record<RiotLane, { games: number; wins: number; kda: number }>
|
|
||||||
>;
|
|
||||||
topChampions: Array<{ championId: number; games: number; winRate: number }>;
|
topChampions: Array<{ championId: number; games: number; winRate: number }>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -227,7 +227,9 @@ export class MatchStatsFragmentBuilder {
|
|||||||
participant,
|
participant,
|
||||||
rawParticipant,
|
rawParticipant,
|
||||||
buildEvents: rawParticipant
|
buildEvents: rawParticipant
|
||||||
? buildEventsByParticipantId.get(rawParticipant.participantId)
|
? buildEventsByParticipantId.get(
|
||||||
|
rawParticipant.participantId,
|
||||||
|
)
|
||||||
: undefined,
|
: undefined,
|
||||||
checkpoints: rawParticipant
|
checkpoints: rawParticipant
|
||||||
? checkpointsByParticipantId.get(rawParticipant.participantId)
|
? checkpointsByParticipantId.get(rawParticipant.participantId)
|
||||||
@@ -418,10 +420,7 @@ export class MatchStatsFragmentBuilder {
|
|||||||
private toBuildEventsByParticipantId(
|
private toBuildEventsByParticipantId(
|
||||||
timeline?: RiotMatchTimelineDto,
|
timeline?: RiotMatchTimelineDto,
|
||||||
): Map<number, ParticipantBuildEvents> {
|
): Map<number, ParticipantBuildEvents> {
|
||||||
const buildEventsByParticipantId = new Map<
|
const buildEventsByParticipantId = new Map<number, ParticipantBuildEvents>();
|
||||||
number,
|
|
||||||
ParticipantBuildEvents
|
|
||||||
>();
|
|
||||||
if (!timeline?.info.frames.length) return buildEventsByParticipantId;
|
if (!timeline?.info.frames.length) return buildEventsByParticipantId;
|
||||||
|
|
||||||
const getEvents = (participantId: number): ParticipantBuildEvents => {
|
const getEvents = (participantId: number): ParticipantBuildEvents => {
|
||||||
@@ -797,16 +796,13 @@ export class MatchStatsFragmentBuilder {
|
|||||||
? timelineDragon
|
? timelineDragon
|
||||||
: (rawObjectives?.dragon?.kills ?? 0),
|
: (rawObjectives?.dragon?.kills ?? 0),
|
||||||
inhibitor: rawObjectives?.inhibitor?.kills ?? 0,
|
inhibitor: rawObjectives?.inhibitor?.kills ?? 0,
|
||||||
baron:
|
baron: (timelineObjectives?.baron ?? 0) > 0
|
||||||
(timelineObjectives?.baron ?? 0) > 0
|
|
||||||
? (timelineObjectives?.baron ?? 0)
|
? (timelineObjectives?.baron ?? 0)
|
||||||
: (rawObjectives?.baron?.kills ?? 0),
|
: (rawObjectives?.baron?.kills ?? 0),
|
||||||
riftHerald:
|
riftHerald: (timelineObjectives?.riftHerald ?? 0) > 0
|
||||||
(timelineObjectives?.riftHerald ?? 0) > 0
|
|
||||||
? (timelineObjectives?.riftHerald ?? 0)
|
? (timelineObjectives?.riftHerald ?? 0)
|
||||||
: (rawObjectives?.riftHerald?.kills ?? 0),
|
: (rawObjectives?.riftHerald?.kills ?? 0),
|
||||||
voidGrub:
|
voidGrub: (timelineObjectives?.voidGrub ?? 0) > 0
|
||||||
(timelineObjectives?.voidGrub ?? 0) > 0
|
|
||||||
? (timelineObjectives?.voidGrub ?? 0)
|
? (timelineObjectives?.voidGrub ?? 0)
|
||||||
: (rawObjectives?.horde?.kills ?? 0),
|
: (rawObjectives?.horde?.kills ?? 0),
|
||||||
elderDragon: hasProjectedDragon ? timelineElder : 0,
|
elderDragon: hasProjectedDragon ? timelineElder : 0,
|
||||||
|
|||||||
@@ -125,8 +125,8 @@ describe('MatchStatsRepository', () => {
|
|||||||
|
|
||||||
if (
|
if (
|
||||||
stored &&
|
stored &&
|
||||||
stored.sourceCompetitionId?.equals(fragment.sourceCompetitionId) &&
|
stored.sourceCompetitionId?.equals(fragment.sourceCompetitionId!) &&
|
||||||
stored.sourceRevision <= fragment.sourceRevision
|
stored.sourceRevision! <= fragment.sourceRevision!
|
||||||
) {
|
) {
|
||||||
stored = fragment;
|
stored = fragment;
|
||||||
return { matchedCount: 1, upsertedCount: 0 };
|
return { matchedCount: 1, upsertedCount: 0 };
|
||||||
|
|||||||
@@ -6,7 +6,10 @@ import {
|
|||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
import { ConnectionService } from '../global/database/connection.service';
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
import { CommunityDocument, UserDocument } from '../global/database/schema';
|
import {
|
||||||
|
CommunityDocument,
|
||||||
|
UserDocument,
|
||||||
|
} from '../global/database/schema';
|
||||||
|
|
||||||
export interface CreateCommunityInput {
|
export interface CreateCommunityInput {
|
||||||
name: string;
|
name: string;
|
||||||
|
|||||||
@@ -485,7 +485,11 @@ function createHarness(
|
|||||||
let competitionCall = 0;
|
let competitionCall = 0;
|
||||||
const competitionModel = {
|
const competitionModel = {
|
||||||
findOneAndUpdate: jest.fn(
|
findOneAndUpdate: jest.fn(
|
||||||
(_filter: unknown, update: { $setOnInsert: InsertPayload }) => {
|
(
|
||||||
|
_filter: unknown,
|
||||||
|
update: { $setOnInsert: InsertPayload },
|
||||||
|
_queryOptions: unknown,
|
||||||
|
) => {
|
||||||
insertedPayloads.push(update.$setOnInsert);
|
insertedPayloads.push(update.$setOnInsert);
|
||||||
const selected = options.competitionResults?.[competitionCall++];
|
const selected = options.competitionResults?.[competitionCall++];
|
||||||
if (selected instanceof Error) return rejectedQuery(selected);
|
if (selected instanceof Error) return rejectedQuery(selected);
|
||||||
|
|||||||
@@ -429,14 +429,8 @@ export function applyCompetitionDomainInvariantIndexes(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export type CompetitionModelName =
|
|
||||||
| 'competition'
|
|
||||||
| 'competitionFact'
|
|
||||||
| 'competitionOutbox'
|
|
||||||
| 'tournamentCodeAssignment';
|
|
||||||
|
|
||||||
export const competitionModelDefinitions: Array<{
|
export const competitionModelDefinitions: Array<{
|
||||||
name: CompetitionModelName;
|
name: string;
|
||||||
schema: mongoose.Schema;
|
schema: mongoose.Schema;
|
||||||
schemaName: string;
|
schemaName: string;
|
||||||
}> = [
|
}> = [
|
||||||
|
|||||||
@@ -1,8 +1,4 @@
|
|||||||
import { projectCompetition } from './competition-projector';
|
import { projectCompetition } from './competition-projector';
|
||||||
import {
|
|
||||||
CompetitionDomainError,
|
|
||||||
type CompetitionDomainErrorCode,
|
|
||||||
} from './domain-error';
|
|
||||||
import { generateSeriesGraph } from './series-graph';
|
import { generateSeriesGraph } from './series-graph';
|
||||||
|
|
||||||
describe('projectCompetition', () => {
|
describe('projectCompetition', () => {
|
||||||
@@ -327,8 +323,7 @@ describe('projectCompetition', () => {
|
|||||||
'team-1',
|
'team-1',
|
||||||
);
|
);
|
||||||
|
|
||||||
expectCompetitionDomainError(
|
expect(() =>
|
||||||
() =>
|
|
||||||
projectCompetition({
|
projectCompetition({
|
||||||
competitionId,
|
competitionId,
|
||||||
revision: 1,
|
revision: 1,
|
||||||
@@ -338,7 +333,10 @@ describe('projectCompetition', () => {
|
|||||||
seriesGraph,
|
seriesGraph,
|
||||||
facts: [{ ...accepted, seriesId: 'series-does-not-exist' }],
|
facts: [{ ...accepted, seriesId: 'series-does-not-exist' }],
|
||||||
}),
|
}),
|
||||||
'GAME_SERIES_MISMATCH',
|
).toThrow(
|
||||||
|
expect.objectContaining({
|
||||||
|
code: 'GAME_SERIES_MISMATCH',
|
||||||
|
}),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -358,8 +356,7 @@ describe('projectCompetition', () => {
|
|||||||
'team-1',
|
'team-1',
|
||||||
);
|
);
|
||||||
|
|
||||||
expectCompetitionDomainError(
|
expect(() =>
|
||||||
() =>
|
|
||||||
projectCompetition({
|
projectCompetition({
|
||||||
competitionId,
|
competitionId,
|
||||||
revision: 1,
|
revision: 1,
|
||||||
@@ -369,7 +366,10 @@ describe('projectCompetition', () => {
|
|||||||
seriesGraph,
|
seriesGraph,
|
||||||
facts: [{ ...accepted, gameSlotId: 'slot-does-not-exist' }],
|
facts: [{ ...accepted, gameSlotId: 'slot-does-not-exist' }],
|
||||||
}),
|
}),
|
||||||
'GAME_SLOT_INVALID',
|
).toThrow(
|
||||||
|
expect.objectContaining({
|
||||||
|
code: 'GAME_SLOT_INVALID',
|
||||||
|
}),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -382,8 +382,7 @@ describe('projectCompetition', () => {
|
|||||||
};
|
};
|
||||||
const seriesGraph = generateSeriesGraph({ competitionId, teams, format });
|
const seriesGraph = generateSeriesGraph({ competitionId, teams, format });
|
||||||
|
|
||||||
expectCompetitionDomainError(
|
expect(() =>
|
||||||
() =>
|
|
||||||
projectCompetition({
|
projectCompetition({
|
||||||
competitionId,
|
competitionId,
|
||||||
revision: 1,
|
revision: 1,
|
||||||
@@ -409,7 +408,10 @@ describe('projectCompetition', () => {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
}),
|
}),
|
||||||
'ADJUDICATION_INVALID',
|
).toThrow(
|
||||||
|
expect.objectContaining({
|
||||||
|
code: 'ADJUDICATION_INVALID',
|
||||||
|
}),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -615,23 +617,3 @@ interface GameSlotLike {
|
|||||||
id: string;
|
id: string;
|
||||||
ordinal: number;
|
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,7 +1,6 @@
|
|||||||
import {
|
import {
|
||||||
assertReversalPreview,
|
assertReversalPreview,
|
||||||
buildReversalFacts,
|
buildReversalFacts,
|
||||||
CompetitionReversalError,
|
|
||||||
previewSeriesReversal,
|
previewSeriesReversal,
|
||||||
} from './competition-reversal';
|
} from './competition-reversal';
|
||||||
|
|
||||||
@@ -20,8 +19,7 @@ describe('Competition reversal planning', () => {
|
|||||||
];
|
];
|
||||||
|
|
||||||
it('rejects strict reversal when a descendant has result activity', () => {
|
it('rejects strict reversal when a descendant has result activity', () => {
|
||||||
expectCompetitionReversalError(
|
expect(() =>
|
||||||
() =>
|
|
||||||
previewSeriesReversal({
|
previewSeriesReversal({
|
||||||
competitionId: 'competition-1',
|
competitionId: 'competition-1',
|
||||||
revision: 2,
|
revision: 2,
|
||||||
@@ -31,7 +29,8 @@ describe('Competition reversal planning', () => {
|
|||||||
facts,
|
facts,
|
||||||
assignments,
|
assignments,
|
||||||
}),
|
}),
|
||||||
'REVERSAL_DESCENDANT_ACTIVITY',
|
).toThrow(
|
||||||
|
expect.objectContaining({ code: 'REVERSAL_DESCENDANT_ACTIVITY' }),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -106,8 +105,7 @@ describe('Competition reversal planning', () => {
|
|||||||
assignments,
|
assignments,
|
||||||
});
|
});
|
||||||
|
|
||||||
expectCompetitionReversalError(
|
expect(() =>
|
||||||
() =>
|
|
||||||
assertReversalPreview(
|
assertReversalPreview(
|
||||||
{
|
{
|
||||||
competitionId: 'competition-1',
|
competitionId: 'competition-1',
|
||||||
@@ -120,8 +118,7 @@ describe('Competition reversal planning', () => {
|
|||||||
},
|
},
|
||||||
preview.impactHash,
|
preview.impactHash,
|
||||||
),
|
),
|
||||||
'REVERSAL_PREVIEW_STALE',
|
).toThrow(expect.objectContaining({ code: 'REVERSAL_PREVIEW_STALE' }));
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('emits one append-only reversal fact for every active result fact', () => {
|
it('emits one append-only reversal fact for every active result fact', () => {
|
||||||
@@ -163,26 +160,6 @@ 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>>) {
|
function series(id: string, sources: Array<Record<string, unknown>>) {
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
|
|||||||
@@ -9,8 +9,7 @@ import { DakaoOutboxService } from './dakao-outbox.service';
|
|||||||
|
|
||||||
const SWEEP_INTERVAL_MS = 60 * 1000;
|
const SWEEP_INTERVAL_MS = 60 * 1000;
|
||||||
const STALE_OUTBOX_MS = 5 * 60 * 1000;
|
const STALE_OUTBOX_MS = 5 * 60 * 1000;
|
||||||
const SWEEP_LOCK_KEY =
|
const SWEEP_LOCK_KEY = 'distributed-lock:dakao-outbox:sweep-stale-publish-leases';
|
||||||
'distributed-lock:dakao-outbox:sweep-stale-publish-leases';
|
|
||||||
const SWEEP_LOCK_EXPIRATION_DURATION_MILLISECONDS = 55_000;
|
const SWEEP_LOCK_EXPIRATION_DURATION_MILLISECONDS = 55_000;
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
|
|||||||
@@ -78,7 +78,9 @@ export class DakaoOutboxService {
|
|||||||
await this.natsService.publishJetStream(params.subject, params.envelope, {
|
await this.natsService.publishJetStream(params.subject, params.envelope, {
|
||||||
messageId: params.eventId,
|
messageId: params.eventId,
|
||||||
});
|
});
|
||||||
await OutboxModel.updateOne(updateFilter, {
|
await OutboxModel.updateOne(
|
||||||
|
updateFilter,
|
||||||
|
{
|
||||||
$set: {
|
$set: {
|
||||||
state: 'published',
|
state: 'published',
|
||||||
publishedAt: new Date(),
|
publishedAt: new Date(),
|
||||||
@@ -89,9 +91,12 @@ export class DakaoOutboxService {
|
|||||||
publishLeaseOwnerIdentifier: '',
|
publishLeaseOwnerIdentifier: '',
|
||||||
publishLeaseExpiresAt: '',
|
publishLeaseExpiresAt: '',
|
||||||
},
|
},
|
||||||
}).exec();
|
},
|
||||||
|
).exec();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
await OutboxModel.updateOne(updateFilter, {
|
await OutboxModel.updateOne(
|
||||||
|
updateFilter,
|
||||||
|
{
|
||||||
$inc: { publishAttempts: 1 },
|
$inc: { publishAttempts: 1 },
|
||||||
$set: {
|
$set: {
|
||||||
lastPublishError: (err as Error)?.message ?? String(err),
|
lastPublishError: (err as Error)?.message ?? String(err),
|
||||||
@@ -100,7 +105,8 @@ export class DakaoOutboxService {
|
|||||||
publishLeaseOwnerIdentifier: '',
|
publishLeaseOwnerIdentifier: '',
|
||||||
publishLeaseExpiresAt: '',
|
publishLeaseExpiresAt: '',
|
||||||
},
|
},
|
||||||
}).exec();
|
},
|
||||||
|
).exec();
|
||||||
this.logger.error(
|
this.logger.error(
|
||||||
`Failed to publish Dakao outbox eventId=${params.eventId}: ${
|
`Failed to publish Dakao outbox eventId=${params.eventId}: ${
|
||||||
(err as Error)?.stack ?? err
|
(err as Error)?.stack ?? err
|
||||||
|
|||||||
@@ -1,122 +0,0 @@
|
|||||||
import mongoose from 'mongoose';
|
|
||||||
import { ConnectionService } from '../global/database/connection.service';
|
|
||||||
import { RiotAccountService } from '../riot/riot-account.service';
|
|
||||||
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
|
|
||||||
import { DakaoUserService } from './dakao-user.service';
|
|
||||||
|
|
||||||
const communityId = new mongoose.Types.ObjectId();
|
|
||||||
const params = {
|
|
||||||
communityId,
|
|
||||||
kakaoTalkId: 'new-id',
|
|
||||||
previousNickname: '예전 닉',
|
|
||||||
};
|
|
||||||
|
|
||||||
function setup() {
|
|
||||||
const user = {
|
|
||||||
_id: new mongoose.Types.ObjectId(),
|
|
||||||
communityId,
|
|
||||||
kakaoTalkId: 'old-id',
|
|
||||||
kakaoTalkNickname: '예전 닉',
|
|
||||||
riotAccounts: [{ puuid: 'puuid', gameName: '소환사', tagLine: 'KR1' }],
|
|
||||||
role: 'member',
|
|
||||||
};
|
|
||||||
const find = jest.fn().mockReturnValue({
|
|
||||||
limit: jest
|
|
||||||
.fn()
|
|
||||||
.mockReturnValue({ exec: jest.fn().mockResolvedValue([user]) }),
|
|
||||||
});
|
|
||||||
const findOne = jest
|
|
||||||
.fn()
|
|
||||||
.mockReturnValue({ exec: jest.fn().mockResolvedValue(null) });
|
|
||||||
const update = jest
|
|
||||||
.fn()
|
|
||||||
.mockImplementation(async () => ({ ...user, kakaoTalkId: 'new-id' }));
|
|
||||||
const findOneAndUpdate = jest.fn().mockReturnValue({ exec: update });
|
|
||||||
const service = new DakaoUserService(
|
|
||||||
{
|
|
||||||
getModel: jest
|
|
||||||
.fn()
|
|
||||||
.mockResolvedValue({ find, findOne, findOneAndUpdate }),
|
|
||||||
} as unknown as ConnectionService,
|
|
||||||
{} as RiotAccountService,
|
|
||||||
{} as RiotAccountEnrichmentService,
|
|
||||||
);
|
|
||||||
return { service, user, find, findOne, findOneAndUpdate, update };
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('DakaoUserService.transferKakaoTalkId', () => {
|
|
||||||
it('selects registered users by exact nickname in the current community and changes only the ID', async () => {
|
|
||||||
const { service, user, find, findOneAndUpdate } = setup();
|
|
||||||
expect(await service.transferKakaoTalkId(params)).toBe('transferred');
|
|
||||||
expect(find).toHaveBeenCalledWith({
|
|
||||||
communityId,
|
|
||||||
kakaoTalkNickname: '예전 닉',
|
|
||||||
'riotAccounts.0': { $exists: true },
|
|
||||||
});
|
|
||||||
expect(findOneAndUpdate).toHaveBeenCalledWith(
|
|
||||||
{
|
|
||||||
_id: user._id,
|
|
||||||
communityId,
|
|
||||||
kakaoTalkId: 'old-id',
|
|
||||||
kakaoTalkNickname: '예전 닉',
|
|
||||||
'riotAccounts.0': { $exists: true },
|
|
||||||
},
|
|
||||||
{ $set: { kakaoTalkId: 'new-id' } },
|
|
||||||
{ returnDocument: 'after' },
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it.each([
|
|
||||||
['not-found', 0],
|
|
||||||
['ambiguous', 2],
|
|
||||||
] as const)('returns %s without mutation', async (status, count) => {
|
|
||||||
const { service, user, find, findOneAndUpdate } = setup();
|
|
||||||
find.mockReturnValue({
|
|
||||||
limit: () => ({
|
|
||||||
exec: async () => Array.from({ length: count }, () => user),
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
expect(await service.transferKakaoTalkId(params)).toBe(status);
|
|
||||||
expect(findOneAndUpdate).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('does not mutate an already linked user', async () => {
|
|
||||||
const { service, user, findOneAndUpdate } = setup();
|
|
||||||
user.kakaoTalkId = 'new-id';
|
|
||||||
expect(await service.transferKakaoTalkId(params)).toBe('already-linked');
|
|
||||||
expect(findOneAndUpdate).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('refuses an ID occupied by another user', async () => {
|
|
||||||
const { service, findOne, findOneAndUpdate } = setup();
|
|
||||||
findOne.mockReturnValue({
|
|
||||||
exec: async () => ({ _id: new mongoose.Types.ObjectId() }),
|
|
||||||
});
|
|
||||||
expect(await service.transferKakaoTalkId(params)).toBe('id-conflict');
|
|
||||||
expect(findOne).toHaveBeenCalledWith({
|
|
||||||
communityId,
|
|
||||||
kakaoTalkId: 'new-id',
|
|
||||||
});
|
|
||||||
expect(findOneAndUpdate).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('reports a concurrent change instead of overwriting it', async () => {
|
|
||||||
const { service, update } = setup();
|
|
||||||
update.mockResolvedValue(null);
|
|
||||||
expect(await service.transferKakaoTalkId(params)).toBe('changed');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('handles a concurrent ID collision', async () => {
|
|
||||||
const { service, update } = setup();
|
|
||||||
update.mockRejectedValue({ code: 11000 });
|
|
||||||
expect(await service.transferKakaoTalkId(params)).toBe('id-conflict');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('propagates unexpected database failures for retry', async () => {
|
|
||||||
const { service, update } = setup();
|
|
||||||
update.mockRejectedValue(new Error('database unavailable'));
|
|
||||||
await expect(service.transferKakaoTalkId(params)).rejects.toThrow(
|
|
||||||
'database unavailable',
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -105,7 +105,7 @@ describe('DakaoUserService', () => {
|
|||||||
tagLine: 'KR2',
|
tagLine: 'KR2',
|
||||||
isPrimary: false,
|
isPrimary: false,
|
||||||
});
|
});
|
||||||
expect(result.user.riotAccounts[0]).toMatchObject({
|
expect((result.user.riotAccounts as RiotAccount[])[0]).toMatchObject({
|
||||||
puuid: 'puuid-1',
|
puuid: 'puuid-1',
|
||||||
isPrimary: true,
|
isPrimary: true,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -60,14 +60,6 @@ interface ResolvedRiotIdentity {
|
|||||||
const DEFAULT_RIOT_PLATFORM: RiotPlatformRoute = 'kr';
|
const DEFAULT_RIOT_PLATFORM: RiotPlatformRoute = 'kr';
|
||||||
const DEFAULT_RIOT_REGION: RiotRegionalRoute = 'asia';
|
const DEFAULT_RIOT_REGION: RiotRegionalRoute = 'asia';
|
||||||
|
|
||||||
export type KakaoDataTransferResult =
|
|
||||||
| 'transferred'
|
|
||||||
| 'already-linked'
|
|
||||||
| 'not-found'
|
|
||||||
| 'ambiguous'
|
|
||||||
| 'id-conflict'
|
|
||||||
| 'changed';
|
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class DakaoUserService {
|
export class DakaoUserService {
|
||||||
private readonly logger = new Logger(DakaoUserService.name);
|
private readonly logger = new Logger(DakaoUserService.name);
|
||||||
@@ -95,7 +87,7 @@ export class DakaoUserService {
|
|||||||
if (!community) {
|
if (!community) {
|
||||||
throw new DakaoUserError('community_not_found', dakaoProjectId);
|
throw new DakaoUserError('community_not_found', dakaoProjectId);
|
||||||
}
|
}
|
||||||
return community._id;
|
return community._id as mongoose.Types.ObjectId;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async upsertUser(params: {
|
public async upsertUser(params: {
|
||||||
@@ -135,44 +127,6 @@ export class DakaoUserService {
|
|||||||
}).exec();
|
}).exec();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async transferKakaoTalkId(params: {
|
|
||||||
communityId: mongoose.Types.ObjectId;
|
|
||||||
kakaoTalkId: string;
|
|
||||||
previousNickname: string;
|
|
||||||
}): Promise<KakaoDataTransferResult> {
|
|
||||||
const UserModel = await this.connectionService.getModel('user');
|
|
||||||
const targetFilter = {
|
|
||||||
communityId: params.communityId,
|
|
||||||
kakaoTalkNickname: params.previousNickname,
|
|
||||||
'riotAccounts.0': { $exists: true },
|
|
||||||
};
|
|
||||||
const candidates = await UserModel.find(targetFilter).limit(2).exec();
|
|
||||||
if (candidates.length === 0) return 'not-found';
|
|
||||||
if (candidates.length > 1) return 'ambiguous';
|
|
||||||
|
|
||||||
const user = candidates[0];
|
|
||||||
if (user.kakaoTalkId === params.kakaoTalkId) return 'already-linked';
|
|
||||||
const occupied = await this.findUserByKakaoTalkId(params);
|
|
||||||
if (occupied) return 'id-conflict';
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Compare the previous ID so concurrent transfers cannot overwrite one another.
|
|
||||||
const updated = await UserModel.findOneAndUpdate(
|
|
||||||
{
|
|
||||||
...targetFilter,
|
|
||||||
_id: user._id,
|
|
||||||
kakaoTalkId: user.kakaoTalkId ?? null,
|
|
||||||
},
|
|
||||||
{ $set: { kakaoTalkId: params.kakaoTalkId } },
|
|
||||||
{ returnDocument: 'after' },
|
|
||||||
).exec();
|
|
||||||
return updated ? 'transferred' : 'changed';
|
|
||||||
} catch (error) {
|
|
||||||
if ((error as { code?: number })?.code === 11000) return 'id-conflict';
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public async resolveRiotAccount(
|
public async resolveRiotAccount(
|
||||||
context: ResolveContext,
|
context: ResolveContext,
|
||||||
): Promise<ResolveResult> {
|
): Promise<ResolveResult> {
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ import { DakaoUserService } from './dakao-user.service';
|
|||||||
import { DakaoSendResultSubscriber } from './dakao-send-result.subscriber';
|
import { DakaoSendResultSubscriber } from './dakao-send-result.subscriber';
|
||||||
import { DakaoUrlShortenerService } from './dakao-url-shortener.service';
|
import { DakaoUrlShortenerService } from './dakao-url-shortener.service';
|
||||||
import { AccountRegisterHandler } from './handlers/account-register.handler';
|
import { AccountRegisterHandler } from './handlers/account-register.handler';
|
||||||
import { DataTransferHandler } from './handlers/data-transfer.handler';
|
|
||||||
import { MatchCancelHandler } from './handlers/match-cancel.handler';
|
import { MatchCancelHandler } from './handlers/match-cancel.handler';
|
||||||
import { MatchJoinHandler } from './handlers/match-join.handler';
|
import { MatchJoinHandler } from './handlers/match-join.handler';
|
||||||
import { MatchListHandler } from './handlers/match-list.handler';
|
import { MatchListHandler } from './handlers/match-list.handler';
|
||||||
@@ -36,7 +35,6 @@ import { PrimaryAccountChangeHandler } from './handlers/primary-account-change.h
|
|||||||
DakaoUserService,
|
DakaoUserService,
|
||||||
DakaoUrlShortenerService,
|
DakaoUrlShortenerService,
|
||||||
AccountRegisterHandler,
|
AccountRegisterHandler,
|
||||||
DataTransferHandler,
|
|
||||||
MatchListHandler,
|
MatchListHandler,
|
||||||
MatchJoinHandler,
|
MatchJoinHandler,
|
||||||
MatchCancelHandler,
|
MatchCancelHandler,
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ function makeSubscriber(): DakaoSubscriber {
|
|||||||
{} as never,
|
{} as never,
|
||||||
{} as never,
|
{} as never,
|
||||||
{} as never,
|
{} as never,
|
||||||
{} as never,
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -40,48 +39,6 @@ const event = {
|
|||||||
} satisfies DakaoInboundEvent;
|
} satisfies DakaoInboundEvent;
|
||||||
|
|
||||||
describe('DakaoSubscriber', () => {
|
describe('DakaoSubscriber', () => {
|
||||||
it('routes data transfer with the current sender ID and publishes its reply', async () => {
|
|
||||||
const subscriber = makeSubscriber();
|
|
||||||
const segments = [{ kind: 'text', text: ' 데이터 이관 완료' }];
|
|
||||||
const handle = jest.fn().mockResolvedValue(segments);
|
|
||||||
const sendMessage = jest.fn();
|
|
||||||
const markProcessed = jest.fn();
|
|
||||||
Object.assign(subscriber, {
|
|
||||||
dakaoUserService: {
|
|
||||||
resolveCommunityIdByDakaoProjectId: async () => event.projectId,
|
|
||||||
},
|
|
||||||
dataTransferHandler: { handle },
|
|
||||||
publisher: { sendMessage },
|
|
||||||
inbox: { claim: async () => ({ status: 'claimed' }), markProcessed },
|
|
||||||
});
|
|
||||||
await (
|
|
||||||
subscriber as unknown as {
|
|
||||||
handleEvent: (input: DakaoInboundEvent) => Promise<void>;
|
|
||||||
}
|
|
||||||
).handleEvent({
|
|
||||||
...event,
|
|
||||||
origin: {
|
|
||||||
...event.origin,
|
|
||||||
chatLog: {
|
|
||||||
...event.origin.chatLog,
|
|
||||||
message: '!내전 데이터이관 예전 닉',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
expect(handle).toHaveBeenCalledWith({
|
|
||||||
communityId: event.projectId,
|
|
||||||
senderUserId: '12345',
|
|
||||||
senderNickname: '프리리',
|
|
||||||
previousNickname: '예전 닉',
|
|
||||||
});
|
|
||||||
expect(sendMessage).toHaveBeenCalledWith({
|
|
||||||
chatroomId: 'chatroom-1',
|
|
||||||
segments,
|
|
||||||
correlationId: 'log-1',
|
|
||||||
});
|
|
||||||
expect(markProcessed).toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('renders usage help with star emoticon command lines', () => {
|
it('renders usage help with star emoticon command lines', () => {
|
||||||
const subscriber = makeSubscriber() as unknown as {
|
const subscriber = makeSubscriber() as unknown as {
|
||||||
parseErrorReply: (
|
parseErrorReply: (
|
||||||
@@ -108,8 +65,6 @@ describe('DakaoSubscriber', () => {
|
|||||||
text: ' !내전 신청 코드 소환사이름#태그 포지션1,포지션2\u3000\n',
|
text: ' !내전 신청 코드 소환사이름#태그 포지션1,포지션2\u3000\n',
|
||||||
},
|
},
|
||||||
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
||||||
{ kind: 'text', text: ' !내전 취소 코드\u3000\n' },
|
|
||||||
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
|
||||||
{ kind: 'text', text: ' !내전 계정등록 소환사이름#태그\u3000\n' },
|
{ kind: 'text', text: ' !내전 계정등록 소환사이름#태그\u3000\n' },
|
||||||
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
||||||
{
|
{
|
||||||
@@ -119,10 +74,8 @@ describe('DakaoSubscriber', () => {
|
|||||||
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
||||||
{
|
{
|
||||||
kind: 'text',
|
kind: 'text',
|
||||||
text: ' !내전 대표계정변경 소환사이름#태그\u3000\n',
|
text: ' !내전 대표계정변경 소환사이름#태그',
|
||||||
},
|
},
|
||||||
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
|
||||||
{ kind: 'text', text: ' !내전 데이터이관 이전카카오톡채팅방닉네임' },
|
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import { DakaoInboundEvent, DakaoLong, DakaoSegment } from './dakao.types';
|
|||||||
import { DakaoPublisher } from './dakao.publisher';
|
import { DakaoPublisher } from './dakao.publisher';
|
||||||
import { DakaoUserError, DakaoUserService } from './dakao-user.service';
|
import { DakaoUserError, DakaoUserService } from './dakao-user.service';
|
||||||
import { AccountRegisterHandler } from './handlers/account-register.handler';
|
import { AccountRegisterHandler } from './handlers/account-register.handler';
|
||||||
import { DataTransferHandler } from './handlers/data-transfer.handler';
|
|
||||||
import { MatchCancelHandler } from './handlers/match-cancel.handler';
|
import { MatchCancelHandler } from './handlers/match-cancel.handler';
|
||||||
import { MatchJoinHandler } from './handlers/match-join.handler';
|
import { MatchJoinHandler } from './handlers/match-join.handler';
|
||||||
import { MatchListHandler } from './handlers/match-list.handler';
|
import { MatchListHandler } from './handlers/match-list.handler';
|
||||||
@@ -25,11 +24,9 @@ export class DakaoSubscriber implements OnModuleInit {
|
|||||||
private readonly usageCommands = [
|
private readonly usageCommands = [
|
||||||
'!내전 일정',
|
'!내전 일정',
|
||||||
'!내전 신청 코드 소환사이름#태그 포지션1,포지션2',
|
'!내전 신청 코드 소환사이름#태그 포지션1,포지션2',
|
||||||
'!내전 취소 코드',
|
|
||||||
'!내전 계정등록 소환사이름#태그',
|
'!내전 계정등록 소환사이름#태그',
|
||||||
'!내전 선호포지션등록 포지션1,포지션2',
|
'!내전 선호포지션등록 포지션1,포지션2',
|
||||||
'!내전 대표계정변경 소환사이름#태그',
|
'!내전 대표계정변경 소환사이름#태그',
|
||||||
'!내전 데이터이관 이전카카오톡채팅방닉네임',
|
|
||||||
];
|
];
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
@@ -45,7 +42,6 @@ export class DakaoSubscriber implements OnModuleInit {
|
|||||||
private readonly matchCancelHandler: MatchCancelHandler,
|
private readonly matchCancelHandler: MatchCancelHandler,
|
||||||
private readonly preferredPositionRegisterHandler: PreferredPositionRegisterHandler,
|
private readonly preferredPositionRegisterHandler: PreferredPositionRegisterHandler,
|
||||||
private readonly primaryAccountChangeHandler: PrimaryAccountChangeHandler,
|
private readonly primaryAccountChangeHandler: PrimaryAccountChangeHandler,
|
||||||
private readonly dataTransferHandler: DataTransferHandler,
|
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async onModuleInit() {
|
async onModuleInit() {
|
||||||
@@ -123,14 +119,6 @@ export class DakaoSubscriber implements OnModuleInit {
|
|||||||
const command = parseCommand(event.origin.chatLog.message);
|
const command = parseCommand(event.origin.chatLog.message);
|
||||||
|
|
||||||
switch (command.kind) {
|
switch (command.kind) {
|
||||||
case 'data-transfer':
|
|
||||||
segments = await this.dataTransferHandler.handle({
|
|
||||||
communityId,
|
|
||||||
senderUserId: event.userId,
|
|
||||||
senderNickname,
|
|
||||||
previousNickname: command.previousNickname,
|
|
||||||
});
|
|
||||||
break;
|
|
||||||
case 'match-list':
|
case 'match-list':
|
||||||
segments = await this.matchListHandler.handle({
|
segments = await this.matchListHandler.handle({
|
||||||
communityId,
|
communityId,
|
||||||
@@ -313,7 +301,7 @@ export class DakaoSubscriber implements OnModuleInit {
|
|||||||
text:
|
text:
|
||||||
index === this.usageCommands.length - 1
|
index === this.usageCommands.length - 1
|
||||||
? ` ${command}`
|
? ` ${command}`
|
||||||
: ` ${command}\u3000\n`,
|
: ` ${command} \n`,
|
||||||
} as const,
|
} as const,
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,49 +0,0 @@
|
|||||||
import mongoose from 'mongoose';
|
|
||||||
import {
|
|
||||||
DakaoUserService,
|
|
||||||
KakaoDataTransferResult,
|
|
||||||
} from '../dakao-user.service';
|
|
||||||
import { DataTransferHandler } from './data-transfer.handler';
|
|
||||||
|
|
||||||
const params = {
|
|
||||||
communityId: new mongoose.Types.ObjectId(),
|
|
||||||
senderUserId: 'new-id',
|
|
||||||
senderNickname: '현재 닉',
|
|
||||||
previousNickname: '예전 닉',
|
|
||||||
};
|
|
||||||
|
|
||||||
describe('DataTransferHandler', () => {
|
|
||||||
it.each<[KakaoDataTransferResult, string]>([
|
|
||||||
['transferred', '데이터 이관 완료'],
|
|
||||||
['already-linked', '이미 현재 카카오톡 계정에 연결'],
|
|
||||||
['not-found', '찾을 수 없습니다'],
|
|
||||||
['ambiguous', '여러 명'],
|
|
||||||
['id-conflict', '이미 다른 사용자'],
|
|
||||||
['changed', '변경되었습니다'],
|
|
||||||
])('replies to the sender for %s', async (result, message) => {
|
|
||||||
const transferKakaoTalkId = jest.fn().mockResolvedValue(result);
|
|
||||||
const handler = new DataTransferHandler({
|
|
||||||
transferKakaoTalkId,
|
|
||||||
} as unknown as DakaoUserService);
|
|
||||||
expect(await handler.handle(params)).toEqual([
|
|
||||||
{ kind: 'mention', userId: 'new-id', displayText: '현재 닉' },
|
|
||||||
{ kind: 'text', text: expect.stringContaining(message) },
|
|
||||||
]);
|
|
||||||
expect(transferKakaoTalkId).toHaveBeenCalledWith({
|
|
||||||
communityId: params.communityId,
|
|
||||||
kakaoTalkId: 'new-id',
|
|
||||||
previousNickname: '예전 닉',
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('propagates unexpected failures', async () => {
|
|
||||||
const handler = new DataTransferHandler({
|
|
||||||
transferKakaoTalkId: jest
|
|
||||||
.fn()
|
|
||||||
.mockRejectedValue(new Error('database unavailable')),
|
|
||||||
} as unknown as DakaoUserService);
|
|
||||||
await expect(handler.handle(params)).rejects.toThrow(
|
|
||||||
'database unavailable',
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
|
||||||
import mongoose from 'mongoose';
|
|
||||||
import {
|
|
||||||
DakaoUserService,
|
|
||||||
KakaoDataTransferResult,
|
|
||||||
} from '../dakao-user.service';
|
|
||||||
import { DakaoSegment } from '../dakao.types';
|
|
||||||
|
|
||||||
const RESULT_MESSAGES: Record<KakaoDataTransferResult, string> = {
|
|
||||||
transferred:
|
|
||||||
'데이터 이관 완료. 기존 라이엇 계정과 내전 기록이 현재 카카오톡 계정에 연결되었습니다.',
|
|
||||||
'already-linked': '이미 현재 카카오톡 계정에 연결된 사용자입니다.',
|
|
||||||
'not-found':
|
|
||||||
'해당 예전 닉네임으로 라이엇 계정이 등록된 사용자를 찾을 수 없습니다.',
|
|
||||||
ambiguous:
|
|
||||||
'같은 예전 닉네임으로 등록된 사용자가 여러 명입니다. 운영자에게 문의해주세요.',
|
|
||||||
'id-conflict':
|
|
||||||
'현재 카카오톡 계정에 이미 다른 사용자가 등록되어 있습니다. 운영자에게 문의해주세요.',
|
|
||||||
changed: '이관 중 사용자 정보가 변경되었습니다. 다시 시도해주세요.',
|
|
||||||
};
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class DataTransferHandler {
|
|
||||||
constructor(private readonly dakaoUserService: DakaoUserService) {}
|
|
||||||
|
|
||||||
public async handle(params: {
|
|
||||||
communityId: mongoose.Types.ObjectId;
|
|
||||||
senderUserId: string;
|
|
||||||
senderNickname: string;
|
|
||||||
previousNickname: string;
|
|
||||||
}): Promise<DakaoSegment[]> {
|
|
||||||
const result = await this.dakaoUserService.transferKakaoTalkId({
|
|
||||||
communityId: params.communityId,
|
|
||||||
kakaoTalkId: params.senderUserId,
|
|
||||||
previousNickname: params.previousNickname,
|
|
||||||
});
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
kind: 'mention',
|
|
||||||
userId: params.senderUserId,
|
|
||||||
displayText: params.senderNickname,
|
|
||||||
},
|
|
||||||
{ kind: 'text', text: ` ${RESULT_MESSAGES[result]}` },
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -104,9 +104,7 @@ describe('MatchCancelHandler', () => {
|
|||||||
const handler = makeHandler({
|
const handler = makeHandler({
|
||||||
matchService: {
|
matchService: {
|
||||||
cancelJoin,
|
cancelJoin,
|
||||||
list: jest
|
list: jest.fn().mockResolvedValue([
|
||||||
.fn()
|
|
||||||
.mockResolvedValue([
|
|
||||||
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
|
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
|
||||||
]),
|
]),
|
||||||
} as Partial<MatchService>,
|
} as Partial<MatchService>,
|
||||||
|
|||||||
@@ -230,9 +230,7 @@ describe('MatchJoinHandler', () => {
|
|||||||
const resolveRiotAccount = jest.fn();
|
const resolveRiotAccount = jest.fn();
|
||||||
const handler = makeHandler({
|
const handler = makeHandler({
|
||||||
matchService: {
|
matchService: {
|
||||||
list: jest
|
list: jest.fn().mockResolvedValue([
|
||||||
.fn()
|
|
||||||
.mockResolvedValue([
|
|
||||||
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
|
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
|
||||||
]),
|
]),
|
||||||
join,
|
join,
|
||||||
@@ -284,9 +282,7 @@ describe('MatchJoinHandler', () => {
|
|||||||
const join = jest.fn();
|
const join = jest.fn();
|
||||||
const handler = makeHandler({
|
const handler = makeHandler({
|
||||||
matchService: {
|
matchService: {
|
||||||
list: jest
|
list: jest.fn().mockResolvedValue([
|
||||||
.fn()
|
|
||||||
.mockResolvedValue([
|
|
||||||
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
|
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
|
||||||
]),
|
]),
|
||||||
join,
|
join,
|
||||||
|
|||||||
@@ -44,7 +44,9 @@ export class MatchJoinHandler {
|
|||||||
return this.errorReply(params, joinTarget);
|
return this.errorReply(params, joinTarget);
|
||||||
}
|
}
|
||||||
|
|
||||||
let resolved: { user: UserDocument; riotAccount: RiotAccount } | string;
|
let resolved:
|
||||||
|
| { user: UserDocument; riotAccount: RiotAccount }
|
||||||
|
| string;
|
||||||
try {
|
try {
|
||||||
resolved =
|
resolved =
|
||||||
joinTarget.gameName && joinTarget.tagLine
|
joinTarget.gameName && joinTarget.tagLine
|
||||||
@@ -241,7 +243,10 @@ export class MatchJoinHandler {
|
|||||||
const gameName = normalizeRiotIdPart(value.slice(splitAt + 1));
|
const gameName = normalizeRiotIdPart(value.slice(splitAt + 1));
|
||||||
if (!matchTitlePrefix || !gameName) continue;
|
if (!matchTitlePrefix || !gameName) continue;
|
||||||
|
|
||||||
const result = resolveRecruitingMatchReference(matchTitlePrefix, matches);
|
const result = resolveRecruitingMatchReference(
|
||||||
|
matchTitlePrefix,
|
||||||
|
matches,
|
||||||
|
);
|
||||||
if (result.kind === 'matched') {
|
if (result.kind === 'matched') {
|
||||||
return { kind: 'matched', match: result.match, gameName };
|
return { kind: 'matched', match: result.match, gameName };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,33 +22,6 @@ function makeHandler(params: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe('MatchListHandler', () => {
|
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 () => {
|
it('prints short codes, compact KST dates, and short links', async () => {
|
||||||
const match = {
|
const match = {
|
||||||
_id: objectId('333333333333333333333333'),
|
_id: objectId('333333333333333333333333'),
|
||||||
|
|||||||
@@ -19,11 +19,9 @@ export class MatchListHandler {
|
|||||||
senderUserId: string;
|
senderUserId: string;
|
||||||
senderNickname: string;
|
senderNickname: string;
|
||||||
}): Promise<DakaoSegment[]> {
|
}): Promise<DakaoSegment[]> {
|
||||||
const scheduledFrom = new Date();
|
|
||||||
const matches = await this.matchService.list({
|
const matches = await this.matchService.list({
|
||||||
communityId: params.communityId,
|
communityId: params.communityId,
|
||||||
status: 'recruiting',
|
status: 'recruiting',
|
||||||
scheduledFrom,
|
|
||||||
limit: 10,
|
limit: 10,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -20,8 +20,8 @@ export class IdempotencyCache {
|
|||||||
public remember(key: string): void {
|
public remember(key: string): void {
|
||||||
this.evictExpired();
|
this.evictExpired();
|
||||||
if (this.entries.size >= MAX_ENTRIES) {
|
if (this.entries.size >= MAX_ENTRIES) {
|
||||||
const oldestKey: unknown = this.entries.keys().next().value;
|
const oldestKey = this.entries.keys().next().value;
|
||||||
if (typeof oldestKey === 'string') this.entries.delete(oldestKey);
|
if (oldestKey !== undefined) this.entries.delete(oldestKey);
|
||||||
}
|
}
|
||||||
this.entries.set(key, Date.now() + TTL_MS);
|
this.entries.set(key, Date.now() + TTL_MS);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,19 +1,6 @@
|
|||||||
import { CommandParseError, parseCommand } from './command.parser';
|
import { CommandParseError, parseCommand } from './command.parser';
|
||||||
|
|
||||||
describe('parseCommand', () => {
|
describe('parseCommand', () => {
|
||||||
it('parses data transfer with the complete previous nickname', () => {
|
|
||||||
expect(parseCommand(' !내전 데이터이관 예전 닉.* ')).toEqual({
|
|
||||||
kind: 'data-transfer',
|
|
||||||
previousNickname: '예전 닉.*',
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('requires a previous nickname for data transfer', () => {
|
|
||||||
expect(() => parseCommand('!내전 데이터이관 ')).toThrow(
|
|
||||||
new CommandParseError('usage'),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('parses match-list command (목록)', () => {
|
it('parses match-list command (목록)', () => {
|
||||||
expect(parseCommand('!내전 목록')).toEqual({ kind: 'match-list' });
|
expect(parseCommand('!내전 목록')).toEqual({ kind: 'match-list' });
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import { normalizeRiotIdPart } from '../riot-id.util';
|
|||||||
|
|
||||||
export type DakaoCommand =
|
export type DakaoCommand =
|
||||||
| { kind: 'match-list' }
|
| { kind: 'match-list' }
|
||||||
| { kind: 'data-transfer'; previousNickname: string }
|
|
||||||
| {
|
| {
|
||||||
kind: 'account-register';
|
kind: 'account-register';
|
||||||
gameName: string;
|
gameName: string;
|
||||||
@@ -76,9 +75,6 @@ export function parseCommand(rawMessage: string): DakaoCommand {
|
|||||||
return parseCancelArgs(args);
|
return parseCancelArgs(args);
|
||||||
case '계정등록':
|
case '계정등록':
|
||||||
return parseAccountRegisterArgs(args);
|
return parseAccountRegisterArgs(args);
|
||||||
case '데이터이관':
|
|
||||||
if (!args) throw new CommandParseError('usage');
|
|
||||||
return { kind: 'data-transfer', previousNickname: args };
|
|
||||||
case '대표계정변경':
|
case '대표계정변경':
|
||||||
return parsePrimaryAccountChangeArgs(args);
|
return parsePrimaryAccountChangeArgs(args);
|
||||||
case '선호포지션등록':
|
case '선호포지션등록':
|
||||||
|
|||||||
@@ -144,7 +144,7 @@ export function buildDoubleEliminationBracket(
|
|||||||
teamIndex,
|
teamIndex,
|
||||||
}));
|
}));
|
||||||
const bracket: DoubleEliminationBracket = {
|
const bracket: DoubleEliminationBracket = {
|
||||||
teamCount: seededTeamIndexes.length,
|
teamCount: seededTeamIndexes.length as 4 | 8,
|
||||||
resetFinalEnabled: options.resetFinalEnabled,
|
resetFinalEnabled: options.resetFinalEnabled,
|
||||||
resetFinalCreated: false,
|
resetFinalCreated: false,
|
||||||
seeds,
|
seeds,
|
||||||
|
|||||||
@@ -19,9 +19,7 @@ describe('auction Redis schema foundation', () => {
|
|||||||
expect(AuctionSchema.path('revision')).toBeDefined();
|
expect(AuctionSchema.path('revision')).toBeDefined();
|
||||||
expect(AuctionSchema.path('auctionEngineVersion')).toBeDefined();
|
expect(AuctionSchema.path('auctionEngineVersion')).toBeDefined();
|
||||||
expect(AuctionSchema.path('auctionLifecycleId')).toBeDefined();
|
expect(AuctionSchema.path('auctionLifecycleId')).toBeDefined();
|
||||||
expect(
|
expect(AuctionSchema.path('lastAppliedAuctionStateTransitionId')).toBeDefined();
|
||||||
AuctionSchema.path('lastAppliedAuctionStateTransitionId'),
|
|
||||||
).toBeDefined();
|
|
||||||
expect(AuctionSchema.path('currentAuctionHistorySequence')).toBeDefined();
|
expect(AuctionSchema.path('currentAuctionHistorySequence')).toBeDefined();
|
||||||
expect(AuctionSchema.path('startAuctionRequestId')).toBeDefined();
|
expect(AuctionSchema.path('startAuctionRequestId')).toBeDefined();
|
||||||
expect(AuctionSchema.path('startAuctionStateTransitionId')).toBeDefined();
|
expect(AuctionSchema.path('startAuctionStateTransitionId')).toBeDefined();
|
||||||
@@ -38,75 +36,46 @@ describe('auction Redis schema foundation', () => {
|
|||||||
expect(AuctionSchema.path('auctionBidHistory')).toBeDefined();
|
expect(AuctionSchema.path('auctionBidHistory')).toBeDefined();
|
||||||
expect(AuctionSchema.path('currentHighestBidPointAmount')).toBeDefined();
|
expect(AuctionSchema.path('currentHighestBidPointAmount')).toBeDefined();
|
||||||
expect(AuctionSchema.path('currentHighestBidderTeamIndex')).toBeDefined();
|
expect(AuctionSchema.path('currentHighestBidderTeamIndex')).toBeDefined();
|
||||||
expect(
|
expect(AuctionSchema.path('currentBidRoundDeadlineTimestampMS')).toBeDefined();
|
||||||
AuctionSchema.path('currentBidRoundDeadlineTimestampMS'),
|
|
||||||
).toBeDefined();
|
|
||||||
expect(AuctionSchema.path('maximumBidRoundDurationSeconds')).toBeDefined();
|
expect(AuctionSchema.path('maximumBidRoundDurationSeconds')).toBeDefined();
|
||||||
expect(AuctionSchema.path('bidRoundExtensionSeconds')).toBeDefined();
|
expect(AuctionSchema.path('bidRoundExtensionSeconds')).toBeDefined();
|
||||||
expect(AuctionSchema.path('initialTeamBidPointAmount')).toBeDefined();
|
expect(AuctionSchema.path('initialTeamBidPointAmount')).toBeDefined();
|
||||||
expect(AuctionSchema.path('topTierAuctionPriorityThreshold')).toBeDefined();
|
expect(AuctionSchema.path('topTierAuctionPriorityThreshold')).toBeDefined();
|
||||||
expect(
|
expect(AuctionSchema.path('manualTopTierAuctionPriorityUserIds')).toBeDefined();
|
||||||
AuctionSchema.path('manualTopTierAuctionPriorityUserIds'),
|
|
||||||
).toBeDefined();
|
|
||||||
expect(AuctionSchema.path('auctionStartedAtTimestampMS')).toBeDefined();
|
expect(AuctionSchema.path('auctionStartedAtTimestampMS')).toBeDefined();
|
||||||
expect(AuctionSchema.path('auctionCompletedAtTimestampMS')).toBeDefined();
|
expect(AuctionSchema.path('auctionCompletedAtTimestampMS')).toBeDefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('adds history transition fields and reset/undo action enum values', () => {
|
it('adds history transition fields and reset/undo action enum values', () => {
|
||||||
expect(
|
expect(AuctionHistoryEntrySchema.path('auctionStateTransitionId')).toBeDefined();
|
||||||
AuctionHistoryEntrySchema.path('auctionStateTransitionId'),
|
|
||||||
).toBeDefined();
|
|
||||||
expect(AuctionHistoryEntrySchema.path('auctionLifecycleId')).toBeDefined();
|
expect(AuctionHistoryEntrySchema.path('auctionLifecycleId')).toBeDefined();
|
||||||
expect(AuctionHistoryEntrySchema.path('revision')).toBeDefined();
|
expect(AuctionHistoryEntrySchema.path('revision')).toBeDefined();
|
||||||
expect(AuctionHistoryEntrySchema.path('historyMutation')).toBeDefined();
|
expect(AuctionHistoryEntrySchema.path('historyMutation')).toBeDefined();
|
||||||
expect(
|
expect(AuctionHistoryEntrySchema.path('matchSideEffectMutation')).toBeDefined();
|
||||||
AuctionHistoryEntrySchema.path('matchSideEffectMutation'),
|
|
||||||
).toBeDefined();
|
|
||||||
expect(
|
expect(
|
||||||
AuctionHistoryEntrySchema.path<string>('action').options.enum,
|
AuctionHistoryEntrySchema.path<string>('action').options.enum,
|
||||||
).toEqual(
|
).toEqual(
|
||||||
expect.arrayContaining([
|
expect.arrayContaining(['start', 'open-bidding', 'bid', 'sold', 'passed', 'next', 'complete', 'reset', 'undo']),
|
||||||
'start',
|
|
||||||
'open-bidding',
|
|
||||||
'bid',
|
|
||||||
'sold',
|
|
||||||
'passed',
|
|
||||||
'next',
|
|
||||||
'complete',
|
|
||||||
'reset',
|
|
||||||
'undo',
|
|
||||||
]),
|
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('adds unique history indexes for sequence and transition idempotency', () => {
|
it('adds unique history indexes for sequence and transition idempotency', () => {
|
||||||
const indexes = AuctionHistoryEntrySchema.indexes();
|
const indexes = AuctionHistoryEntrySchema.indexes();
|
||||||
|
|
||||||
expect(
|
expect(indexWithKeys(indexes, { auctionId: 1, sequence: 1 })?.[1]).toMatchObject({
|
||||||
indexWithKeys(indexes, { auctionId: 1, sequence: 1 })?.[1],
|
|
||||||
).toMatchObject({
|
|
||||||
unique: true,
|
unique: true,
|
||||||
});
|
});
|
||||||
expect(
|
expect(
|
||||||
indexWithKeys(indexes, {
|
indexWithKeys(indexes, { auctionId: 1, auctionStateTransitionId: 1 })?.[1],
|
||||||
auctionId: 1,
|
|
||||||
auctionStateTransitionId: 1,
|
|
||||||
})?.[1],
|
|
||||||
).toMatchObject({ unique: true, sparse: true });
|
).toMatchObject({ unique: true, sparse: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
it('registers auction side effect application model with lease fields and unique idempotency index', () => {
|
it('registers auction side effect application model with lease fields and unique idempotency index', () => {
|
||||||
|
expect(AuctionSideEffectApplicationSchema.path('processingOwnerToken')).toBeDefined();
|
||||||
expect(
|
expect(
|
||||||
AuctionSideEffectApplicationSchema.path('processingOwnerToken'),
|
AuctionSideEffectApplicationSchema.path('processingLeaseExpiresAtTimestampMS'),
|
||||||
).toBeDefined();
|
|
||||||
expect(
|
|
||||||
AuctionSideEffectApplicationSchema.path(
|
|
||||||
'processingLeaseExpiresAtTimestampMS',
|
|
||||||
),
|
|
||||||
).toBeDefined();
|
|
||||||
expect(
|
|
||||||
AuctionSideEffectApplicationSchema.path('payloadChecksum'),
|
|
||||||
).toBeDefined();
|
).toBeDefined();
|
||||||
|
expect(AuctionSideEffectApplicationSchema.path('payloadChecksum')).toBeDefined();
|
||||||
|
|
||||||
const indexes = AuctionSideEffectApplicationSchema.indexes();
|
const indexes = AuctionSideEffectApplicationSchema.indexes();
|
||||||
expect(
|
expect(
|
||||||
|
|||||||
@@ -2,10 +2,7 @@ import { Injectable, Logger, Scope, OnModuleInit } from '@nestjs/common';
|
|||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
import { applyMongoosePerformancePlugin } from '../observability/mongoose-performance.plugin';
|
import { applyMongoosePerformancePlugin } from '../observability/mongoose-performance.plugin';
|
||||||
import { SecretService } from '../secret/secret.service';
|
import { SecretService } from '../secret/secret.service';
|
||||||
import {
|
import { tournamentModelDefinitions, TournamentModelTypes } from './schema';
|
||||||
tournamentModelDefinitions,
|
|
||||||
type TournamentModelTypes,
|
|
||||||
} from './schema';
|
|
||||||
|
|
||||||
export function resolveMongoDbName(nodeEnv = process.env.NODE_ENV): string {
|
export function resolveMongoDbName(nodeEnv = process.env.NODE_ENV): string {
|
||||||
if (nodeEnv === 'prod') return 'lolympus';
|
if (nodeEnv === 'prod') return 'lolympus';
|
||||||
@@ -45,8 +42,7 @@ export class ConnectionService implements OnModuleInit {
|
|||||||
private connectionPromise: Promise<mongoose.Connection> | null = null;
|
private connectionPromise: Promise<mongoose.Connection> | null = null;
|
||||||
constructor(private readonly secretService: SecretService) {}
|
constructor(private readonly secretService: SecretService) {}
|
||||||
|
|
||||||
private tournamentModels: Map<keyof TournamentModelTypes, unknown> | null =
|
private tournamentModels: Map<string, mongoose.Model<any>> | null = null;
|
||||||
null;
|
|
||||||
|
|
||||||
public async getConnection(): Promise<mongoose.Connection> {
|
public async getConnection(): Promise<mongoose.Connection> {
|
||||||
if (
|
if (
|
||||||
@@ -93,18 +89,14 @@ export class ConnectionService implements OnModuleInit {
|
|||||||
modelKey: K,
|
modelKey: K,
|
||||||
): Promise<mongoose.Model<TournamentModelTypes[K]>> {
|
): Promise<mongoose.Model<TournamentModelTypes[K]>> {
|
||||||
const connection = await this.getConnection();
|
const connection = await this.getConnection();
|
||||||
if (this.tournamentModels) {
|
if (this.tournamentModels)
|
||||||
return this.requireTournamentModel(this.tournamentModels, modelKey);
|
return this.tournamentModels.get(modelKey) as mongoose.Model<
|
||||||
}
|
TournamentModelTypes[K]
|
||||||
|
>;
|
||||||
|
|
||||||
const models = new Map<keyof TournamentModelTypes, unknown>();
|
const models = new Map<K, mongoose.Model<TournamentModelTypes[K]>>();
|
||||||
|
|
||||||
tournamentModelDefinitions.forEach((modelDefinition) => {
|
tournamentModelDefinitions.forEach((modelDefinition) => {
|
||||||
if (!(modelDefinition.schema instanceof mongoose.Schema)) {
|
|
||||||
throw new Error(
|
|
||||||
`Invalid Mongoose schema for model ${modelDefinition.name}.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
applyMongoosePerformancePlugin(modelDefinition.schema);
|
applyMongoosePerformancePlugin(modelDefinition.schema);
|
||||||
// 이미 생성된 경우 컴파일 스킵.
|
// 이미 생성된 경우 컴파일 스킵.
|
||||||
if (
|
if (
|
||||||
@@ -114,14 +106,14 @@ export class ConnectionService implements OnModuleInit {
|
|||||||
)
|
)
|
||||||
) {
|
) {
|
||||||
models.set(
|
models.set(
|
||||||
modelDefinition.name,
|
modelDefinition.name as K,
|
||||||
connection.models[modelDefinition.name],
|
connection.models[modelDefinition.name],
|
||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
} else {
|
} else {
|
||||||
models.set(
|
models.set(
|
||||||
modelDefinition.name,
|
modelDefinition.name as K,
|
||||||
connection.model(
|
connection.model<TournamentModelTypes[K]>(
|
||||||
modelDefinition.name,
|
modelDefinition.name,
|
||||||
modelDefinition.schema,
|
modelDefinition.schema,
|
||||||
modelDefinition.schemaName,
|
modelDefinition.schemaName,
|
||||||
@@ -131,18 +123,7 @@ export class ConnectionService implements OnModuleInit {
|
|||||||
});
|
});
|
||||||
|
|
||||||
this.tournamentModels = models;
|
this.tournamentModels = models;
|
||||||
return this.requireTournamentModel(models, modelKey);
|
return models.get(modelKey) as mongoose.Model<TournamentModelTypes[K]>;
|
||||||
}
|
|
||||||
|
|
||||||
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(
|
public async createSession(
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { DynamicModule, Module } from '@nestjs/common';
|
||||||
import { ConnectionService } from './connection.service';
|
import { ConnectionService } from './connection.service';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
|
|||||||
@@ -45,10 +45,7 @@ export async function migrateAuctionPassHistory(
|
|||||||
};
|
};
|
||||||
}> = [];
|
}> = [];
|
||||||
|
|
||||||
for await (const doc of db
|
for await (const doc of db.collection('auction').find({}).limit(options.limit ?? 0)) {
|
||||||
.collection('auction')
|
|
||||||
.find({})
|
|
||||||
.limit(options.limit ?? 0)) {
|
|
||||||
stats.scannedAuctions += 1;
|
stats.scannedAuctions += 1;
|
||||||
const set: Record<string, unknown> = {};
|
const set: Record<string, unknown> = {};
|
||||||
let changed = false;
|
let changed = false;
|
||||||
|
|||||||
@@ -27,8 +27,7 @@ function createDb(params: {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
async bulkWrite(
|
async bulkWrite(writes: Array<{
|
||||||
writes: Array<{
|
|
||||||
updateOne: {
|
updateOne: {
|
||||||
filter: { _id: unknown };
|
filter: { _id: unknown };
|
||||||
update: {
|
update: {
|
||||||
@@ -36,12 +35,9 @@ function createDb(params: {
|
|||||||
$unset: Record<string, ''>;
|
$unset: Record<string, ''>;
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
}>,
|
}>) {
|
||||||
) {
|
|
||||||
for (const write of writes) {
|
for (const write of writes) {
|
||||||
const doc = docs.find(
|
const doc = docs.find((item) => item._id === write.updateOne.filter._id);
|
||||||
(item) => item._id === write.updateOne.filter._id,
|
|
||||||
);
|
|
||||||
if (!doc) continue;
|
if (!doc) continue;
|
||||||
Object.assign(doc, write.updateOne.update.$set);
|
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)) {
|
||||||
@@ -61,10 +57,7 @@ describe('migrateTeamIndex', () => {
|
|||||||
auctions: [
|
auctions: [
|
||||||
{
|
{
|
||||||
_id: 'auction-1',
|
_id: 'auction-1',
|
||||||
teams: [
|
teams: [{ side: 'blue', groupIndex: 1 }, { side: 'red', groupIndex: 1 }],
|
||||||
{ side: 'blue', groupIndex: 1 },
|
|
||||||
{ side: 'red', groupIndex: 1 },
|
|
||||||
],
|
|
||||||
bids: [{ side: 'red', groupIndex: 1, amount: 100 }],
|
bids: [{ side: 'red', groupIndex: 1, amount: 100 }],
|
||||||
currentBidder: 'red',
|
currentBidder: 'red',
|
||||||
currentBidderGroupIndex: 1,
|
currentBidderGroupIndex: 1,
|
||||||
@@ -73,10 +66,7 @@ describe('migrateTeamIndex', () => {
|
|||||||
matches: [
|
matches: [
|
||||||
{
|
{
|
||||||
_id: 'match-1',
|
_id: 'match-1',
|
||||||
teams: [
|
teams: [{ side: 'blue', groupIndex: 1 }, { side: 'red', groupIndex: 1 }],
|
||||||
{ side: 'blue', groupIndex: 1 },
|
|
||||||
{ side: 'red', groupIndex: 1 },
|
|
||||||
],
|
|
||||||
result: {
|
result: {
|
||||||
winnerSide: 'blue',
|
winnerSide: 'blue',
|
||||||
blueScore: 1,
|
blueScore: 1,
|
||||||
@@ -122,10 +112,7 @@ describe('migrateTeamIndex', () => {
|
|||||||
currentBidderTeamIndex: 2,
|
currentBidderTeamIndex: 2,
|
||||||
});
|
});
|
||||||
expect(collections.match[0]).toMatchObject({
|
expect(collections.match[0]).toMatchObject({
|
||||||
teams: [
|
teams: [{ teamIndex: 1, name: '1팀' }, { teamIndex: 2, name: '2팀' }],
|
||||||
{ teamIndex: 1, name: '1팀' },
|
|
||||||
{ teamIndex: 2, name: '2팀' },
|
|
||||||
],
|
|
||||||
result: {
|
result: {
|
||||||
winnerTeamIndex: 1,
|
winnerTeamIndex: 1,
|
||||||
games: [
|
games: [
|
||||||
|
|||||||
@@ -45,20 +45,8 @@ export async function migrateTeamIndex(
|
|||||||
changedMatches: 0,
|
changedMatches: 0,
|
||||||
};
|
};
|
||||||
|
|
||||||
await migrateCollection(
|
await migrateCollection(db.collection('auction'), options.limit, dryRun, stats, 'auction');
|
||||||
db.collection('auction'),
|
await migrateCollection(db.collection('match'), options.limit, dryRun, stats, 'match');
|
||||||
options.limit,
|
|
||||||
dryRun,
|
|
||||||
stats,
|
|
||||||
'auction',
|
|
||||||
);
|
|
||||||
await migrateCollection(
|
|
||||||
db.collection('match'),
|
|
||||||
options.limit,
|
|
||||||
dryRun,
|
|
||||||
stats,
|
|
||||||
'match',
|
|
||||||
);
|
|
||||||
|
|
||||||
return stats;
|
return stats;
|
||||||
}
|
}
|
||||||
@@ -155,8 +143,7 @@ function migrateMatch(doc: AnyDoc) {
|
|||||||
const migrated = { ...team };
|
const migrated = { ...team };
|
||||||
const teamIndex = readTeamIndex(migrated);
|
const teamIndex = readTeamIndex(migrated);
|
||||||
if (teamIndex !== undefined) migrated.teamIndex = teamIndex;
|
if (teamIndex !== undefined) migrated.teamIndex = teamIndex;
|
||||||
if (!migrated.name && typeof teamIndex === 'number')
|
if (!migrated.name && typeof teamIndex === 'number') migrated.name = `${teamIndex}팀`;
|
||||||
migrated.name = `${teamIndex}팀`;
|
|
||||||
if ('side' in migrated || 'groupIndex' in migrated) changed = true;
|
if ('side' in migrated || 'groupIndex' in migrated) changed = true;
|
||||||
delete migrated.side;
|
delete migrated.side;
|
||||||
delete migrated.groupIndex;
|
delete migrated.groupIndex;
|
||||||
@@ -213,10 +200,7 @@ function migrateResult(result: Record<string, unknown>) {
|
|||||||
migrated.games = games;
|
migrated.games = games;
|
||||||
|
|
||||||
const seriesResults = asArray(result.seriesResults).map((series) => {
|
const seriesResults = asArray(result.seriesResults).map((series) => {
|
||||||
if (
|
if (typeof series.teamAIndex === 'number' && typeof series.teamBIndex === 'number') {
|
||||||
typeof series.teamAIndex === 'number' &&
|
|
||||||
typeof series.teamBIndex === 'number'
|
|
||||||
) {
|
|
||||||
return series;
|
return series;
|
||||||
}
|
}
|
||||||
changed = true;
|
changed = true;
|
||||||
@@ -232,9 +216,7 @@ function migrateResult(result: Record<string, unknown>) {
|
|||||||
const teamBIndex = Math.max(legacyBlueTeamIndex, legacyRedTeamIndex);
|
const teamBIndex = Math.max(legacyBlueTeamIndex, legacyRedTeamIndex);
|
||||||
const blueScore = numberOrDefault(series.blueScore, 0);
|
const blueScore = numberOrDefault(series.blueScore, 0);
|
||||||
const redScore = numberOrDefault(series.redScore, 0);
|
const redScore = numberOrDefault(series.redScore, 0);
|
||||||
const winnerSide = isSide(series.winnerSide)
|
const winnerSide = isSide(series.winnerSide) ? series.winnerSide : undefined;
|
||||||
? series.winnerSide
|
|
||||||
: undefined;
|
|
||||||
const winnerTeamIndex =
|
const winnerTeamIndex =
|
||||||
winnerSide === 'blue'
|
winnerSide === 'blue'
|
||||||
? legacyBlueTeamIndex
|
? legacyBlueTeamIndex
|
||||||
@@ -249,11 +231,12 @@ function migrateResult(result: Record<string, unknown>) {
|
|||||||
winnerTeamIndex,
|
winnerTeamIndex,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
migrated.seriesResults =
|
migrated.seriesResults = seriesResults.length > 0 ? seriesResults : buildSeries(games);
|
||||||
seriesResults.length > 0 ? seriesResults : buildSeries(games);
|
|
||||||
|
|
||||||
if (typeof migrated.winnerTeamIndex !== 'number') {
|
if (typeof migrated.winnerTeamIndex !== 'number') {
|
||||||
const migratedSeriesResults = asArray(migrated.seriesResults);
|
const migratedSeriesResults = Array.isArray(migrated.seriesResults)
|
||||||
|
? migrated.seriesResults
|
||||||
|
: [];
|
||||||
migrated.winnerTeamIndex =
|
migrated.winnerTeamIndex =
|
||||||
resolveWinnerTeamIndex(migratedSeriesResults) ??
|
resolveWinnerTeamIndex(migratedSeriesResults) ??
|
||||||
(isSide(migrated.winnerSide)
|
(isSide(migrated.winnerSide)
|
||||||
@@ -261,11 +244,7 @@ function migrateResult(result: Record<string, unknown>) {
|
|||||||
: undefined);
|
: undefined);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (
|
if ('winnerSide' in migrated || 'blueScore' in migrated || 'redScore' in migrated) {
|
||||||
'winnerSide' in migrated ||
|
|
||||||
'blueScore' in migrated ||
|
|
||||||
'redScore' in migrated
|
|
||||||
) {
|
|
||||||
changed = true;
|
changed = true;
|
||||||
}
|
}
|
||||||
delete migrated.winnerSide;
|
delete migrated.winnerSide;
|
||||||
@@ -293,12 +272,8 @@ function buildSeries(games: Record<string, unknown>[]) {
|
|||||||
const teamAIndex = Math.min(blueTeamIndex, redTeamIndex);
|
const teamAIndex = Math.min(blueTeamIndex, redTeamIndex);
|
||||||
const teamBIndex = Math.max(blueTeamIndex, redTeamIndex);
|
const teamBIndex = Math.max(blueTeamIndex, redTeamIndex);
|
||||||
const key = `${teamAIndex}:${teamBIndex}`;
|
const key = `${teamAIndex}:${teamBIndex}`;
|
||||||
const current = bySeries.get(key) ?? {
|
const current =
|
||||||
teamAIndex,
|
bySeries.get(key) ?? { teamAIndex, teamBIndex, teamAWins: 0, teamBWins: 0 };
|
||||||
teamBIndex,
|
|
||||||
teamAWins: 0,
|
|
||||||
teamBWins: 0,
|
|
||||||
};
|
|
||||||
if (winnerTeamIndex === teamAIndex) current.teamAWins += 1;
|
if (winnerTeamIndex === teamAIndex) current.teamAWins += 1;
|
||||||
if (winnerTeamIndex === teamBIndex) current.teamBWins += 1;
|
if (winnerTeamIndex === teamBIndex) current.teamBWins += 1;
|
||||||
current.winnerTeamIndex =
|
current.winnerTeamIndex =
|
||||||
@@ -356,7 +331,5 @@ function numberOrDefault(value: unknown, fallback: number) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function numberOrUndefined(value: unknown) {
|
function numberOrUndefined(value: unknown) {
|
||||||
return typeof value === 'number' && Number.isFinite(value)
|
return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
|
||||||
? value
|
|
||||||
: undefined;
|
|
||||||
}
|
}
|
||||||
+4
-10
@@ -30,8 +30,7 @@ function createDb(params: { auctions?: Doc[]; history?: Doc[] }) {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
async bulkWrite(
|
async bulkWrite(writes: Array<{
|
||||||
writes: Array<{
|
|
||||||
updateOne: {
|
updateOne: {
|
||||||
filter: { _id: unknown };
|
filter: { _id: unknown };
|
||||||
update: {
|
update: {
|
||||||
@@ -39,17 +38,12 @@ function createDb(params: { auctions?: Doc[]; history?: Doc[] }) {
|
|||||||
$unset?: Record<string, ''>;
|
$unset?: Record<string, ''>;
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
}>,
|
}>) {
|
||||||
) {
|
|
||||||
for (const write of writes) {
|
for (const write of writes) {
|
||||||
const doc = docs.find(
|
const doc = docs.find((item) => item._id === write.updateOne.filter._id);
|
||||||
(item) => item._id === write.updateOne.filter._id,
|
|
||||||
);
|
|
||||||
if (!doc) continue;
|
if (!doc) continue;
|
||||||
Object.assign(doc, write.updateOne.update.$set ?? {});
|
Object.assign(doc, write.updateOne.update.$set ?? {});
|
||||||
for (const key of Object.keys(
|
for (const key of Object.keys(write.updateOne.update.$unset ?? {})) {
|
||||||
write.updateOne.update.$unset ?? {},
|
|
||||||
)) {
|
|
||||||
delete doc[key];
|
delete doc[key];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-14
@@ -31,10 +31,7 @@ interface MigrationStats {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type AnyDoc = Record<string, unknown> & { _id: unknown };
|
type AnyDoc = Record<string, unknown> & { _id: unknown };
|
||||||
type UpdateDoc = {
|
type UpdateDoc = { $set?: Record<string, unknown>; $unset?: Record<string, ''> };
|
||||||
$set?: Record<string, unknown>;
|
|
||||||
$unset?: Record<string, ''>;
|
|
||||||
};
|
|
||||||
|
|
||||||
const AUCTION_FIELD_RENAMES: Array<{
|
const AUCTION_FIELD_RENAMES: Array<{
|
||||||
from: string;
|
from: string;
|
||||||
@@ -46,11 +43,7 @@ const AUCTION_FIELD_RENAMES: Array<{
|
|||||||
{ from: 'passedQueue', to: 'passedAuctionPlayerQueue' },
|
{ from: 'passedQueue', to: 'passedAuctionPlayerQueue' },
|
||||||
{ from: 'auctionRound', to: 'currentAuctionRound' },
|
{ from: 'auctionRound', to: 'currentAuctionRound' },
|
||||||
{ from: 'currentIndex', to: 'currentAuctionPlayerOrderIndex' },
|
{ from: 'currentIndex', to: 'currentAuctionPlayerOrderIndex' },
|
||||||
{
|
{ from: 'bids', to: 'auctionBidHistory', transform: transformAuctionBidHistory },
|
||||||
from: 'bids',
|
|
||||||
to: 'auctionBidHistory',
|
|
||||||
transform: transformAuctionBidHistory,
|
|
||||||
},
|
|
||||||
{ from: 'currentBid', to: 'currentHighestBidPointAmount' },
|
{ from: 'currentBid', to: 'currentHighestBidPointAmount' },
|
||||||
{ from: 'currentBidderTeamIndex', to: 'currentHighestBidderTeamIndex' },
|
{ from: 'currentBidderTeamIndex', to: 'currentHighestBidderTeamIndex' },
|
||||||
{
|
{
|
||||||
@@ -164,8 +157,7 @@ async function countDuplicateHistorySequences(
|
|||||||
const duplicates = new Set<string>();
|
const duplicates = new Set<string>();
|
||||||
for await (const doc of collection.find({}).limit(limit ?? 0)) {
|
for await (const doc of collection.find({}).limit(limit ?? 0)) {
|
||||||
const auctionId = stringifyId(doc.auctionId);
|
const auctionId = stringifyId(doc.auctionId);
|
||||||
const sequence =
|
const sequence = typeof doc.sequence === 'number' ? doc.sequence : undefined;
|
||||||
typeof doc.sequence === 'number' ? doc.sequence : undefined;
|
|
||||||
if (!auctionId || sequence === undefined) continue;
|
if (!auctionId || sequence === undefined) continue;
|
||||||
|
|
||||||
const key = `${auctionId}:${sequence}`;
|
const key = `${auctionId}:${sequence}`;
|
||||||
@@ -330,9 +322,6 @@ function legacyAuctionLifecycleId(value: unknown): string {
|
|||||||
|
|
||||||
function stringifyId(value: unknown): string | undefined {
|
function stringifyId(value: unknown): string | undefined {
|
||||||
if (value === undefined || value === null) return undefined;
|
if (value === undefined || value === null) return undefined;
|
||||||
// MongoDB ObjectId and migration fixture IDs intentionally rely on their
|
|
||||||
// stable string representation.
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-base-to-string
|
|
||||||
return typeof value === 'string' ? value : String(value);
|
return typeof value === 'string' ? value : String(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
-3
@@ -117,9 +117,7 @@ function createDb(params: {
|
|||||||
function matchesFilter(doc: Doc, filter: Record<string, unknown>): boolean {
|
function matchesFilter(doc: Doc, filter: Record<string, unknown>): boolean {
|
||||||
const clauses = filter.$or;
|
const clauses = filter.$or;
|
||||||
if (Array.isArray(clauses)) {
|
if (Array.isArray(clauses)) {
|
||||||
return (clauses as unknown[]).some(
|
return clauses.some((clause) => matchesFilter(doc, clause));
|
||||||
(clause) => isRecord(clause) && matchesFilter(doc, clause),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return Object.entries(filter).every(([key, value]) => {
|
return Object.entries(filter).every(([key, value]) => {
|
||||||
|
|||||||
+16
-14
@@ -1,4 +1,11 @@
|
|||||||
type TournamentCodeState = string;
|
type TournamentCodeState =
|
||||||
|
| 'available'
|
||||||
|
| 'reserved'
|
||||||
|
| 'used'
|
||||||
|
| 'released'
|
||||||
|
| 'expired'
|
||||||
|
| 'voided'
|
||||||
|
| string;
|
||||||
|
|
||||||
type AnyDoc = Record<string, unknown> & { _id: unknown };
|
type AnyDoc = Record<string, unknown> & { _id: unknown };
|
||||||
type IndexKey = Record<string, 1 | -1>;
|
type IndexKey = Record<string, 1 | -1>;
|
||||||
@@ -29,7 +36,7 @@ interface MigrationCollection {
|
|||||||
$unset?: Record<string, ''>;
|
$unset?: Record<string, ''>;
|
||||||
},
|
},
|
||||||
options?: { ordered?: boolean },
|
options?: { ordered?: boolean },
|
||||||
): Promise<unknown>;
|
): Promise<{ matchedCount?: number; modifiedCount?: number } | unknown>;
|
||||||
indexes?(): Promise<MigrationIndex[]>;
|
indexes?(): Promise<MigrationIndex[]>;
|
||||||
dropIndex?(name: string): Promise<unknown>;
|
dropIndex?(name: string): Promise<unknown>;
|
||||||
createIndex?(
|
createIndex?(
|
||||||
@@ -509,17 +516,15 @@ function summarizeGroups(
|
|||||||
function summarizeCode(doc: TournamentCodeDoc): TournamentCodeDuplicateSummary {
|
function summarizeCode(doc: TournamentCodeDoc): TournamentCodeDuplicateSummary {
|
||||||
return {
|
return {
|
||||||
bracketMatchId:
|
bracketMatchId:
|
||||||
doc.bracketMatchId === undefined
|
doc.bracketMatchId === undefined ? undefined : String(doc.bracketMatchId),
|
||||||
? undefined
|
code: doc.code === undefined ? undefined : String(doc.code),
|
||||||
: stringifyId(doc.bracketMatchId),
|
|
||||||
code: doc.code === undefined ? undefined : stringifyId(doc.code),
|
|
||||||
gameNumber:
|
gameNumber:
|
||||||
doc.gameNumber === undefined ? undefined : stringifyId(doc.gameNumber),
|
doc.gameNumber === undefined ? undefined : String(doc.gameNumber),
|
||||||
id: stringifyId(doc._id) ?? '',
|
id: stringifyId(doc._id) ?? '',
|
||||||
matchId: doc.matchId === undefined ? undefined : stringifyId(doc.matchId),
|
matchId: doc.matchId === undefined ? undefined : stringifyId(doc.matchId),
|
||||||
riotMatchId:
|
riotMatchId:
|
||||||
doc.riotMatchId === undefined ? undefined : stringifyId(doc.riotMatchId),
|
doc.riotMatchId === undefined ? undefined : String(doc.riotMatchId),
|
||||||
state: doc.state,
|
state: doc.state === undefined ? undefined : String(doc.state),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -744,19 +749,16 @@ function readModifiedCount(result: unknown): number {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function hasField(doc: Record<string, unknown>, key: string): boolean {
|
function hasField(doc: Record<string, unknown>, key: string): boolean {
|
||||||
return Object.hasOwn(doc, key);
|
return Object.prototype.hasOwnProperty.call(doc, key);
|
||||||
}
|
}
|
||||||
|
|
||||||
function stringifyKeyPart(value: unknown): string {
|
function stringifyKeyPart(value: unknown): string {
|
||||||
if (value === null) return '<null>';
|
if (value === null) return '<null>';
|
||||||
if (value === undefined) return '<undefined>';
|
if (value === undefined) return '<undefined>';
|
||||||
return stringifyId(value) ?? '<unknown>';
|
return stringifyId(value) ?? String(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
function stringifyId(value: unknown): string | undefined {
|
function stringifyId(value: unknown): string | undefined {
|
||||||
if (value === undefined || value === null) return undefined;
|
if (value === undefined || value === null) return undefined;
|
||||||
// MongoDB ObjectId and migration fixture IDs intentionally rely on their
|
|
||||||
// stable string representation.
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-base-to-string
|
|
||||||
return typeof value === 'string' ? value : String(value);
|
return typeof value === 'string' ? value : String(value);
|
||||||
}
|
}
|
||||||
+2
-6
@@ -11,11 +11,7 @@ import {
|
|||||||
} from '../../../double-elimination/double-elimination.util';
|
} from '../../../double-elimination/double-elimination.util';
|
||||||
import { TOURNAMENT_CODE_EXPIRY_MARGIN_MS } from '../../../tournament-code/tournament-code.constants';
|
import { TOURNAMENT_CODE_EXPIRY_MARGIN_MS } from '../../../tournament-code/tournament-code.constants';
|
||||||
import { ConnectionService } from '../connection.service';
|
import { ConnectionService } from '../connection.service';
|
||||||
import type {
|
import type { MatchDocument, TournamentCodeDocument } from '../schema';
|
||||||
MatchDocument,
|
|
||||||
TournamentCode,
|
|
||||||
TournamentCodeDocument,
|
|
||||||
} from '../schema';
|
|
||||||
import { SecretModule } from '../../secret/secret.module';
|
import { SecretModule } from '../../secret/secret.module';
|
||||||
|
|
||||||
interface CliOptions {
|
interface CliOptions {
|
||||||
@@ -338,7 +334,7 @@ function printPlan(plan: MatchRepairPlan) {
|
|||||||
async function applyPlan(
|
async function applyPlan(
|
||||||
match: MatchDocument,
|
match: MatchDocument,
|
||||||
plan: MatchRepairPlan,
|
plan: MatchRepairPlan,
|
||||||
TournamentCodeModel: mongoose.Model<TournamentCode>,
|
TournamentCodeModel: mongoose.Model<any>,
|
||||||
session: mongoose.ClientSession,
|
session: mongoose.ClientSession,
|
||||||
) {
|
) {
|
||||||
if (plan.skippedReason) return;
|
if (plan.skippedReason) return;
|
||||||
|
|||||||
+12
-14
@@ -5,7 +5,10 @@ import { NestFactory } from '@nestjs/core';
|
|||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
import { readFile } from 'node:fs/promises';
|
import { readFile } from 'node:fs/promises';
|
||||||
import { resolve } from 'node:path';
|
import { resolve } from 'node:path';
|
||||||
import { ConnectionService, resolveMongoDbName } from '../connection.service';
|
import {
|
||||||
|
ConnectionService,
|
||||||
|
resolveMongoDbName,
|
||||||
|
} from '../connection.service';
|
||||||
import type {
|
import type {
|
||||||
MatchDocument,
|
MatchDocument,
|
||||||
MatchGameAssignment,
|
MatchGameAssignment,
|
||||||
@@ -211,16 +214,12 @@ async function main() {
|
|||||||
printPlan(options, match, codes, plan);
|
printPlan(options, match, codes, plan);
|
||||||
|
|
||||||
if (options.dryRun) {
|
if (options.dryRun) {
|
||||||
console.log(
|
console.log('No writes were made. Re-run with --apply to update MongoDB.');
|
||||||
'No writes were made. Re-run with --apply to update MongoDB.',
|
|
||||||
);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const session = await (
|
const session = await (await connectionService.getConnection()).startSession();
|
||||||
await connectionService.getConnection()
|
|
||||||
).startSession();
|
|
||||||
try {
|
try {
|
||||||
await session.withTransaction(async () => {
|
await session.withTransaction(async () => {
|
||||||
await applyTournamentCodeUpdates(plan, now, session);
|
await applyTournamentCodeUpdates(plan, now, session);
|
||||||
@@ -231,9 +230,9 @@ async function main() {
|
|||||||
status: 'finished',
|
status: 'finished',
|
||||||
roundRobinMaxRounds: options.maxRounds,
|
roundRobinMaxRounds: options.maxRounds,
|
||||||
gameSchedule: plan.schedule,
|
gameSchedule: plan.schedule,
|
||||||
tournamentCodeIds: [...plan.usedCodeByOldGameNumber.values()].map(
|
tournamentCodeIds: [
|
||||||
(code) => code._id,
|
...plan.usedCodeByOldGameNumber.values(),
|
||||||
),
|
].map((code) => code._id),
|
||||||
resultPollState: {
|
resultPollState: {
|
||||||
startedAt: match.resultPollState?.startedAt ?? now,
|
startedAt: match.resultPollState?.startedAt ?? now,
|
||||||
lastPolledAt: now,
|
lastPolledAt: now,
|
||||||
@@ -424,9 +423,7 @@ function partitionIntoRounds(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!fillRound(0)) {
|
if (!fillRound(0)) {
|
||||||
throw new Error(
|
throw new Error('Could not partition result games into simultaneous rounds.');
|
||||||
'Could not partition result games into simultaneous rounds.',
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return rounds;
|
return rounds;
|
||||||
@@ -589,7 +586,8 @@ function buildSeriesResults(games: MatchGameResult[]): MatchSeriesResult[] {
|
|||||||
}
|
}
|
||||||
return [...bySeries.values()].sort(
|
return [...bySeries.values()].sort(
|
||||||
(left, right) =>
|
(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();
|
.toArray();
|
||||||
}
|
}
|
||||||
|
|
||||||
function printDuplicateHistorySequences(
|
function printDuplicateHistorySequences(groups: Awaited<
|
||||||
groups: Awaited<ReturnType<typeof listDuplicateHistorySequences>>,
|
ReturnType<typeof listDuplicateHistorySequences>
|
||||||
) {
|
>) {
|
||||||
if (groups.length === 0) {
|
if (groups.length === 0) {
|
||||||
console.log('No duplicate auctionHistory auctionId+sequence groups found.');
|
console.log('No duplicate auctionHistory auctionId+sequence groups found.');
|
||||||
return;
|
return;
|
||||||
@@ -248,8 +248,7 @@ async function repairDuplicateHistorySequences(
|
|||||||
): Promise<DuplicateSequenceRepairStats> {
|
): Promise<DuplicateSequenceRepairStats> {
|
||||||
const historyCollection = db.collection('auctionHistory');
|
const historyCollection = db.collection('auctionHistory');
|
||||||
const auctionCollection = db.collection('auction');
|
const auctionCollection = db.collection('auction');
|
||||||
const affectedAuctionIds =
|
const affectedAuctionIds = await findAuctionIdsWithDuplicateHistorySequences(db);
|
||||||
await findAuctionIdsWithDuplicateHistorySequences(db);
|
|
||||||
const stats: DuplicateSequenceRepairStats = {
|
const stats: DuplicateSequenceRepairStats = {
|
||||||
affectedAuctions: affectedAuctionIds.length,
|
affectedAuctions: affectedAuctionIds.length,
|
||||||
changedAuctionSequenceFields: 0,
|
changedAuctionSequenceFields: 0,
|
||||||
|
|||||||
+4
-4
@@ -177,9 +177,7 @@ function parseArgs(argv: string[]): CliOptions {
|
|||||||
|
|
||||||
function parseCommitQuorum(value: string | undefined, label: string) {
|
function parseCommitQuorum(value: string | undefined, label: string) {
|
||||||
if (!value) {
|
if (!value) {
|
||||||
throw new Error(
|
throw new Error(`${label} requires a positive integer, majority, or votingMembers.`);
|
||||||
`${label} requires a positive integer, majority, or votingMembers.`,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
if (value === 'majority' || value === 'votingMembers') return value;
|
if (value === 'majority' || value === 'votingMembers') return value;
|
||||||
return parsePositiveInteger(value, label);
|
return parsePositiveInteger(value, label);
|
||||||
@@ -232,7 +230,9 @@ function printDuplicateGroups(groups: TournamentCodeDuplicateGroupSummary[]) {
|
|||||||
kind: group.kind,
|
kind: group.kind,
|
||||||
loserCodes: group.losers.map((loser) => loser.code ?? '').join(', '),
|
loserCodes: group.losers.map((loser) => loser.code ?? '').join(', '),
|
||||||
loserIds: group.losers.map((loser) => loser.id).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,9 +2485,7 @@ MatchStatsSchema.index({ communityId: 1, userIds: 1 });
|
|||||||
MatchStatsSchema.index({ communityId: 1, userIds: 1, scheduledAt: -1 });
|
MatchStatsSchema.index({ communityId: 1, userIds: 1, scheduledAt: -1 });
|
||||||
MatchStatsSchema.index({ communityId: 1, championIds: 1 });
|
MatchStatsSchema.index({ communityId: 1, championIds: 1 });
|
||||||
|
|
||||||
export const tournamentModelDefinitions: Array<
|
export const tournamentModelDefinitions: ModelDefinition[] = [
|
||||||
ModelDefinition & { name: keyof TournamentModelTypes }
|
|
||||||
> = [
|
|
||||||
...competitionModelDefinitions,
|
...competitionModelDefinitions,
|
||||||
{ name: 'identity', schema: IdentitySchema, schemaName: 'identity' },
|
{ name: 'identity', schema: IdentitySchema, schemaName: 'identity' },
|
||||||
{ name: 'community', schema: CommunitySchema, schemaName: 'community' },
|
{ name: 'community', schema: CommunitySchema, schemaName: 'community' },
|
||||||
|
|||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
export interface ModelDefinition {
|
export interface ModelDefinition {
|
||||||
name: string;
|
name: string;
|
||||||
schema: unknown;
|
schema: mongoose.Schema<any>;
|
||||||
schemaName?: string;
|
schemaName?: string;
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
|
import fs from 'fs/promises';
|
||||||
import { connect } from 'nats';
|
import { connect } from 'nats';
|
||||||
import type { NatsConnection } from 'nats';
|
import type { NatsConnection } from 'nats';
|
||||||
import { SecretModule } from '../secret/secret.module';
|
import { SecretModule } from '../secret/secret.module';
|
||||||
|
|||||||
@@ -34,32 +34,31 @@ type SchemaWithPerformanceMarker = mongoose.Schema & {
|
|||||||
[PERFORMANCE_PLUGIN_APPLIED]?: boolean;
|
[PERFORMANCE_PLUGIN_APPLIED]?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function applyMongoosePerformancePlugin(schemaValue: unknown): void {
|
export function applyMongoosePerformancePlugin(schema: mongoose.Schema): void {
|
||||||
if (!(schemaValue instanceof mongoose.Schema)) {
|
const markedSchema = schema as SchemaWithPerformanceMarker;
|
||||||
throw new TypeError('Mongoose performance plugin requires a Schema.');
|
if (markedSchema[PERFORMANCE_PLUGIN_APPLIED]) return;
|
||||||
}
|
markedSchema[PERFORMANCE_PLUGIN_APPLIED] = true;
|
||||||
const schema = schemaValue as SchemaWithPerformanceMarker;
|
const hookableSchema = schema as any;
|
||||||
if (schema[PERFORMANCE_PLUGIN_APPLIED]) return;
|
|
||||||
schema[PERFORMANCE_PLUGIN_APPLIED] = true;
|
|
||||||
|
|
||||||
schema.pre(QUERY_OPERATION_REGEX, function () {
|
hookableSchema.pre(QUERY_OPERATION_REGEX, function () {
|
||||||
const query = this as QueryWithPerformanceState;
|
const query = this as QueryWithPerformanceState;
|
||||||
query[QUERY_PERFORMANCE_START] = process.hrtime.bigint();
|
query[QUERY_PERFORMANCE_START] = process.hrtime.bigint();
|
||||||
query[QUERY_PERFORMANCE_RECORDED] = false;
|
query[QUERY_PERFORMANCE_RECORDED] = false;
|
||||||
});
|
});
|
||||||
|
|
||||||
schema.post(QUERY_OPERATION_REGEX, function (result: unknown) {
|
hookableSchema.post(
|
||||||
recordQueryPerformance(this as QueryWithPerformanceState, result);
|
|
||||||
});
|
|
||||||
|
|
||||||
schema.post(
|
|
||||||
QUERY_OPERATION_REGEX,
|
QUERY_OPERATION_REGEX,
|
||||||
{ errorHandler: true },
|
function (result: unknown) {
|
||||||
function (
|
recordQueryPerformance(
|
||||||
error: Error,
|
this as unknown as QueryWithPerformanceState,
|
||||||
_result: unknown,
|
result,
|
||||||
next: (error?: mongoose.CallbackError) => void,
|
);
|
||||||
) {
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
hookableSchema.post(
|
||||||
|
QUERY_OPERATION_REGEX,
|
||||||
|
function (error: unknown, _result: unknown, next: (error: unknown) => void) {
|
||||||
recordQueryPerformance(
|
recordQueryPerformance(
|
||||||
this as unknown as QueryWithPerformanceState,
|
this as unknown as QueryWithPerformanceState,
|
||||||
undefined,
|
undefined,
|
||||||
@@ -69,24 +68,19 @@ export function applyMongoosePerformancePlugin(schemaValue: unknown): void {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
schema.pre('aggregate', function () {
|
hookableSchema.pre('aggregate', function () {
|
||||||
const aggregate = this as AggregateWithPerformanceState;
|
const aggregate = this as AggregateWithPerformanceState;
|
||||||
aggregate[QUERY_PERFORMANCE_START] = process.hrtime.bigint();
|
aggregate[QUERY_PERFORMANCE_START] = process.hrtime.bigint();
|
||||||
aggregate[QUERY_PERFORMANCE_RECORDED] = false;
|
aggregate[QUERY_PERFORMANCE_RECORDED] = false;
|
||||||
});
|
});
|
||||||
|
|
||||||
schema.post('aggregate', function (result: unknown) {
|
hookableSchema.post('aggregate', function (result: unknown) {
|
||||||
recordAggregatePerformance(this as AggregateWithPerformanceState, result);
|
recordAggregatePerformance(this as AggregateWithPerformanceState, result);
|
||||||
});
|
});
|
||||||
|
|
||||||
schema.post(
|
hookableSchema.post(
|
||||||
'aggregate',
|
'aggregate',
|
||||||
{ errorHandler: true },
|
function (error: unknown, _result: unknown, next: (error: unknown) => void) {
|
||||||
function (
|
|
||||||
error: Error,
|
|
||||||
_result: unknown,
|
|
||||||
next: (error?: mongoose.CallbackError) => void,
|
|
||||||
) {
|
|
||||||
recordAggregatePerformance(
|
recordAggregatePerformance(
|
||||||
this as AggregateWithPerformanceState,
|
this as AggregateWithPerformanceState,
|
||||||
undefined,
|
undefined,
|
||||||
|
|||||||
@@ -11,7 +11,9 @@ interface NewRelicCustomEventApi {
|
|||||||
eventType: string,
|
eventType: string,
|
||||||
attributes: Record<string, NewRelicAttributeValue>,
|
attributes: Record<string, NewRelicAttributeValue>,
|
||||||
): void;
|
): void;
|
||||||
addCustomAttributes(attributes: Record<string, NewRelicAttributeValue>): void;
|
addCustomAttributes(
|
||||||
|
attributes: Record<string, NewRelicAttributeValue>,
|
||||||
|
): void;
|
||||||
setTransactionName(name: string): void;
|
setTransactionName(name: string): void;
|
||||||
}
|
}
|
||||||
const agent = newrelicAgent as unknown as NewRelicCustomEventApi;
|
const agent = newrelicAgent as unknown as NewRelicCustomEventApi;
|
||||||
|
|||||||
@@ -52,7 +52,8 @@ export interface ApiRequestPerformanceEvent {
|
|||||||
leanQueryCount: number;
|
leanQueryCount: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface MongooseQueryPerformanceEvent extends MongooseQueryPerformance {
|
export interface MongooseQueryPerformanceEvent
|
||||||
|
extends MongooseQueryPerformance {
|
||||||
type: 'mongoose-query';
|
type: 'mongoose-query';
|
||||||
timestamp: string;
|
timestamp: string;
|
||||||
requestId?: string;
|
requestId?: string;
|
||||||
@@ -91,7 +92,10 @@ export function resolveApiPerformanceConfig(
|
|||||||
const enabled = readBoolean(env.API_PERF_OBSERVABILITY_ENABLED, false);
|
const enabled = readBoolean(env.API_PERF_OBSERVABILITY_ENABLED, false);
|
||||||
return {
|
return {
|
||||||
enabled,
|
enabled,
|
||||||
localEventsEnabled: readBoolean(env.API_PERF_LOCAL_EVENTS_ENABLED, enabled),
|
localEventsEnabled: readBoolean(
|
||||||
|
env.API_PERF_LOCAL_EVENTS_ENABLED,
|
||||||
|
enabled,
|
||||||
|
),
|
||||||
localEventFile:
|
localEventFile:
|
||||||
env.API_PERF_LOCAL_EVENT_FILE || '/tmp/lolympus-api-performance.ndjson',
|
env.API_PERF_LOCAL_EVENT_FILE || '/tmp/lolympus-api-performance.ndjson',
|
||||||
newRelicRequestEventsEnabled: readBoolean(
|
newRelicRequestEventsEnabled: readBoolean(
|
||||||
|
|||||||
@@ -35,7 +35,8 @@ export interface RunWithDistributedLockOptions {
|
|||||||
lockRetryDelayMilliseconds?: number;
|
lockRetryDelayMilliseconds?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface RunWithRenewedDistributedLockOptions extends RunWithDistributedLockOptions {
|
export interface RunWithRenewedDistributedLockOptions
|
||||||
|
extends RunWithDistributedLockOptions {
|
||||||
lockRenewalIntervalMilliseconds: number;
|
lockRenewalIntervalMilliseconds: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -54,13 +55,16 @@ export class DistributedLockService {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const lockOwnershipToken = options.lockOwnershipToken ?? randomUUID();
|
const lockOwnershipToken = options.lockOwnershipToken ?? randomUUID();
|
||||||
const result = await this.redisService
|
const result = await this.redisService.raw().sendCommand([
|
||||||
.raw()
|
'SET',
|
||||||
.sendCommand<
|
options.lockKey,
|
||||||
string | null
|
lockOwnershipToken,
|
||||||
>(['SET', options.lockKey, lockOwnershipToken, 'NX', 'PX', String(options.lockExpirationDurationMilliseconds)]);
|
'NX',
|
||||||
|
'PX',
|
||||||
|
String(options.lockExpirationDurationMilliseconds),
|
||||||
|
]);
|
||||||
|
|
||||||
if (result !== 'OK') return null;
|
if (String(result) !== 'OK') return null;
|
||||||
return {
|
return {
|
||||||
lockKey: options.lockKey,
|
lockKey: options.lockKey,
|
||||||
lockOwnershipToken,
|
lockOwnershipToken,
|
||||||
@@ -72,9 +76,7 @@ export class DistributedLockService {
|
|||||||
public async releaseLockIfOwned(
|
public async releaseLockIfOwned(
|
||||||
lockOwnership: DistributedLockOwnership,
|
lockOwnership: DistributedLockOwnership,
|
||||||
): Promise<boolean> {
|
): Promise<boolean> {
|
||||||
const result = await this.redisService
|
const result = await this.redisService.raw().sendCommand([
|
||||||
.raw()
|
|
||||||
.sendCommand([
|
|
||||||
'EVAL',
|
'EVAL',
|
||||||
RELEASE_LOCK_IF_OWNED_SCRIPT,
|
RELEASE_LOCK_IF_OWNED_SCRIPT,
|
||||||
'1',
|
'1',
|
||||||
@@ -86,16 +88,15 @@ export class DistributedLockService {
|
|||||||
|
|
||||||
public async extendLockIfOwned(
|
public async extendLockIfOwned(
|
||||||
lockOwnership: DistributedLockOwnership,
|
lockOwnership: DistributedLockOwnership,
|
||||||
lockExpirationDurationMilliseconds = lockOwnership.lockExpirationDurationMilliseconds,
|
lockExpirationDurationMilliseconds =
|
||||||
|
lockOwnership.lockExpirationDurationMilliseconds,
|
||||||
): Promise<boolean> {
|
): Promise<boolean> {
|
||||||
this.assertPositiveDuration(
|
this.assertPositiveDuration(
|
||||||
lockExpirationDurationMilliseconds,
|
lockExpirationDurationMilliseconds,
|
||||||
'lockExpirationDurationMilliseconds',
|
'lockExpirationDurationMilliseconds',
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = await this.redisService
|
const result = await this.redisService.raw().sendCommand([
|
||||||
.raw()
|
|
||||||
.sendCommand([
|
|
||||||
'EVAL',
|
'EVAL',
|
||||||
EXTEND_LOCK_IF_OWNED_SCRIPT,
|
EXTEND_LOCK_IF_OWNED_SCRIPT,
|
||||||
'1',
|
'1',
|
||||||
@@ -119,7 +120,7 @@ export class DistributedLockService {
|
|||||||
await this.releaseLockIfOwned(lockOwnership).catch((error: unknown) => {
|
await this.releaseLockIfOwned(lockOwnership).catch((error: unknown) => {
|
||||||
this.logger.warn(
|
this.logger.warn(
|
||||||
`Failed to release distributed lock ${lockOwnership.lockKey}: ${
|
`Failed to release distributed lock ${lockOwnership.lockKey}: ${
|
||||||
error instanceof Error ? error.message : String(error)
|
error instanceof Error ? error.message : error
|
||||||
}`,
|
}`,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
@@ -138,7 +139,8 @@ export class DistributedLockService {
|
|||||||
const lockOwnership = await this.acquireLockWithRetry(options);
|
const lockOwnership = await this.acquireLockWithRetry(options);
|
||||||
if (!lockOwnership) return null;
|
if (!lockOwnership) return null;
|
||||||
|
|
||||||
const lockRenewalTimer = setInterval(() => {
|
let lockRenewalTimer: NodeJS.Timeout | undefined;
|
||||||
|
lockRenewalTimer = setInterval(() => {
|
||||||
void this.extendLockIfOwned(lockOwnership).then((wasExtended) => {
|
void this.extendLockIfOwned(lockOwnership).then((wasExtended) => {
|
||||||
if (wasExtended) return;
|
if (wasExtended) return;
|
||||||
this.logger.warn(
|
this.logger.warn(
|
||||||
@@ -151,11 +153,11 @@ export class DistributedLockService {
|
|||||||
try {
|
try {
|
||||||
return await operation(lockOwnership);
|
return await operation(lockOwnership);
|
||||||
} finally {
|
} finally {
|
||||||
clearInterval(lockRenewalTimer);
|
if (lockRenewalTimer) clearInterval(lockRenewalTimer);
|
||||||
await this.releaseLockIfOwned(lockOwnership).catch((error: unknown) => {
|
await this.releaseLockIfOwned(lockOwnership).catch((error: unknown) => {
|
||||||
this.logger.warn(
|
this.logger.warn(
|
||||||
`Failed to release distributed lock ${lockOwnership.lockKey}: ${
|
`Failed to release distributed lock ${lockOwnership.lockKey}: ${
|
||||||
error instanceof Error ? error.message : String(error)
|
error instanceof Error ? error.message : error
|
||||||
}`,
|
}`,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -25,9 +25,7 @@ async function readFirstSecret(
|
|||||||
{
|
{
|
||||||
provide: REDIS_CLIENT,
|
provide: REDIS_CLIENT,
|
||||||
inject: [SecretService],
|
inject: [SecretService],
|
||||||
useFactory: async (
|
useFactory: async (secretService: SecretService): Promise<RedisClient> => {
|
||||||
secretService: SecretService,
|
|
||||||
): Promise<RedisClient> => {
|
|
||||||
await secretService.ready();
|
await secretService.ready();
|
||||||
|
|
||||||
const [url, endpoint, username, password] = await Promise.all([
|
const [url, endpoint, username, password] = await Promise.all([
|
||||||
@@ -54,12 +52,8 @@ async function readFirstSecret(
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
client.on('error', (error: unknown) => {
|
client.on('error', (error) => {
|
||||||
logger.error(
|
logger.error(`Redis client error: ${error?.message ?? error}`);
|
||||||
`Redis client error: ${
|
|
||||||
error instanceof Error ? error.message : String(error)
|
|
||||||
}`,
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
await client.connect();
|
await client.connect();
|
||||||
|
|||||||
@@ -6,9 +6,7 @@ function createRedisService(client: Record<string, unknown>) {
|
|||||||
|
|
||||||
describe('RedisService stream pending recovery', () => {
|
describe('RedisService stream pending recovery', () => {
|
||||||
it('normalizes XAUTOCLAIM array replies into stream entries', async () => {
|
it('normalizes XAUTOCLAIM array replies into stream entries', async () => {
|
||||||
const sendCommand = jest
|
const sendCommand = jest.fn().mockResolvedValue([
|
||||||
.fn()
|
|
||||||
.mockResolvedValue([
|
|
||||||
'0-0',
|
'0-0',
|
||||||
[
|
[
|
||||||
[
|
[
|
||||||
|
|||||||
@@ -35,14 +35,11 @@ interface RawStreamReadResult {
|
|||||||
|
|
||||||
function normalizeStreamFields(fields: unknown): Record<string, string> {
|
function normalizeStreamFields(fields: unknown): Record<string, string> {
|
||||||
if (Array.isArray(fields)) {
|
if (Array.isArray(fields)) {
|
||||||
const values = fields as unknown[];
|
|
||||||
const normalized: Record<string, string> = {};
|
const normalized: Record<string, string> = {};
|
||||||
for (let index = 0; index < values.length; index += 2) {
|
for (let index = 0; index < fields.length; index += 2) {
|
||||||
const key = values[index];
|
const key = fields[index];
|
||||||
if (key === undefined) continue;
|
if (key === undefined) continue;
|
||||||
normalized[redisValueToString(key)] = redisValueToString(
|
normalized[String(key)] = String(fields[index + 1] ?? '');
|
||||||
values[index + 1],
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
return normalized;
|
return normalized;
|
||||||
}
|
}
|
||||||
@@ -226,7 +223,9 @@ export class RedisService implements OnModuleDestroy {
|
|||||||
])) as unknown;
|
])) as unknown;
|
||||||
|
|
||||||
const responseItems = Array.isArray(response) ? response : [];
|
const responseItems = Array.isArray(response) ? response : [];
|
||||||
const rawMessages = Array.isArray(responseItems[1]) ? responseItems[1] : [];
|
const rawMessages = Array.isArray(responseItems[1])
|
||||||
|
? responseItems[1]
|
||||||
|
: [];
|
||||||
|
|
||||||
return {
|
return {
|
||||||
nextStartId: String(responseItems[0] ?? '0-0'),
|
nextStartId: String(responseItems[0] ?? '0-0'),
|
||||||
@@ -259,14 +258,12 @@ export class RedisService implements OnModuleDestroy {
|
|||||||
return this.client.publish(channel, message);
|
return this.client.publish(channel, message);
|
||||||
}
|
}
|
||||||
|
|
||||||
private normalizeClaimedStreamMessage(
|
private normalizeClaimedStreamMessage(rawMessage: unknown): StreamEntry | null {
|
||||||
rawMessage: unknown,
|
|
||||||
): StreamEntry | null {
|
|
||||||
if (Array.isArray(rawMessage)) {
|
if (Array.isArray(rawMessage)) {
|
||||||
const [id, fields] = rawMessage as unknown[];
|
const [id, fields] = rawMessage;
|
||||||
if (id === undefined) return null;
|
if (id === undefined) return null;
|
||||||
return {
|
return {
|
||||||
id: redisValueToString(id),
|
id: String(id),
|
||||||
message: normalizeStreamFields(fields),
|
message: normalizeStreamFields(fields),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -294,17 +291,3 @@ export class RedisService implements OnModuleDestroy {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function redisValueToString(value: unknown): string {
|
|
||||||
if (typeof value === 'string') return value;
|
|
||||||
if (
|
|
||||||
typeof value === 'number' ||
|
|
||||||
typeof value === 'boolean' ||
|
|
||||||
typeof value === 'bigint'
|
|
||||||
) {
|
|
||||||
return String(value);
|
|
||||||
}
|
|
||||||
if (Buffer.isBuffer(value)) return value.toString('utf8');
|
|
||||||
if (value === undefined || value === null) return '';
|
|
||||||
return JSON.stringify(value) ?? '';
|
|
||||||
}
|
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/require-await, @typescript-eslint/unbound-method */
|
||||||
import { readFileSync } from 'node:fs';
|
import { readFileSync } from 'node:fs';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
import type { CompetitionBootstrapService } from '../competition/competition-bootstrap.service';
|
import type { CompetitionBootstrapService } from '../competition/competition-bootstrap.service';
|
||||||
|
|||||||
@@ -46,13 +46,11 @@ export function countKnownParticipants(
|
|||||||
): { team100: number; team200: number; total: number } {
|
): { team100: number; team200: number; total: number } {
|
||||||
const team100 = detail.info.participants.filter(
|
const team100 = detail.info.participants.filter(
|
||||||
(participant) =>
|
(participant) =>
|
||||||
participant.teamId === RIOT_BLUE_TEAM_ID &&
|
participant.teamId === RIOT_BLUE_TEAM_ID && userByPuuid.has(participant.puuid),
|
||||||
userByPuuid.has(participant.puuid),
|
|
||||||
).length;
|
).length;
|
||||||
const team200 = detail.info.participants.filter(
|
const team200 = detail.info.participants.filter(
|
||||||
(participant) =>
|
(participant) =>
|
||||||
participant.teamId === RIOT_RED_TEAM_ID &&
|
participant.teamId === RIOT_RED_TEAM_ID && userByPuuid.has(participant.puuid),
|
||||||
userByPuuid.has(participant.puuid),
|
|
||||||
).length;
|
).length;
|
||||||
return { team100, team200, total: team100 + team200 };
|
return { team100, team200, total: team100 + team200 };
|
||||||
}
|
}
|
||||||
@@ -80,16 +78,13 @@ export function buildParticipantsSnapshot(
|
|||||||
tagLine: user.account.tagLine || participant.riotIdTagLine,
|
tagLine: user.account.tagLine || participant.riotIdTagLine,
|
||||||
profileIconId: user.account.profileIconId,
|
profileIconId: user.account.profileIconId,
|
||||||
tier:
|
tier:
|
||||||
user.account.tiers.find(
|
user.account.tiers.find((tier) => tier.queueType === 'RANKED_SOLO_5x5') ??
|
||||||
(tier) => tier.queueType === 'RANKED_SOLO_5x5',
|
user.account.tiers[0],
|
||||||
) ?? user.account.tiers[0],
|
|
||||||
preferredPositions: user.preferredPositions,
|
preferredPositions: user.preferredPositions,
|
||||||
joinedAt: new Date(detail.info.gameCreation),
|
joinedAt: new Date(detail.info.gameCreation),
|
||||||
};
|
};
|
||||||
})
|
})
|
||||||
.filter((participant): participant is MatchParticipant =>
|
.filter((participant): participant is MatchParticipant => Boolean(participant));
|
||||||
Boolean(participant),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function buildTeams(
|
export function buildTeams(
|
||||||
@@ -110,9 +105,7 @@ export function buildTeams(
|
|||||||
assignedPosition: resolveAssignedPosition(participant, user),
|
assignedPosition: resolveAssignedPosition(participant, user),
|
||||||
};
|
};
|
||||||
})
|
})
|
||||||
.filter((member): member is NonNullable<typeof member> =>
|
.filter((member): member is NonNullable<typeof member> => Boolean(member));
|
||||||
Boolean(member),
|
|
||||||
);
|
|
||||||
return {
|
return {
|
||||||
teamIndex,
|
teamIndex,
|
||||||
name: `${teamIndex}팀`,
|
name: `${teamIndex}팀`,
|
||||||
|
|||||||
@@ -3,7 +3,9 @@ import mongoose from 'mongoose';
|
|||||||
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
|
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
|
||||||
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
|
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
|
||||||
import { RiotJobQueueService } from '../riot-job-queue/riot-job-queue.service';
|
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';
|
import { MatchHistoryService } from './match-history.service';
|
||||||
|
|
||||||
interface RefreshBody {
|
interface RefreshBody {
|
||||||
|
|||||||
@@ -1,8 +1,4 @@
|
|||||||
import {
|
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
|
||||||
BadRequestException,
|
|
||||||
Injectable,
|
|
||||||
NotFoundException,
|
|
||||||
} from '@nestjs/common';
|
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
import { ConnectionService } from '../global/database/connection.service';
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
import type {
|
import type {
|
||||||
@@ -20,7 +16,10 @@ import {
|
|||||||
type RiotQueueGroup,
|
type RiotQueueGroup,
|
||||||
type RiotRankFilter,
|
type RiotRankFilter,
|
||||||
} from '../riot/riot-queue.constants';
|
} from '../riot/riot-queue.constants';
|
||||||
import type { RiotMatchDto, RiotMatchParticipantDto } from '../riot/riot.types';
|
import type {
|
||||||
|
RiotMatchDto,
|
||||||
|
RiotMatchParticipantDto,
|
||||||
|
} from '../riot/riot.types';
|
||||||
import type {
|
import type {
|
||||||
ChampionStatsResponse,
|
ChampionStatsResponse,
|
||||||
ChampionStatsRow,
|
ChampionStatsRow,
|
||||||
@@ -105,10 +104,7 @@ export class MatchHistoryService {
|
|||||||
fetchedAt: tier.fetchedAt.toISOString(),
|
fetchedAt: tier.fetchedAt.toISOString(),
|
||||||
})),
|
})),
|
||||||
tierHistory: [...context.account.tierHistory]
|
tierHistory: [...context.account.tierHistory]
|
||||||
.sort(
|
.sort((left, right) => left.recordedAt.getTime() - right.recordedAt.getTime())
|
||||||
(left, right) =>
|
|
||||||
left.recordedAt.getTime() - right.recordedAt.getTime(),
|
|
||||||
)
|
|
||||||
.map((entry) => ({
|
.map((entry) => ({
|
||||||
queueType: entry.queueType,
|
queueType: entry.queueType,
|
||||||
tier: entry.tier,
|
tier: entry.tier,
|
||||||
@@ -174,11 +170,7 @@ export class MatchHistoryService {
|
|||||||
seasonId: params.filters.seasonId,
|
seasonId: params.filters.seasonId,
|
||||||
});
|
});
|
||||||
const { queueIds } = this.resolveQueueFilters(params.filters);
|
const { queueIds } = this.resolveQueueFilters(params.filters);
|
||||||
const limit = this.clampLimit(
|
const limit = this.clampLimit(params.filters.limit, DEFAULT_SUMMARY_LIMIT, 50);
|
||||||
params.filters.limit,
|
|
||||||
DEFAULT_SUMMARY_LIMIT,
|
|
||||||
50,
|
|
||||||
);
|
|
||||||
const docs = await this.findStoredMatches({
|
const docs = await this.findStoredMatches({
|
||||||
context,
|
context,
|
||||||
queueIds,
|
queueIds,
|
||||||
@@ -204,11 +196,7 @@ export class MatchHistoryService {
|
|||||||
seasonId: params.filters.seasonId,
|
seasonId: params.filters.seasonId,
|
||||||
});
|
});
|
||||||
const { queueIds } = this.resolveQueueFilters(params.filters);
|
const { queueIds } = this.resolveQueueFilters(params.filters);
|
||||||
const limit = this.clampLimit(
|
const limit = this.clampLimit(params.filters.limit, DEFAULT_RECENT_LIMIT, 30);
|
||||||
params.filters.limit,
|
|
||||||
DEFAULT_RECENT_LIMIT,
|
|
||||||
30,
|
|
||||||
);
|
|
||||||
const docs = await this.findStoredMatches({
|
const docs = await this.findStoredMatches({
|
||||||
context,
|
context,
|
||||||
queueIds,
|
queueIds,
|
||||||
@@ -224,10 +212,7 @@ export class MatchHistoryService {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
matches: page,
|
matches: page,
|
||||||
nextCursor:
|
nextCursor: views.length > limit ? page[page.length - 1]?.gameCreation ?? null : null,
|
||||||
views.length > limit
|
|
||||||
? (page[page.length - 1]?.gameCreation ?? null)
|
|
||||||
: null,
|
|
||||||
lastFetchedAt: this.resolveLastFetchedAt(docs, context),
|
lastFetchedAt: this.resolveLastFetchedAt(docs, context),
|
||||||
season: context.season,
|
season: context.season,
|
||||||
};
|
};
|
||||||
@@ -470,9 +455,8 @@ export class MatchHistoryService {
|
|||||||
puuid: string,
|
puuid: string,
|
||||||
): RiotMatchParticipantDto | null {
|
): RiotMatchParticipantDto | null {
|
||||||
return (
|
return (
|
||||||
match.info.participants.find(
|
match.info.participants.find((participant) => participant.puuid === puuid) ??
|
||||||
(participant) => participant.puuid === puuid,
|
null
|
||||||
) ?? null
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -586,8 +570,7 @@ export class MatchHistoryService {
|
|||||||
return {
|
return {
|
||||||
matchId: dto.metadata.matchId,
|
matchId: dto.metadata.matchId,
|
||||||
queueId: dto.info.queueId,
|
queueId: dto.info.queueId,
|
||||||
queueLabel:
|
queueLabel: RIOT_QUEUE_LABELS[dto.info.queueId] ?? `큐 ${dto.info.queueId}`,
|
||||||
RIOT_QUEUE_LABELS[dto.info.queueId] ?? `큐 ${dto.info.queueId}`,
|
|
||||||
gameCreation: dto.info.gameCreation,
|
gameCreation: dto.info.gameCreation,
|
||||||
gameDuration: dto.info.gameDuration,
|
gameDuration: dto.info.gameDuration,
|
||||||
win: participant.win,
|
win: participant.win,
|
||||||
@@ -701,15 +684,11 @@ export class MatchHistoryService {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
puuid: participant.puuid,
|
puuid: participant.puuid,
|
||||||
gameName:
|
gameName: participant.riotIdGameName || participant.summonerName || 'Unknown',
|
||||||
participant.riotIdGameName ||
|
|
||||||
participant.summonerName ||
|
|
||||||
'Unknown',
|
|
||||||
tagLine: participant.riotIdTagLine || '',
|
tagLine: participant.riotIdTagLine || '',
|
||||||
championId: participant.championId,
|
championId: participant.championId,
|
||||||
championLevel: participant.champLevel,
|
championLevel: participant.champLevel,
|
||||||
teamPosition:
|
teamPosition: participant.teamPosition || participant.individualPosition,
|
||||||
participant.teamPosition || participant.individualPosition,
|
|
||||||
kills: participant.kills,
|
kills: participant.kills,
|
||||||
deaths: participant.deaths,
|
deaths: participant.deaths,
|
||||||
assists: participant.assists,
|
assists: participant.assists,
|
||||||
@@ -741,9 +720,7 @@ export class MatchHistoryService {
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
private resolvePerks(
|
private resolvePerks(participant: RiotMatchParticipantDto): RecentMatchView['perks'] {
|
||||||
participant: RiotMatchParticipantDto,
|
|
||||||
): RecentMatchView['perks'] {
|
|
||||||
const primary = participant.perks.styles.find(
|
const primary = participant.perks.styles.find(
|
||||||
(style) => style.description === 'primaryStyle',
|
(style) => style.description === 'primaryStyle',
|
||||||
);
|
);
|
||||||
@@ -773,19 +750,11 @@ export class MatchHistoryService {
|
|||||||
) as Partial<Record<RiotLane, number>>;
|
) as Partial<Record<RiotLane, number>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
private resolveTopChampions(
|
private resolveTopChampions(views: RecentMatchView[]): RecentSummaryResponse['topChampions'] {
|
||||||
views: RecentMatchView[],
|
const byChampion = new Map<number, { games: number; wins: number; rating: number }>();
|
||||||
): RecentSummaryResponse['topChampions'] {
|
|
||||||
const byChampion = new Map<
|
|
||||||
number,
|
|
||||||
{ games: number; wins: number; rating: number }
|
|
||||||
>();
|
|
||||||
for (const view of views) {
|
for (const view of views) {
|
||||||
const stat = byChampion.get(view.championId) ?? {
|
const stat =
|
||||||
games: 0,
|
byChampion.get(view.championId) ?? { games: 0, wins: 0, rating: 0 };
|
||||||
wins: 0,
|
|
||||||
rating: 0,
|
|
||||||
};
|
|
||||||
stat.games += 1;
|
stat.games += 1;
|
||||||
stat.wins += view.win ? 1 : 0;
|
stat.wins += view.win ? 1 : 0;
|
||||||
stat.rating += view.rating;
|
stat.rating += view.rating;
|
||||||
@@ -828,8 +797,7 @@ export class MatchHistoryService {
|
|||||||
participant.deaths,
|
participant.deaths,
|
||||||
participant.assists,
|
participant.assists,
|
||||||
);
|
);
|
||||||
const kp =
|
const kp = teamKills > 0 ? (participant.kills + participant.assists) / teamKills : 0;
|
||||||
teamKills > 0 ? (participant.kills + participant.assists) / teamKills : 0;
|
|
||||||
const csPerMin = this.resolveTotalCs(participant) / Math.max(minutes, 1);
|
const csPerMin = this.resolveTotalCs(participant) / Math.max(minutes, 1);
|
||||||
const visionPerMin = participant.visionScore / Math.max(minutes, 1);
|
const visionPerMin = participant.visionScore / Math.max(minutes, 1);
|
||||||
const score =
|
const score =
|
||||||
@@ -847,13 +815,8 @@ export class MatchHistoryService {
|
|||||||
): number {
|
): number {
|
||||||
const teamDamage = match.info.participants
|
const teamDamage = match.info.participants
|
||||||
.filter((candidate) => candidate.teamId === participant.teamId)
|
.filter((candidate) => candidate.teamId === participant.teamId)
|
||||||
.reduce(
|
.reduce((sum, candidate) => sum + candidate.totalDamageDealtToChampions, 0);
|
||||||
(sum, candidate) => sum + candidate.totalDamageDealtToChampions,
|
return teamDamage > 0 ? participant.totalDamageDealtToChampions / teamDamage : 0;
|
||||||
0,
|
|
||||||
);
|
|
||||||
return teamDamage > 0
|
|
||||||
? participant.totalDamageDealtToChampions / teamDamage
|
|
||||||
: 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private resolveTotalCs(participant: RiotMatchParticipantDto): number {
|
private resolveTotalCs(participant: RiotMatchParticipantDto): number {
|
||||||
@@ -864,16 +827,11 @@ export class MatchHistoryService {
|
|||||||
match: RiotMatchDto,
|
match: RiotMatchDto,
|
||||||
participant: RiotMatchParticipantDto,
|
participant: RiotMatchParticipantDto,
|
||||||
): number {
|
): number {
|
||||||
return Math.max(
|
return Math.max((participant.timePlayed || match.info.gameDuration) / 60, 1);
|
||||||
(participant.timePlayed || match.info.gameDuration) / 60,
|
|
||||||
1,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private resolveKda(kills: number, deaths: number, assists: number): number {
|
private resolveKda(kills: number, deaths: number, assists: number): number {
|
||||||
return deaths === 0
|
return deaths === 0 ? kills + assists : this.round((kills + assists) / deaths);
|
||||||
? kills + assists
|
|
||||||
: this.round((kills + assists) / deaths);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private resolveLastFetchedAt(
|
private resolveLastFetchedAt(
|
||||||
@@ -883,11 +841,9 @@ export class MatchHistoryService {
|
|||||||
if (docs.length === 0) {
|
if (docs.length === 0) {
|
||||||
return context.account.recentStatsFetchedAt?.toISOString() ?? null;
|
return context.account.recentStatsFetchedAt?.toISOString() ?? null;
|
||||||
}
|
}
|
||||||
const oldest = docs.reduce(
|
const oldest = docs.reduce((acc, doc) =>
|
||||||
(acc, doc) =>
|
|
||||||
doc.fetchedAt.getTime() < acc.getTime() ? doc.fetchedAt : acc,
|
doc.fetchedAt.getTime() < acc.getTime() ? doc.fetchedAt : acc,
|
||||||
docs[0].fetchedAt,
|
docs[0].fetchedAt);
|
||||||
);
|
|
||||||
return oldest.toISOString();
|
return oldest.toISOString();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -902,17 +858,14 @@ export class MatchHistoryService {
|
|||||||
.map((row) => row.lastFetchedAt)
|
.map((row) => row.lastFetchedAt)
|
||||||
.filter((value): value is Date => value instanceof Date)
|
.filter((value): value is Date => value instanceof Date)
|
||||||
.reduce<Date | null>(
|
.reduce<Date | null>(
|
||||||
(acc, value) => (!acc || value.getTime() < acc.getTime() ? value : acc),
|
(acc, value) =>
|
||||||
|
!acc || value.getTime() < acc.getTime() ? value : acc,
|
||||||
null,
|
null,
|
||||||
);
|
);
|
||||||
return oldest?.toISOString() ?? null;
|
return oldest?.toISOString() ?? null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private clampLimit(
|
private clampLimit(value: number | undefined, fallback: number, max: number): number {
|
||||||
value: number | undefined,
|
|
||||||
fallback: number,
|
|
||||||
max: number,
|
|
||||||
): number {
|
|
||||||
if (!value || !Number.isFinite(value)) return fallback;
|
if (!value || !Number.isFinite(value)) return fallback;
|
||||||
return Math.max(1, Math.min(Math.floor(value), max));
|
return Math.max(1, Math.min(Math.floor(value), max));
|
||||||
}
|
}
|
||||||
@@ -929,12 +882,18 @@ export class MatchHistoryService {
|
|||||||
return Math.round(value * 10) / 10;
|
return Math.round(value * 10) / 10;
|
||||||
}
|
}
|
||||||
|
|
||||||
private numberField(value: RiotMatchParticipantDto, key: string): number {
|
private numberField(
|
||||||
|
value: RiotMatchParticipantDto,
|
||||||
|
key: string,
|
||||||
|
): number {
|
||||||
const field = value[key];
|
const field = value[key];
|
||||||
return typeof field === 'number' && Number.isFinite(field) ? field : 0;
|
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;
|
return value[key] === true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -34,7 +34,7 @@ describe('MatchController participant access', () => {
|
|||||||
|
|
||||||
it('requires an authenticated community member for the self-join route', () => {
|
it('requires an authenticated community member for the self-join route', () => {
|
||||||
// Metadata must be read from the unbound prototype method itself.
|
// Metadata must be read from the unbound prototype method itself.
|
||||||
|
// eslint-disable-next-line @typescript-eslint/unbound-method
|
||||||
const handler = MatchController.prototype.joinMatch;
|
const handler = MatchController.prototype.joinMatch;
|
||||||
const roles = Reflect.getMetadata(ROLES_KEY, handler) as
|
const roles = Reflect.getMetadata(ROLES_KEY, handler) as
|
||||||
| string[]
|
| string[]
|
||||||
|
|||||||
@@ -5,9 +5,7 @@ describe('MatchService', () => {
|
|||||||
function createServiceWithCreateModels() {
|
function createServiceWithCreateModels() {
|
||||||
const createdPayloads: Record<string, unknown>[] = [];
|
const createdPayloads: Record<string, unknown>[] = [];
|
||||||
const MatchModel = {
|
const MatchModel = {
|
||||||
create: jest
|
create: jest.fn().mockImplementation(async (payload) => {
|
||||||
.fn()
|
|
||||||
.mockImplementation(async (payload: Record<string, unknown>) => {
|
|
||||||
createdPayloads.push(payload);
|
createdPayloads.push(payload);
|
||||||
return payload;
|
return payload;
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ export class BackgroundRefreshScheduler
|
|||||||
.catch((err: unknown) => {
|
.catch((err: unknown) => {
|
||||||
this.logger.warn(
|
this.logger.warn(
|
||||||
`Background refresh leader release failed: ${
|
`Background refresh leader release failed: ${
|
||||||
err instanceof Error ? err.message : String(err)
|
err instanceof Error ? err.message : err
|
||||||
}`,
|
}`,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -8,11 +8,7 @@ import { RiotJobWorkerService } from './riot-job-worker.service';
|
|||||||
import { RiotRefreshGateway } from './riot-refresh.gateway';
|
import { RiotRefreshGateway } from './riot-refresh.gateway';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [RiotModule, LegacyImportModule, forwardRef(() => TournamentResultModule)],
|
||||||
RiotModule,
|
|
||||||
LegacyImportModule,
|
|
||||||
forwardRef(() => TournamentResultModule),
|
|
||||||
],
|
|
||||||
controllers: [RiotJobQueueController],
|
controllers: [RiotJobQueueController],
|
||||||
providers: [RiotJobQueueService, RiotJobWorkerService, RiotRefreshGateway],
|
providers: [RiotJobQueueService, RiotJobWorkerService, RiotRefreshGateway],
|
||||||
exports: [RiotJobQueueService],
|
exports: [RiotJobQueueService],
|
||||||
|
|||||||
@@ -95,8 +95,7 @@ export class RiotJobQueueService {
|
|||||||
jobId: existingJobId,
|
jobId: existingJobId,
|
||||||
queueGroup,
|
queueGroup,
|
||||||
alreadyQueued: true,
|
alreadyQueued: true,
|
||||||
etaSeconds:
|
etaSeconds: existingStatus?.etaSeconds ?? queuePosition * RIOT_JOB_AVG_SECONDS,
|
||||||
existingStatus?.etaSeconds ?? queuePosition * RIOT_JOB_AVG_SECONDS,
|
|
||||||
queuePosition: existingStatus?.queuePosition ?? queuePosition,
|
queuePosition: existingStatus?.queuePosition ?? queuePosition,
|
||||||
});
|
});
|
||||||
continue;
|
continue;
|
||||||
@@ -128,8 +127,7 @@ export class RiotJobQueueService {
|
|||||||
jobId,
|
jobId,
|
||||||
queueGroup,
|
queueGroup,
|
||||||
alreadyQueued: true,
|
alreadyQueued: true,
|
||||||
etaSeconds:
|
etaSeconds: status?.etaSeconds ?? queuePosition * RIOT_JOB_AVG_SECONDS,
|
||||||
status?.etaSeconds ?? queuePosition * RIOT_JOB_AVG_SECONDS,
|
|
||||||
queuePosition: status?.queuePosition ?? queuePosition,
|
queuePosition: status?.queuePosition ?? queuePosition,
|
||||||
});
|
});
|
||||||
continue;
|
continue;
|
||||||
@@ -166,10 +164,7 @@ export class RiotJobQueueService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.setParent(
|
await this.setParent(parentJobId, subJobs.map((job) => job.jobId));
|
||||||
parentJobId,
|
|
||||||
subJobs.map((job) => job.jobId),
|
|
||||||
);
|
|
||||||
if (params.priority === 'high' && needsNewJob) {
|
if (params.priority === 'high' && needsNewJob) {
|
||||||
await this.markRefreshRequested(context.user._id, context.account.puuid);
|
await this.markRefreshRequested(context.user._id, context.account.puuid);
|
||||||
}
|
}
|
||||||
@@ -215,7 +210,7 @@ export class RiotJobQueueService {
|
|||||||
|
|
||||||
public async promoteDueScheduledJobs(limit = 100): Promise<number> {
|
public async promoteDueScheduledJobs(limit = 100): Promise<number> {
|
||||||
const client = this.redisService.raw();
|
const client = this.redisService.raw();
|
||||||
const entries = await client.sendCommand<string[]>([
|
const raw = (await client.sendCommand([
|
||||||
'ZRANGEBYSCORE',
|
'ZRANGEBYSCORE',
|
||||||
RIOT_JOB_SCHEDULED_ZSET,
|
RIOT_JOB_SCHEDULED_ZSET,
|
||||||
'-inf',
|
'-inf',
|
||||||
@@ -223,15 +218,16 @@ export class RiotJobQueueService {
|
|||||||
'LIMIT',
|
'LIMIT',
|
||||||
'0',
|
'0',
|
||||||
String(limit),
|
String(limit),
|
||||||
]);
|
])) as string[] | null;
|
||||||
|
const entries = raw ?? [];
|
||||||
let promoted = 0;
|
let promoted = 0;
|
||||||
|
|
||||||
for (const entry of entries) {
|
for (const entry of entries) {
|
||||||
const removed = await client.sendCommand<number>([
|
const removed = (await client.sendCommand([
|
||||||
'ZREM',
|
'ZREM',
|
||||||
RIOT_JOB_SCHEDULED_ZSET,
|
RIOT_JOB_SCHEDULED_ZSET,
|
||||||
entry,
|
entry,
|
||||||
]);
|
])) as number;
|
||||||
if (removed !== 1) continue;
|
if (removed !== 1) continue;
|
||||||
const job = this.parseScheduledJob(entry);
|
const job = this.parseScheduledJob(entry);
|
||||||
if (!job) continue;
|
if (!job) continue;
|
||||||
@@ -257,8 +253,8 @@ export class RiotJobQueueService {
|
|||||||
const subJobs = (
|
const subJobs = (
|
||||||
await Promise.all(jobIds.map((jobId) => this.getStatus(jobId)))
|
await Promise.all(jobIds.map((jobId) => this.getStatus(jobId)))
|
||||||
).filter((status): status is RiotJobStatus => Boolean(status));
|
).filter((status): status is RiotJobStatus => Boolean(status));
|
||||||
const done = subJobs.filter(
|
const done = subJobs.filter((job) =>
|
||||||
(job) => job.state === 'completed' || job.state === 'failed',
|
job.state === 'completed' || job.state === 'failed',
|
||||||
).length;
|
).length;
|
||||||
const state = this.resolveParentState(subJobs);
|
const state = this.resolveParentState(subJobs);
|
||||||
|
|
||||||
@@ -415,9 +411,7 @@ export class RiotJobQueueService {
|
|||||||
job: PollTournamentResultJob,
|
job: PollTournamentResultJob,
|
||||||
deferUntilMs: number,
|
deferUntilMs: number,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
await this.redisService
|
await this.redisService.raw().sendCommand([
|
||||||
.raw()
|
|
||||||
.sendCommand([
|
|
||||||
'ZADD',
|
'ZADD',
|
||||||
RIOT_JOB_SCHEDULED_ZSET,
|
RIOT_JOB_SCHEDULED_ZSET,
|
||||||
String(deferUntilMs),
|
String(deferUntilMs),
|
||||||
@@ -455,10 +449,7 @@ export class RiotJobQueueService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async setParent(
|
private async setParent(parentJobId: string, jobIds: string[]): Promise<void> {
|
||||||
parentJobId: string,
|
|
||||||
jobIds: string[],
|
|
||||||
): Promise<void> {
|
|
||||||
await this.redisService.setJson(
|
await this.redisService.setJson(
|
||||||
this.parentKey(parentJobId),
|
this.parentKey(parentJobId),
|
||||||
jobIds,
|
jobIds,
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
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 { RiotQueueGroup } from '../riot/riot-queue.constants';
|
||||||
import type { PollTournamentResultJob } from '../tournament-result/tournament-result.types';
|
import type { PollTournamentResultJob } from '../tournament-result/tournament-result.types';
|
||||||
import type { LegacyImportMemberJob } from '../legacy-import/legacy-import.types';
|
import type { LegacyImportMemberJob } from '../legacy-import/legacy-import.types';
|
||||||
|
|||||||
@@ -21,9 +21,7 @@ function makeWorker() {
|
|||||||
deleteStreamEntries: jest.fn().mockResolvedValue(undefined),
|
deleteStreamEntries: jest.fn().mockResolvedValue(undefined),
|
||||||
} as unknown as jest.Mocked<RedisService>;
|
} as unknown as jest.Mocked<RedisService>;
|
||||||
const distributedLockService = {
|
const distributedLockService = {
|
||||||
runWithRenewedLock: jest
|
runWithRenewedLock: jest.fn().mockImplementation(async (options, operation) =>
|
||||||
.fn()
|
|
||||||
.mockImplementation(async (options, operation) =>
|
|
||||||
operation({
|
operation({
|
||||||
lockKey: options.lockKey,
|
lockKey: options.lockKey,
|
||||||
lockOwnershipToken: 'lock-owner',
|
lockOwnershipToken: 'lock-owner',
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
|
|||||||
.catch((error: unknown) => {
|
.catch((error: unknown) => {
|
||||||
this.logger.warn(
|
this.logger.warn(
|
||||||
`Failed to release Riot job worker leader lock: ${
|
`Failed to release Riot job worker leader lock: ${
|
||||||
error instanceof Error ? error.message : String(error)
|
error instanceof Error ? error.message : error
|
||||||
}`,
|
}`,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -31,10 +31,10 @@ export class RiotRefreshGateway {
|
|||||||
private readonly logger = new Logger(RiotRefreshGateway.name);
|
private readonly logger = new Logger(RiotRefreshGateway.name);
|
||||||
|
|
||||||
@SubscribeMessage('subscribe')
|
@SubscribeMessage('subscribe')
|
||||||
public handleSubscribe(
|
public async handleSubscribe(
|
||||||
@ConnectedSocket() socket: Socket,
|
@ConnectedSocket() socket: Socket,
|
||||||
@MessageBody() payload: SubscribePayload,
|
@MessageBody() payload: SubscribePayload,
|
||||||
): void {
|
) {
|
||||||
const rooms = this.resolveRooms(payload);
|
const rooms = this.resolveRooms(payload);
|
||||||
if (rooms.length === 0) {
|
if (rooms.length === 0) {
|
||||||
socket.emit('error', { message: 'Invalid riot refresh subscription.' });
|
socket.emit('error', { message: 'Invalid riot refresh subscription.' });
|
||||||
@@ -47,7 +47,7 @@ export class RiotRefreshGateway {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
void socket.join(rooms);
|
await Promise.all(rooms.map((room) => socket.join(room)));
|
||||||
socket.emit('subscribed', { rooms });
|
socket.emit('subscribed', { rooms });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -70,10 +70,7 @@ export class RiotRefreshGateway {
|
|||||||
if (typeof payload?.puuid === 'string' && payload.puuid.trim()) {
|
if (typeof payload?.puuid === 'string' && payload.puuid.trim()) {
|
||||||
rooms.push(`puuid:${payload.puuid.trim()}`);
|
rooms.push(`puuid:${payload.puuid.trim()}`);
|
||||||
}
|
}
|
||||||
if (
|
if (typeof payload?.parentJobId === 'string' && payload.parentJobId.trim()) {
|
||||||
typeof payload?.parentJobId === 'string' &&
|
|
||||||
payload.parentJobId.trim()
|
|
||||||
) {
|
|
||||||
rooms.push(`parent:${payload.parentJobId.trim()}`);
|
rooms.push(`parent:${payload.parentJobId.trim()}`);
|
||||||
}
|
}
|
||||||
return rooms;
|
return rooms;
|
||||||
|
|||||||
@@ -198,7 +198,8 @@ describe('RiotAccountEnrichmentService', () => {
|
|||||||
masteryService,
|
masteryService,
|
||||||
recentMatchesService,
|
recentMatchesService,
|
||||||
recentStatsService,
|
recentStatsService,
|
||||||
} = makeService({
|
} =
|
||||||
|
makeService({
|
||||||
user,
|
user,
|
||||||
summoner: {
|
summoner: {
|
||||||
getByPuuid: jest.fn().mockResolvedValue({
|
getByPuuid: jest.fn().mockResolvedValue({
|
||||||
|
|||||||
@@ -148,18 +148,14 @@ describe('RiotDdragonService', () => {
|
|||||||
'ddragon:manifest:v5:ko_KR',
|
'ddragon:manifest:v5:ko_KR',
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
summonerSpells: expect.objectContaining({
|
summonerSpells: expect.objectContaining({
|
||||||
'4': expect.objectContaining({
|
'4': expect.objectContaining({ description: '커서 방향으로 순간이동합니다.' }),
|
||||||
description: '커서 방향으로 순간이동합니다.',
|
|
||||||
}),
|
|
||||||
}),
|
}),
|
||||||
runesReforged: expect.arrayContaining([
|
runesReforged: expect.arrayContaining([
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
slots: expect.arrayContaining([
|
slots: expect.arrayContaining([
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
runes: expect.arrayContaining([
|
runes: expect.arrayContaining([
|
||||||
expect.objectContaining({
|
expect.objectContaining({ longDesc: expect.stringContaining('기본 공격') }),
|
||||||
longDesc: expect.stringContaining('기본 공격'),
|
|
||||||
}),
|
|
||||||
]),
|
]),
|
||||||
}),
|
}),
|
||||||
]),
|
]),
|
||||||
|
|||||||
Loaded 100 of 170 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user