style(api): apply prettier formatting

This commit is contained in:
dahyeon committed 2026-07-24 21:42:28 -07:00
1 parent 80fef25af3
commit 96fede9fe5
74 files changed
+677 -396

No files matched your search

@@ -79,7 +79,9 @@ describe('AuctionDeadlineScheduler', () => {
.spyOn(scheduler, 'processDueBidRoundDeadlines') .spyOn(scheduler, 'processDueBidRoundDeadlines')
.mockResolvedValue({ completed: 0, prepared: 0, skipped: 0 }); .mockResolvedValue({ completed: 0, prepared: 0, skipped: 0 });
await (scheduler as unknown as { safeTick: () => Promise<void> }).safeTick(); await (
scheduler as unknown as { safeTick: () => Promise<void> }
).safeTick();
const leaderLockToken = redis.acquireTokenLock.mock.calls[0]?.[1]; const leaderLockToken = redis.acquireTokenLock.mock.calls[0]?.[1];
expect(redis.acquireTokenLock).toHaveBeenCalledWith( expect(redis.acquireTokenLock).toHaveBeenCalledWith(
@@ -100,7 +102,9 @@ describe('AuctionDeadlineScheduler', () => {
.spyOn(scheduler, 'processDueBidRoundDeadlines') .spyOn(scheduler, 'processDueBidRoundDeadlines')
.mockResolvedValue({ completed: 0, prepared: 0, skipped: 0 }); .mockResolvedValue({ completed: 0, prepared: 0, skipped: 0 });
await (scheduler as unknown as { safeTick: () => Promise<void> }).safeTick(); await (
scheduler as unknown as { safeTick: () => Promise<void> }
).safeTick();
expect(processDueBidRoundDeadlinesSpy).not.toHaveBeenCalled(); expect(processDueBidRoundDeadlinesSpy).not.toHaveBeenCalled();
expect(redis.releaseTokenLock).not.toHaveBeenCalled(); expect(redis.releaseTokenLock).not.toHaveBeenCalled();
@@ -129,10 +133,12 @@ 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,
@@ -149,7 +155,10 @@ describe('AuctionDeadlineScheduler', () => {
expect(auctionService.completePreparedExpiry).toHaveBeenCalledTimes(1); expect(auctionService.completePreparedExpiry).toHaveBeenCalledTimes(1);
// 만료 확정 결과는 즉시 1차 broadcast돼야 한다(클라가 입찰 라운드에 멈춰 // 만료 확정 결과는 즉시 1차 broadcast돼야 한다(클라가 입찰 라운드에 멈춰
// 후속 액션에서 CONFLICT가 반복되는 것을 막는 핵심 동작). // 후속 액션에서 CONFLICT가 반복되는 것을 막는 핵심 동작).
expect(eventBus.broadcastState).toHaveBeenCalledWith(matchId, completedState); expect(eventBus.broadcastState).toHaveBeenCalledWith(
matchId,
completedState,
);
}); });
it('skips noop expiry preparations', async () => { it('skips noop expiry preparations', async () => {
@@ -189,10 +198,7 @@ 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 = [ const matchIds = ['665f2f01f1f1f1f1f1f1f1f1', '665f2f02f1f1f1f1f1f1f1f1'];
'665f2f01f1f1f1f1f1f1f1f1',
'665f2f02f1f1f1f1f1f1f1f1',
];
const { auctionService, redisCommand, scheduler } = makeScheduler({ const { auctionService, redisCommand, scheduler } = makeScheduler({
dueReply: matchIds, dueReply: matchIds,
}); });
@@ -101,7 +101,9 @@ export class AuctionDeadlineScheduler implements OnModuleInit, OnModuleDestroy {
currentRedisTimestampMS: number, currentRedisTimestampMS: number,
batchLimit: number, batchLimit: number,
): Promise<string[]> { ): Promise<string[]> {
const reply = await this.auctionRedisService.raw().sendCommand([ const reply = await this.auctionRedisService
.raw()
.sendCommand([
'ZRANGEBYSCORE', 'ZRANGEBYSCORE',
BID_ROUND_DEADLINE_QUEUE_KEY, BID_ROUND_DEADLINE_QUEUE_KEY,
'-inf', '-inf',
@@ -177,11 +179,11 @@ export class AuctionDeadlineScheduler implements OnModuleInit, OnModuleDestroy {
return { completed, prepared, skipped }; return { completed, prepared, skipped };
} }
private async removeBidRoundDeadlineQueueEntry(matchId: string): Promise<void> { private async removeBidRoundDeadlineQueueEntry(
await this.auctionRedisService.raw().sendCommand([ matchId: string,
'ZREM', ): Promise<void> {
BID_ROUND_DEADLINE_QUEUE_KEY, await this.auctionRedisService
matchId, .raw()
]); .sendCommand(['ZREM', BID_ROUND_DEADLINE_QUEUE_KEY, matchId]);
} }
} }
@@ -20,9 +20,8 @@ export class AuctionEventBusService {
} }
public broadcastState(matchId: string, state: AuctionStateResponse): void { public broadcastState(matchId: string, state: AuctionStateResponse): void {
this.auctionNamespace?.to(matchId).emit( this.auctionNamespace
'state', ?.to(matchId)
serializeRealtimeAuction(state), .emit('state', serializeRealtimeAuction(state));
);
} }
} }
@@ -22,7 +22,10 @@ describe('resolveAuctionRejectionReason', () => {
it('maps known BadRequest messages without a structured code', () => { it('maps known BadRequest messages without a structured code', () => {
expect( expect(
resolveAuctionRejectionReason(undefined, 'Cannot advance from current phase.'), resolveAuctionRejectionReason(
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,7 +41,9 @@ 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.raw().sendCommand([ const result = await this.auctionRedisService
.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",
@@ -78,8 +80,7 @@ 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) <= (state.processingLeaseExpiresAtTimestampMS ?? 0) <= currentRedisTimestampMS
currentRedisTimestampMS
); );
} }
@@ -59,8 +59,7 @@ export class AuctionController {
initialTeamBidPointAmount: c.initialTeamBidPointAmount, initialTeamBidPointAmount: c.initialTeamBidPointAmount,
})), })),
initialTeamBidPointAmount: body.initialTeamBidPointAmount ?? 1000, initialTeamBidPointAmount: body.initialTeamBidPointAmount ?? 1000,
maximumBidRoundDurationSeconds: maximumBidRoundDurationSeconds: body.maximumBidRoundDurationSeconds ?? 30,
body.maximumBidRoundDurationSeconds ?? 30,
bidRoundExtensionSeconds: body.bidRoundExtensionSeconds ?? 5, bidRoundExtensionSeconds: body.bidRoundExtensionSeconds ?? 5,
topTierAuctionPriorityThreshold: topTierAuctionPriorityThreshold:
body.topTierAuctionPriorityThreshold ?? 'NONE', body.topTierAuctionPriorityThreshold ?? 'NONE',
+18 -12
View File
@@ -92,9 +92,7 @@ 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 export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
implements OnGatewayConnection, OnGatewayInit
{
@WebSocketServer() @WebSocketServer()
private server!: Namespace; private server!: Namespace;
@@ -205,7 +203,9 @@ export class AuctionGateway
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,
@@ -417,8 +417,9 @@ export class AuctionGateway
private consumeBidRateLimit(socket: Socket): boolean { private consumeBidRateLimit(socket: Socket): boolean {
const currentTimestampMS = Date.now(); const currentTimestampMS = Date.now();
const previousState = socket.data const previousState = socket.data.auctionBidRateLimit as
.auctionBidRateLimit as BidRateLimitState | undefined; | BidRateLimitState
| undefined;
if ( if (
!previousState || !previousState ||
currentTimestampMS - previousState.windowStartedAtTimestampMS >= currentTimestampMS - previousState.windowStartedAtTimestampMS >=
@@ -633,7 +634,9 @@ export class AuctionGateway
typeof errorPayload.code === 'string' ? errorPayload.code : undefined, typeof errorPayload.code === 'string' ? errorPayload.code : undefined,
errorPayload.message, errorPayload.message,
); );
const resyncRecommended = isAuctionResyncRecommended(auctionRejectionReason); const resyncRecommended = isAuctionResyncRecommended(
auctionRejectionReason,
);
const state = resyncRecommended const state = resyncRecommended
? await this.fetchSerializedAuctionState(matchId) ? await this.fetchSerializedAuctionState(matchId)
: undefined; : undefined;
@@ -688,7 +691,9 @@ export class AuctionGateway
return { return {
code: error instanceof Error ? error.message : 'UNKNOWN', code: error instanceof Error ? error.message : 'UNKNOWN',
message: message:
error instanceof Error ? error.message : 'Unexpected auction gateway error.', error instanceof Error
? error.message
: 'Unexpected auction gateway error.',
}; };
} }
@@ -724,7 +729,10 @@ export class AuctionGateway
auction: AuctionStateResponse, auction: AuctionStateResponse,
bidRequestId?: string, bidRequestId?: string,
): Record<string, unknown> | null { ): Record<string, unknown> | null {
const serialized = this.serializeAuction(auction) as Record<string, unknown>; 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,
@@ -775,9 +783,7 @@ export class AuctionGateway
}; };
} }
private isBidDeltaResponse( private isBidDeltaResponse(value: unknown): value is AuctionBidDeltaResponse {
value: unknown,
): value is AuctionBidDeltaResponse {
return ( return (
typeof value === 'object' && typeof value === 'object' &&
value !== null && value !== null &&
@@ -210,8 +210,12 @@ 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(['REPLAY', 'APPLIED', 'transition-1', '2100']) makeService([
.service.applyTransition('match-1', { 'REPLAY',
'APPLIED',
'transition-1',
'2100',
]).service.applyTransition('match-1', {
afterAuctionStructureStateJson: '{}', afterAuctionStructureStateJson: '{}',
auctionHistorySequence: 5, auctionHistorySequence: 5,
auctionLifecycleId: 'life-1', auctionLifecycleId: 'life-1',
@@ -233,8 +237,12 @@ describe('AuctionRedisCommandService', () => {
}); });
await expect( await expect(
makeService(['REJECTED', 'CONFLICT', 'transition-1', '2200']) makeService([
.service.applyTransition('match-1', { 'REJECTED',
'CONFLICT',
'transition-1',
'2200',
]).service.applyTransition('match-1', {
afterAuctionStructureStateJson: '{}', afterAuctionStructureStateJson: '{}',
auctionHistorySequence: 5, auctionHistorySequence: 5,
auctionLifecycleId: 'life-1', auctionLifecycleId: 'life-1',
@@ -288,8 +296,13 @@ 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(['REPLAY', 'passed', 'expire-1', '12', '3100']) makeService([
.service.expirePrepare('match-1', { 'REPLAY',
'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',
@@ -360,8 +373,11 @@ describe('AuctionRedisCommandService', () => {
}); });
await expect( await expect(
makeService(['REJECTED', 'INVALID_PATCH_ARITY', '4200']) makeService([
.service.hydrateState('match-1', { 'REJECTED',
'INVALID_PATCH_ARITY',
'4200',
]).service.hydrateState('match-1', {
auctionHistorySequence: 3, auctionHistorySequence: 3,
auctionLifecycleId: 'life-1', auctionLifecycleId: 'life-1',
maximumBidRoundDurationSeconds: 30, maximumBidRoundDurationSeconds: 30,
@@ -85,7 +85,9 @@ export function stringifyAuctionRedisStructureState(
return JSON.stringify(buildAuctionRedisStructureState(input)); return JSON.stringify(buildAuctionRedisStructureState(input));
} }
function countAuctionTeamMembersIncludingCaptain(team: RedisAuctionTeam): number { function countAuctionTeamMembersIncludingCaptain(
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,7 +1,10 @@
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(commandReplies: unknown[], currentServerTimestampMS = 1000) { function makeService(
commandReplies: unknown[],
currentServerTimestampMS = 1000,
) {
const sendCommand = jest const sendCommand = jest
.fn() .fn()
.mockImplementation(() => Promise.resolve(commandReplies.shift())); .mockImplementation(() => Promise.resolve(commandReplies.shift()));
@@ -149,7 +152,9 @@ describe('AuctionRedisStateReaderService', () => {
[], [],
]); ]);
await expect(service.readAuctionStateView('match-1')).resolves.toMatchObject({ await expect(
service.readAuctionStateView('match-1'),
).resolves.toMatchObject({
auctionLifecycleId: 'life-1', auctionLifecycleId: 'life-1',
auctionTeams: [], auctionTeams: [],
phase: 'presenting', phase: 'presenting',
@@ -181,7 +186,6 @@ 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,7 +42,9 @@ 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.raw().sendCommand([ const reply = await this.auctionRedisService
.raw()
.sendCommand([
'HMGET', 'HMGET',
keys.liveStateKey, keys.liveStateKey,
'auctionLifecycleId', 'auctionLifecycleId',
@@ -68,7 +70,9 @@ 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.raw().sendCommand([ const liveReply = await this.auctionRedisService
.raw()
.sendCommand([
'HMGET', 'HMGET',
keys.liveStateKey, keys.liveStateKey,
'phase', 'phase',
@@ -102,17 +106,22 @@ 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 [currentServerTimestampMS, liveReply, structureStateJson, bidEntries] = const [
await Promise.all([ currentServerTimestampMS,
liveReply,
structureStateJson,
bidEntries,
] = await Promise.all([
this.auctionRedisService.getCurrentRedisTimestampMS(), this.auctionRedisService.getCurrentRedisTimestampMS(),
this.auctionRedisService.raw().sendCommand(['HGETALL', keys.liveStateKey]), this.auctionRedisService
this.auctionRedisService.raw().sendCommand(['GET', keys.structureStateKey]), .raw()
this.auctionRedisService.raw().sendCommand([ .sendCommand(['HGETALL', keys.liveStateKey]),
'LRANGE', this.auctionRedisService
keys.bidHistoryKey, .raw()
'0', .sendCommand(['GET', keys.structureStateKey]),
'-1', this.auctionRedisService
]), .raw()
.sendCommand(['LRANGE', keys.bidHistoryKey, '0', '-1']),
]); ]);
const liveState = parseHashReply(liveReply, { const liveState = parseHashReply(liveReply, {
@@ -210,7 +219,10 @@ 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 (!options.includeInternalLiveStateFields && isInternalLiveStateField(field)) { if (
!options.includeInternalLiveStateFields &&
isInternalLiveStateField(field)
) {
continue; continue;
} }
const value = String(rawValue); const value = String(rawValue);
@@ -91,9 +91,7 @@ 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( expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain("redis.call('SADD'");
"redis.call('SADD'",
);
expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain( expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain(
"redis.call('HINCRBY'", "redis.call('HINCRBY'",
); );
@@ -64,9 +64,7 @@ describe('auction bid redis script contract', () => {
expect(AUCTION_BID_SCRIPT.lua).toContain("redis.call('TIME')"); expect(AUCTION_BID_SCRIPT.lua).toContain("redis.call('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( expect(AUCTION_BID_SCRIPT.lua).toContain('currentHighestBidPointAmount');
'currentHighestBidPointAmount',
);
expect(AUCTION_BID_SCRIPT.lua).not.toContain('cjson.decode'); expect(AUCTION_BID_SCRIPT.lua).not.toContain('cjson.decode');
}); });
}); });
@@ -3,9 +3,11 @@ 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: 'auction:match-1:auctionActionRequestResultOrder', actionRequestResultOrderKey:
'auction:match-1:auctionActionRequestResultOrder',
actionRequestResultsKey: 'auction:match-1:auctionActionRequestResults', actionRequestResultsKey: 'auction:match-1:auctionActionRequestResults',
appliedTransitionIdsKey: 'auction:match-1:appliedAuctionStateTransitionIds', appliedTransitionIdsKey:
'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',
@@ -15,7 +15,9 @@ 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(jest.fn().mockResolvedValue(['1781700000', '123000'])); const service = makeService(
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,7 +22,11 @@ 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.message : typeof error === 'string' ? error : ''; error instanceof Error
? error.message
: typeof error === 'string'
? error
: '';
return /\bNOSCRIPT\b/iu.test(message); return /\bNOSCRIPT\b/iu.test(message);
} }
@@ -100,9 +100,7 @@ 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( expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain('INVALID_PATCH_ARITY');
'INVALID_PATCH_ARITY',
);
expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain( expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain(
'mongoRevision > redisRevision', 'mongoRevision > redisRevision',
); );
+1 -4
View File
@@ -1,8 +1,5 @@
import type { JWTHeaderParameters, JWTPayload } from 'jose'; import type { JWTHeaderParameters, JWTPayload } from 'jose';
import type { import type { IdentityDocument, UserDocument } from '../global/database/schema';
IdentityDocument,
UserDocument,
} from '../global/database/schema';
import type { IdentityProviderName } from './jwt.service'; import type { IdentityProviderName } from './jwt.service';
declare module 'express' { declare module 'express' {
+1 -4
View File
@@ -2,10 +2,7 @@ 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 { import { IdentityDocument, UserDocument } from '../global/database/schema';
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';
+2 -1
View File
@@ -84,7 +84,8 @@ export class JwtAuthGuard implements CanActivate {
} }
throw new Error(`Unknown issuer: ${iss}`); throw new Error(`Unknown issuer: ${iss}`);
} catch (err) { } catch (err) {
const message = err instanceof Error ? err.message : 'Unable to decode token'; const message =
err instanceof Error ? err.message : 'Unable to decode token';
throw new UnauthorizedException(message); throw new UnauthorizedException(message);
} }
} }
@@ -7,9 +7,10 @@ import {
import mongoose from 'mongoose'; import mongoose from 'mongoose';
@Injectable() @Injectable()
export class ParseObjectIdPipe export class ParseObjectIdPipe implements PipeTransform<
implements PipeTransform<string, mongoose.Types.ObjectId> string,
{ mongoose.Types.ObjectId
> {
public transform( public transform(
value: string, value: string,
metadata: ArgumentMetadata, metadata: ArgumentMetadata,
@@ -23,7 +23,14 @@ export class CommunityStatsController {
) { ) {
return this.communityStatsService.getMatches({ return this.communityStatsService.getMatches({
communityId, communityId,
filters: this.toFilters({ seasonId, from, to, championId, cursor, limit }), filters: this.toFilters({
seasonId,
from,
to,
championId,
cursor,
limit,
}),
}); });
} }
@@ -85,7 +92,14 @@ export class CommunityStatsController {
return this.communityStatsService.getUserInternalHistory({ return this.communityStatsService.getUserInternalHistory({
communityId, communityId,
userId, userId,
filters: this.toFilters({ seasonId, from, to, championId, cursor, limit }), filters: this.toFilters({
seasonId,
from,
to,
championId,
cursor,
limit,
}),
}); });
} }
@@ -7,7 +7,10 @@ import type {
RiotLane, RiotLane,
TeamSide, TeamSide,
} from '../global/database/schema'; } from '../global/database/schema';
import type { RecentMatchView, HistorySeasonDto } from '../match-history/match-history.types'; import type {
RecentMatchView,
HistorySeasonDto,
} from '../match-history/match-history.types';
export interface CommunityStatsFilters { export interface CommunityStatsFilters {
seasonId?: string; seasonId?: string;
@@ -80,7 +83,9 @@ export interface LeaderboardRow {
avgCsPerMin: number; avgCsPerMin: number;
avgDamageShare: number; avgDamageShare: number;
avgVisionScore: number; avgVisionScore: number;
byLane: Partial<Record<RiotLane, { games: number; wins: number; kda: number }>>; byLane: Partial<
Record<RiotLane, { games: number; wins: number; kda: number }>
>;
topChampions: Array<{ championId: number; games: number; winRate: number }>; topChampions: Array<{ championId: number; games: number; winRate: number }>;
} }
@@ -227,9 +227,7 @@ export class MatchStatsFragmentBuilder {
participant, participant,
rawParticipant, rawParticipant,
buildEvents: rawParticipant buildEvents: rawParticipant
? buildEventsByParticipantId.get( ? buildEventsByParticipantId.get(rawParticipant.participantId)
rawParticipant.participantId,
)
: undefined, : undefined,
checkpoints: rawParticipant checkpoints: rawParticipant
? checkpointsByParticipantId.get(rawParticipant.participantId) ? checkpointsByParticipantId.get(rawParticipant.participantId)
@@ -420,7 +418,10 @@ export class MatchStatsFragmentBuilder {
private toBuildEventsByParticipantId( private toBuildEventsByParticipantId(
timeline?: RiotMatchTimelineDto, timeline?: RiotMatchTimelineDto,
): Map<number, ParticipantBuildEvents> { ): Map<number, ParticipantBuildEvents> {
const buildEventsByParticipantId = new Map<number, ParticipantBuildEvents>(); const buildEventsByParticipantId = new Map<
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 => {
@@ -796,13 +797,16 @@ export class MatchStatsFragmentBuilder {
? timelineDragon ? timelineDragon
: (rawObjectives?.dragon?.kills ?? 0), : (rawObjectives?.dragon?.kills ?? 0),
inhibitor: rawObjectives?.inhibitor?.kills ?? 0, inhibitor: rawObjectives?.inhibitor?.kills ?? 0,
baron: (timelineObjectives?.baron ?? 0) > 0 baron:
(timelineObjectives?.baron ?? 0) > 0
? (timelineObjectives?.baron ?? 0) ? (timelineObjectives?.baron ?? 0)
: (rawObjectives?.baron?.kills ?? 0), : (rawObjectives?.baron?.kills ?? 0),
riftHerald: (timelineObjectives?.riftHerald ?? 0) > 0 riftHerald:
(timelineObjectives?.riftHerald ?? 0) > 0
? (timelineObjectives?.riftHerald ?? 0) ? (timelineObjectives?.riftHerald ?? 0)
: (rawObjectives?.riftHerald?.kills ?? 0), : (rawObjectives?.riftHerald?.kills ?? 0),
voidGrub: (timelineObjectives?.voidGrub ?? 0) > 0 voidGrub:
(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,
@@ -6,10 +6,7 @@ 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 { import { CommunityDocument, UserDocument } from '../global/database/schema';
CommunityDocument,
UserDocument,
} from '../global/database/schema';
export interface CreateCommunityInput { export interface CreateCommunityInput {
name: string; name: string;
@@ -9,7 +9,8 @@ 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 = 'distributed-lock:dakao-outbox:sweep-stale-publish-leases'; const SWEEP_LOCK_KEY =
'distributed-lock:dakao-outbox:sweep-stale-publish-leases';
const SWEEP_LOCK_EXPIRATION_DURATION_MILLISECONDS = 55_000; const SWEEP_LOCK_EXPIRATION_DURATION_MILLISECONDS = 55_000;
@Injectable() @Injectable()
@@ -78,9 +78,7 @@ 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( await OutboxModel.updateOne(updateFilter, {
updateFilter,
{
$set: { $set: {
state: 'published', state: 'published',
publishedAt: new Date(), publishedAt: new Date(),
@@ -91,12 +89,9 @@ export class DakaoOutboxService {
publishLeaseOwnerIdentifier: '', publishLeaseOwnerIdentifier: '',
publishLeaseExpiresAt: '', publishLeaseExpiresAt: '',
}, },
}, }).exec();
).exec();
} catch (err) { } catch (err) {
await OutboxModel.updateOne( await OutboxModel.updateOne(updateFilter, {
updateFilter,
{
$inc: { publishAttempts: 1 }, $inc: { publishAttempts: 1 },
$set: { $set: {
lastPublishError: (err as Error)?.message ?? String(err), lastPublishError: (err as Error)?.message ?? String(err),
@@ -105,8 +100,7 @@ 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
@@ -104,7 +104,9 @@ describe('MatchCancelHandler', () => {
const handler = makeHandler({ const handler = makeHandler({
matchService: { matchService: {
cancelJoin, cancelJoin,
list: jest.fn().mockResolvedValue([ list: jest
.fn()
.mockResolvedValue([
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' }, { _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
]), ]),
} as Partial<MatchService>, } as Partial<MatchService>,
@@ -230,7 +230,9 @@ describe('MatchJoinHandler', () => {
const resolveRiotAccount = jest.fn(); const resolveRiotAccount = jest.fn();
const handler = makeHandler({ const handler = makeHandler({
matchService: { matchService: {
list: jest.fn().mockResolvedValue([ list: jest
.fn()
.mockResolvedValue([
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' }, { _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
]), ]),
join, join,
@@ -282,7 +284,9 @@ describe('MatchJoinHandler', () => {
const join = jest.fn(); const join = jest.fn();
const handler = makeHandler({ const handler = makeHandler({
matchService: { matchService: {
list: jest.fn().mockResolvedValue([ list: jest
.fn()
.mockResolvedValue([
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' }, { _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
]), ]),
join, join,
@@ -44,9 +44,7 @@ export class MatchJoinHandler {
return this.errorReply(params, joinTarget); return this.errorReply(params, joinTarget);
} }
let resolved: let resolved: { user: UserDocument; riotAccount: RiotAccount } | string;
| { user: UserDocument; riotAccount: RiotAccount }
| string;
try { try {
resolved = resolved =
joinTarget.gameName && joinTarget.tagLine joinTarget.gameName && joinTarget.tagLine
@@ -243,10 +241,7 @@ 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( const result = resolveRecruitingMatchReference(matchTitlePrefix, matches);
matchTitlePrefix,
matches,
);
if (result.kind === 'matched') { if (result.kind === 'matched') {
return { kind: 'matched', match: result.match, gameName }; return { kind: 'matched', match: result.match, gameName };
} }
@@ -19,7 +19,9 @@ 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(AuctionSchema.path('lastAppliedAuctionStateTransitionId')).toBeDefined(); expect(
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();
@@ -36,46 +38,75 @@ 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(AuctionSchema.path('currentBidRoundDeadlineTimestampMS')).toBeDefined(); expect(
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(AuctionSchema.path('manualTopTierAuctionPriorityUserIds')).toBeDefined(); expect(
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(AuctionHistoryEntrySchema.path('auctionStateTransitionId')).toBeDefined(); expect(
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(AuctionHistoryEntrySchema.path('matchSideEffectMutation')).toBeDefined(); expect(
AuctionHistoryEntrySchema.path('matchSideEffectMutation'),
).toBeDefined();
expect( expect(
AuctionHistoryEntrySchema.path<string>('action').options.enum, AuctionHistoryEntrySchema.path<string>('action').options.enum,
).toEqual( ).toEqual(
expect.arrayContaining(['start', 'open-bidding', 'bid', 'sold', 'passed', 'next', 'complete', 'reset', 'undo']), expect.arrayContaining([
'start',
'open-bidding',
'bid',
'sold',
'passed',
'next',
'complete',
'reset',
'undo',
]),
); );
}); });
it('adds unique history indexes for sequence and transition idempotency', () => { it('adds unique history indexes for sequence and transition idempotency', () => {
const indexes = AuctionHistoryEntrySchema.indexes(); const indexes = AuctionHistoryEntrySchema.indexes();
expect(indexWithKeys(indexes, { auctionId: 1, sequence: 1 })?.[1]).toMatchObject({ expect(
indexWithKeys(indexes, { auctionId: 1, sequence: 1 })?.[1],
).toMatchObject({
unique: true, unique: true,
}); });
expect( expect(
indexWithKeys(indexes, { auctionId: 1, auctionStateTransitionId: 1 })?.[1], indexWithKeys(indexes, {
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('processingLeaseExpiresAtTimestampMS'), AuctionSideEffectApplicationSchema.path('processingOwnerToken'),
).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(
@@ -45,7 +45,10 @@ export async function migrateAuctionPassHistory(
}; };
}> = []; }> = [];
for await (const doc of db.collection('auction').find({}).limit(options.limit ?? 0)) { for await (const doc of db
.collection('auction')
.find({})
.limit(options.limit ?? 0)) {
stats.scannedAuctions += 1; stats.scannedAuctions += 1;
const set: Record<string, unknown> = {}; const set: Record<string, unknown> = {};
let changed = false; let changed = false;
@@ -27,7 +27,8 @@ function createDb(params: {
}, },
}; };
}, },
async bulkWrite(writes: Array<{ async bulkWrite(
writes: Array<{
updateOne: { updateOne: {
filter: { _id: unknown }; filter: { _id: unknown };
update: { update: {
@@ -35,9 +36,12 @@ function createDb(params: {
$unset: Record<string, ''>; $unset: Record<string, ''>;
}; };
}; };
}>) { }>,
) {
for (const write of writes) { for (const write of writes) {
const doc = docs.find((item) => item._id === write.updateOne.filter._id); const doc = docs.find(
(item) => item._id === write.updateOne.filter._id,
);
if (!doc) continue; 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)) {
@@ -57,7 +61,10 @@ describe('migrateTeamIndex', () => {
auctions: [ auctions: [
{ {
_id: 'auction-1', _id: 'auction-1',
teams: [{ side: 'blue', groupIndex: 1 }, { side: 'red', groupIndex: 1 }], teams: [
{ side: 'blue', groupIndex: 1 },
{ side: 'red', groupIndex: 1 },
],
bids: [{ side: 'red', groupIndex: 1, amount: 100 }], bids: [{ side: 'red', groupIndex: 1, amount: 100 }],
currentBidder: 'red', currentBidder: 'red',
currentBidderGroupIndex: 1, currentBidderGroupIndex: 1,
@@ -66,7 +73,10 @@ describe('migrateTeamIndex', () => {
matches: [ matches: [
{ {
_id: 'match-1', _id: 'match-1',
teams: [{ side: 'blue', groupIndex: 1 }, { side: 'red', groupIndex: 1 }], teams: [
{ side: 'blue', groupIndex: 1 },
{ side: 'red', groupIndex: 1 },
],
result: { result: {
winnerSide: 'blue', winnerSide: 'blue',
blueScore: 1, blueScore: 1,
@@ -112,7 +122,10 @@ describe('migrateTeamIndex', () => {
currentBidderTeamIndex: 2, currentBidderTeamIndex: 2,
}); });
expect(collections.match[0]).toMatchObject({ expect(collections.match[0]).toMatchObject({
teams: [{ teamIndex: 1, name: '1팀' }, { teamIndex: 2, name: '2팀' }], teams: [
{ teamIndex: 1, name: '1팀' },
{ teamIndex: 2, name: '2팀' },
],
result: { result: {
winnerTeamIndex: 1, winnerTeamIndex: 1,
games: [ games: [
@@ -45,8 +45,20 @@ export async function migrateTeamIndex(
changedMatches: 0, changedMatches: 0,
}; };
await migrateCollection(db.collection('auction'), options.limit, dryRun, stats, 'auction'); await migrateCollection(
await migrateCollection(db.collection('match'), options.limit, dryRun, stats, 'match'); db.collection('auction'),
options.limit,
dryRun,
stats,
'auction',
);
await migrateCollection(
db.collection('match'),
options.limit,
dryRun,
stats,
'match',
);
return stats; return stats;
} }
@@ -143,7 +155,8 @@ 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') migrated.name = `${teamIndex}팀`; if (!migrated.name && typeof teamIndex === 'number')
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;
@@ -200,7 +213,10 @@ 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 (typeof series.teamAIndex === 'number' && typeof series.teamBIndex === 'number') { if (
typeof series.teamAIndex === 'number' &&
typeof series.teamBIndex === 'number'
) {
return series; return series;
} }
changed = true; changed = true;
@@ -216,7 +232,9 @@ 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) ? series.winnerSide : undefined; const winnerSide = isSide(series.winnerSide)
? series.winnerSide
: undefined;
const winnerTeamIndex = const winnerTeamIndex =
winnerSide === 'blue' winnerSide === 'blue'
? legacyBlueTeamIndex ? legacyBlueTeamIndex
@@ -231,7 +249,8 @@ function migrateResult(result: Record<string, unknown>) {
winnerTeamIndex, winnerTeamIndex,
}; };
}); });
migrated.seriesResults = seriesResults.length > 0 ? seriesResults : buildSeries(games); migrated.seriesResults =
seriesResults.length > 0 ? seriesResults : buildSeries(games);
if (typeof migrated.winnerTeamIndex !== 'number') { if (typeof migrated.winnerTeamIndex !== 'number') {
const migratedSeriesResults = Array.isArray(migrated.seriesResults) const migratedSeriesResults = Array.isArray(migrated.seriesResults)
@@ -244,7 +263,11 @@ function migrateResult(result: Record<string, unknown>) {
: undefined); : undefined);
} }
if ('winnerSide' in migrated || 'blueScore' in migrated || 'redScore' in migrated) { if (
'winnerSide' in migrated ||
'blueScore' in migrated ||
'redScore' in migrated
) {
changed = true; changed = true;
} }
delete migrated.winnerSide; delete migrated.winnerSide;
@@ -272,8 +295,12 @@ 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 = const current = bySeries.get(key) ?? {
bySeries.get(key) ?? { teamAIndex, teamBIndex, teamAWins: 0, teamBWins: 0 }; teamAIndex,
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 =
@@ -331,5 +358,7 @@ function numberOrDefault(value: unknown, fallback: number) {
} }
function numberOrUndefined(value: unknown) { function numberOrUndefined(value: unknown) {
return typeof value === 'number' && Number.isFinite(value) ? value : undefined; return typeof value === 'number' && Number.isFinite(value)
? value
: undefined;
} }
@@ -30,7 +30,8 @@ function createDb(params: { auctions?: Doc[]; history?: Doc[] }) {
}, },
}; };
}, },
async bulkWrite(writes: Array<{ async bulkWrite(
writes: Array<{
updateOne: { updateOne: {
filter: { _id: unknown }; filter: { _id: unknown };
update: { update: {
@@ -38,12 +39,17 @@ 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((item) => item._id === write.updateOne.filter._id); const doc = docs.find(
(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 ?? {},
)) {
delete doc[key]; delete doc[key];
} }
} }
@@ -31,7 +31,10 @@ interface MigrationStats {
} }
type AnyDoc = Record<string, unknown> & { _id: unknown }; type AnyDoc = Record<string, unknown> & { _id: unknown };
type UpdateDoc = { $set?: Record<string, unknown>; $unset?: Record<string, ''> }; type UpdateDoc = {
$set?: Record<string, unknown>;
$unset?: Record<string, ''>;
};
const AUCTION_FIELD_RENAMES: Array<{ const AUCTION_FIELD_RENAMES: Array<{
from: string; from: string;
@@ -43,7 +46,11 @@ 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' },
{ {
@@ -157,7 +164,8 @@ 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 = typeof doc.sequence === 'number' ? doc.sequence : undefined; const sequence =
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}`;
@@ -5,10 +5,7 @@ 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 { import { ConnectionService, resolveMongoDbName } from '../connection.service';
ConnectionService,
resolveMongoDbName,
} from '../connection.service';
import type { import type {
MatchDocument, MatchDocument,
MatchGameAssignment, MatchGameAssignment,
@@ -214,12 +211,16 @@ async function main() {
printPlan(options, match, codes, plan); printPlan(options, match, codes, plan);
if (options.dryRun) { if (options.dryRun) {
console.log('No writes were made. Re-run with --apply to update MongoDB.'); console.log(
'No writes were made. Re-run with --apply to update MongoDB.',
);
return; return;
} }
const now = new Date(); const now = new Date();
const session = await (await connectionService.getConnection()).startSession(); const session = await (
await connectionService.getConnection()
).startSession();
try { try {
await session.withTransaction(async () => { await session.withTransaction(async () => {
await applyTournamentCodeUpdates(plan, now, session); await applyTournamentCodeUpdates(plan, now, session);
@@ -230,9 +231,9 @@ async function main() {
status: 'finished', status: 'finished',
roundRobinMaxRounds: options.maxRounds, roundRobinMaxRounds: options.maxRounds,
gameSchedule: plan.schedule, gameSchedule: plan.schedule,
tournamentCodeIds: [ tournamentCodeIds: [...plan.usedCodeByOldGameNumber.values()].map(
...plan.usedCodeByOldGameNumber.values(), (code) => code._id,
].map((code) => code._id), ),
resultPollState: { resultPollState: {
startedAt: match.resultPollState?.startedAt ?? now, startedAt: match.resultPollState?.startedAt ?? now,
lastPolledAt: now, lastPolledAt: now,
@@ -423,7 +424,9 @@ function partitionIntoRounds(
} }
if (!fillRound(0)) { if (!fillRound(0)) {
throw new Error('Could not partition result games into simultaneous rounds.'); throw new Error(
'Could not partition result games into simultaneous rounds.',
);
} }
return rounds; return rounds;
@@ -586,8 +589,7 @@ function buildSeriesResults(games: MatchGameResult[]): MatchSeriesResult[] {
} }
return [...bySeries.values()].sort( return [...bySeries.values()].sort(
(left, right) => (left, right) =>
left.teamAIndex - right.teamAIndex || left.teamAIndex - right.teamAIndex || left.teamBIndex - right.teamBIndex,
left.teamBIndex - right.teamBIndex,
); );
} }
@@ -219,9 +219,9 @@ async function listDuplicateHistorySequences(
.toArray(); .toArray();
} }
function printDuplicateHistorySequences(groups: Awaited< function printDuplicateHistorySequences(
ReturnType<typeof listDuplicateHistorySequences> groups: Awaited<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,7 +248,8 @@ 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 = await findAuctionIdsWithDuplicateHistorySequences(db); const affectedAuctionIds =
await findAuctionIdsWithDuplicateHistorySequences(db);
const stats: DuplicateSequenceRepairStats = { const stats: DuplicateSequenceRepairStats = {
affectedAuctions: affectedAuctionIds.length, affectedAuctions: affectedAuctionIds.length,
changedAuctionSequenceFields: 0, changedAuctionSequenceFields: 0,
@@ -177,7 +177,9 @@ 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(`${label} requires a positive integer, majority, or votingMembers.`); throw new Error(
`${label} requires a positive integer, majority, or votingMembers.`,
);
} }
if (value === 'majority' || value === 'votingMembers') return value; if (value === 'majority' || value === 'votingMembers') return value;
return parsePositiveInteger(value, label); return parsePositiveInteger(value, label);
@@ -230,9 +232,7 @@ 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 loserStates: group.losers.map((loser) => loser.state ?? '').join(', '),
.map((loser) => loser.state ?? '')
.join(', '),
})), })),
); );
} }
@@ -46,19 +46,20 @@ export function applyMongoosePerformancePlugin(schema: mongoose.Schema): void {
query[QUERY_PERFORMANCE_RECORDED] = false; query[QUERY_PERFORMANCE_RECORDED] = false;
}); });
hookableSchema.post( hookableSchema.post(QUERY_OPERATION_REGEX, function (result: unknown) {
QUERY_OPERATION_REGEX,
function (result: unknown) {
recordQueryPerformance( recordQueryPerformance(
this as unknown as QueryWithPerformanceState, this as unknown as QueryWithPerformanceState,
result, result,
); );
}, });
);
hookableSchema.post( hookableSchema.post(
QUERY_OPERATION_REGEX, QUERY_OPERATION_REGEX,
function (error: unknown, _result: unknown, next: (error: unknown) => void) { function (
error: unknown,
_result: unknown,
next: (error: unknown) => void,
) {
recordQueryPerformance( recordQueryPerformance(
this as unknown as QueryWithPerformanceState, this as unknown as QueryWithPerformanceState,
undefined, undefined,
@@ -80,7 +81,11 @@ export function applyMongoosePerformancePlugin(schema: mongoose.Schema): void {
hookableSchema.post( hookableSchema.post(
'aggregate', 'aggregate',
function (error: unknown, _result: unknown, next: (error: unknown) => void) { function (
error: unknown,
_result: unknown,
next: (error: unknown) => void,
) {
recordAggregatePerformance( recordAggregatePerformance(
this as AggregateWithPerformanceState, this as AggregateWithPerformanceState,
undefined, undefined,
@@ -11,9 +11,7 @@ interface NewRelicCustomEventApi {
eventType: string, eventType: string,
attributes: Record<string, NewRelicAttributeValue>, attributes: Record<string, NewRelicAttributeValue>,
): void; ): void;
addCustomAttributes( addCustomAttributes(attributes: Record<string, NewRelicAttributeValue>): void;
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,8 +52,7 @@ export interface ApiRequestPerformanceEvent {
leanQueryCount: number; leanQueryCount: number;
} }
export interface MongooseQueryPerformanceEvent export interface MongooseQueryPerformanceEvent extends MongooseQueryPerformance {
extends MongooseQueryPerformance {
type: 'mongoose-query'; type: 'mongoose-query';
timestamp: string; timestamp: string;
requestId?: string; requestId?: string;
@@ -92,10 +91,7 @@ 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( localEventsEnabled: readBoolean(env.API_PERF_LOCAL_EVENTS_ENABLED, enabled),
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,8 +35,7 @@ export interface RunWithDistributedLockOptions {
lockRetryDelayMilliseconds?: number; lockRetryDelayMilliseconds?: number;
} }
export interface RunWithRenewedDistributedLockOptions export interface RunWithRenewedDistributedLockOptions extends RunWithDistributedLockOptions {
extends RunWithDistributedLockOptions {
lockRenewalIntervalMilliseconds: number; lockRenewalIntervalMilliseconds: number;
} }
@@ -55,7 +54,9 @@ export class DistributedLockService {
); );
const lockOwnershipToken = options.lockOwnershipToken ?? randomUUID(); const lockOwnershipToken = options.lockOwnershipToken ?? randomUUID();
const result = await this.redisService.raw().sendCommand([ const result = await this.redisService
.raw()
.sendCommand([
'SET', 'SET',
options.lockKey, options.lockKey,
lockOwnershipToken, lockOwnershipToken,
@@ -76,7 +77,9 @@ export class DistributedLockService {
public async releaseLockIfOwned( public async releaseLockIfOwned(
lockOwnership: DistributedLockOwnership, lockOwnership: DistributedLockOwnership,
): Promise<boolean> { ): Promise<boolean> {
const result = await this.redisService.raw().sendCommand([ const result = await this.redisService
.raw()
.sendCommand([
'EVAL', 'EVAL',
RELEASE_LOCK_IF_OWNED_SCRIPT, RELEASE_LOCK_IF_OWNED_SCRIPT,
'1', '1',
@@ -88,15 +91,16 @@ export class DistributedLockService {
public async extendLockIfOwned( public async extendLockIfOwned(
lockOwnership: DistributedLockOwnership, lockOwnership: DistributedLockOwnership,
lockExpirationDurationMilliseconds = lockExpirationDurationMilliseconds = lockOwnership.lockExpirationDurationMilliseconds,
lockOwnership.lockExpirationDurationMilliseconds,
): Promise<boolean> { ): Promise<boolean> {
this.assertPositiveDuration( this.assertPositiveDuration(
lockExpirationDurationMilliseconds, lockExpirationDurationMilliseconds,
'lockExpirationDurationMilliseconds', 'lockExpirationDurationMilliseconds',
); );
const result = await this.redisService.raw().sendCommand([ const result = await this.redisService
.raw()
.sendCommand([
'EVAL', 'EVAL',
EXTEND_LOCK_IF_OWNED_SCRIPT, EXTEND_LOCK_IF_OWNED_SCRIPT,
'1', '1',
@@ -25,7 +25,9 @@ async function readFirstSecret(
{ {
provide: REDIS_CLIENT, provide: REDIS_CLIENT,
inject: [SecretService], inject: [SecretService],
useFactory: async (secretService: SecretService): Promise<RedisClient> => { useFactory: async (
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([
@@ -6,7 +6,9 @@ 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.fn().mockResolvedValue([ const sendCommand = jest
.fn()
.mockResolvedValue([
'0-0', '0-0',
[ [
[ [
@@ -223,9 +223,7 @@ 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]) const rawMessages = Array.isArray(responseItems[1]) ? responseItems[1] : [];
? responseItems[1]
: [];
return { return {
nextStartId: String(responseItems[0] ?? '0-0'), nextStartId: String(responseItems[0] ?? '0-0'),
@@ -258,7 +256,9 @@ export class RedisService implements OnModuleDestroy {
return this.client.publish(channel, message); return this.client.publish(channel, message);
} }
private normalizeClaimedStreamMessage(rawMessage: unknown): StreamEntry | null { private normalizeClaimedStreamMessage(
rawMessage: unknown,
): StreamEntry | null {
if (Array.isArray(rawMessage)) { if (Array.isArray(rawMessage)) {
const [id, fields] = rawMessage; const [id, fields] = rawMessage;
if (id === undefined) return null; if (id === undefined) return null;
@@ -46,11 +46,13 @@ 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 && userByPuuid.has(participant.puuid), participant.teamId === RIOT_BLUE_TEAM_ID &&
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 && userByPuuid.has(participant.puuid), participant.teamId === RIOT_RED_TEAM_ID &&
userByPuuid.has(participant.puuid),
).length; ).length;
return { team100, team200, total: team100 + team200 }; return { team100, team200, total: team100 + team200 };
} }
@@ -78,13 +80,16 @@ 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((tier) => tier.queueType === 'RANKED_SOLO_5x5') ?? user.account.tiers.find(
user.account.tiers[0], (tier) => tier.queueType === 'RANKED_SOLO_5x5',
) ?? 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 => Boolean(participant)); .filter((participant): participant is MatchParticipant =>
Boolean(participant),
);
} }
export function buildTeams( export function buildTeams(
@@ -105,7 +110,9 @@ export function buildTeams(
assignedPosition: resolveAssignedPosition(participant, user), assignedPosition: resolveAssignedPosition(participant, user),
}; };
}) })
.filter((member): member is NonNullable<typeof member> => Boolean(member)); .filter((member): member is NonNullable<typeof member> =>
Boolean(member),
);
return { return {
teamIndex, teamIndex,
name: `${teamIndex}팀`, name: `${teamIndex}팀`,
@@ -3,9 +3,7 @@ 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 { import type { RiotJobPriority } from '../riot-job-queue/riot-job-queue.types';
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,4 +1,8 @@
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common'; import {
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 {
@@ -16,10 +20,7 @@ import {
type RiotQueueGroup, type RiotQueueGroup,
type RiotRankFilter, type RiotRankFilter,
} from '../riot/riot-queue.constants'; } from '../riot/riot-queue.constants';
import type { import type { RiotMatchDto, RiotMatchParticipantDto } from '../riot/riot.types';
RiotMatchDto,
RiotMatchParticipantDto,
} from '../riot/riot.types';
import type { import type {
ChampionStatsResponse, ChampionStatsResponse,
ChampionStatsRow, ChampionStatsRow,
@@ -104,7 +105,10 @@ export class MatchHistoryService {
fetchedAt: tier.fetchedAt.toISOString(), fetchedAt: tier.fetchedAt.toISOString(),
})), })),
tierHistory: [...context.account.tierHistory] tierHistory: [...context.account.tierHistory]
.sort((left, right) => left.recordedAt.getTime() - right.recordedAt.getTime()) .sort(
(left, right) =>
left.recordedAt.getTime() - right.recordedAt.getTime(),
)
.map((entry) => ({ .map((entry) => ({
queueType: entry.queueType, queueType: entry.queueType,
tier: entry.tier, tier: entry.tier,
@@ -170,7 +174,11 @@ 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(params.filters.limit, DEFAULT_SUMMARY_LIMIT, 50); const limit = this.clampLimit(
params.filters.limit,
DEFAULT_SUMMARY_LIMIT,
50,
);
const docs = await this.findStoredMatches({ const docs = await this.findStoredMatches({
context, context,
queueIds, queueIds,
@@ -196,7 +204,11 @@ 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(params.filters.limit, DEFAULT_RECENT_LIMIT, 30); const limit = this.clampLimit(
params.filters.limit,
DEFAULT_RECENT_LIMIT,
30,
);
const docs = await this.findStoredMatches({ const docs = await this.findStoredMatches({
context, context,
queueIds, queueIds,
@@ -212,7 +224,10 @@ export class MatchHistoryService {
return { return {
matches: page, matches: page,
nextCursor: views.length > limit ? page[page.length - 1]?.gameCreation ?? null : null, nextCursor:
views.length > limit
? (page[page.length - 1]?.gameCreation ?? null)
: null,
lastFetchedAt: this.resolveLastFetchedAt(docs, context), lastFetchedAt: this.resolveLastFetchedAt(docs, context),
season: context.season, season: context.season,
}; };
@@ -455,8 +470,9 @@ export class MatchHistoryService {
puuid: string, puuid: string,
): RiotMatchParticipantDto | null { ): RiotMatchParticipantDto | null {
return ( return (
match.info.participants.find((participant) => participant.puuid === puuid) ?? match.info.participants.find(
null (participant) => participant.puuid === puuid,
) ?? null
); );
} }
@@ -570,7 +586,8 @@ export class MatchHistoryService {
return { return {
matchId: dto.metadata.matchId, matchId: dto.metadata.matchId,
queueId: dto.info.queueId, queueId: dto.info.queueId,
queueLabel: RIOT_QUEUE_LABELS[dto.info.queueId] ?? `큐 ${dto.info.queueId}`, queueLabel:
RIOT_QUEUE_LABELS[dto.info.queueId] ?? `큐 ${dto.info.queueId}`,
gameCreation: dto.info.gameCreation, gameCreation: dto.info.gameCreation,
gameDuration: dto.info.gameDuration, gameDuration: dto.info.gameDuration,
win: participant.win, win: participant.win,
@@ -684,11 +701,15 @@ export class MatchHistoryService {
return { return {
puuid: participant.puuid, puuid: participant.puuid,
gameName: participant.riotIdGameName || participant.summonerName || 'Unknown', gameName:
participant.riotIdGameName ||
participant.summonerName ||
'Unknown',
tagLine: participant.riotIdTagLine || '', tagLine: participant.riotIdTagLine || '',
championId: participant.championId, championId: participant.championId,
championLevel: participant.champLevel, championLevel: participant.champLevel,
teamPosition: participant.teamPosition || participant.individualPosition, teamPosition:
participant.teamPosition || participant.individualPosition,
kills: participant.kills, kills: participant.kills,
deaths: participant.deaths, deaths: participant.deaths,
assists: participant.assists, assists: participant.assists,
@@ -720,7 +741,9 @@ export class MatchHistoryService {
})); }));
} }
private resolvePerks(participant: RiotMatchParticipantDto): RecentMatchView['perks'] { private resolvePerks(
participant: RiotMatchParticipantDto,
): RecentMatchView['perks'] {
const primary = participant.perks.styles.find( const primary = participant.perks.styles.find(
(style) => style.description === 'primaryStyle', (style) => style.description === 'primaryStyle',
); );
@@ -750,11 +773,19 @@ export class MatchHistoryService {
) as Partial<Record<RiotLane, number>>; ) as Partial<Record<RiotLane, number>>;
} }
private resolveTopChampions(views: RecentMatchView[]): RecentSummaryResponse['topChampions'] { private resolveTopChampions(
const byChampion = new Map<number, { games: number; wins: number; rating: number }>(); views: RecentMatchView[],
): 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 = const stat = byChampion.get(view.championId) ?? {
byChampion.get(view.championId) ?? { games: 0, wins: 0, rating: 0 }; games: 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;
@@ -797,7 +828,8 @@ export class MatchHistoryService {
participant.deaths, participant.deaths,
participant.assists, participant.assists,
); );
const kp = teamKills > 0 ? (participant.kills + participant.assists) / teamKills : 0; const kp =
teamKills > 0 ? (participant.kills + participant.assists) / teamKills : 0;
const csPerMin = this.resolveTotalCs(participant) / Math.max(minutes, 1); const 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 =
@@ -815,8 +847,13 @@ 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((sum, candidate) => sum + candidate.totalDamageDealtToChampions, 0); .reduce(
return teamDamage > 0 ? participant.totalDamageDealtToChampions / teamDamage : 0; (sum, candidate) => sum + candidate.totalDamageDealtToChampions,
0,
);
return teamDamage > 0
? participant.totalDamageDealtToChampions / teamDamage
: 0;
} }
private resolveTotalCs(participant: RiotMatchParticipantDto): number { private resolveTotalCs(participant: RiotMatchParticipantDto): number {
@@ -827,11 +864,16 @@ export class MatchHistoryService {
match: RiotMatchDto, match: RiotMatchDto,
participant: RiotMatchParticipantDto, participant: RiotMatchParticipantDto,
): number { ): number {
return Math.max((participant.timePlayed || match.info.gameDuration) / 60, 1); return Math.max(
(participant.timePlayed || match.info.gameDuration) / 60,
1,
);
} }
private resolveKda(kills: number, deaths: number, assists: number): number { private resolveKda(kills: number, deaths: number, assists: number): number {
return deaths === 0 ? kills + assists : this.round((kills + assists) / deaths); return deaths === 0
? kills + assists
: this.round((kills + assists) / deaths);
} }
private resolveLastFetchedAt( private resolveLastFetchedAt(
@@ -841,9 +883,11 @@ 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((acc, doc) => const oldest = docs.reduce(
(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();
} }
@@ -858,14 +902,17 @@ 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) => (!acc || value.getTime() < acc.getTime() ? value : acc),
!acc || value.getTime() < acc.getTime() ? value : acc,
null, null,
); );
return oldest?.toISOString() ?? null; return oldest?.toISOString() ?? null;
} }
private clampLimit(value: number | undefined, fallback: number, max: number): number { private clampLimit(
value: number | undefined,
fallback: number,
max: number,
): number {
if (!value || !Number.isFinite(value)) return fallback; 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));
} }
@@ -882,18 +929,12 @@ export class MatchHistoryService {
return Math.round(value * 10) / 10; return Math.round(value * 10) / 10;
} }
private numberField( private numberField(value: RiotMatchParticipantDto, key: string): number {
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( private booleanField(value: RiotMatchParticipantDto, key: string): boolean {
value: RiotMatchParticipantDto,
key: string,
): boolean {
return value[key] === true; return value[key] === true;
} }
} }
@@ -8,7 +8,11 @@ import { RiotJobWorkerService } from './riot-job-worker.service';
import { RiotRefreshGateway } from './riot-refresh.gateway'; import { RiotRefreshGateway } from './riot-refresh.gateway';
@Module({ @Module({
imports: [RiotModule, LegacyImportModule, forwardRef(() => TournamentResultModule)], imports: [
RiotModule,
LegacyImportModule,
forwardRef(() => TournamentResultModule),
],
controllers: [RiotJobQueueController], controllers: [RiotJobQueueController],
providers: [RiotJobQueueService, RiotJobWorkerService, RiotRefreshGateway], providers: [RiotJobQueueService, RiotJobWorkerService, RiotRefreshGateway],
exports: [RiotJobQueueService], exports: [RiotJobQueueService],
@@ -95,7 +95,8 @@ export class RiotJobQueueService {
jobId: existingJobId, jobId: existingJobId,
queueGroup, queueGroup,
alreadyQueued: true, alreadyQueued: true,
etaSeconds: existingStatus?.etaSeconds ?? queuePosition * RIOT_JOB_AVG_SECONDS, etaSeconds:
existingStatus?.etaSeconds ?? queuePosition * RIOT_JOB_AVG_SECONDS,
queuePosition: existingStatus?.queuePosition ?? queuePosition, queuePosition: existingStatus?.queuePosition ?? queuePosition,
}); });
continue; continue;
@@ -127,7 +128,8 @@ export class RiotJobQueueService {
jobId, jobId,
queueGroup, queueGroup,
alreadyQueued: true, alreadyQueued: true,
etaSeconds: status?.etaSeconds ?? queuePosition * RIOT_JOB_AVG_SECONDS, etaSeconds:
status?.etaSeconds ?? queuePosition * RIOT_JOB_AVG_SECONDS,
queuePosition: status?.queuePosition ?? queuePosition, queuePosition: status?.queuePosition ?? queuePosition,
}); });
continue; continue;
@@ -164,7 +166,10 @@ export class RiotJobQueueService {
}); });
} }
await this.setParent(parentJobId, subJobs.map((job) => job.jobId)); await this.setParent(
parentJobId,
subJobs.map((job) => job.jobId),
);
if (params.priority === 'high' && needsNewJob) { if (params.priority === 'high' && needsNewJob) {
await this.markRefreshRequested(context.user._id, context.account.puuid); await this.markRefreshRequested(context.user._id, context.account.puuid);
} }
@@ -253,8 +258,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((job) => const done = subJobs.filter(
job.state === 'completed' || job.state === 'failed', (job) => job.state === 'completed' || job.state === 'failed',
).length; ).length;
const state = this.resolveParentState(subJobs); const state = this.resolveParentState(subJobs);
@@ -411,7 +416,9 @@ export class RiotJobQueueService {
job: PollTournamentResultJob, job: PollTournamentResultJob,
deferUntilMs: number, deferUntilMs: number,
): Promise<void> { ): Promise<void> {
await this.redisService.raw().sendCommand([ await this.redisService
.raw()
.sendCommand([
'ZADD', 'ZADD',
RIOT_JOB_SCHEDULED_ZSET, RIOT_JOB_SCHEDULED_ZSET,
String(deferUntilMs), String(deferUntilMs),
@@ -449,7 +456,10 @@ export class RiotJobQueueService {
); );
} }
private async setParent(parentJobId: string, jobIds: string[]): Promise<void> { private async setParent(
parentJobId: string,
jobIds: string[],
): Promise<void> {
await this.redisService.setJson( await this.redisService.setJson(
this.parentKey(parentJobId), this.parentKey(parentJobId),
jobIds, jobIds,
@@ -1,7 +1,4 @@
import type { import type { RiotPlatformRoute, RiotRegionalRoute } from '../riot/riot.types';
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,7 +21,9 @@ 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.fn().mockImplementation(async (options, operation) => runWithRenewedLock: jest
.fn()
.mockImplementation(async (options, operation) =>
operation({ operation({
lockKey: options.lockKey, lockKey: options.lockKey,
lockOwnershipToken: 'lock-owner', lockOwnershipToken: 'lock-owner',
@@ -70,7 +70,10 @@ 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 (typeof payload?.parentJobId === 'string' && payload.parentJobId.trim()) { if (
typeof payload?.parentJobId === 'string' &&
payload.parentJobId.trim()
) {
rooms.push(`parent:${payload.parentJobId.trim()}`); rooms.push(`parent:${payload.parentJobId.trim()}`);
} }
return rooms; return rooms;
@@ -198,8 +198,7 @@ describe('RiotAccountEnrichmentService', () => {
masteryService, masteryService,
recentMatchesService, recentMatchesService,
recentStatsService, recentStatsService,
} = } = makeService({
makeService({
user, user,
summoner: { summoner: {
getByPuuid: jest.fn().mockResolvedValue({ getByPuuid: jest.fn().mockResolvedValue({
@@ -148,14 +148,18 @@ 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({ description: '커서 방향으로 순간이동합니다.' }), '4': expect.objectContaining({
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({ longDesc: expect.stringContaining('기본 공격') }), expect.objectContaining({
longDesc: expect.stringContaining('기본 공격'),
}),
]), ]),
}), }),
]), ]),
@@ -114,7 +114,9 @@ export class RiotDdragonService {
constructor(private readonly redisService: RedisService) {} constructor(private readonly redisService: RedisService) {}
public async getManifest(locale: string = DEFAULT_LOCALE): Promise<DdragonManifest> { public async getManifest(
locale: string = DEFAULT_LOCALE,
): Promise<DdragonManifest> {
const normalizedLocale = normalizeLocale(locale); const normalizedLocale = normalizeLocale(locale);
const cacheKey = manifestCacheKey(normalizedLocale); const cacheKey = manifestCacheKey(normalizedLocale);
@@ -139,12 +141,14 @@ export class RiotDdragonService {
private async buildManifest(locale: string): Promise<DdragonManifest> { private async buildManifest(locale: string): Promise<DdragonManifest> {
const version = await this.fetchLatestVersion(); const version = await this.fetchLatestVersion();
const [champions, summonerSpells, runesReforged, items] = await Promise.all([ const [champions, summonerSpells, runesReforged, items] = await Promise.all(
[
this.fetchChampionMap(version, locale), this.fetchChampionMap(version, locale),
this.fetchSummonerSpellMap(version, locale), this.fetchSummonerSpellMap(version, locale),
this.fetchRuneStyles(version, locale), this.fetchRuneStyles(version, locale),
this.fetchItemMap(version, locale), this.fetchItemMap(version, locale),
]); ],
);
return { return {
version, version,
cdn: DDRAGON_CDN, cdn: DDRAGON_CDN,
@@ -158,7 +162,9 @@ export class RiotDdragonService {
} }
private async fetchLatestVersion(): Promise<string> { private async fetchLatestVersion(): Promise<string> {
const versions = await this.fetchJson<unknown>(`${DDRAGON_BASE}/api/versions.json`); const versions = await this.fetchJson<unknown>(
`${DDRAGON_BASE}/api/versions.json`,
);
if (!Array.isArray(versions) || typeof versions[0] !== 'string') { if (!Array.isArray(versions) || typeof versions[0] !== 'string') {
throw new Error('ddragon versions.json response is malformed.'); throw new Error('ddragon versions.json response is malformed.');
} }
@@ -219,7 +225,9 @@ export class RiotDdragonService {
const url = `${DDRAGON_CDN}/${version}/data/${locale}/runesReforged.json`; const url = `${DDRAGON_CDN}/${version}/data/${locale}/runesReforged.json`;
const payload = await this.fetchJson<unknown>(url); const payload = await this.fetchJson<unknown>(url);
if (!Array.isArray(payload)) { if (!Array.isArray(payload)) {
throw new Error(`ddragon runesReforged.json response is malformed (${url}).`); throw new Error(
`ddragon runesReforged.json response is malformed (${url}).`,
);
} }
return payload return payload
@@ -229,8 +237,7 @@ export class RiotDdragonService {
key: style.key, key: style.key,
icon: style.icon, icon: style.icon,
name: style.name, name: style.name,
shortDesc: shortDesc: typeof style.shortDesc === 'string' ? style.shortDesc : '',
typeof style.shortDesc === 'string' ? style.shortDesc : '',
longDesc: typeof style.longDesc === 'string' ? style.longDesc : '', longDesc: typeof style.longDesc === 'string' ? style.longDesc : '',
slots: (style.slots ?? []).map((slot) => ({ slots: (style.slots ?? []).map((slot) => ({
runes: (slot.runes ?? []) runes: (slot.runes ?? [])
@@ -290,9 +297,7 @@ export class RiotDdragonService {
signal: controller.signal, signal: controller.signal,
}); });
if (!response.ok) { if (!response.ok) {
throw new Error( throw new Error(`ddragon request failed (${response.status}): ${url}`);
`ddragon request failed (${response.status}): ${url}`,
);
} }
return (await response.json()) as T; return (await response.json()) as T;
} catch (err) { } catch (err) {
@@ -1,9 +1,6 @@
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { RiotClientService } from './riot.client.service'; import { RiotClientService } from './riot.client.service';
import { import { RiotLeagueEntryDto, RiotPlatformLookupOptions } from './riot.types';
RiotLeagueEntryDto,
RiotPlatformLookupOptions,
} from './riot.types';
@Injectable() @Injectable()
export class RiotLeagueService { export class RiotLeagueService {
@@ -98,9 +98,7 @@ function validateMatchIdsLookupOptions(
assertOptionalNonNegativeInteger(options.endTime, 'endTime'); assertOptionalNonNegativeInteger(options.endTime, 'endTime');
if (options.type !== undefined && !RIOT_MATCH_TYPES.includes(options.type)) { if (options.type !== undefined && !RIOT_MATCH_TYPES.includes(options.type)) {
throw new RangeError( throw new RangeError(`type must be one of: ${RIOT_MATCH_TYPES.join(', ')}`);
`type must be one of: ${RIOT_MATCH_TYPES.join(', ')}`,
);
} }
if ( if (
@@ -278,7 +276,9 @@ function parseTimelineParticipant(
index: number, index: number,
): RiotMatchTimelineParticipantDto { ): RiotMatchTimelineParticipantDto {
if (!isRecord(value)) { if (!isRecord(value)) {
throw new TypeError(`timeline.info.participants[${index}] must be an object.`); throw new TypeError(
`timeline.info.participants[${index}] must be an object.`,
);
} }
return { return {
@@ -287,7 +287,10 @@ function parseTimelineParticipant(
value.participantId, value.participantId,
`timeline.info.participants[${index}].participantId`, `timeline.info.participants[${index}].participantId`,
), ),
puuid: requireString(value.puuid, `timeline.info.participants[${index}].puuid`), puuid: requireString(
value.puuid,
`timeline.info.participants[${index}].puuid`,
),
}; };
} }
@@ -589,7 +592,10 @@ function parseParticipant(
}; };
} }
function parsePerks(value: unknown, participantIndex: number): RiotMatchPerksDto { function parsePerks(
value: unknown,
participantIndex: number,
): RiotMatchPerksDto {
if (!isRecord(value)) { if (!isRecord(value)) {
throw new TypeError( throw new TypeError(
`participants[${participantIndex}].perks must be an object.`, `participants[${participantIndex}].perks must be an object.`,
@@ -732,7 +738,9 @@ function parseBan(
banIndex: number, banIndex: number,
): RiotMatchBanDto { ): RiotMatchBanDto {
if (!isRecord(value)) { if (!isRecord(value)) {
throw new TypeError(`teams[${teamIndex}].bans[${banIndex}] must be an object.`); throw new TypeError(
`teams[${teamIndex}].bans[${banIndex}] must be an object.`,
);
} }
return { return {
@@ -781,7 +789,9 @@ function parseObjective(
key: keyof RiotMatchObjectivesDto, key: keyof RiotMatchObjectivesDto,
): RiotMatchObjectiveDto { ): RiotMatchObjectiveDto {
if (!isRecord(value)) { if (!isRecord(value)) {
throw new TypeError(`teams[${teamIndex}].objectives.${key} must be an object.`); throw new TypeError(
`teams[${teamIndex}].objectives.${key} must be an object.`,
);
} }
return { return {
@@ -84,5 +84,10 @@ export function isRiotQueueGroup(value: string): value is RiotQueueGroup {
} }
export function isRiotRankFilter(value: string): value is RiotRankFilter { export function isRiotRankFilter(value: string): value is RiotRankFilter {
return value === 'all' || value === 'solo' || value === 'flex' || value === 'normal'; return (
value === 'all' ||
value === 'solo' ||
value === 'flex' ||
value === 'normal'
);
} }
@@ -150,13 +150,16 @@ async function runWithConcurrency<T>(
if (items.length === 0) return; if (items.length === 0) return;
const queue = [...items]; const queue = [...items];
const runners = Array.from({ length: Math.min(concurrency, queue.length) }, async () => { const runners = Array.from(
{ length: Math.min(concurrency, queue.length) },
async () => {
while (queue.length > 0) { while (queue.length > 0) {
const item = queue.shift(); const item = queue.shift();
if (item === undefined) return; if (item === undefined) return;
await worker(item); await worker(item);
} }
}); },
);
await Promise.all(runners); await Promise.all(runners);
} }
@@ -44,17 +44,29 @@ export class RiotRecentStatsService {
); );
for (const match of filteredMatches) { for (const match of filteredMatches) {
const participant = match.info.participants.find((entry) => entry.puuid === puuid); const participant = match.info.participants.find(
(entry) => entry.puuid === puuid,
);
if (!participant) continue; if (!participant) continue;
accumulateAggregate(overall, participant, match.info.gameCreation, match.info.gameDuration); accumulateAggregate(
overall,
participant,
match.info.gameCreation,
match.info.gameDuration,
);
const lane = resolveLane(participant); const lane = resolveLane(participant);
if (!lane) continue; if (!lane) continue;
const aggregate = laneAggregates.get(lane); const aggregate = laneAggregates.get(lane);
if (!aggregate) continue; if (!aggregate) continue;
accumulateAggregate(aggregate, participant, match.info.gameCreation, match.info.gameDuration); accumulateAggregate(
aggregate,
participant,
match.info.gameCreation,
match.info.gameDuration,
);
} }
if (overall.games === 0) { if (overall.games === 0) {
@@ -133,7 +145,8 @@ function finalizeAggregate(aggregate: Aggregate): RiotLaneStats {
const mostPlayedChampionIds = [...aggregate.championCounts.entries()] const mostPlayedChampionIds = [...aggregate.championCounts.entries()]
.sort((left, right) => { .sort((left, right) => {
if (right[1] !== left[1]) return right[1] - left[1]; if (right[1] !== left[1]) return right[1] - left[1];
const rightLastPlayed = aggregate.lastPlayedAtByChampion.get(right[0]) ?? 0; const rightLastPlayed =
aggregate.lastPlayedAtByChampion.get(right[0]) ?? 0;
const leftLastPlayed = aggregate.lastPlayedAtByChampion.get(left[0]) ?? 0; const leftLastPlayed = aggregate.lastPlayedAtByChampion.get(left[0]) ?? 0;
if (rightLastPlayed !== leftLastPlayed) { if (rightLastPlayed !== leftLastPlayed) {
return rightLastPlayed - leftLastPlayed; return rightLastPlayed - leftLastPlayed;
@@ -1,9 +1,6 @@
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { RiotClientService } from './riot.client.service'; import { RiotClientService } from './riot.client.service';
import { import { RiotPlatformLookupOptions, RiotSummonerDto } from './riot.types';
RiotPlatformLookupOptions,
RiotSummonerDto,
} from './riot.types';
@Injectable() @Injectable()
export class RiotSummonerService { export class RiotSummonerService {
@@ -17,8 +17,12 @@ describe('RiotWebhookController', () => {
}); });
it('logs the incoming webhook payload and returns an acknowledgement', () => { it('logs the incoming webhook payload and returns an acknowledgement', () => {
const logSpy = jest.spyOn(console, 'log').mockImplementation(() => undefined); const logSpy = jest
const dirSpy = jest.spyOn(console, 'dir').mockImplementation(() => undefined); .spyOn(console, 'log')
.mockImplementation(() => undefined);
const dirSpy = jest
.spyOn(console, 'dir')
.mockImplementation(() => undefined);
const request = { const request = {
method: 'POST', method: 'POST',
originalUrl: '/riot/webhooks/tournament', originalUrl: '/riot/webhooks/tournament',
@@ -1,10 +1,4 @@
import { import { All, Controller, HttpCode, HttpStatus, Req } from '@nestjs/common';
All,
Controller,
HttpCode,
HttpStatus,
Req,
} from '@nestjs/common';
import type { Request } from 'express'; import type { Request } from 'express';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator'; import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
+8 -3
View File
@@ -263,7 +263,10 @@ export interface RiotMatchTimelineInfoDto extends Record<string, unknown> {
participants?: RiotMatchTimelineParticipantDto[]; participants?: RiotMatchTimelineParticipantDto[];
} }
export interface RiotMatchTimelineParticipantDto extends Record<string, unknown> { export interface RiotMatchTimelineParticipantDto extends Record<
string,
unknown
> {
participantId: number; participantId: number;
puuid: string; puuid: string;
} }
@@ -294,8 +297,10 @@ export interface RiotMatchTimelineEventDto extends Record<string, unknown> {
victimId?: number; victimId?: number;
} }
export interface RiotMatchTimelineParticipantFrameDto export interface RiotMatchTimelineParticipantFrameDto extends Record<
extends Record<string, unknown> { string,
unknown
> {
participantId: number; participantId: number;
totalGold: number; totalGold: number;
xp: number; xp: number;
@@ -8,9 +8,7 @@ import {
describe('round-robin util', () => { describe('round-robin util', () => {
it('builds every team pair in lexicographic order', () => { it('builds every team pair in lexicographic order', () => {
expect(roundRobinPairs(2)).toEqual([ expect(roundRobinPairs(2)).toEqual([{ teamAIndex: 1, teamBIndex: 2 }]);
{ teamAIndex: 1, teamBIndex: 2 },
]);
expect(roundRobinPairs(4)).toEqual([ expect(roundRobinPairs(4)).toEqual([
{ teamAIndex: 1, teamBIndex: 2 }, { teamAIndex: 1, teamBIndex: 2 },
{ teamAIndex: 1, teamBIndex: 3 }, { teamAIndex: 1, teamBIndex: 3 },
@@ -33,8 +31,9 @@ describe('round-robin util', () => {
for (const roundNumber of [1, 2, 3, 4, 5]) { for (const roundNumber of [1, 2, 3, 4, 5]) {
const round = schedule.filter((game) => game.roundNumber === roundNumber); const round = schedule.filter((game) => game.roundNumber === roundNumber);
expect(round).toHaveLength(3); expect(round).toHaveLength(3);
expect(new Set(round.flatMap((game) => [game.teamAIndex, game.teamBIndex]))) expect(
.toHaveProperty('size', 6); new Set(round.flatMap((game) => [game.teamAIndex, game.teamBIndex])),
).toHaveProperty('size', 6);
} }
}); });
@@ -59,10 +59,7 @@ export function roundRobinGameSchedule(
typeof options.maxRounds === 'number' && Number.isFinite(options.maxRounds) typeof options.maxRounds === 'number' && Number.isFinite(options.maxRounds)
? Math.floor(options.maxRounds) ? Math.floor(options.maxRounds)
: fullRoundCount; : fullRoundCount;
const roundLimit = Math.max( const roundLimit = Math.max(0, Math.min(fullRoundCount, requestedRoundCount));
0,
Math.min(fullRoundCount, requestedRoundCount),
);
if (roundLimit === 0) return []; if (roundLimit === 0) return [];
const bye = 0; const bye = 0;
@@ -46,9 +46,7 @@ describe('TournamentCodeVendorService', () => {
ok: true, ok: true,
status: 200, status: 200,
json: jest.fn().mockResolvedValue({ json: jest.fn().mockResolvedValue({
tournament_code_list: [ tournament_code_list: ['KR05090-85d64e26-0a7d-438b-9ada-11784e46add3'],
'KR05090-85d64e26-0a7d-438b-9ada-11784e46add3',
],
}), }),
}); });
const service = new TournamentCodeVendorService(); const service = new TournamentCodeVendorService();
+5 -5
View File
@@ -13,10 +13,7 @@ import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
import '../auth/auth-request'; import '../auth/auth-request';
import { CurrentUser } from '../auth/current-user.decorator'; import { CurrentUser } from '../auth/current-user.decorator';
import { ConnectionService } from '../global/database/connection.service'; import { ConnectionService } from '../global/database/connection.service';
import type { import type { IdentityDocument, UserDocument } from '../global/database/schema';
IdentityDocument,
UserDocument,
} from '../global/database/schema';
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service'; import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
import type { MeResponseDto } from './dto/me-response.dto'; import type { MeResponseDto } from './dto/me-response.dto';
import { RefreshRiotAccountDto } from './dto/refresh-riot-account.dto'; import { RefreshRiotAccountDto } from './dto/refresh-riot-account.dto';
@@ -56,7 +53,10 @@ export class UserController {
@Body() body: RefreshRiotAccountDto, @Body() body: RefreshRiotAccountDto,
) { ) {
const resolvedUser = const resolvedUser =
user ?? (req.identity ? await this.findUserByIdentityAndPuuid(req.identity, puuid) : null); user ??
(req.identity
? await this.findUserByIdentityAndPuuid(req.identity, puuid)
: null);
if (!resolvedUser) { if (!resolvedUser) {
throw new UnauthorizedException('Authentication required.'); throw new UnauthorizedException('Authentication required.');
} }
@@ -123,9 +123,8 @@ describe('api performance report generation', () => {
expect(rows).toHaveLength(3); expect(rows).toHaveLength(3);
expect( expect(
rows.find( rows.find((row) => row.route === '/communities/:communityId/matches')
(row) => row.route === '/communities/:communityId/matches', ?.status,
)?.status,
).toBe('document-heavy'); ).toBe('document-heavy');
expect(rows.filter((row) => row.status === 'no-samples')).toHaveLength(2); expect(rows.filter((row) => row.status === 'no-samples')).toHaveLength(2);
}); });
@@ -208,11 +207,11 @@ describe('api performance report generation', () => {
expect(buildNewRelicCustomEventNrql('lolympus-api', '1 day ago')).toContain( expect(buildNewRelicCustomEventNrql('lolympus-api', '1 day ago')).toContain(
'FACET method, route', 'FACET method, route',
); );
expect( expect(buildNewRelicTransactionNrql('lolympus-api', '1 day ago')).toContain(
buildNewRelicTransactionNrql('lolympus-api', '1 day ago'), 'FROM Transaction',
).toContain('FROM Transaction'); );
expect( expect(buildNewRelicTransactionNrql('lolympus-api', '1 day ago')).toContain(
buildNewRelicTransactionNrql('lolympus-api', '1 day ago'), 'FACET name',
).toContain('FACET name'); );
}); });
}); });
+15 -13
View File
@@ -7,10 +7,7 @@ import type {
ApiRequestPerformanceEvent, ApiRequestPerformanceEvent,
} from '../modules/global/observability/performance-observer'; } from '../modules/global/observability/performance-observer';
export type ReportSource = export type ReportSource = 'local' | 'newrelic-custom' | 'newrelic-transaction';
| 'local'
| 'newrelic-custom'
| 'newrelic-transaction';
export interface ApiRoute { export interface ApiRoute {
method: string; method: string;
@@ -143,7 +140,8 @@ export function buildEndpointReportFromLocalEvents(params: {
const rowsByKey = new Map<string, EndpointReportRow>(); const rowsByKey = new Map<string, EndpointReportRow>();
for (const route of params.routes) { for (const route of params.routes) {
const events = requestsByRoute.get(routeKey(route.method, route.route)) ?? []; const events =
requestsByRoute.get(routeKey(route.method, route.route)) ?? [];
rowsByKey.set( rowsByKey.set(
routeKey(route.method, route.route), routeKey(route.method, route.route),
summarizeRequestEvents(route, events, { summarizeRequestEvents(route, events, {
@@ -538,8 +536,7 @@ function classifyRow(
(row.docsReturnedP95 !== null && (row.docsReturnedP95 !== null &&
row.docsReturnedP95 > options.docsReturnedP95Budget) || row.docsReturnedP95 > options.docsReturnedP95Budget) ||
(row.hydratedDocsReturnedP95 !== null && (row.hydratedDocsReturnedP95 !== null &&
row.hydratedDocsReturnedP95 > row.hydratedDocsReturnedP95 > options.hydratedDocsReturnedP95Budget)
options.hydratedDocsReturnedP95Budget)
) { ) {
return 'document-heavy'; return 'document-heavy';
} }
@@ -615,7 +612,10 @@ function max(values: number[]): number | null {
return Math.max(...values); return Math.max(...values);
} }
function percentileField(value: unknown, percentileValue: number): number | null { function percentileField(
value: unknown,
percentileValue: number,
): number | null {
if (!value || typeof value !== 'object') return null; if (!value || typeof value !== 'object') return null;
const map = value as Record<string, unknown>; const map = value as Record<string, unknown>;
return numberOrNull(map[String(percentileValue)] ?? map[percentileValue]); return numberOrNull(map[String(percentileValue)] ?? map[percentileValue]);
@@ -654,7 +654,11 @@ function parseArgs(argv: string[]): ReportOptions {
args.set(key, rawValue ?? true); args.set(key, rawValue ?? true);
} }
const source = stringArg(args, 'source', defaultReportSource()) as ReportSource; const source = stringArg(
args,
'source',
defaultReportSource(),
) as ReportSource;
return { return {
source, source,
rootDir: path.resolve( rootDir: path.resolve(
@@ -739,8 +743,7 @@ async function buildReport(options: ReportOptions): Promise<string> {
events: await readLocalPerformanceEvents(options.inputFile), events: await readLocalPerformanceEvents(options.inputFile),
p95BudgetMs: options.p95BudgetMs, p95BudgetMs: options.p95BudgetMs,
docsReturnedP95Budget: options.docsReturnedP95Budget, docsReturnedP95Budget: options.docsReturnedP95Budget,
hydratedDocsReturnedP95Budget: hydratedDocsReturnedP95Budget: options.hydratedDocsReturnedP95Budget,
options.hydratedDocsReturnedP95Budget,
}) })
: await fetchNewRelicEndpointRows({ : await fetchNewRelicEndpointRows({
source: options.source, source: options.source,
@@ -753,8 +756,7 @@ async function buildReport(options: ReportOptions): Promise<string> {
since: options.since, since: options.since,
p95BudgetMs: options.p95BudgetMs, p95BudgetMs: options.p95BudgetMs,
docsReturnedP95Budget: options.docsReturnedP95Budget, docsReturnedP95Budget: options.docsReturnedP95Budget,
hydratedDocsReturnedP95Budget: hydratedDocsReturnedP95Budget: options.hydratedDocsReturnedP95Budget,
options.hydratedDocsReturnedP95Budget,
}); });
const notes = const notes =
options.source === 'newrelic-custom' && measuredRows.length === 0 options.source === 'newrelic-custom' && measuredRows.length === 0
+63 -38
View File
@@ -11,7 +11,10 @@ import { AuctionRedisCommandService } from '../modules/auction/redis/auction-red
import { buildAuctionRedisKeys } from '../modules/auction/redis/auction-redis.keys'; import { buildAuctionRedisKeys } from '../modules/auction/redis/auction-redis.keys';
import { AuctionRedisService } from '../modules/auction/redis/auction-redis.service'; import { AuctionRedisService } from '../modules/auction/redis/auction-redis.service';
import { AuctionRedisStateReaderService } from '../modules/auction/redis/auction-redis-state-reader.service'; import { AuctionRedisStateReaderService } from '../modules/auction/redis/auction-redis-state-reader.service';
import { ConnectionService, resolveMongoDbName } from '../modules/global/database/connection.service'; import {
ConnectionService,
resolveMongoDbName,
} from '../modules/global/database/connection.service';
import { import {
assertDistinctRedisInstances, assertDistinctRedisInstances,
resolveRedisClientOptions, resolveRedisClientOptions,
@@ -69,7 +72,10 @@ async function readFirstSecret(
} }
function requireSafeNodeEnv(): void { function requireSafeNodeEnv(): void {
if (process.env.NODE_ENV === 'prod' && process.env.ALLOW_PROD_AUCTION_REHEARSAL !== 'true') { if (
process.env.NODE_ENV === 'prod' &&
process.env.ALLOW_PROD_AUCTION_REHEARSAL !== 'true'
) {
throw new Error( throw new Error(
'Refusing to run auction Redis rehearsal against prod. Set ALLOW_PROD_AUCTION_REHEARSAL=true only for an explicit production drill.', 'Refusing to run auction Redis rehearsal against prod. Set ALLOW_PROD_AUCTION_REHEARSAL=true only for an explicit production drill.',
); );
@@ -85,15 +91,20 @@ async function createRedisClientFromSecrets(
kind: 'common' | 'auction', kind: 'common' | 'auction',
): Promise<RedisClient> { ): Promise<RedisClient> {
const prefix = kind === 'auction' ? 'AUCTION_REDIS' : 'REDIS'; const prefix = kind === 'auction' ? 'AUCTION_REDIS' : 'REDIS';
const urlKeys = kind === 'auction' ? [`${prefix}_URL`] : ['REDIS_URL', 'GARNET_URL']; const urlKeys =
kind === 'auction' ? [`${prefix}_URL`] : ['REDIS_URL', 'GARNET_URL'];
const endpointKeys = const endpointKeys =
kind === 'auction' ? [`${prefix}_ENDPOINT`] : ['REDIS_ENDPOINT', 'GARNET_ENDPOINT']; kind === 'auction'
? [`${prefix}_ENDPOINT`]
: ['REDIS_ENDPOINT', 'GARNET_ENDPOINT'];
const usernameKeys = const usernameKeys =
kind === 'auction' kind === 'auction'
? [`${prefix}_USERNAME`, `${prefix}_USERID`] ? [`${prefix}_USERNAME`, `${prefix}_USERID`]
: ['REDIS_USERNAME', 'REDIS_USERID', 'GARNET_USERNAME', 'GARNET_USERID']; : ['REDIS_USERNAME', 'REDIS_USERID', 'GARNET_USERNAME', 'GARNET_USERID'];
const passwordKeys = const passwordKeys =
kind === 'auction' ? [`${prefix}_PASSWORD`] : ['REDIS_PASSWORD', 'GARNET_PASSWORD']; kind === 'auction'
? [`${prefix}_PASSWORD`]
: ['REDIS_PASSWORD', 'GARNET_PASSWORD'];
const [url, endpoint, username, password] = await Promise.all([ const [url, endpoint, username, password] = await Promise.all([
readFirstSecret(secretService, urlKeys), readFirstSecret(secretService, urlKeys),
readFirstSecret(secretService, endpointKeys), readFirstSecret(secretService, endpointKeys),
@@ -117,15 +128,12 @@ async function createRedisClientFromSecrets(
return client; return client;
} }
async function assertRedisTopology( async function assertRedisTopology(secretService: SecretService): Promise<{
secretService: SecretService, auctionRedisClient: RedisClient;
): Promise<{ auctionRedisClient: RedisClient; commonRedisClient: RedisClient }> { commonRedisClient: RedisClient;
const [ }> {
redisUrl, const [redisUrl, redisEndpoint, auctionRedisUrl, auctionRedisEndpoint] =
redisEndpoint, await Promise.all([
auctionRedisUrl,
auctionRedisEndpoint,
] = await Promise.all([
readFirstSecret(secretService, ['REDIS_URL', 'GARNET_URL']), readFirstSecret(secretService, ['REDIS_URL', 'GARNET_URL']),
readFirstSecret(secretService, ['REDIS_ENDPOINT', 'GARNET_ENDPOINT']), readFirstSecret(secretService, ['REDIS_ENDPOINT', 'GARNET_ENDPOINT']),
readFirstSecret(secretService, ['AUCTION_REDIS_URL']), readFirstSecret(secretService, ['AUCTION_REDIS_URL']),
@@ -162,7 +170,9 @@ async function cleanupRedis(
matchId: mongoose.Types.ObjectId, matchId: mongoose.Types.ObjectId,
): Promise<void> { ): Promise<void> {
const keys = buildAuctionRedisKeys(matchId.toString()); const keys = buildAuctionRedisKeys(matchId.toString());
await auctionRedisService.raw().sendCommand([ await auctionRedisService
.raw()
.sendCommand([
'DEL', 'DEL',
keys.liveStateKey, keys.liveStateKey,
keys.structureStateKey, keys.structureStateKey,
@@ -175,15 +185,15 @@ async function cleanupRedis(
keys.rehydrateLockKey, keys.rehydrateLockKey,
keys.stateTransitionLockKey, keys.stateTransitionLockKey,
]); ]);
await auctionRedisService.raw().sendCommand([ await auctionRedisService
'ZREM', .raw()
keys.deadlineQueueKey, .sendCommand(['ZREM', keys.deadlineQueueKey, matchId.toString()]);
matchId.toString(),
]);
let cursor = '0'; let cursor = '0';
do { do {
const reply = await auctionRedisService.raw().sendCommand([ const reply = await auctionRedisService
.raw()
.sendCommand([
'SCAN', 'SCAN',
cursor, cursor,
'MATCH', 'MATCH',
@@ -195,12 +205,12 @@ async function cleanupRedis(
cursor = String(reply[0]); cursor = String(reply[0]);
const payloadKeys = Array.isArray(reply[1]) ? reply[1].map(String) : []; const payloadKeys = Array.isArray(reply[1]) ? reply[1].map(String) : [];
if (payloadKeys.length > 0) { if (payloadKeys.length > 0) {
await auctionRedisService.raw().sendCommand([ await auctionRedisService
'ZREM', .raw()
keys.durabilityRetryQueueKey, .sendCommand(['ZREM', keys.durabilityRetryQueueKey, ...payloadKeys]);
...payloadKeys, await auctionRedisService
]); .raw()
await auctionRedisService.raw().sendCommand([ .sendCommand([
'ZREM', 'ZREM',
keys.durabilityDeadLetterQueueKey, keys.durabilityDeadLetterQueueKey,
...payloadKeys, ...payloadKeys,
@@ -236,7 +246,8 @@ async function cleanupMongo(
resources: RehearsalResources, resources: RehearsalResources,
): Promise<void> { ): Promise<void> {
const AuctionModel = await connectionService.getModel('auction'); const AuctionModel = await connectionService.getModel('auction');
const AuctionHistoryModel = await connectionService.getModel('auctionHistory'); const AuctionHistoryModel =
await connectionService.getModel('auctionHistory');
const SideEffectModel = await connectionService.getModel( const SideEffectModel = await connectionService.getModel(
'auctionSideEffectApplication', 'auctionSideEffectApplication',
); );
@@ -325,7 +336,9 @@ async function seedMatch(
userId, userId,
})), })),
scheduledAt: new Date(Date.now() + 60_000), scheduledAt: new Date(Date.now() + 60_000),
shortCode: `R${Math.random().toString(36).slice(2, 6)}`.slice(0, 6).toUpperCase(), shortCode: `R${Math.random().toString(36).slice(2, 6)}`
.slice(0, 6)
.toUpperCase(),
status: 'recruiting', status: 'recruiting',
title: `${REHEARSAL_PREFIX}-${suffix}`, title: `${REHEARSAL_PREFIX}-${suffix}`,
}); });
@@ -371,7 +384,8 @@ function assertState(
state: Record<string, unknown> | null, state: Record<string, unknown> | null,
expectedPhase: string, expectedPhase: string,
): Record<string, unknown> { ): Record<string, unknown> {
if (!state) throw new Error(`Expected auction state phase=${expectedPhase}, got null`); if (!state)
throw new Error(`Expected auction state phase=${expectedPhase}, got null`);
if (state.phase !== expectedPhase) { if (state.phase !== expectedPhase) {
throw new Error( throw new Error(
`Expected auction phase=${expectedPhase}, got ${String(state.phase)}`, `Expected auction phase=${expectedPhase}, got ${String(state.phase)}`,
@@ -390,7 +404,9 @@ async function main(): Promise<void> {
const configService = new ConfigService(process.env); const configService = new ConfigService(process.env);
const secretService = new SecretService(configService); const secretService = new SecretService(configService);
await secretService.ready(); await secretService.ready();
logStep(`secrets loaded, nodeEnv=${process.env.NODE_ENV}, db=${resolveMongoDbName()}`); logStep(
`secrets loaded, nodeEnv=${process.env.NODE_ENV}, db=${resolveMongoDbName()}`,
);
const { auctionRedisClient, commonRedisClient } = const { auctionRedisClient, commonRedisClient } =
await assertRedisTopology(secretService); await assertRedisTopology(secretService);
@@ -498,7 +514,8 @@ async function main(): Promise<void> {
matchId: resources.matchId, matchId: resources.matchId,
teamIndex: 1, teamIndex: 1,
}); });
if (!('revision' in bidResult)) throw new Error('Bid did not return state.'); if (!('revision' in bidResult))
throw new Error('Bid did not return state.');
logStep('bid OK'); logStep('bid OK');
await auctionService.markSold({ await auctionService.markSold({
@@ -537,8 +554,12 @@ async function main(): Promise<void> {
), ),
'bidding', 'bidding',
); );
const secondBiddingKeys = buildAuctionRedisKeys(resources.matchId.toString()); const secondBiddingKeys = buildAuctionRedisKeys(
const queuedDeadlineScore = await auctionRedisService.raw().sendCommand([ resources.matchId.toString(),
);
const queuedDeadlineScore = await auctionRedisService
.raw()
.sendCommand([
'ZSCORE', 'ZSCORE',
secondBiddingKeys.deadlineQueueKey, secondBiddingKeys.deadlineQueueKey,
resources.matchId.toString(), resources.matchId.toString(),
@@ -567,7 +588,8 @@ async function main(): Promise<void> {
communityId: resources.communityId, communityId: resources.communityId,
matchId: resources.matchId, matchId: resources.matchId,
}); });
const undoTarget = historyBeforeUndo[historyBeforeUndo.length - 1]?.sequence; const undoTarget =
historyBeforeUndo[historyBeforeUndo.length - 1]?.sequence;
if (!undoTarget) throw new Error('No history sequence to undo.'); if (!undoTarget) throw new Error('No history sequence to undo.');
await auctionService.undoTo({ await auctionService.undoTo({
auctionActionRequestId: randomUUID(), auctionActionRequestId: randomUUID(),
@@ -584,7 +606,8 @@ async function main(): Promise<void> {
matchId: resources.matchId, matchId: resources.matchId,
}); });
await flushDurability(durabilityScheduler); await flushDurability(durabilityScheduler);
const resetState = await auctionRedisStateReaderService.readAuctionStateView( const resetState =
await auctionRedisStateReaderService.readAuctionStateView(
resources.matchId.toString(), resources.matchId.toString(),
); );
if (resetState) { if (resetState) {
@@ -635,9 +658,11 @@ async function main(): Promise<void> {
} }
} }
void main().then(() => { void main()
.then(() => {
process.exit(0); process.exit(0);
}).catch((error) => { })
.catch((error) => {
console.error('[auction-rehearsal] FAILED:', error); console.error('[auction-rehearsal] FAILED:', error);
process.exit(1); process.exit(1);
}); });
+1 -2
View File
@@ -751,8 +751,7 @@ function createRecentStatsSummary(
avgDeaths: input.avgDeaths, avgDeaths: input.avgDeaths,
avgAssists: input.avgAssists, avgAssists: input.avgAssists,
avgCs: input.avgCs, avgCs: input.avgCs,
avgCsPerMin: avgCsPerMin: input.avgCsPerMin ?? Math.round((input.avgCs / 28) * 10) / 10,
input.avgCsPerMin ?? Math.round((input.avgCs / 28) * 10) / 10,
mostPlayedChampionIds: championIds, mostPlayedChampionIds: championIds,
}; };