Compare commits

..
25 Commits
Author SHA1 Message Date
dahyeon 4b8ccf0077 fix: harden result polling and Redis 8.10 operations
Preserve tournament result jobs through lock contention and transient failures,
atomically schedule retries before acknowledgement, and publish initial polls
after releasing the preparation lock.

Fix Redis connection blocking, durability Hash cleanup, duplicate auction
request ordering, and scheduled-job promotion. Use native Redis 8.10 stream,
lock, counter, and field-expiring cache operations with invalidation fencing.

Repair 90 test type errors and add a repeatable API typecheck command.

Validation: 704 API tests, 129 web tests, 31 real Redis integration tests,
3 dependency checks, workspace type checks and builds, and changed-file lint.
2026-11-09 17:33:13 +09:00
dahyeon 0c4c4239ec fix(redis): share Garnet endpoint and update database versions 2026-11-09 16:30:12 +09:00
dahyeon 9117c9c0a4 fix(deps): resolve production high and critical vulnerabilities
Pin vulnerable transitive dependencies to patched releases and replace Infisical SDK bootstrap calls with a compatible HTTP client. Add dependency-security and secret-loading regression coverage.
2026-11-07 20:21:54 +09:00
dahyeon 5bc748dc4d fix(auction): prevent skipped players and incomplete completion 2026-11-05 23:14:14 +09:00
dahyeon de84ad5309 Merge pull request 'fix(dakao): clarify command usage messages' (#15) from release/88 into main
Reviewed-on: #15
2026-09-26 15:37:04 +00:00
dahyeon cd1525c87a Merge pull request 'chore: remove bundled skills directory' (#14) from release/88 into main
Reviewed-on: #14
2026-09-19 11:25:40 +00:00
dahyeon 58e24ccd75 Merge pull request 'fix(deps): patch Socket.IO parser, nanoid and multer vulnerabilities' (#13) from release/88 into main
Reviewed-on: #13
2026-09-19 10:51:05 +00:00
dahyeon 384d460ad6 Merge pull request 'feat(dakao): transfer existing users to new KakaoTalk IDs' (#12) from release/88 into main
Reviewed-on: #12
2026-09-19 10:44:08 +00:00
dahyeon 904f1fc4a4 Merge pull request 'refactor(web): hide history connection status' (#11) from agent/hide-history-realtime-status into main
Reviewed-on: #11
2026-07-25 18:07:21 +00:00
dahyeon f526257d9c refactor(web): hide history connection status 2026-07-25 11:06:28 -07:00
dahyeon 34a47c053e Merge pull request 'feat(api): refresh Riot ID during background updates' (#10) from agent/refresh-riot-id-by-puuid into main
Reviewed-on: #10
2026-07-25 16:13:18 +00:00
dahyeon e3f39fd8b8 feat(api): refresh Riot ID during background updates 2026-07-25 09:08:29 -07:00
dahyeon 4385ba7b8b Merge pull request 'feat(api): refresh Riot ID by PUUID' (#9) from agent/refresh-riot-id-by-puuid into main
Reviewed-on: #9
2026-07-25 15:38:33 +00:00
dahyeon 9cd5850d43 feat(api): refresh Riot ID by PUUID 2026-07-25 08:37:42 -07:00
dahyeon 79534cf43c Merge pull request 'refactor(web): remove redundant history result column' (#8) from agent/remove-history-result-column into main
Reviewed-on: #8
2026-07-25 14:38:57 +00:00
dahyeon 03be85d07b refactor(web): remove redundant history result column 2026-07-25 07:37:32 -07:00
dahyeon d269bdd92b Merge pull request 'chore(deps): resolve high audit findings' (#7) from release/87 into main
Reviewed-on: #7
2026-07-25 08:52:22 +00:00
dahyeon 760da1cbea Merge pull request 'fix(dakao): hide started matches from schedule' (#6) from release/87 into main
Reviewed-on: #6
2026-07-25 08:07:42 +00:00
dahyeon ac0d2b53f0 Merge pull request 'fix(web): satisfy React hook lint rules' (#5) from release/87 into main
Reviewed-on: #5
2026-07-25 06:40:40 +00:00
dahyeon a24726d7da Merge pull request 'fix(api): eliminate unsafe lint warnings' (#4) from release/87 into main
Reviewed-on: #4
2026-07-25 05:23:15 +00:00
dahyeon 9e2f2c61e7 Merge pull request 'release/87' (#3) from release/87 into main
Reviewed-on: #3
2026-07-25 04:59:34 +00:00
dahyeon 1f75c6318a Merge pull request 'release/86' (#2) from release/86 into main
Reviewed-on: #2
2026-07-15 08:56:05 +00:00
dahyeon 8ec9edc35f feat(web): align double-elimination winner connector rails 2026-07-15 01:41:52 -07:00
dahyeon 61f1db0e6a fix(web): align bracket score-card row geometry 2026-07-15 01:06:26 -07:00
dahyeon c155f26272 Merge pull request 'Release 77' (#1) from release/77 into main
Reviewed-on: #1
2026-06-09 13:36:48 +00:00
84 changed files with 5386 additions and 808 deletions

No files matched your search

+3
View File
@@ -28,6 +28,9 @@ website/LICENSE
!AGENTS.md
!docs/specs/internal-match-game-analysis.md
!docs/plans/internal-match-game-analysis-p0-p1.md
!docs/specs/double-elimination-connector-routing.md
!docs/plans/double-elimination-connector-routing.md
!docs/plans/redis-8.10-optimization.md
!agents/**/*.md
!skills/**/*.md
/tmp/
+21 -5
View File
@@ -94,9 +94,8 @@ LOLYMPUS는 이 반복 작업을 줄이는 데 초점을 맞췄습니다. 운영
- TypeScript
- TanStack Query
- NestJS
- MongoDB
- Redis
- Redis 8.4 (경매 실시간 상태 전용)
- MongoDB 8.3
- Redis 8.10 (일반 캐시/스트림과 경매 실시간 상태 공유)
- NATS
- Riot API
- pnpm workspace
@@ -118,9 +117,9 @@ scripts/ deployment and maintenance scripts
- Node.js 24 이상
- pnpm 10.4.1 (`packageManager` 기준, `corepack enable`로 활성화 권장)
- MongoDB 7.0, 일반 캐시/스트림용 Redis, 경매 실시간 상태 전용 Redis 8.4, NATS 실행 환경
- MongoDB 8.3, Redis 8.10, NATS 실행 환경
경매 Redis는 라이브 경매 상태의 source of truth로 사용되므로 일반 캐시/스트림 Redis와 물리적으로 분리해야 합니다. API는 `REDIS_URL`/`REDIS_ENDPOINT`와 별도로 `AUCTION_REDIS_URL`/`AUCTION_REDIS_ENDPOINT`를 읽고, 두 값이 같은 호스트/포트를 가리키면 부팅을 거부합니다.
일반 캐시/스트림, 경매 실시간 상태, WebSocket Pub/Sub는 `GARNET_ENDPOINT`로 지정한 하나의 Redis 인스턴스를 공유합니다. 값은 `host:port`, `redis://...`, `rediss://...` 형식을 지원합니다. 인증이 필요하면 기존 `GARNET_USERID`(또는 `GARNET_USERNAME`)와 `GARNET_PASSWORD`를 설정합니다. `REDIS_*`, `AUCTION_REDIS_*`, `GARNET_URL` 연결 설정은 사용하지 않습니다. 경매 점검 스크립트도 같은 설정을 사용합니다.
## 실행 방법
@@ -132,6 +131,21 @@ pnpm start:web:dev
웹 앱은 기본적으로 `apps/web/.env.development` 값을 사용합니다. API 환경값은 `apps/project.env`와 실행 환경의 시크릿 설정을 함께 확인합니다.
### Redis 변경 검증
Redis 8.10.x의 `XREADGROUP CLAIM`, `XACKDEL ACKED`, `DELEX`, `SET IFEQ`, `INCREX`, `HSETEX`를 사용합니다. 스트림의 대기 읽기는 별도 연결에서 실행하며, 처리되지 않은 작업은 길이 제한을 초과해도 보존합니다.
```bash
pnpm --filter api test -- --runInBand
pnpm --filter api typecheck
pnpm --filter api test:redis
pnpm --filter api build
```
`test:redis`는 PATH의 `redis-server` 또는 `REDIS_TEST_SERVER`에 지정한 실행 파일로 Redis 8.10.x를 직접 실행합니다. 임의의 로컬 포트와 일회용 암호를 사용하고, 저장을 비활성화하며, 종료 후 프로세스와 임시 디렉터리를 정리합니다. 애플리케이션 Redis 연결 설정은 사용하지 않습니다. Windows에서는 PowerShell에서 `$env:REDIS_TEST_SERVER = 'C:\tools\redis\redis-server.exe'`처럼 지정할 수 있습니다.
커뮤니티 통계 캐시는 `riot:communitystats:v2:{communityId}:scope` Hash로 전환됩니다. 항목별 TTL은 일반 5분, 완성된 상세 24시간, 미완성 상세 60초를 유지합니다. 이전 String 캐시는 기존 TTL로 만료되며 새 캐시는 첫 조회에 생성됩니다. 구버전과 신버전은 무효화 대상이 다르므로 API 인스턴스를 같은 버전으로 함께 전환해야 합니다. 구현 범위와 검증 기록은 [Redis 변경 계획](docs/plans/redis-8.10-optimization.md)을 참고하세요.
### API New Relic APM
API 서버는 `newrelic` Node.js agent를 앱 코드보다 먼저 preload합니다. Docker 런타임과 `pnpm start:api:*` 스크립트 모두 `NEW_RELIC_HOME`을 API 패키지로 지정해 `apps/api/newrelic.cjs` 설정을 읽습니다.
@@ -164,6 +178,8 @@ API 성능 계측은 기본 비활성화이며 필요할 때 `API_PERF_OBSERVABI
| `pnpm start:web:dev` | 웹 앱 개발 서버 실행 |
| `pnpm start:api:dev` | API 서버 dev 환경 실행 |
| `pnpm --filter api test` | API 테스트 실행 |
| `pnpm --filter api typecheck` | 테스트를 포함한 API 타입 검사 |
| `pnpm --filter api test:redis` | 격리된 Redis 8.10 통합 테스트 실행 |
| `pnpm --filter api perf:routes` | API 성능 리포트 대상 route 출력 |
| `pnpm --filter api perf:report` | API 성능 리포트 생성 |
| `pnpm --filter web build:staging` | 웹 staging 빌드 검증 |
+2
View File
@@ -22,6 +22,8 @@
"start:debug": "nest start --debug --watch",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"typecheck": "tsc --noEmit --incremental false",
"test:redis": "node test/run-redis-tests.mjs",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
@@ -5,6 +5,15 @@ import {
} from './auction-rejection';
describe('resolveAuctionRejectionReason', () => {
it('reports roster validation failures without recommending a retry', () => {
const reason = resolveAuctionRejectionReason(
'AUCTION_ROSTER_INVALID',
'Auction roster validation failed.',
);
expect(reason).toBe('AUCTION_TRANSITION_REJECTED_BECAUSE_ROSTER_INVALID');
expect(isAuctionResyncRecommended(reason)).toBe(false);
});
it('maps the internal CONFLICT code to the descriptive transition reason', () => {
expect(resolveAuctionRejectionReason('CONFLICT')).toBe(
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_LIVE_STATE_CHANGED_BEFORE_APPLY,
@@ -16,7 +16,7 @@
* resync 권장 여부:
* - `AUCTION_RESYNC_RECOMMENDED_REASONS`에 속한 reason은 "클라가 본 상태가 이미
* 바뀌었다(낙관적 동시성 충돌/만료/단계 전이)"는 신호다. 이 경우 클라는 최신
* state로 rebaseline한 뒤 (구조 액션이라면) 1회 재시도하는 것이 안전하다.
* state로 rebaseline한다. 구조 액션 재시도는 원래 대상과 단계가 같을 때만 허용한다.
* - 반대로 정원 초과/포인트 부족처럼 "상태를 새로고침해도 결과가 같은" 거부는
* resync 권장 대상이 아니다(재시도해도 또 거부됨).
*/
@@ -29,9 +29,12 @@ export const AUCTION_REJECTION_REASON = {
/** 입찰 단계가 아닌데 입찰 단계 전환을 시도함(이미 sold/passed/presenting 등). */
AUCTION_TRANSITION_REJECTED_BECAUSE_AUCTION_NOT_IN_BIDDING_PHASE:
'AUCTION_TRANSITION_REJECTED_BECAUSE_AUCTION_NOT_IN_BIDDING_PHASE',
/** 현재 단계에서 "다음"으로 진행할 수 없음(sold/passed/presenting이 아님 — 보통 이미 진행됨). */
/** 낙찰 또는 유찰이 확정되지 않아 다음 선수로 진행할 수 없음. */
AUCTION_TRANSITION_REJECTED_BECAUSE_PHASE_DOES_NOT_ALLOW_ADVANCE:
'AUCTION_TRANSITION_REJECTED_BECAUSE_PHASE_DOES_NOT_ALLOW_ADVANCE',
/** 원 참가자 명단과 실제 팀 배정이 일치하지 않아 완료할 수 없음. */
AUCTION_TRANSITION_REJECTED_BECAUSE_ROSTER_INVALID:
'AUCTION_TRANSITION_REJECTED_BECAUSE_ROSTER_INVALID',
/** 낙찰 처리할 유효한 최고 입찰이 없음(만료 처리로 이미 정리됐을 수 있음). */
AUCTION_TRANSITION_REJECTED_BECAUSE_NO_WINNING_BID_TO_MARK_SOLD:
'AUCTION_TRANSITION_REJECTED_BECAUSE_NO_WINNING_BID_TO_MARK_SOLD',
@@ -83,6 +86,8 @@ export type AuctionRejectionReason =
/** 내부 짧은 코드 → 설명적 reason. */
const INTERNAL_CODE_TO_REASON: Record<string, AuctionRejectionReason> = {
AUCTION_ROSTER_INVALID:
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_ROSTER_INVALID,
CONFLICT:
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_LIVE_STATE_CHANGED_BEFORE_APPLY,
STALE_BID_ROUND:
@@ -1365,6 +1365,267 @@ describe('AuctionService', () => {
}
});
describe('redis next safety', () => {
function createFortyPlayerAuction() {
const matchId = new mongoose.Types.ObjectId();
const participantIds = Array.from(
{ length: 40 },
() => new mongoose.Types.ObjectId(),
);
const auction = {
_id: new mongoose.Types.ObjectId(),
matchId,
auctionEngineVersion: 'redis-v1',
auctionLifecycleId: 'life-1',
};
const state = {
auctionLifecycleId: 'life-1',
auctionTeams: participantIds
.slice(0, 8)
.map((captainUserId, index) => ({
teamIndex: index + 1,
captainUserId: captainUserId.toString(),
remainingBidPointAmount: 960,
members: participantIds
.slice(8 + index * 4, 12 + index * 4)
.map((userId) => ({
userId: userId.toString(),
assignedPosition: 'MID',
memberAcquisitionBidPointAmount: 10,
})),
})),
auctionPlayerOrder: participantIds.slice(8).map((userId) => ({
userId: userId.toString(),
preferredPositions: [{ position: 'MID', priority: 1 }],
passCount: 0,
})),
bidRoundExtensionSeconds: 5,
currentAuctionHistorySequence: 121,
currentAuctionPlayerOrderIndex: 31,
currentAuctionRound: 1,
initialTeamBidPointAmount: 1000,
maximumBidRoundDurationSeconds: 15,
passedAuctionPlayerQueue: [] as Array<{
userId: string;
preferredPositions: Array<{ position: string; priority: number }>;
passCount: number;
}>,
phase: 'sold',
revision: 479,
topTierAuctionPriorityThreshold: 'NONE',
};
const match = {
_id: matchId,
participants: participantIds.map((userId) => ({
userId,
excluded: false,
preferredPositions: [{ position: 'MID', priority: 1 }],
})),
status: 'team-built',
teams: [],
save: jest.fn().mockResolvedValue(undefined),
};
const dependencies = createService({
auction: { findOne: jest.fn().mockResolvedValue(auction) },
match: { findById: jest.fn().mockResolvedValue(match) },
});
dependencies.auctionRedisStateReaderService.readAuctionStateView.mockResolvedValue(
state,
);
dependencies.auctionRedisCommandService.applyTransition.mockImplementation(
async (_matchId: string, input: Record<string, unknown>) => {
Object.assign(
state,
parseJsonRecord(
input.afterAuctionStructureStateJson,
'afterAuctionStructureStateJson',
),
input.liveStatePatch,
{
revision: Number(input.expectedRevision) + 1,
currentAuctionHistorySequence: input.auctionHistorySequence,
},
);
return {
auctionStateTransitionId: String(input.auctionStateTransitionId),
currentServerTimestampMS: 1780000000000,
ok: true,
revision: state.revision,
};
},
);
return { ...dependencies, matchId, match, state, participantIds };
}
it.each([12, 31])(
'rejects next for a presenting player at index %i without skipping or completing',
async (index) => {
const { service, matchId, state, auctionRedisCommandService } =
createFortyPlayerAuction();
state.phase = 'presenting';
state.currentAuctionPlayerOrderIndex = index;
const before = structuredClone(state);
await expect(service.next(matchId)).rejects.toThrow(
'Cannot advance from current phase.',
);
expect(state).toEqual(before);
expect(
auctionRedisCommandService.reserveActionRequest,
).not.toHaveBeenCalled();
expect(
auctionRedisCommandService.applyTransition,
).not.toHaveBeenCalled();
},
);
it('rejects completion when only 39 of the 40 participants are assigned', async () => {
const { service, matchId, state, match, auctionRedisCommandService } =
createFortyPlayerAuction();
state.auctionTeams[6].members.pop();
const before = structuredClone(state);
await expect(service.next(matchId)).rejects.toThrow(
'Auction roster validation failed.',
);
expect(state).toEqual(before);
expect(auctionRedisCommandService.applyTransition).not.toHaveBeenCalled();
expect(match.save).not.toHaveBeenCalled();
});
it('checks original eligible participants even if a missing player also disappeared from the order', async () => {
const { service, matchId, state, auctionRedisCommandService } =
createFortyPlayerAuction();
const missingPlayer = state.auctionTeams[6].members.pop()!;
state.auctionPlayerOrder = state.auctionPlayerOrder.filter(
(player) => player.userId !== missingPlayer.userId,
);
state.currentAuctionPlayerOrderIndex =
state.auctionPlayerOrder.length - 1;
const before = structuredClone(state);
await expect(service.next(matchId)).rejects.toThrow(
'Auction roster validation failed.',
);
expect(state).toEqual(before);
expect(auctionRedisCommandService.applyTransition).not.toHaveBeenCalled();
});
it('rejects a duplicate assignment even when the assigned count still equals 40', async () => {
const { service, matchId, state, auctionRedisCommandService } =
createFortyPlayerAuction();
state.auctionTeams[0].members[0].userId =
state.auctionTeams[1].members[0].userId;
await expect(service.next(matchId)).rejects.toThrow(
'Auction roster validation failed.',
);
expect(state.phase).toBe('sold');
expect(auctionRedisCommandService.applyTransition).not.toHaveBeenCalled();
});
it('rejects duplicate captain membership even when every expected user is present', async () => {
const { service, matchId, state, auctionRedisCommandService } =
createFortyPlayerAuction();
state.auctionTeams[0].members.push({
userId: state.auctionTeams[0].captainUserId,
assignedPosition: 'MID',
memberAcquisitionBidPointAmount: 10,
});
await expect(service.next(matchId)).rejects.toThrow(
'Auction roster validation failed.',
);
expect(state.phase).toBe('sold');
expect(auctionRedisCommandService.applyTransition).not.toHaveBeenCalled();
});
it('rejects an unexpected assigned user even when all 40 assignments are unique', async () => {
const { service, matchId, state, auctionRedisCommandService } =
createFortyPlayerAuction();
state.auctionTeams[0].members[0].userId =
new mongoose.Types.ObjectId().toString();
await expect(service.next(matchId)).rejects.toThrow(
'Auction roster validation failed.',
);
expect(state.phase).toBe('sold');
expect(auctionRedisCommandService.applyTransition).not.toHaveBeenCalled();
});
it('completes all 40 eligible participants once, allowing repeat order entries after passes and excluding cut participants', async () => {
const { service, matchId, state, match, auctionRedisCommandService } =
createFortyPlayerAuction();
state.auctionPlayerOrder.push({
...state.auctionPlayerOrder[12],
passCount: 1,
});
state.currentAuctionPlayerOrderIndex =
state.auctionPlayerOrder.length - 1;
state.currentAuctionRound = 2;
match.participants.push({
userId: new mongoose.Types.ObjectId(),
excluded: true,
preferredPositions: [{ position: 'MID', priority: 1 }],
});
await expect(service.next(matchId)).resolves.toMatchObject({
phase: 'complete',
revision: 480,
});
expect(auctionRedisCommandService.applyTransition).toHaveBeenCalledTimes(
1,
);
expect(state.auctionTeams).toHaveLength(8);
expect(
state.auctionTeams.every((team) => team.members.length === 4),
).toBe(true);
expect(match.save).not.toHaveBeenCalled();
});
it.each(['sold', 'passed'])(
'advances a nonterminal %s player without demanding a completed roster',
async (phase) => {
const { service, matchId, state } = createFortyPlayerAuction();
state.phase = phase;
state.currentAuctionPlayerOrderIndex = 12;
state.auctionTeams.forEach((team) => {
team.members = [];
});
await expect(service.next(matchId)).resolves.toMatchObject({
phase: 'presenting',
currentAuctionPlayerOrderIndex: 13,
});
},
);
it('requeues passed players for another round without completing an incomplete roster', async () => {
const { service, matchId, state } = createFortyPlayerAuction();
state.phase = 'passed';
state.auctionTeams[7].members.pop();
state.passedAuctionPlayerQueue.push({
...state.auctionPlayerOrder[31],
passCount: 1,
});
await expect(service.next(matchId)).resolves.toMatchObject({
phase: 'presenting',
currentAuctionPlayerOrderIndex: 32,
currentAuctionRound: 2,
passedAuctionPlayerQueue: [],
});
expect(state.auctionPlayerOrder).toHaveLength(33);
});
});
it('syncs match teams when a redis-v1 auction completes', async () => {
const matchId = new mongoose.Types.ObjectId();
const captainUserId = new mongoose.Types.ObjectId();
@@ -1842,7 +2103,7 @@ describe('AuctionService', () => {
});
expect(auction.currentBid).toBe(970);
expect(auction.currentBidderTeamIndex).toBe(1);
expect(auction).toHaveProperty('currentBidderTeamIndex', 1);
expect(auction.bids).toEqual([
expect.objectContaining({
teamIndex: 1,
@@ -2136,7 +2397,7 @@ describe('AuctionService', () => {
await service.next(matchId);
expect(auction.phase).toBe('complete');
expect(auction.completedAt).toBeInstanceOf(Date);
expect(auction).toHaveProperty('completedAt', expect.any(Date));
expect(auction.save).toHaveBeenCalledTimes(1);
expect(match.save).toHaveBeenCalledTimes(2);
expect(match.teams).toEqual([
+63 -55
View File
@@ -39,6 +39,7 @@ import {
stringifyAuctionRedisStructureState,
} from './redis/auction-redis-projection';
import { AuctionRedisService } from './redis/auction-redis.service';
import { AUCTION_CLEANUP_DURABILITY_SCRIPT } from './redis/auction-redis.cleanup';
import { AuctionRedisStateReaderService } from './redis/auction-redis-state-reader.service';
import { shouldHydrateRedisAuctionState } from './redis/auction-redis.state';
// [AUCTION-DEBUG] 경매 "중복 멤버" 조사용 임시 계측. 조사 종료 후 제거 대상.
@@ -1193,11 +1194,7 @@ export class AuctionService {
): Promise<AuctionStateResponse> {
const matchId = auction.matchId.toString();
const state = await this.requireRedisAuctionState(matchId);
if (
state.phase !== 'sold' &&
state.phase !== 'presenting' &&
state.phase !== 'passed'
) {
if (state.phase !== 'sold' && state.phase !== 'passed') {
throw new BadRequestException('Cannot advance from current phase.');
}
@@ -1218,6 +1215,10 @@ export class AuctionService {
structureInput.currentAuctionRound += 1;
structureInput.currentAuctionPlayerOrderIndex = nextIndex;
} else {
await this.assertCompleteAuctionRoster(
auction.matchId,
structureInput.auctionTeams,
);
action = 'complete';
nextPhase = 'complete';
}
@@ -1332,17 +1333,16 @@ export class AuctionService {
if (this.isRedisV1Auction(auction)) {
return this.advanceRedisAuction(auction, actionRequest);
}
if (
auction.phase !== 'sold' &&
auction.phase !== 'presenting' &&
auction.phase !== 'passed'
) {
if (auction.phase !== 'sold' && auction.phase !== 'passed') {
throw new BadRequestException('Cannot advance from current phase.');
}
const nextIndex = auction.currentIndex + 1;
const completesAuction =
nextIndex >= auction.order.length &&
(auction.passedQueue?.length ?? 0) === 0;
if (completesAuction) {
await this.assertCompleteAuctionRoster(matchId, auction.teams);
}
await this.recordSnapshot(auction, completesAuction ? 'complete' : 'next');
if (nextIndex >= auction.order.length) {
if ((auction.passedQueue?.length ?? 0) > 0) {
@@ -2515,6 +2515,52 @@ export class AuctionService {
return ordered.slice(0, desiredAuctionCount);
}
private async assertCompleteAuctionRoster(
matchId: mongoose.Types.ObjectId,
teams: Array<{
captainUserId: mongoose.Types.ObjectId;
members: Array<{ userId: mongoose.Types.ObjectId }>;
}>,
): Promise<void> {
const MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findById(matchId);
if (!match) throw new NotFoundException('Match not found.');
// The queue can contain reauction entries or be corrupted; use the original roster.
const expectedIds = match.participants
.filter((participant) => !participant.excluded)
.map((participant) => participant.userId.toString());
const expected = new Set(expectedIds);
const assignedIds = teams.flatMap((team) => [
team.captainUserId.toString(),
...team.members.map((member) => member.userId.toString()),
]);
const assigned = new Set(assignedIds);
const missingUserIds = expectedIds.filter((id) => !assigned.has(id));
const unexpectedUserIds = [...assigned].filter((id) => !expected.has(id));
if (
expected.size === 0 ||
expected.size !== expectedIds.length ||
assigned.size !== assignedIds.length ||
missingUserIds.length > 0 ||
unexpectedUserIds.length > 0
) {
this.logger.error({
event: 'auction_roster_validation_failed',
matchId: matchId.toString(),
expectedCount: expectedIds.length,
assignedCount: assignedIds.length,
assignedUniqueCount: assigned.size,
missingUserIds,
unexpectedUserIds,
});
throw new BadRequestException({
code: 'AUCTION_ROSTER_INVALID',
message: 'Auction roster validation failed.',
});
}
}
private assertCaptainAssignments(
captains: StartAuctionParams['captains'],
activeParticipants: Array<{ userId: mongoose.Types.ObjectId }>,
@@ -2925,54 +2971,16 @@ export class AuctionService {
const payloadKeys = Array.isArray(reply[1]) ? reply[1].map(String) : [];
if (payloadKeys.length === 0) continue;
const values = await this.auctionRedisService
.raw()
.sendCommand(['MGET', ...payloadKeys]);
const payloadKeysToDelete = payloadKeys.filter((payloadKey, index) =>
this.shouldDeleteRedisDurabilityPayload(
Array.isArray(values) ? values[index] : undefined,
expectedAuctionLifecycleId,
payloadKey,
),
);
if (payloadKeysToDelete.length === 0) continue;
await this.auctionRedisService
.raw()
.sendCommand([
'ZREM',
await this.auctionRedisService.evalScript(
AUCTION_CLEANUP_DURABILITY_SCRIPT,
[
keys.durabilityRetryQueueKey,
...payloadKeysToDelete,
]);
await this.auctionRedisService
.raw()
.sendCommand([
'ZREM',
keys.durabilityDeadLetterQueueKey,
...payloadKeysToDelete,
]);
await this.auctionRedisService
.raw()
.sendCommand(['DEL', ...payloadKeysToDelete]);
} while (cursor !== '0');
}
private shouldDeleteRedisDurabilityPayload(
payloadValue: unknown,
expectedAuctionLifecycleId: string | undefined,
payloadKey: string,
): boolean {
if (!expectedAuctionLifecycleId) return true;
if (typeof payloadValue !== 'string') return false;
try {
const payload = JSON.parse(payloadValue) as Record<string, unknown>;
return payload.auctionLifecycleId === expectedAuctionLifecycleId;
} catch {
this.logger.warn(
`Failed to parse auction durability payload ${payloadKey}.`,
...payloadKeys,
],
[expectedAuctionLifecycleId ?? ''],
);
return false;
}
} while (cursor !== '0');
}
private enqueueBackgroundOrderEnrichment(params: {
@@ -317,7 +317,7 @@ if actionRequestScopeKey ~= '' then
actionRequestPrefix .. 'responseServerTimestampMS',
tostring(currentRedisTimestampMS)
)
redis.call('RPUSH', auctionActionRequestResultOrderKey, actionRequestScopeKey)
-- The reservation already inserted this request into the order list.
end
return {'OK', auctionStateTransitionId, tostring(newRevision), tostring(currentRedisTimestampMS)}
@@ -0,0 +1,27 @@
import { defineAuctionRedisScript } from './auction-redis.scripts';
// Compare the lifecycle and remove the payload and its indexes atomically.
export const AUCTION_CLEANUP_DURABILITY_SCRIPT = defineAuctionRedisScript(
'auction.cleanupDurability',
`
local deleted = 0
for i = 3, #KEYS do
local key = KEYS[i]
local keyType = redis.call('TYPE', key).ok
local matches = ARGV[1] == ''
if not matches and keyType == 'hash' then
matches = redis.call('HGET', key, 'auctionLifecycleId') == ARGV[1]
elseif not matches and keyType == 'string' then
-- Retain compatibility with payloads written before the Hash format.
local ok, payload = pcall(cjson.decode, redis.call('GET', key))
matches = ok and type(payload) == 'table' and payload.auctionLifecycleId == ARGV[1]
end
if matches then
redis.call('ZREM', KEYS[1], key)
redis.call('ZREM', KEYS[2], key)
deleted = deleted + redis.call('UNLINK', key)
end
end
return deleted
`,
);
@@ -2,10 +2,7 @@ import { Logger, Module } from '@nestjs/common';
import { createClient } from 'redis';
import { SecretModule } from '../../global/secret/secret.module';
import { SecretService } from '../../global/secret/secret.service';
import {
assertDistinctRedisInstances,
resolveRedisClientOptions,
} from '../../global/redis/redis.config';
import { loadRedisClientOptions } from '../../global/redis/redis.config';
import { AUCTION_REDIS_CLIENT } from './auction-redis.constants';
import {
AuctionRedisService,
@@ -14,18 +11,6 @@ import {
import { AuctionRedisCommandService } from './auction-redis-command.service';
import { AuctionRedisStateReaderService } from './auction-redis-state-reader.service';
async function readFirstSecret(
secretService: SecretService,
keys: string[],
): Promise<string | undefined> {
for (const key of keys) {
const value = await secretService.get<string>(key, '');
const trimmed = value.trim();
if (trimmed) return trimmed;
}
return undefined;
}
@Module({
imports: [SecretModule],
providers: [
@@ -35,45 +20,10 @@ async function readFirstSecret(
useFactory: async (
secretService: SecretService,
): Promise<AuctionRedisClient> => {
await secretService.ready();
const [
redisUrl,
redisEndpoint,
auctionRedisUrl,
auctionRedisEndpoint,
auctionRedisUsername,
auctionRedisPassword,
] = await Promise.all([
readFirstSecret(secretService, ['REDIS_URL', 'GARNET_URL']),
readFirstSecret(secretService, ['REDIS_ENDPOINT', 'GARNET_ENDPOINT']),
readFirstSecret(secretService, ['AUCTION_REDIS_URL']),
readFirstSecret(secretService, ['AUCTION_REDIS_ENDPOINT']),
readFirstSecret(secretService, [
'AUCTION_REDIS_USERNAME',
'AUCTION_REDIS_USERID',
]),
readFirstSecret(secretService, ['AUCTION_REDIS_PASSWORD']),
]);
const redisOptions = resolveRedisClientOptions({
endpoint: redisEndpoint,
endpointEnvName: 'REDIS_ENDPOINT',
url: redisUrl,
urlEnvName: 'REDIS_URL',
});
const auctionRedisOptions = resolveRedisClientOptions({
endpoint: auctionRedisEndpoint,
endpointEnvName: 'AUCTION_REDIS_ENDPOINT',
password: auctionRedisPassword,
url: auctionRedisUrl,
urlEnvName: 'AUCTION_REDIS_URL',
username: auctionRedisUsername,
});
assertDistinctRedisInstances(redisOptions.url, auctionRedisOptions.url);
const logger = new Logger('AuctionRedisClient');
const client = createClient(auctionRedisOptions);
const client = createClient(
await loadRedisClientOptions(secretService),
);
client.on('error', (error: unknown) => {
logger.error(
`Auction Redis client error: ${
@@ -129,13 +129,7 @@ export class AuctionRedisService implements OnModuleDestroy {
}
public async releaseTokenLock(key: string, token: string): Promise<boolean> {
const result = await this.client.sendCommand([
'EVAL',
'if redis.call("GET", KEYS[1]) == ARGV[1] then return redis.call("DEL", KEYS[1]) else return 0 end',
'1',
key,
token,
]);
const result = await this.client.sendCommand(['DELEX', key, 'IFEQ', token]);
return Number(result) === 1;
}
}
@@ -4,6 +4,7 @@ import { ConnectionService } from '../global/database/connection.service';
import { IdentityDocument, UserDocument } from '../global/database/schema';
import { UserResolverGuard } from './user-resolver.guard';
import './auth-request';
import type { Request } from 'express';
function createContext(request: Record<string, unknown>): ExecutionContext {
return {
@@ -24,7 +25,7 @@ describe('UserResolverGuard', () => {
const connectionService = {
getModel: jest.fn().mockResolvedValue({ findOne }),
} as unknown as ConnectionService;
const request = {
const request: Pick<Request, 'params' | 'identity' | 'user'> = {
params: { communityId: communityId.toString() },
identity: { _id: identityId } as IdentityDocument,
};
@@ -1,8 +1,67 @@
import { Injectable, Logger } from '@nestjs/common';
import { randomUUID } from 'crypto';
import { RedisService } from '../global/redis/redis.service';
const COMMUNITY_STATS_TTL_SECONDS = 5 * 60;
const COMMUNITY_STATS_DETAIL_TTL_SECONDS = 24 * 60 * 60;
const CACHE_SCOPES = [
'matches',
'leaderboard',
'teamInsights',
'matchDetail',
'userInternal',
] as const;
type CacheScope = (typeof CACHE_SCOPES)[number];
function communityPrefix(communityId: string): string {
return `riot:communitystats:v2:{${communityId}}`;
}
export class CommunityStatsCacheKey {
public readonly generationKey: string;
public readonly hashKey: string;
public generation?: string;
constructor(
communityId: string,
scope: CacheScope,
public readonly field: string,
) {
const prefix = communityPrefix(communityId);
this.generationKey = `${prefix}:generation`;
this.hashKey = `${prefix}:${scope}`;
}
public get identity(): string {
return JSON.stringify([this.hashKey, this.generation, this.field]);
}
}
const READ_CACHE_SCRIPT = `
local generation = redis.call('GET', KEYS[1])
if not generation then
generation = ARGV[1]
redis.call('SET', KEYS[1], generation)
end
return {generation, redis.call('HGET', KEYS[2], ARGV[2])}
`;
const WRITE_CACHE_SCRIPT = `
if redis.call('GET', KEYS[1]) ~= ARGV[1] then return 0 end
redis.call('HSETEX', KEYS[2], 'EX', ARGV[4], 'FIELDS', 1, ARGV[2], ARGV[3])
return 1
`;
const INVALIDATE_CACHE_SCRIPT = `
-- A fill started before invalidation cannot publish into the new generation.
redis.call('SET', KEYS[1], ARGV[1])
local deleted = 0
for i = 2, #KEYS do
deleted = deleted + redis.call('HLEN', KEYS[i])
redis.call('UNLINK', KEYS[i])
end
return deleted
`;
@Injectable()
export class CommunityStatsCacheService {
@@ -10,61 +69,72 @@ export class CommunityStatsCacheService {
constructor(private readonly redisService: RedisService) {}
public get<T>(key: string): Promise<T | null> {
return this.redisService.getJson<T>(key);
public async get<T>(key: CommunityStatsCacheKey): Promise<T | null> {
const reply = await this.redisService
.raw()
.sendCommand<
[string, string | null]
>(['EVAL', READ_CACHE_SCRIPT, '2', key.generationKey, key.hashKey, randomUUID(), key.field]);
key.generation = reply[0];
if (!reply[1]) return null;
try {
return JSON.parse(reply[1]) as T;
} catch {
this.logger.warn(
`Failed to parse community stats cache field in ${key.hashKey}.`,
);
return null;
}
}
public set(
key: string,
public async set(
key: CommunityStatsCacheKey,
value: unknown,
ttlSeconds = COMMUNITY_STATS_TTL_SECONDS,
): Promise<void> {
return this.redisService.setJson(key, value, ttlSeconds);
if (!key.generation)
throw new Error(
'Read the cache generation before starting a cache fill.',
);
if (!Number.isInteger(ttlSeconds) || ttlSeconds <= 0)
throw new Error('Cache TTL must be a positive integer.');
await this.redisService
.raw()
.sendCommand([
'EVAL',
WRITE_CACHE_SCRIPT,
'2',
key.generationKey,
key.hashKey,
key.generation,
key.field,
JSON.stringify(value),
String(ttlSeconds),
]);
}
public setDetail(key: string, value: unknown): Promise<void> {
public setDetail(key: CommunityStatsCacheKey, value: unknown): Promise<void> {
return this.set(key, value, COMMUNITY_STATS_DETAIL_TTL_SECONDS);
}
public async invalidateCommunity(communityId: string): Promise<number> {
const prefix = `riot:communitystats:`;
const match = `${prefix}*${communityId}*`;
const client = this.redisService.raw();
let cursor = '0';
let deleted = 0;
do {
const reply = await client.sendCommand([
'SCAN',
cursor,
'MATCH',
match,
'COUNT',
'100',
]);
if (!Array.isArray(reply)) {
throw new Error('Redis SCAN returned an invalid response.');
}
const values = reply as unknown[];
const nextCursor = values[0];
const rawKeys = values[1];
if (typeof nextCursor !== 'string') {
throw new Error('Redis SCAN returned an invalid cursor.');
}
cursor = nextCursor;
const keys = Array.isArray(rawKeys)
? (rawKeys as unknown[]).filter(
(key): key is string => typeof key === 'string',
)
: [];
if (keys.length > 0) {
deleted += await client.del(keys);
}
} while (cursor !== '0');
const prefix = communityPrefix(communityId);
const deleted = Number(
await this.redisService
.raw()
.sendCommand([
'EVAL',
INVALIDATE_CACHE_SCRIPT,
String(CACHE_SCOPES.length + 1),
`${prefix}:generation`,
...CACHE_SCOPES.map((scope) => `${prefix}:${scope}`),
randomUUID(),
]),
);
if (deleted > 0) {
this.logger.debug(
`Invalidated ${deleted} community stats cache keys for ${communityId}.`,
`Invalidated ${deleted} community stats cache entries for ${communityId}.`,
);
}
return deleted;
@@ -1,6 +1,9 @@
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import { CommunityStatsCacheService } from './community-stats-cache.service';
import {
CommunityStatsCacheKey,
CommunityStatsCacheService,
} from './community-stats-cache.service';
import { CommunityStatsService } from './community-stats.service';
import type {
InternalMatchCardView,
@@ -281,7 +284,7 @@ describe('CommunityStatsService', () => {
expect(setDetail).toHaveBeenCalledTimes(2);
expect(setDetail).toHaveBeenNthCalledWith(
2,
expect.stringContaining(':r4:'),
expect.objectContaining({ field: expect.stringContaining(':r4:') }),
invalidCheckpointResponse,
);
});
@@ -338,7 +341,7 @@ describe('CommunityStatsService', () => {
const set = jest
.fn()
.mockImplementation(
(_key: string, value: InternalMatchDetailResponse) => {
(_key: CommunityStatsCacheKey, value: InternalMatchDetailResponse) => {
cachedResponse = value;
return Promise.resolve();
},
@@ -346,7 +349,7 @@ describe('CommunityStatsService', () => {
const setDetail = jest
.fn()
.mockImplementation(
(_key: string, value: InternalMatchDetailResponse) => {
(_key: CommunityStatsCacheKey, value: InternalMatchDetailResponse) => {
cachedResponse = value;
return Promise.resolve();
},
@@ -377,7 +380,7 @@ describe('CommunityStatsService', () => {
expect(backedOff).toBe(fallback);
expect(buildAndUpsert).toHaveBeenCalledTimes(1);
expect(set).toHaveBeenCalledWith(
expect.stringContaining(':r4:'),
expect.objectContaining({ field: expect.stringContaining(':r4:') }),
fallback,
60,
);
@@ -389,7 +392,7 @@ describe('CommunityStatsService', () => {
expect(buildAndUpsert).toHaveBeenCalledTimes(2);
expect(setDetail).toHaveBeenCalledTimes(1);
expect(setDetail).toHaveBeenCalledWith(
expect.stringContaining(':r4:'),
expect.objectContaining({ field: expect.stringContaining(':r4:') }),
recovered,
);
});
@@ -547,7 +550,9 @@ describe('CommunityStatsService', () => {
).toEqual([matchId.toString()]);
expect(buildBaseDataset).not.toHaveBeenCalled();
expect(cacheService.set).toHaveBeenCalledWith(
expect.stringContaining(`userInternal:v3:${userId.toString()}`),
expect.objectContaining({
field: expect.stringContaining(`userInternal:v3:${userId.toString()}`),
}),
response,
);
});
@@ -11,7 +11,10 @@ import type {
HistorySeasonDto,
RecentMatchView,
} from '../match-history/match-history.types';
import { CommunityStatsCacheService } from './community-stats-cache.service';
import {
CommunityStatsCacheKey,
CommunityStatsCacheService,
} from './community-stats-cache.service';
import type {
CommunityStatsFilters,
InternalMatchCardView,
@@ -219,21 +222,25 @@ export class CommunityStatsService {
communityId: mongoose.Types.ObjectId;
matchId: mongoose.Types.ObjectId;
}): Promise<InternalMatchDetailResponse> {
const key = `riot:communitystats:matchDetail:v${MATCH_STATS_BUILDER_VERSION}:r${MATCH_DETAIL_RESPONSE_CACHE_VERSION}:${params.communityId.toString()}:${params.matchId.toString()}`;
const key = new CommunityStatsCacheKey(
params.communityId.toString(),
'matchDetail',
`v${MATCH_STATS_BUILDER_VERSION}:r${MATCH_DETAIL_RESPONSE_CACHE_VERSION}:${params.matchId.toString()}`,
);
const cached =
await this.cacheService.get<InternalMatchDetailResponse>(key);
if (cached && isCompleteMatchDetailResponse(cached)) return cached;
const inFlight = this.matchDetailInFlight.get(key);
const inFlight = this.matchDetailInFlight.get(key.identity);
if (inFlight) return inFlight;
const promise = this.buildMatchDetailResponse(params, key);
this.matchDetailInFlight.set(key, promise);
this.matchDetailInFlight.set(key.identity, promise);
try {
return await promise;
} finally {
if (this.matchDetailInFlight.get(key) === promise) {
this.matchDetailInFlight.delete(key);
if (this.matchDetailInFlight.get(key.identity) === promise) {
this.matchDetailInFlight.delete(key.identity);
}
}
}
@@ -243,7 +250,7 @@ export class CommunityStatsService {
communityId: mongoose.Types.ObjectId;
matchId: mongoose.Types.ObjectId;
},
key: string,
key: CommunityStatsCacheKey,
): Promise<InternalMatchDetailResponse> {
const dataset = await this.buildBaseDataset(params.communityId, {
seasonId: 'all',
@@ -346,16 +353,16 @@ export class CommunityStatsService {
// Auction viewers can all request the same next player's internal history
// at once. Coalesce local cache misses so one player change does one DB read.
const inFlight = this.userInternalHistoryInFlight.get(key);
const inFlight = this.userInternalHistoryInFlight.get(key.identity);
if (inFlight) return inFlight;
const promise = this.buildUserInternalHistoryResponse(params, key);
this.userInternalHistoryInFlight.set(key, promise);
this.userInternalHistoryInFlight.set(key.identity, promise);
try {
return await promise;
} finally {
if (this.userInternalHistoryInFlight.get(key) === promise) {
this.userInternalHistoryInFlight.delete(key);
if (this.userInternalHistoryInFlight.get(key.identity) === promise) {
this.userInternalHistoryInFlight.delete(key.identity);
}
}
}
@@ -428,7 +435,7 @@ export class CommunityStatsService {
userId: mongoose.Types.ObjectId;
filters: CommunityStatsFilters;
},
cacheKey: string,
cacheKey: CommunityStatsCacheKey,
): Promise<UserInternalHistoryResponse> {
const context = await this.resolveContext(
params.communityId,
@@ -1138,18 +1145,31 @@ export class CommunityStatsService {
scope: string,
communityId: mongoose.Types.ObjectId,
filters: CommunityStatsFilters,
): string {
return [
'riot:communitystats',
scope,
): CommunityStatsCacheKey {
const cacheScope = scope.startsWith('userInternal:')
? 'userInternal'
: scope;
if (
cacheScope !== 'matches' &&
cacheScope !== 'leaderboard' &&
cacheScope !== 'teamInsights' &&
cacheScope !== 'userInternal'
) {
throw new Error(`Unsupported community stats cache scope: ${scope}`);
}
return new CommunityStatsCacheKey(
communityId.toString(),
filters.seasonId ?? 'current',
filters.from ?? '',
filters.to ?? '',
filters.championId ?? '',
filters.cursor ?? '',
filters.limit ?? '',
].join(':');
cacheScope,
JSON.stringify([
scope,
filters.seasonId ?? 'current',
filters.from ?? '',
filters.to ?? '',
filters.championId ?? '',
filters.cursor ?? '',
filters.limit ?? '',
]),
);
}
private clampLimit(
@@ -106,6 +106,8 @@ describe('MatchStatsFragmentBuilder', () => {
puuid: 'puuid-2',
gameName: 'Opponent',
profileIconId: 8,
preferredPositions: [],
joinedAt: new Date('2026-05-03T00:00:00.000Z'),
});
match.teams[1].members.push({ userId: redUserId, assignedPosition: 'TOP' });
match.result?.games[0].participants.push({
@@ -269,7 +271,7 @@ describe('MatchStatsFragmentBuilder', () => {
teamId: 200,
win: false,
});
const timeline = {
const timeline: RiotMatchTimelineDto = {
metadata: {
dataVersion: '2',
matchId: 'KR_1',
@@ -280,6 +282,7 @@ describe('MatchStatsFragmentBuilder', () => {
frames: [
{
timestamp: 0,
events: [],
participantFrames: {
'1': {
participantId: 1,
@@ -507,9 +510,7 @@ describe('MatchStatsFragmentBuilder', () => {
const fragment = builder.buildFragment({
match,
rawByRiotMatchId: new Map([['KR_1', raw as RiotMatchDto]]),
timelineByRiotMatchId: new Map([
['KR_1', timeline as RiotMatchTimelineDto],
]),
timelineByRiotMatchId: new Map([['KR_1', timeline]]),
});
expect(fragment.gameDetails[0]).toMatchObject({
@@ -794,9 +795,7 @@ describe('MatchStatsFragmentBuilder', () => {
} as RiotMatchDto,
],
]),
timelineByRiotMatchId: new Map([
['KR_1', timeline as RiotMatchTimelineDto],
]),
timelineByRiotMatchId: new Map([['KR_1', timeline]]),
});
expect(
shortFragment.records.every((record) => record.checkpoints === undefined),
@@ -281,15 +281,26 @@ describe('MatchStatsService', () => {
MatchStatsFragmentBuilder['buildFragment']
>[0];
const buildCalls: BuildParams[] = [];
const builtFragment = {
matchCard: { matchId: matchId.toString() },
const builtFragment: ReturnType<
MatchStatsFragmentBuilder['buildFragment']
> = {
matchCard: {
matchId: matchId.toString(),
title: '내전',
scheduledAt: match.scheduledAt.toISOString(),
status: 'finished',
gameCount: 1,
games: [],
teams: [],
seriesResults: [],
},
records: [],
gameDetails: [],
userIds: [],
championIds: [],
gameCreationMin: 1_000,
gameCreationMax: 2_000,
} as ReturnType<MatchStatsFragmentBuilder['buildFragment']>;
};
const buildFragment = jest.fn((params: BuildParams) => {
buildCalls.push(params);
return builtFragment;
@@ -10,7 +10,7 @@ describe('CompetitionBootstrapService', () => {
it('creates a deterministic paired-Series Competition and immutable snapshots', async () => {
const firstHarness = createHarness();
const firstService = new CompetitionBootstrapService(
firstHarness.connectionService as ConnectionService,
firstHarness.connectionService,
);
const match = matchSnapshot({ gameMode: 'pair', teamCount: 2 });
@@ -88,7 +88,7 @@ describe('CompetitionBootstrapService', () => {
const secondHarness = createHarness();
const secondService = new CompetitionBootstrapService(
secondHarness.connectionService as ConnectionService,
secondHarness.connectionService,
);
await secondService.bootstrap({
...match,
@@ -106,9 +106,7 @@ describe('CompetitionBootstrapService', () => {
it('maps round-robin configuration and preserves a limited round count', async () => {
const harness = createHarness();
const service = new CompetitionBootstrapService(
harness.connectionService as ConnectionService,
);
const service = new CompetitionBootstrapService(harness.connectionService);
await service.bootstrap(
matchSnapshot({
@@ -132,9 +130,7 @@ describe('CompetitionBootstrapService', () => {
it('maps double elimination seeds and stage-specific Series rules', async () => {
const harness = createHarness();
const service = new CompetitionBootstrapService(
harness.connectionService as ConnectionService,
);
const service = new CompetitionBootstrapService(harness.connectionService);
const match = matchSnapshot({
gameMode: 'double-elimination',
teamCount: 4,
@@ -177,14 +173,14 @@ describe('CompetitionBootstrapService', () => {
{ legacyTeamIndex: 4, seedNumber: 3 },
]);
expect(
inserted.seriesGraph.find(({ code }) => code === 'WB_R1_M1').rule,
inserted.seriesGraph.find(({ code }) => code === 'WB_R1_M1')?.rule,
).toEqual({ type: 'first-to', winsRequired: 3, maxGames: 5 });
expect(
inserted.seriesGraph.find(({ code }) => code?.startsWith('LB_')).rule,
inserted.seriesGraph.find(({ code }) => code?.startsWith('LB_'))?.rule,
).toEqual({ type: 'first-to', winsRequired: 1, maxGames: 1 });
expect(
inserted.seriesGraph.find(({ code }) => code === 'GF')?.rule,
).toEqual({ type: 'first-to', winsRequired: 1, maxGames: 1 });
expect(inserted.seriesGraph.find(({ code }) => code === 'GF').rule).toEqual(
{ type: 'first-to', winsRequired: 1, maxGames: 1 },
);
expect(
inserted.seriesGraph.find(({ code }) => code === 'GF_RESET'),
).toMatchObject({
@@ -195,9 +191,7 @@ describe('CompetitionBootstrapService', () => {
it('rejects double elimination until authoritative seeds are persisted', async () => {
const harness = createHarness();
const service = new CompetitionBootstrapService(
harness.connectionService as ConnectionService,
);
const service = new CompetitionBootstrapService(harness.connectionService);
await expect(
service.bootstrap(
@@ -253,7 +247,7 @@ describe('CompetitionBootstrapService', () => {
for (const [label, mutate] of cases) {
const harness = createHarness();
const service = new CompetitionBootstrapService(
harness.connectionService as ConnectionService,
harness.connectionService,
);
const match = matchSnapshot({ gameMode: 'pair', teamCount: 2 });
mutate(match);
@@ -272,7 +266,7 @@ describe('CompetitionBootstrapService', () => {
it('rejects bracket mode live but explicitly maps it for legacy migration', async () => {
const liveHarness = createHarness();
const liveService = new CompetitionBootstrapService(
liveHarness.connectionService as ConnectionService,
liveHarness.connectionService,
);
const match = matchSnapshot({ gameMode: 'bracket', teamCount: 2 });
@@ -285,7 +279,7 @@ describe('CompetitionBootstrapService', () => {
const migrationHarness = createHarness();
const migrationService = new CompetitionBootstrapService(
migrationHarness.connectionService as ConnectionService,
migrationHarness.connectionService,
);
await migrationService.bootstrap(match, { source: 'legacy-migration' });
@@ -296,9 +290,7 @@ describe('CompetitionBootstrapService', () => {
it('upserts once and links only an unlinked or already-linked Match in one transaction', async () => {
const harness = createHarness();
const service = new CompetitionBootstrapService(
harness.connectionService as ConnectionService,
);
const service = new CompetitionBootstrapService(harness.connectionService);
const competition = await service.bootstrap(
matchSnapshot({ gameMode: 'pair', teamCount: 2 }),
@@ -342,9 +334,7 @@ describe('CompetitionBootstrapService', () => {
revision: 4,
};
const harness = createHarness({ existingCompetition: existing });
const service = new CompetitionBootstrapService(
harness.connectionService as ConnectionService,
);
const service = new CompetitionBootstrapService(harness.connectionService);
const result = await service.bootstrap(
matchSnapshot({ gameMode: 'pair', teamCount: 2 }),
@@ -372,9 +362,7 @@ describe('CompetitionBootstrapService', () => {
competitionResults: [duplicateKey, winner],
sessionCount: 2,
});
const service = new CompetitionBootstrapService(
harness.connectionService as ConnectionService,
);
const service = new CompetitionBootstrapService(harness.connectionService);
const result = await service.bootstrap(
matchSnapshot({ gameMode: 'pair', teamCount: 2 }),
@@ -391,9 +379,7 @@ describe('CompetitionBootstrapService', () => {
it('aborts when the Match is already linked to a different Competition', async () => {
const harness = createHarness({ matchUpdateResult: { matchedCount: 0 } });
const service = new CompetitionBootstrapService(
harness.connectionService as ConnectionService,
);
const service = new CompetitionBootstrapService(harness.connectionService);
await expect(
service.bootstrap(matchSnapshot({ gameMode: 'pair', teamCount: 2 })),
@@ -508,7 +494,7 @@ function createHarness(
const connectionService = {
createSession: jest.fn(() => Promise.resolve(sessions[sessionIndex++])),
getModel: jest.fn((name: string) => Promise.resolve(models[name])),
};
} as unknown as jest.Mocked<ConnectionService>;
return {
sessions,
@@ -22,9 +22,7 @@ describe('CompetitionCommandService', () => {
it('rejects a stale expected revision and aborts without writing', async () => {
const harness = createHarness({ competitionRevision: 8 });
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
const service = new CompetitionCommandService(harness.connectionService);
await expect(service.acceptGame(acceptGameCommand())).rejects.toMatchObject(
{
@@ -44,9 +42,7 @@ describe('CompetitionCommandService', () => {
it('uses the expected revision in the persistence CAS and aborts a lost race', async () => {
const harness = createHarness({ casResult: null });
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
const service = new CompetitionCommandService(harness.connectionService);
await expect(service.acceptGame(acceptGameCommand())).rejects.toMatchObject(
{
@@ -86,9 +82,7 @@ describe('CompetitionCommandService', () => {
return Promise.resolve([receipt]);
},
);
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
const service = new CompetitionCommandService(harness.connectionService);
const command = acceptGameCommand();
const first = await service.acceptGame(command);
@@ -133,9 +127,7 @@ describe('CompetitionCommandService', () => {
});
},
);
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
const service = new CompetitionCommandService(harness.connectionService);
await expect(
service.acceptGame(acceptGameCommand()),
@@ -162,9 +154,7 @@ describe('CompetitionCommandService', () => {
revision: 8,
}),
);
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
const service = new CompetitionCommandService(harness.connectionService);
await expect(service.acceptGame(acceptGameCommand())).rejects.toMatchObject(
{
@@ -180,9 +170,7 @@ describe('CompetitionCommandService', () => {
it('atomically accepts a code-backed game, projects it, and enqueues an event', async () => {
const harness = createHarness();
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
const service = new CompetitionCommandService(harness.connectionService);
const command = {
...acceptGameCommand(),
tournamentCode: {
@@ -279,9 +267,7 @@ describe('CompetitionCommandService', () => {
it('appends an administrative adjudication through the same command runner', async () => {
const harness = createHarness();
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
const service = new CompetitionCommandService(harness.connectionService);
const result = await service.adjudicateSeries({
competitionId: COMPETITION_ID,
@@ -316,9 +302,7 @@ describe('CompetitionCommandService', () => {
facts: reversal.facts,
assignments: reversal.assignments,
});
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
const service = new CompetitionCommandService(harness.connectionService);
const preview = await service.previewSeriesReversal({
competitionId: COMPETITION_ID,
@@ -348,9 +332,7 @@ describe('CompetitionCommandService', () => {
it('rejects a reversal preview at a stale revision', async () => {
const reversal = reversalFixture();
const harness = createHarness({ competition: reversal.competition });
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
const service = new CompetitionCommandService(harness.connectionService);
await expect(
service.previewSeriesReversal({
@@ -372,9 +354,7 @@ describe('CompetitionCommandService', () => {
facts: reversal.facts,
assignments: reversal.assignments,
});
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
const service = new CompetitionCommandService(harness.connectionService);
const preview = await service.previewSeriesReversal({
competitionId: COMPETITION_ID,
expectedRevision: 7,
@@ -485,9 +465,7 @@ describe('CompetitionCommandService', () => {
}),
)
.mockResolvedValueOnce([]);
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
const service = new CompetitionCommandService(harness.connectionService);
const preview = await service.previewSeriesReversal({
competitionId: COMPETITION_ID,
expectedRevision: 7,
@@ -635,7 +613,7 @@ function createHarness(
const connectionService = {
createSession: jest.fn().mockResolvedValue(session),
getModel: jest.fn((name: string) => Promise.resolve(models[name])),
};
} as unknown as jest.Mocked<ConnectionService>;
return {
session,
@@ -160,9 +160,7 @@ const SERIES_ID = 'series-1';
const GAME_SLOT_ID = 'slot-1';
function createService(harness: ReturnType<typeof createHarness>) {
return new CompetitionQueryService(
harness.connectionService as ConnectionService,
);
return new CompetitionQueryService(harness.connectionService);
}
function createHarness(options: { competition?: unknown } = {}) {
@@ -244,7 +242,7 @@ function createHarness(options: { competition?: unknown } = {}) {
factModel,
connectionService: {
getModel: jest.fn((name: string) => Promise.resolve(models[name])),
},
} as unknown as jest.Mocked<ConnectionService>,
};
}
@@ -127,7 +127,7 @@ describe('Competition persistence schemas', () => {
function expectIndexes(
schema: {
indexes(): Array<[Record<string, number>, Record<string, unknown>]>;
indexes(): ReturnType<typeof CompetitionSchema.indexes>;
},
expected: Array<{
keys: Record<string, number>;
@@ -589,9 +589,10 @@ function acceptedGameFactory(competitionId: string) {
};
}
function projectedSeries<
T extends { series: Array<{ code?: string; seriesId: string }> },
>(projection: T, code: string) {
function projectedSeries<T extends { code?: string; seriesId: string }>(
projection: { series: T[] },
code: string,
) {
const series = projection.series.find((candidate) => candidate.code === code);
if (!series) throw new Error(`Missing projected series ${code}`);
return series;
@@ -223,11 +223,21 @@ describe('DakaoUserService', () => {
puuid: 'puuid-1',
gameName: '기존소환사',
tagLine: 'KR1',
profileIconId: 1,
revisionDate: 0,
summonerLevel: 30,
tiers: [],
tierHistory: [],
matchIds: [],
championMasteries: [],
championRecords: {},
isPrimary: true,
createdAt: new Date('2026-05-03T00:00:00.000Z'),
updatedAt: new Date('2026-05-03T00:00:00.000Z'),
},
],
save,
} as Partial<UserDocument>,
} satisfies Partial<UserDocument>,
});
await expect(
@@ -35,7 +35,7 @@ describe('parseCommand', () => {
matchAndRiotId: '69b63bc96da18dfdb218ee8c 프리리#KR1',
});
if (result.kind === 'match-join') {
expect(result.positions.positions).toEqual(['MID', 'TOP']);
expect(result.positions?.positions).toEqual(['MID', 'TOP']);
}
});
@@ -62,9 +62,7 @@ describe('auction Redis schema foundation', () => {
expect(
AuctionHistoryEntrySchema.path('matchSideEffectMutation'),
).toBeDefined();
expect(
AuctionHistoryEntrySchema.path<string>('action').options.enum,
).toEqual(
expect(AuctionHistoryEntrySchema.path('action').options.enum).toEqual(
expect.arrayContaining([
'start',
'open-bidding',
@@ -1,8 +1,10 @@
import { migrateTeamIndex } from './20260502-team-index';
type MigrationDocument = Record<string, unknown> & { _id: unknown };
function createDb(params: {
auctions?: Array<Record<string, unknown>>;
matches?: Array<Record<string, unknown>>;
auctions?: MigrationDocument[];
matches?: MigrationDocument[];
}) {
const collections = {
auction: params.auctions ?? [],
@@ -40,6 +40,14 @@ describe('repair-double-elimination-series-rules buildRepairPlan', () => {
{
gameNumber: 1,
bracketMatchId: 'WB_R2_M1',
riotMatchId: 'KR_1',
blueTeamIndex: 4,
redTeamIndex: 6,
winnerTeamIndex: 4,
winnerSide: 'blue',
gameCreation: Date.parse('2026-05-03T00:00:00.000Z'),
gameDuration: 1800,
participants: [],
},
],
seriesResults: [],
@@ -59,16 +59,15 @@ describe('DistributedLockService', () => {
).resolves.toBe(true);
expect(sendCommand).toHaveBeenCalledWith([
'EVAL',
expect.stringContaining('redis.call("GET", KEYS[1]) == ARGV[1]'),
'1',
'DELEX',
'distributed-lock:test',
'IFEQ',
'owner-token',
]);
});
it('extends a lock only when the ownership token matches', async () => {
const sendCommand = jest.fn().mockResolvedValue(1);
const sendCommand = jest.fn().mockResolvedValue('OK');
const service = createService(sendCommand);
await expect(
@@ -83,11 +82,12 @@ describe('DistributedLockService', () => {
).resolves.toBe(true);
expect(sendCommand).toHaveBeenCalledWith([
'EVAL',
expect.stringContaining('PEXPIRE'),
'1',
'SET',
'distributed-lock:test',
'owner-token',
'IFEQ',
'owner-token',
'PX',
'45000',
]);
});
@@ -2,20 +2,6 @@ import { Injectable, Logger } from '@nestjs/common';
import { randomUUID } from 'crypto';
import { RedisService } from './redis.service';
const RELEASE_LOCK_IF_OWNED_SCRIPT = `
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
end
return 0
`;
const EXTEND_LOCK_IF_OWNED_SCRIPT = `
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("PEXPIRE", KEYS[1], ARGV[2])
end
return 0
`;
export interface DistributedLockOwnership {
lockKey: string;
lockOwnershipToken: string;
@@ -75,10 +61,9 @@ export class DistributedLockService {
const result = await this.redisService
.raw()
.sendCommand([
'EVAL',
RELEASE_LOCK_IF_OWNED_SCRIPT,
'1',
'DELEX',
lockOwnership.lockKey,
'IFEQ',
lockOwnership.lockOwnershipToken,
]);
return Number(result) === 1;
@@ -95,15 +80,10 @@ export class DistributedLockService {
const result = await this.redisService
.raw()
.sendCommand([
'EVAL',
EXTEND_LOCK_IF_OWNED_SCRIPT,
'1',
lockOwnership.lockKey,
lockOwnership.lockOwnershipToken,
String(lockExpirationDurationMilliseconds),
]);
return Number(result) === 1;
.sendCommand<
string | null
>(['SET', lockOwnership.lockKey, lockOwnership.lockOwnershipToken, 'IFEQ', lockOwnership.lockOwnershipToken, 'PX', String(lockExpirationDurationMilliseconds)]);
return result === 'OK';
}
public async runWithLock<TResult>(
@@ -1,12 +1,8 @@
import {
assertDistinctRedisInstances,
normalizeRedisUrl,
resolveRedisClientOptions,
} from './redis.config';
import { normalizeRedisUrl, resolveRedisClientOptions } from './redis.config';
describe('redis.config', () => {
it('normalizes host:port endpoints into redis URLs', () => {
expect(normalizeRedisUrl('127.0.0.1:6379', 'REDIS_ENDPOINT')).toBe(
expect(normalizeRedisUrl(' 127.0.0.1:6379 ')).toBe(
'redis://127.0.0.1:6379',
);
expect(normalizeRedisUrl('rediss://cache.example.com:6380')).toBe(
@@ -15,8 +11,8 @@ describe('redis.config', () => {
});
it('throws a clear error for empty endpoints', () => {
expect(() => normalizeRedisUrl(' ', 'REDIS_ENDPOINT')).toThrow(
'REDIS_ENDPOINT cannot be empty',
expect(() => normalizeRedisUrl(' ')).toThrow(
'GARNET_ENDPOINT cannot be empty',
);
});
@@ -26,34 +22,32 @@ describe('redis.config', () => {
endpoint: 'redis.internal:6379',
username: '',
password: undefined,
endpointEnvName: 'REDIS_ENDPOINT',
}),
).toEqual({
url: 'redis://redis.internal:6379',
});
});
it('rejects auction Redis when it points at the same physical Redis instance', () => {
expect(() =>
assertDistinctRedisInstances(
'redis://cache.internal:6379/0',
'redis://cache.internal:6379/1',
),
).toThrow('AUCTION_REDIS must use a separate Redis instance');
});
it.each([undefined, '', ' '])(
'rejects a missing or blank endpoint: %p',
(endpoint) => {
expect(() => resolveRedisClientOptions({ endpoint })).toThrow(
'GARNET_ENDPOINT cannot be empty',
);
},
);
it('allows different Redis hosts or ports', () => {
expect(() =>
assertDistinctRedisInstances(
'redis://cache.internal:6379',
'redis://auction.internal:6379',
),
).not.toThrow();
expect(() =>
assertDistinctRedisInstances(
'redis://cache.internal:6379',
'redis://cache.internal:6380',
),
).not.toThrow();
it('preserves TLS, database selection, and credentials', () => {
expect(
resolveRedisClientOptions({
endpoint: ' rediss://garnet.internal:6380/1 ',
username: ' garnet-user ',
password: ' garnet-password ',
}),
).toEqual({
url: 'rediss://garnet.internal:6380/1',
username: 'garnet-user',
password: 'garnet-password',
});
});
});
@@ -1,3 +1,5 @@
import type { SecretService } from '../secret/secret.service';
export interface RedisClientOptions {
password?: string;
url: string;
@@ -6,10 +8,7 @@ export interface RedisClientOptions {
export interface ResolveRedisClientOptionsParams {
endpoint?: string;
endpointEnvName?: string;
password?: string;
url?: string;
urlEnvName?: string;
username?: string;
}
@@ -18,13 +17,10 @@ function trimOptional(value: string | undefined): string | undefined {
return trimmed ? trimmed : undefined;
}
export function normalizeRedisUrl(
endpointOrUrl: string,
envName = 'REDIS_URL',
): string {
export function normalizeRedisUrl(endpointOrUrl: string): string {
const trimmed = endpointOrUrl.trim();
if (!trimmed) {
throw new Error(`${envName} cannot be empty`);
throw new Error('GARNET_ENDPOINT cannot be empty');
}
if (/^redis(s)?:\/\//iu.test(trimmed)) {
return trimmed;
@@ -35,19 +31,8 @@ export function normalizeRedisUrl(
export function resolveRedisClientOptions(
params: ResolveRedisClientOptionsParams,
): RedisClientOptions {
const url = trimOptional(params.url);
const endpoint = trimOptional(params.endpoint);
const selectedEndpoint = url ?? endpoint;
const selectedEnvName = url
? (params.urlEnvName ?? 'REDIS_URL')
: (params.endpointEnvName ?? 'REDIS_ENDPOINT');
if (!selectedEndpoint) {
throw new Error(`${selectedEnvName} cannot be empty`);
}
const options: RedisClientOptions = {
url: normalizeRedisUrl(selectedEndpoint, selectedEnvName),
url: normalizeRedisUrl(params.endpoint ?? ''),
};
const username = trimOptional(params.username);
const password = trimOptional(params.password);
@@ -56,22 +41,20 @@ export function resolveRedisClientOptions(
return options;
}
function parseRedisInstanceIdentity(redisUrl: string): string {
const url = new URL(normalizeRedisUrl(redisUrl));
const hostname = url.hostname.toLowerCase();
const port = url.port || '6379';
return `${hostname}:${port}`;
}
export async function loadRedisClientOptions(
secretService: Pick<SecretService, 'get' | 'ready'>,
): Promise<RedisClientOptions> {
await secretService.ready();
const [endpoint, username, userId, password] = await Promise.all([
secretService.get<string>('GARNET_ENDPOINT', ''),
secretService.get<string>('GARNET_USERNAME', ''),
secretService.get<string>('GARNET_USERID', ''),
secretService.get<string>('GARNET_PASSWORD', ''),
]);
export function assertDistinctRedisInstances(
redisUrl: string,
auctionRedisUrl: string,
): void {
const redisIdentity = parseRedisInstanceIdentity(redisUrl);
const auctionRedisIdentity = parseRedisInstanceIdentity(auctionRedisUrl);
if (redisIdentity === auctionRedisIdentity) {
throw new Error(
'AUCTION_REDIS must use a separate Redis instance from REDIS because auction Redis is a live state source of truth.',
);
}
return resolveRedisClientOptions({
endpoint,
password,
username: trimOptional(username) ?? userId,
});
}
@@ -0,0 +1,99 @@
import { Test } from '@nestjs/testing';
import { createClient } from 'redis';
import { AuctionRedisModule } from '../../auction/redis/auction-redis.module';
import { AuctionRedisService } from '../../auction/redis/auction-redis.service';
import { SecretService } from '../secret/secret.service';
import { RedisModule } from './redis.module';
import { RedisService, type RedisClient } from './redis.service';
jest.mock('redis', () => ({ createClient: jest.fn() }));
describe('shared Garnet instance', () => {
it.each([
{
name: 'only GARNET_ENDPOINT is configured',
secrets: { GARNET_ENDPOINT: 'garnet.internal:6379' },
options: { url: 'redis://garnet.internal:6379' },
},
{
name: 'existing Garnet credentials are configured',
secrets: {
GARNET_ENDPOINT: ' rediss://garnet.internal:6380/1 ',
GARNET_USERID: 'garnet-user',
GARNET_PASSWORD: 'garnet-password',
},
options: {
url: 'rediss://garnet.internal:6380/1',
username: 'garnet-user',
password: 'garnet-password',
},
},
{
name: 'obsolete Redis settings are also configured',
secrets: {
GARNET_ENDPOINT: 'garnet.internal:6379',
GARNET_USERNAME: 'garnet-user',
GARNET_PASSWORD: 'garnet-password',
GARNET_URL: 'redis://obsolete-garnet.internal:6379',
REDIS_URL: 'redis://obsolete-common.internal:6379',
REDIS_ENDPOINT: 'obsolete-common.internal:6379',
REDIS_USERNAME: 'obsolete-common-user',
REDIS_PASSWORD: 'obsolete-common-password',
AUCTION_REDIS_URL: 'redis://obsolete-common.internal:6379',
AUCTION_REDIS_ENDPOINT: 'obsolete-common.internal:6379',
AUCTION_REDIS_USERNAME: 'obsolete-auction-user',
AUCTION_REDIS_PASSWORD: 'obsolete-auction-password',
},
options: {
url: 'redis://garnet.internal:6379',
username: 'garnet-user',
password: 'garnet-password',
},
},
])('boots both Redis modules when $name', async ({ secrets, options }) => {
const values: Record<string, string | undefined> = secrets;
const secretService = {
ready: jest.fn().mockResolvedValue(undefined),
get: jest.fn((key: string, fallback: string) =>
Promise.resolve(values[key] ?? fallback),
),
};
const clients = Array.from({ length: 2 }, () => ({
connect: jest.fn().mockResolvedValue(undefined),
on: jest.fn(),
quit: jest.fn().mockResolvedValue(undefined),
destroy: jest.fn(),
}));
const createClientMock = jest.mocked(createClient);
createClientMock.mockReset();
for (const client of clients) {
createClientMock.mockReturnValueOnce(client as unknown as RedisClient);
}
const module = await Test.createTestingModule({
imports: [RedisModule, AuctionRedisModule],
})
.overrideProvider(SecretService)
.useValue(secretService)
.compile();
try {
await module.init();
expect(createClientMock).toHaveBeenCalledTimes(2);
for (let index = 0; index < clients.length; index++) {
expect(createClientMock).toHaveBeenNthCalledWith(index + 1, options);
expect(clients[index].connect).toHaveBeenCalledTimes(1);
}
expect(clients).toContain(module.get(RedisService).raw());
expect(clients).toContain(module.get(AuctionRedisService).raw());
expect(module.get(RedisService).raw()).not.toBe(
module.get(AuctionRedisService).raw(),
);
} finally {
await module.close();
}
for (const client of clients) {
expect(client.quit).toHaveBeenCalledTimes(1);
}
});
});
@@ -3,22 +3,10 @@ import { createClient } from 'redis';
import { SecretModule } from '../secret/secret.module';
import { SecretService } from '../secret/secret.service';
import { REDIS_CLIENT } from './redis.constants';
import { resolveRedisClientOptions } from './redis.config';
import { loadRedisClientOptions } from './redis.config';
import { DistributedLockService } from './distributed-lock.service';
import { RedisService, type RedisClient } from './redis.service';
async function readFirstSecret(
secretService: SecretService,
keys: string[],
): Promise<string | undefined> {
for (const key of keys) {
const value = await secretService.get<string>(key, '');
const trimmed = value.trim();
if (trimmed) return trimmed;
}
return undefined;
}
@Module({
imports: [SecretModule],
providers: [
@@ -28,30 +16,9 @@ async function readFirstSecret(
useFactory: async (
secretService: SecretService,
): Promise<RedisClient> => {
await secretService.ready();
const [url, endpoint, username, password] = await Promise.all([
readFirstSecret(secretService, ['REDIS_URL', 'GARNET_URL']),
readFirstSecret(secretService, ['REDIS_ENDPOINT', 'GARNET_ENDPOINT']),
readFirstSecret(secretService, [
'REDIS_USERNAME',
'REDIS_USERID',
'GARNET_USERNAME',
'GARNET_USERID',
]),
readFirstSecret(secretService, ['REDIS_PASSWORD', 'GARNET_PASSWORD']),
]);
const logger = new Logger('RedisClient');
const client = createClient(
resolveRedisClientOptions({
endpoint,
endpointEnvName: 'REDIS_ENDPOINT',
password,
url,
urlEnvName: 'REDIS_URL',
username,
}),
await loadRedisClientOptions(secretService),
);
client.on('error', (error: unknown) => {
@@ -5,6 +5,24 @@ function createRedisService(client: Record<string, unknown>) {
}
describe('RedisService stream pending recovery', () => {
it('destroys a dedicated client when connection startup fails without closing the shared client', async () => {
const error = new Error('connection failed');
const dedicated = {
on: jest.fn(),
connect: jest.fn().mockRejectedValue(error),
isOpen: true,
destroy: jest.fn(),
};
const shared = {
duplicate: jest.fn().mockReturnValue(dedicated),
destroy: jest.fn(),
};
const service = createRedisService(shared);
await expect(service.createDedicatedConnection()).rejects.toBe(error);
expect(dedicated.destroy).toHaveBeenCalledTimes(1);
expect(shared.destroy).not.toHaveBeenCalled();
});
it('normalizes XAUTOCLAIM array replies into stream entries', async () => {
const sendCommand = jest
.fn()
@@ -83,6 +83,20 @@ export class RedisService implements OnModuleDestroy {
return this.client;
}
public async createDedicatedConnection(): Promise<RedisService> {
const client = this.client.duplicate();
client.on('error', (error: unknown) => {
this.logger.warn(`Dedicated Redis connection error: ${String(error)}`);
});
try {
await client.connect();
return new RedisService(client);
} catch (error) {
if (client.isOpen) client.destroy();
throw error;
}
}
public async getJson<T>(key: string): Promise<T | null> {
const raw = await this.client.get(key);
if (!raw) return null;
@@ -142,6 +156,13 @@ export class RedisService implements OnModuleDestroy {
return this.client.del(key);
}
public async deleteStringIfEqual(
key: string,
value: string,
): Promise<number> {
return this.client.sendCommand<number>(['DELEX', key, 'IFEQ', value]);
}
public async appendStream(
key: string,
fields: Record<string, string>,
@@ -158,7 +179,10 @@ export class RedisService implements OnModuleDestroy {
}
: undefined;
return this.client.xAdd(key, '*', fields, trimOptions);
return this.client.xAdd(key, '*', fields, {
...trimOptions,
policy: 'ACKED',
});
}
public async createConsumerGroup(
@@ -174,11 +198,13 @@ export class RedisService implements OnModuleDestroy {
group: string,
consumer: string,
startId: string,
options?: { blockMs?: number; count?: number },
options?: { blockMs?: number; count?: number; claimMinIdleMs?: number },
): Promise<StreamReadResult[] | null> {
const readOptions: { BLOCK?: number; COUNT?: number } = {};
const readOptions: { BLOCK?: number; COUNT?: number; CLAIM?: number } = {};
if (options?.blockMs !== undefined) readOptions.BLOCK = options.blockMs;
if (options?.count !== undefined) readOptions.COUNT = options.count;
if (options?.claimMinIdleMs !== undefined)
readOptions.CLAIM = options.claimMinIdleMs;
const reply = await this.client.xReadGroup(
group,
@@ -244,6 +270,14 @@ export class RedisService implements OnModuleDestroy {
return this.client.xAck(key, group, ids);
}
public async acknowledgeAndDeleteStream(
key: string,
group: string,
ids: string | string[],
): Promise<void> {
await this.client.xAckDel(key, group, ids, 'ACKED');
}
public async deleteStreamEntries(
key: string,
ids: string | string[],
@@ -0,0 +1,183 @@
import { loadInfisicalSecrets } from './infisical-client';
const options = {
siteUrl: 'https://infisical.example.test/prefix',
clientId: 'test-client',
clientSecret: 'test-secret',
projectId: 'test-project',
environment: 'staging',
};
const secrets = [{ secretKey: 'TEST_SECRET', secretValue: 'value' }];
const json = (value: unknown, status = 200) =>
new Response(JSON.stringify(value), { status });
describe('Infisical bootstrap client', () => {
const originalFetch = global.fetch;
let fetchMock: jest.Mock;
beforeEach(() => {
fetchMock = jest.fn();
global.fetch = fetchMock;
});
afterEach(() => {
global.fetch = originalFetch;
jest.useRealTimers();
jest.restoreAllMocks();
});
it.each([
'https://infisical.example.test/prefix',
'https://infisical.example.test/prefix/',
])(
'preserves SDK URLs, auth headers and list defaults for %s',
async (siteUrl) => {
fetchMock
.mockResolvedValueOnce(json({ accessToken: 'token' }))
.mockResolvedValueOnce(json({ secrets }));
await expect(
loadInfisicalSecrets({ ...options, siteUrl }),
).resolves.toEqual({ secrets });
expect(fetchMock).toHaveBeenNthCalledWith(
1,
'https://infisical.example.test/prefix/api/v1/auth/universal-auth/login',
expect.objectContaining({
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
clientId: options.clientId,
clientSecret: options.clientSecret,
}),
}),
);
expect(fetchMock).toHaveBeenNthCalledWith(
2,
'https://infisical.example.test/prefix/api/v3/secrets/raw?workspaceId=test-project&environment=staging&expandSecretReferences=true&include_imports=false&recursive=false&viewSecretValue=true',
expect.objectContaining({
method: 'GET',
headers: { Authorization: 'Bearer token' },
}),
);
},
);
it('retries network errors and 429 using the same request', async () => {
jest.useFakeTimers();
jest.spyOn(Math, 'random').mockReturnValue(0.5);
fetchMock
.mockRejectedValueOnce(new Error('network error'))
.mockResolvedValueOnce(json({}, 429))
.mockResolvedValueOnce(json({ accessToken: 'token' }))
.mockResolvedValueOnce(json({ secrets }));
const result = loadInfisicalSecrets(options);
await jest.runAllTimersAsync();
await expect(result).resolves.toEqual({ secrets });
expect(fetchMock).toHaveBeenCalledTimes(4);
expect(fetchMock.mock.calls.slice(0, 3).map(([url]) => url)).toEqual(
Array(3).fill(
'https://infisical.example.test/prefix/api/v1/auth/universal-auth/login',
),
);
expect(jest.getTimerCount()).toBe(0);
});
it.each([401, 403, 500])(
'does not retry HTTP %i or fetch secrets after failed login',
async (status) => {
fetchMock.mockResolvedValueOnce(json({ message: 'test-secret' }, status));
await expect(loadInfisicalSecrets(options)).rejects.toThrow(
`failed with ${status}`,
);
expect(fetchMock).toHaveBeenCalledTimes(1);
},
);
it('stops after four retries and does not expose response bodies', async () => {
jest.useFakeTimers();
fetchMock.mockImplementation(() =>
Promise.resolve(json({ message: 'test-secret' }, 429)),
);
const error = loadInfisicalSecrets(options).catch(
(value: unknown) => value,
);
await jest.runAllTimersAsync();
expect(await error).toEqual(
expect.objectContaining({
message: expect.stringContaining('failed with 429'),
}),
);
expect(((await error) as Error).message).not.toContain('test-secret');
expect(fetchMock).toHaveBeenCalledTimes(5);
expect(jest.getTimerCount()).toBe(0);
});
it('aborts each stalled attempt after ten seconds and bounds the retries', async () => {
jest.useFakeTimers();
jest.spyOn(Math, 'random').mockReturnValue(0.5);
fetchMock.mockImplementation(
(_url: string, init: RequestInit) =>
new Promise((_resolve, reject) => {
init.signal!.addEventListener(
'abort',
() => reject(new Error('aborted')),
{ once: true },
);
}),
);
const error = loadInfisicalSecrets(options).catch(
(value: unknown) => value,
);
await jest.advanceTimersByTimeAsync(9_999);
expect(fetchMock).toHaveBeenCalledTimes(1);
expect((fetchMock.mock.calls[0][1] as RequestInit).signal!.aborted).toBe(
false,
);
await jest.runAllTimersAsync();
expect(await error).toEqual(new Error('aborted'));
expect(fetchMock).toHaveBeenCalledTimes(5);
expect(jest.getTimerCount()).toBe(0);
});
it.each([{}, { accessToken: '' }, { accessToken: 123 }])(
'rejects invalid login response %j',
async (login) => {
fetchMock.mockResolvedValueOnce(json(login));
await expect(loadInfisicalSecrets(options)).rejects.toThrow(
'did not return an access token',
);
expect(fetchMock).toHaveBeenCalledTimes(1);
},
);
it.each(['login', 'secrets'])(
'does not leak malformed %s response bodies through errors',
async (operation) => {
if (operation === 'secrets') {
fetchMock.mockResolvedValueOnce(json({ accessToken: 'token' }));
}
fetchMock.mockResolvedValueOnce(new Response('sensitive-secret'));
const error = await loadInfisicalSecrets(options).catch(
(value: unknown) => value,
);
expect(error).toHaveProperty(
'message',
'Infisical returned an invalid JSON response',
);
expect((error as Error).stack).not.toContain('sensitive-secret');
expect(fetchMock).toHaveBeenCalledTimes(operation === 'login' ? 1 : 2);
},
);
it.each([
{},
{ secrets: null },
{ secrets: [{ secretKey: 'KEY', secretValue: 123 }] },
])('rejects invalid secrets response %j', async (result) => {
fetchMock
.mockResolvedValueOnce(json({ accessToken: 'token' }))
.mockResolvedValueOnce(json(result));
await expect(loadInfisicalSecrets(options)).rejects.toThrow(
'invalid secrets response',
);
});
});
@@ -0,0 +1,123 @@
interface InfisicalOptions {
siteUrl: string;
clientId: string;
clientSecret: string;
projectId: string;
environment: string;
}
interface InfisicalSecret {
secretKey: string;
secretValue: string;
}
const REQUEST_TIMEOUT_MS = 10_000;
const MAX_RETRIES = 4;
/** The two Infisical operations used during SecretService initialization. */
export async function loadInfisicalSecrets(
options: InfisicalOptions,
): Promise<{ secrets: InfisicalSecret[] }> {
const baseUrl = options.siteUrl.endsWith('/')
? options.siteUrl
: `${options.siteUrl}/`;
const login = await requestJson(
new URL('api/v1/auth/universal-auth/login', baseUrl),
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
clientId: options.clientId,
clientSecret: options.clientSecret,
}),
},
);
if (
!isRecord(login) ||
typeof login.accessToken !== 'string' ||
!login.accessToken
) {
throw new Error('Infisical login did not return an access token');
}
// Preserve the SDK's v3 endpoint and defaults, including self-hosted URL prefixes.
const url = new URL('api/v3/secrets/raw', baseUrl);
url.search = new URLSearchParams({
workspaceId: options.projectId,
environment: options.environment,
expandSecretReferences: 'true',
include_imports: 'false',
recursive: 'false',
viewSecretValue: 'true',
}).toString();
const result = await requestJson(url, {
method: 'GET',
headers: { Authorization: `Bearer ${login.accessToken}` },
});
if (
!isRecord(result) ||
!Array.isArray(result.secrets) ||
!result.secrets.every(isSecret)
) {
throw new Error('Infisical returned an invalid secrets response');
}
return { secrets: result.secrets };
}
async function requestJson(url: URL, init: RequestInit): Promise<unknown> {
for (let attempt = 0; ; attempt += 1) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
let response: Response;
try {
response = await fetch(url.toString(), {
...init,
signal: controller.signal,
});
} catch (error) {
if (attempt >= MAX_RETRIES) throw error;
clearTimeout(timeout);
await retryDelay(attempt);
continue;
} finally {
clearTimeout(timeout);
}
// Match the SDK: retry network errors and 429, but not other HTTP errors.
if (response.status === 429 && attempt < MAX_RETRIES) {
await response.body?.cancel();
await retryDelay(attempt);
continue;
}
if (!response.ok) {
await response.body?.cancel();
throw new Error(
`Infisical ${init.method} ${url.pathname} failed with ${response.status}`,
);
}
try {
return await response.json();
} catch {
// JSON parse errors can contain secrets from the response body.
throw new Error('Infisical returned an invalid JSON response');
}
}
}
function retryDelay(attempt: number): Promise<void> {
const base = 1_000 * 2 ** attempt;
const delay = base + base * 0.2 * (Math.random() * 2 - 1);
return new Promise((resolve) => setTimeout(resolve, delay));
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
function isSecret(value: unknown): value is InfisicalSecret {
return (
isRecord(value) &&
typeof value.secretKey === 'string' &&
typeof value.secretValue === 'string'
);
}
@@ -9,6 +9,7 @@ function makeConfig(values: Record<string, string | undefined> = {}) {
describe('SecretService', () => {
const originalEnv = process.env;
const originalFetch = global.fetch;
let fetchMock: jest.Mock;
beforeEach(() => {
@@ -23,9 +24,94 @@ describe('SecretService', () => {
afterEach(() => {
process.env = originalEnv;
global.fetch = originalFetch;
jest.restoreAllMocks();
});
function infisicalConfig() {
return makeConfig({
SECRET_SOURCE: 'infisical',
INFISICAL_SITE_URL: 'https://infisical.example.test/',
INFISICAL_CLIENT_ID: 'test-client',
INFISICAL_CLIENT_SECRET: 'test-secret',
INFISICAL_PROJECT_ID: 'test-project',
CONFIG_FALLBACK: 'config-value',
});
}
it.each([
['prod', 'prod'],
['staging', 'staging'],
['dev', 'dev'],
['production', 'dev'],
])('preserves environment mapping %s -> %s', async (nodeEnv, environment) => {
process.env.NODE_ENV = nodeEnv;
fetchMock
.mockResolvedValueOnce(Response.json({ accessToken: 'token' }))
.mockResolvedValueOnce(Response.json({ secrets: [] }));
await new SecretService(infisicalConfig()).ready();
const url = new URL(fetchMock.mock.calls[1][0] as string);
expect(url.searchParams.get('environment')).toBe(environment);
});
it('shares initialization, caches secrets, and preserves empty values and fallbacks', async () => {
process.env.TEST_EMPTY = 'existing-value';
fetchMock
.mockResolvedValueOnce(Response.json({ accessToken: 'token' }))
.mockResolvedValueOnce(
Response.json({
secrets: [
{ secretKey: 'TEST_SECRET', secretValue: 'first' },
{ secretKey: 'TEST_SECRET', secretValue: 'last' },
{ secretKey: 'TEST_EMPTY', secretValue: '' },
],
imports: [
{ secrets: [{ secretKey: 'TEST_IMPORT', secretValue: 'ignored' }] },
],
}),
);
const service = new SecretService(infisicalConfig());
await Promise.all([
service.ready(),
service.get('TEST_SECRET'),
service.ready(),
]);
await expect(service.get('TEST_SECRET')).resolves.toBe('last');
await expect(service.get('TEST_EMPTY')).resolves.toBe('');
await expect(service.get('CONFIG_FALLBACK')).resolves.toBe('config-value');
await expect(service.get('TEST_IMPORT', 'missing')).resolves.toBe(
'missing',
);
expect(process.env.TEST_SECRET).toBe('last');
expect(process.env.TEST_EMPTY).toBe('existing-value');
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('does not publish partial secrets after failure and permits a later retry', async () => {
fetchMock
.mockResolvedValueOnce(Response.json({ accessToken: 'token' }))
.mockResolvedValueOnce(
Response.json({
secrets: [
{ secretKey: 'TEST_SECRET', secretValue: 'partial' },
{ secretKey: 'INVALID', secretValue: 123 },
],
}),
)
.mockResolvedValueOnce(Response.json({ accessToken: 'new-token' }))
.mockResolvedValueOnce(
Response.json({
secrets: [{ secretKey: 'TEST_SECRET', secretValue: 'complete' }],
}),
);
const service = new SecretService(infisicalConfig());
await expect(service.ready()).rejects.toThrow('invalid secrets response');
expect(process.env.TEST_SECRET).toBeUndefined();
await service.ready();
await expect(service.get('TEST_SECRET')).resolves.toBe('complete');
expect(fetchMock).toHaveBeenCalledTimes(4);
});
it('defaults to environment-provided secrets without IMDS lookup', async () => {
process.env.TEST_SECRET = 'from-env';
const service = new SecretService(makeConfig());
@@ -1,6 +1,6 @@
import { Injectable, Logger } from '@nestjs/common';
import { InfisicalSDK } from '@infisical/sdk';
import { ConfigService } from '@nestjs/config';
import { loadInfisicalSecrets } from './infisical-client';
type SecretMap = Record<string, string | undefined>;
type SecretSource = 'env' | 'infisical';
@@ -71,23 +71,14 @@ export class SecretService {
private async fetchInfisicalSecrets(): Promise<void> {
const bootstrapConfig = await this.resolveInfisicalBootstrapConfig();
const infisicalClient = new InfisicalSDK({
siteUrl: bootstrapConfig.siteUrl,
});
await infisicalClient.auth().universalAuth.login({
clientId: bootstrapConfig.clientId,
clientSecret: bootstrapConfig.clientSecret,
});
const res = await infisicalClient.secrets().listSecrets({
const res = await loadInfisicalSecrets({
...bootstrapConfig,
environment:
process.env.NODE_ENV === 'prod'
? 'prod'
: process.env.NODE_ENV === 'staging'
? 'staging'
: 'dev',
projectId: bootstrapConfig.projectId,
});
// 임시 객체에 채운 뒤 한 번에 교체(일관성 보장)
@@ -691,12 +691,20 @@ function createImportFixture() {
gameName: `player-${index + 1}`,
tagLine: 'KR1',
profileIconId: index + 1,
revisionDate: 0,
summonerLevel: 30,
tiers: [],
tierHistory: [],
matchIds: [],
championMasteries: [],
championRecords: {},
isPrimary: true,
createdAt: new Date('2026-07-12T00:00:00.000Z'),
updatedAt: new Date('2026-07-12T00:00:00.000Z'),
},
displayName: `player-${index + 1}`,
preferredPositions: [],
} as LegacyUserSnapshot,
} satisfies LegacyUserSnapshot,
]),
);
const participants = users.map(({ puuid }, index) => ({
@@ -3,6 +3,11 @@ import { presentPublicMatch } from './match-public.presenter';
describe('presentPublicMatch', () => {
it('whitelists recruiting fields and excludes result/code internals', () => {
const doubleElimination: NonNullable<
Parameters<typeof presentPublicMatch>[0]['doubleElimination']
> & { bracketMatches: Array<{ winnerTeamIndex: number }> } = {
bracketMatches: [{ winnerTeamIndex: 3 }],
};
const response = presentPublicMatch({
_id: oid('1'),
communityId: oid('2'),
@@ -60,7 +65,7 @@ describe('presentPublicMatch', () => {
tournamentCodeIds: [oid('6')],
tournamentCodes: [{ code: 'SECRET' }],
result: { winnerTeamIndex: 3, games: [], seriesResults: [] },
doubleElimination: { bracketMatches: [{ winnerTeamIndex: 3 }] },
doubleElimination,
resultPollState: { state: 'polling' },
legacyImportSource: { triggeringPuuid: 'secret' },
});
@@ -473,7 +473,7 @@ describe('MatchService', () => {
userId: targetUserId,
preferredPositions: [
{ position: 'TOP', priority: 1 },
{ position: 'JUNGLE', priority: 2 },
{ position: 'JGL', priority: 2 },
{ position: 'MID', priority: 3 },
],
},
@@ -489,7 +489,7 @@ describe('MatchService', () => {
communityId,
targetUserId,
mainPosition: 'MID',
subPosition: 'SUPPORT',
subPosition: 'SUP',
}),
).resolves.toBe(updatedMatch);
expect(MatchModel.findOneAndUpdate).toHaveBeenCalledWith(
@@ -503,9 +503,9 @@ describe('MatchService', () => {
$set: {
'participants.$[participant].preferredPositions': [
{ position: 'MID', priority: 1 },
{ position: 'SUPPORT', priority: 2 },
{ position: 'SUP', priority: 2 },
{ position: 'TOP', priority: 3 },
{ position: 'JUNGLE', priority: 4 },
{ position: 'JGL', priority: 4 },
],
},
},
@@ -9,7 +9,10 @@ import {
StaleAccountRepository,
} from './stale-account.repository';
type SchedulerInternals = BackgroundRefreshScheduler & {
type SchedulerInternals = Pick<
BackgroundRefreshScheduler,
keyof BackgroundRefreshScheduler
> & {
tick(): Promise<void>;
};
@@ -32,7 +35,7 @@ function candidate(puuid: string): StaleAccountCandidate {
function makeScheduler() {
const rawClient = {
sendCommand: jest.fn().mockResolvedValue(1),
sendCommand: jest.fn().mockResolvedValue([1, 1]),
};
const redis = {
getString: jest.fn().mockResolvedValue(null),
@@ -53,6 +56,7 @@ function makeScheduler() {
} as unknown as jest.Mocked<RiotRateLimiterService>;
const enrichmentService = {
markRefreshRequested: jest.fn().mockResolvedValue(undefined),
refreshRiotIdentity: jest.fn().mockResolvedValue('unchanged'),
enrichRiotAccount: jest.fn().mockResolvedValue(successResult()),
} as unknown as jest.Mocked<RiotAccountEnrichmentService>;
const staleAccountRepository = {
@@ -64,7 +68,7 @@ function makeScheduler() {
rateLimiter,
enrichmentService,
staleAccountRepository,
) as SchedulerInternals;
) as unknown as SchedulerInternals;
return {
scheduler,
@@ -83,7 +87,7 @@ describe('BackgroundRefreshScheduler', () => {
jest.restoreAllMocks();
});
it('schedules ticks without requiring RIOT_BG_REFRESH_ENABLED', () => {
it('schedules ticks without requiring RIOT_BG_REFRESH_ENABLED', async () => {
jest.useFakeTimers();
const setIntervalSpy = jest.spyOn(global, 'setInterval');
const { scheduler } = makeScheduler();
@@ -91,7 +95,7 @@ describe('BackgroundRefreshScheduler', () => {
scheduler.onModuleInit();
expect(setIntervalSpy).toHaveBeenCalledTimes(2);
scheduler.onModuleDestroy();
await scheduler.onModuleDestroy();
});
it('uses the dawn refresh gate ratio inside the KST background window', async () => {
@@ -134,7 +138,7 @@ describe('BackgroundRefreshScheduler', () => {
expect(staleAccountRepository.findStaleAccounts).not.toHaveBeenCalled();
});
it('marks and enriches each stale candidate without background precharge', async () => {
it('marks, refreshes identity, and enriches each stale candidate without background precharge', async () => {
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z'));
const { scheduler, enrichmentService, staleAccountRepository } =
makeScheduler();
@@ -149,11 +153,21 @@ describe('BackgroundRefreshScheduler', () => {
candidates[0].userId,
'puuid-1',
);
expect(enrichmentService.refreshRiotIdentity).toHaveBeenNthCalledWith(1, {
userId: candidates[0].userId,
puuid: 'puuid-1',
});
expect(enrichmentService.refreshRiotIdentity).toHaveBeenCalledTimes(2);
expect(enrichmentService.enrichRiotAccount).toHaveBeenNthCalledWith(2, {
userId: candidates[1].userId,
puuid: 'puuid-2',
options: { force: false },
});
expect(
enrichmentService.refreshRiotIdentity.mock.invocationCallOrder[0],
).toBeLessThan(
enrichmentService.enrichRiotAccount.mock.invocationCallOrder[0],
);
});
it('stops the candidate loop when the refresh gate closes mid-tick', async () => {
@@ -192,16 +206,33 @@ describe('BackgroundRefreshScheduler', () => {
expect(enrichmentService.enrichRiotAccount).toHaveBeenCalledTimes(2);
expect(rawClient.sendCommand).toHaveBeenCalledWith([
'INCR',
'riot:bg:fail:puuid-1',
]);
expect(rawClient.sendCommand).toHaveBeenCalledWith([
'EXPIRE',
'INCREX',
'riot:bg:fail:puuid-1',
'BYINT',
'1',
'EX',
'86400',
]);
});
it('continues statistics enrichment without a failure counter when identity refresh fails', async () => {
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z'));
const { scheduler, rawClient, enrichmentService, staleAccountRepository } =
makeScheduler();
const account = candidate('puuid-1');
staleAccountRepository.findStaleAccounts.mockResolvedValue([account]);
enrichmentService.refreshRiotIdentity.mockResolvedValueOnce('failed');
await scheduler.tick();
expect(enrichmentService.refreshRiotIdentity).toHaveBeenCalledWith({
userId: account.userId,
puuid: 'puuid-1',
});
expect(enrichmentService.enrichRiotAccount).toHaveBeenCalledTimes(1);
expect(rawClient.sendCommand).not.toHaveBeenCalled();
});
it('skips candidates already in failure backoff', async () => {
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z'));
const { scheduler, redis, enrichmentService, staleAccountRepository } =
@@ -217,6 +248,7 @@ describe('BackgroundRefreshScheduler', () => {
await scheduler.tick();
expect(enrichmentService.markRefreshRequested).not.toHaveBeenCalled();
expect(enrichmentService.refreshRiotIdentity).not.toHaveBeenCalled();
expect(enrichmentService.enrichRiotAccount).not.toHaveBeenCalled();
});
});
@@ -15,7 +15,10 @@ import {
} from '../global/redis/distributed-lock.service';
import { RedisService } from '../global/redis/redis.service';
import { isInKstBackgroundWindow } from './kst-window.util';
import { StaleAccountRepository } from './stale-account.repository';
import {
type StaleAccountCandidate,
StaleAccountRepository,
} from './stale-account.repository';
const TICK_INTERVAL_MS = 60_000;
const LEADER_LOCK_KEY = 'distributed-lock:riot-background-refresh:leader';
@@ -133,6 +136,7 @@ export class BackgroundRefreshScheduler
candidate.userId,
candidate.puuid,
);
await this.refreshRiotIdentity(candidate);
try {
const result = await this.enrichmentService.enrichRiotAccount({
@@ -165,6 +169,28 @@ export class BackgroundRefreshScheduler
);
}
private async refreshRiotIdentity(
candidate: StaleAccountCandidate,
): Promise<void> {
try {
const result = await this.enrichmentService.refreshRiotIdentity({
userId: candidate.userId,
puuid: candidate.puuid,
});
if (result !== 'failed') return;
this.logger.warn(
`Background Riot identity refresh failed for ${candidate.puuid}.`,
);
} catch (err) {
this.logger.warn(
`Background Riot identity refresh failed for ${candidate.puuid}: ${
err instanceof Error ? err.message : String(err)
}`,
);
}
}
private currentRefreshGatePolicy(): RefreshGatePolicy {
const isDawn = isInKstBackgroundWindow();
return {
@@ -225,14 +251,16 @@ export class BackgroundRefreshScheduler
private async bumpFailureCounter(puuid: string): Promise<void> {
const key = this.failureBackoffKey(puuid);
const client = this.redis.raw();
const response = await client.sendCommand(['INCR', key]);
await client.sendCommand([
'EXPIRE',
const response = await client.sendCommand([
'INCREX',
key,
'BYINT',
'1',
'EX',
String(FAILURE_BACKOFF_TTL_SECONDS),
]);
const count = Number(response ?? 0);
const count = Number(Array.isArray(response) ? response[0] : 0);
if (Number.isFinite(count) && count >= FAILURE_BACKOFF_THRESHOLD) {
this.logger.warn(
`Background Riot refresh backoff enabled for ${puuid} after ${count} failures.`,
@@ -0,0 +1,22 @@
export const PROMOTE_SCHEDULED_RIOT_JOB_SCRIPT = `
local score = redis.call('ZSCORE', KEYS[1], ARGV[1])
if not score or tonumber(score) > tonumber(ARGV[2]) then
return 0
end
-- Append before removing: a failed XADD must leave the job retryable.
-- Script atomicity prevents a second promoter from appending the same member.
redis.call('XADD', KEYS[2], 'ACKED', 'MAXLEN', '~', '10000', '*', 'job', ARGV[1])
redis.call('ZREM', KEYS[1], ARGV[1])
return 1
`;
export const RESCHEDULE_TOURNAMENT_RESULT_POLL_SCRIPT = `
local pending = redis.call('XPENDING', KEYS[1], ARGV[1], ARGV[2], ARGV[2], 1)
if #pending == 0 then
return 0
end
-- Persist first: even a command error must never acknowledge unsaved work.
redis.call('ZADD', KEYS[2], ARGV[3], ARGV[4])
redis.call('XACKDEL', KEYS[1], ARGV[1], 'ACKED', 'IDS', 1, ARGV[2])
return 1
`;
@@ -6,6 +6,10 @@ import {
NotFoundException,
} from '@nestjs/common';
import { randomUUID } from 'crypto';
import {
PROMOTE_SCHEDULED_RIOT_JOB_SCRIPT,
RESCHEDULE_TOURNAMENT_RESULT_POLL_SCRIPT,
} from './riot-job-queue.scripts';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import type {
@@ -23,6 +27,7 @@ import {
EnqueueRefreshResult,
RIOT_JOB_AVG_SECONDS,
RIOT_JOB_DEDUP_TTL_SECONDS,
RIOT_JOB_GROUP,
RIOT_JOB_HIGH_COOLDOWN_SECONDS,
RIOT_JOB_HIGH_STREAM,
RIOT_JOB_LOW_COOLDOWN_SECONDS,
@@ -213,13 +218,41 @@ export class RiotJobQueueService {
};
}
public async rescheduleTournamentResultPoll(params: {
stream: string;
entryId: string;
job: PollTournamentResultJob;
}): Promise<void> {
const retryCount = (params.job.retryCount ?? 0) + 1;
const retryJob: PollTournamentResultJob = { ...params.job, retryCount };
const delayMs = Math.min(
30_000 * 2 ** Math.min(retryCount - 1, 4),
300_000,
);
// Keep job identity stable so a recovered delivery shares its processing lock.
await this.redisService
.raw()
.sendCommand([
'EVAL',
RESCHEDULE_TOURNAMENT_RESULT_POLL_SCRIPT,
'2',
params.stream,
RIOT_JOB_SCHEDULED_ZSET,
RIOT_JOB_GROUP,
params.entryId,
String(Date.now() + delayMs),
JSON.stringify(retryJob),
]);
}
public async promoteDueScheduledJobs(limit = 100): Promise<number> {
const client = this.redisService.raw();
const now = Date.now();
const entries = await client.sendCommand<string[]>([
'ZRANGEBYSCORE',
RIOT_JOB_SCHEDULED_ZSET,
'-inf',
String(Date.now()),
String(now),
'LIMIT',
'0',
String(limit),
@@ -227,16 +260,22 @@ export class RiotJobQueueService {
let promoted = 0;
for (const entry of entries) {
const removed = await client.sendCommand<number>([
'ZREM',
RIOT_JOB_SCHEDULED_ZSET,
entry,
]);
if (removed !== 1) continue;
const job = this.parseScheduledJob(entry);
if (!job) continue;
await this.appendJob(job);
promoted += 1;
if (!job) {
await client.zRem(RIOT_JOB_SCHEDULED_ZSET, entry);
continue;
}
promoted += Number(
await client.sendCommand([
'EVAL',
PROMOTE_SCHEDULED_RIOT_JOB_SCRIPT,
'2',
RIOT_JOB_SCHEDULED_ZSET,
this.resolveStream(job.priority),
entry,
String(now),
]),
);
}
return promoted;
@@ -300,7 +339,10 @@ export class RiotJobQueueService {
};
await Promise.all([
this.setStatus(next),
this.redisService.delete(this.dedupKey(job.puuid, job.queueGroup)),
this.redisService.deleteStringIfEqual(
this.dedupKey(job.puuid, job.queueGroup),
job.jobId,
),
]);
return this.toEvent(next);
}
@@ -321,7 +363,10 @@ export class RiotJobQueueService {
};
await Promise.all([
this.setStatus(next),
this.redisService.delete(this.dedupKey(job.puuid, job.queueGroup)),
this.redisService.deleteStringIfEqual(
this.dedupKey(job.puuid, job.queueGroup),
job.jobId,
),
]);
return this.toEvent(next);
}
@@ -0,0 +1,159 @@
import type { StreamEntry } from '../global/redis/redis.service';
import type { PollTournamentResultJob } from '../tournament-result/tournament-result.types';
import { RiotJobWorkerService } from './riot-job-worker.service';
import { RIOT_JOB_HIGH_STREAM } from './riot-job-queue.types';
const job: PollTournamentResultJob = {
kind: 'poll-tournament-result',
jobId: 'poll-1',
matchId: 'match-1',
attempt: 3,
expandedToAllPuuids: true,
enqueuedAt: 1,
priority: 'high',
};
function harness() {
const entry: StreamEntry = {
id: '1-0',
message: { job: JSON.stringify(job) },
};
const pending = new Set([entry.id]);
const scheduled: PollTournamentResultJob[] = [];
const processPollJob = jest.fn().mockResolvedValue(undefined);
const acknowledge = jest.fn().mockImplementation(async () => {
pending.delete(entry.id);
await Promise.resolve();
});
const reschedule = jest
.fn()
.mockImplementation(
async (params: {
stream: string;
entryId: string;
job: PollTournamentResultJob;
}) => {
scheduled.push(params.job);
pending.delete(params.entryId);
await Promise.resolve();
},
);
const locks = {
runWithRenewedLock: jest
.fn()
.mockImplementation(
async (_options: unknown, operation: () => Promise<unknown>) =>
operation(),
),
};
const worker = new RiotJobWorkerService(
{ acknowledgeAndDeleteStream: acknowledge } as never,
locks as never,
{ rescheduleTournamentResultPoll: reschedule } as never,
{} as never,
{} as never,
{} as never,
{ processPollJob } as never,
{} as never,
{} as never,
);
const process = () =>
(
worker as unknown as {
processEntry(stream: string, entry: StreamEntry): Promise<void>;
}
).processEntry(RIOT_JOB_HIGH_STREAM, entry);
return {
entry,
pending,
scheduled,
processPollJob,
acknowledge,
reschedule,
locks,
process,
};
}
describe('Tournament result worker retry delivery', () => {
it.each(['match lock unavailable', 'database write failed'])(
'preserves failed work in delayed retry instead of completing it: %s',
async (reason) => {
const h = harness();
h.processPollJob.mockRejectedValue(new Error(reason));
await h.process();
expect(h.scheduled).toEqual([job]);
expect(h.pending.size).toBe(0);
expect(h.acknowledge).not.toHaveBeenCalled();
},
);
it('leaves the original pending when saving the delayed retry fails', async () => {
const h = harness();
h.processPollJob.mockRejectedValue(new Error('database write failed'));
h.reschedule.mockRejectedValue(new Error('Redis unavailable'));
await expect(h.process()).rejects.toThrow('Redis unavailable');
expect(h.pending.has(h.entry.id)).toBe(true);
expect(h.scheduled).toEqual([]);
expect(h.acknowledge).not.toHaveBeenCalled();
});
it('retains the original while retry persistence is still in flight', async () => {
const h = harness();
h.processPollJob.mockRejectedValue(new Error('match lock unavailable'));
let releaseRetry!: () => void;
let retryStarted!: () => void;
const started = new Promise<void>((resolve) => {
retryStarted = resolve;
});
const retry = new Promise<void>((resolve) => {
releaseRetry = resolve;
});
h.reschedule.mockImplementation(async () => {
retryStarted();
await retry;
h.scheduled.push(job);
h.pending.delete(h.entry.id);
});
const processing = h.process();
// Race against completion so the buggy worker fails instead of hanging.
await Promise.race([started, processing]);
try {
expect(h.pending.has(h.entry.id)).toBe(true);
expect(h.acknowledge).not.toHaveBeenCalled();
} finally {
releaseRetry();
await processing;
}
});
it('acknowledges successfully processed work without scheduling retry', async () => {
const h = harness();
await h.process();
expect(h.pending.size).toBe(0);
expect(h.scheduled).toEqual([]);
expect(h.acknowledge).toHaveBeenCalledTimes(1);
});
it('does not acknowledge work owned by another job worker', async () => {
const h = harness();
h.locks.runWithRenewedLock.mockResolvedValue(null);
await h.process();
expect(h.pending.has(h.entry.id)).toBe(true);
expect(h.processPollJob).not.toHaveBeenCalled();
expect(h.scheduled).toEqual([]);
});
it('leaves a successful job pending if its acknowledgement fails', async () => {
const h = harness();
h.acknowledge.mockRejectedValue(new Error('acknowledgement unavailable'));
await expect(h.process()).rejects.toThrow('acknowledgement unavailable');
expect(h.pending.has(h.entry.id)).toBe(true);
expect(h.scheduled).toEqual([]);
});
});
@@ -1,12 +1,17 @@
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import { DistributedLockService } from '../global/redis/distributed-lock.service';
import { RedisService } from '../global/redis/redis.service';
import { RedisService, StreamEntry } from '../global/redis/redis.service';
import { LegacyImportService } from '../legacy-import/legacy-import.service';
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
import { RiotRecentMatchesService } from '../riot/riot-recent-matches.service';
import { TournamentResultService } from '../tournament-result/tournament-result.service';
import { RIOT_JOB_GROUP, RiotRefreshSubJob } from './riot-job-queue.types';
import {
RIOT_JOB_GROUP,
RIOT_JOB_HIGH_STREAM,
RIOT_JOB_LOW_STREAM,
RiotRefreshSubJob,
} from './riot-job-queue.types';
import { RiotJobQueueService } from './riot-job-queue.service';
import { RiotJobWorkerService } from './riot-job-worker.service';
import { RiotRefreshGateway } from './riot-refresh.gateway';
@@ -16,9 +21,17 @@ function execResult<T>(value: T) {
}
function makeWorker() {
const readerClient = { isOpen: true, destroy: jest.fn() };
const streamReader = {
raw: jest.fn().mockReturnValue(readerClient),
readGroup: jest.fn().mockResolvedValue(null),
} as unknown as jest.Mocked<RedisService>;
const redisService = {
acknowledgeStream: jest.fn().mockResolvedValue(undefined),
deleteStreamEntries: jest.fn().mockResolvedValue(undefined),
acknowledgeAndDeleteStream: jest.fn().mockResolvedValue(undefined),
createConsumerGroup: jest.fn().mockResolvedValue(undefined),
createDedicatedConnection: jest.fn().mockResolvedValue(streamReader),
raw: jest.fn(),
readGroup: jest.fn(),
} as unknown as jest.Mocked<RedisService>;
const distributedLockService = {
runWithRenewedLock: jest
@@ -33,6 +46,7 @@ function makeWorker() {
),
} as unknown as jest.Mocked<DistributedLockService>;
const jobQueueService = {
promoteDueScheduledJobs: jest.fn().mockResolvedValue(0),
markProcessing: jest.fn().mockResolvedValue(undefined),
markCompleted: jest.fn().mockResolvedValue({
parentJobId: 'parent-1',
@@ -62,6 +76,7 @@ function makeWorker() {
processMemberJob: jest.fn(),
} as unknown as jest.Mocked<LegacyImportService>;
const enrichmentService = {
refreshRiotIdentity: jest.fn().mockResolvedValue('unchanged'),
refreshLeagueEntries: jest.fn().mockResolvedValue('updated'),
} as unknown as jest.Mocked<RiotAccountEnrichmentService>;
@@ -86,10 +101,106 @@ function makeWorker() {
connectionService,
refreshGateway,
enrichmentService,
streamReader,
readerClient,
};
}
type WorkerInternals = {
stopped: boolean;
loop(): Promise<void>;
tryBecomeLeader(): Promise<boolean>;
readOne(
stream: string,
blockMs: number,
): Promise<{ stream: string; message: StreamEntry } | null>;
processEntry(stream: string, entry: StreamEntry): Promise<void>;
};
describe('RiotJobWorkerService', () => {
it('connects a dedicated reader after creating groups and only closes that reader', async () => {
const { worker, redisService, streamReader, readerClient } = makeWorker();
const internal = worker as unknown as WorkerInternals;
jest.spyOn(internal, 'loop').mockResolvedValue(undefined);
await worker.onModuleInit();
expect(redisService.createConsumerGroup).toHaveBeenCalledWith(
RIOT_JOB_HIGH_STREAM,
RIOT_JOB_GROUP,
);
expect(redisService.createConsumerGroup).toHaveBeenCalledWith(
RIOT_JOB_LOW_STREAM,
RIOT_JOB_GROUP,
);
expect(
redisService.createConsumerGroup.mock.invocationCallOrder[1],
).toBeLessThan(
redisService.createDedicatedConnection.mock.invocationCallOrder[0],
);
await internal.readOne(RIOT_JOB_HIGH_STREAM, 100);
expect(streamReader.readGroup).toHaveBeenCalledWith(
RIOT_JOB_HIGH_STREAM,
RIOT_JOB_GROUP,
expect.any(String),
'>',
{ count: 1, blockMs: 100, claimMinIdleMs: 1800000 },
);
expect(redisService.readGroup).not.toHaveBeenCalled();
await worker.onModuleDestroy();
expect(readerClient.destroy).toHaveBeenCalledTimes(1);
expect(redisService.raw).not.toHaveBeenCalled();
expect(internal.stopped).toBe(true);
});
it.each([true, false])(
'preserves high-before-low consumption (high available: %s)',
async (highAvailable) => {
const { worker, jobQueueService } = makeWorker();
const internal = worker as unknown as WorkerInternals;
const entry = { id: '1-0', message: { job: '{}' } };
jest.spyOn(internal, 'tryBecomeLeader').mockResolvedValue(true);
const read = jest
.spyOn(internal, 'readOne')
.mockImplementation(async (stream) => {
if (stream === RIOT_JOB_HIGH_STREAM && !highAvailable) return null;
return { stream, message: entry };
});
const process = jest
.spyOn(internal, 'processEntry')
.mockImplementation(async () => {
internal.stopped = true;
});
await internal.loop();
expect(jobQueueService.promoteDueScheduledJobs).toHaveBeenCalledTimes(1);
expect(read.mock.calls).toEqual(
highAvailable
? [[RIOT_JOB_HIGH_STREAM, 100]]
: [
[RIOT_JOB_HIGH_STREAM, 100],
[RIOT_JOB_LOW_STREAM, 1000],
],
);
expect(process).toHaveBeenCalledWith(
highAvailable ? RIOT_JOB_HIGH_STREAM : RIOT_JOB_LOW_STREAM,
entry,
);
},
);
it('does not start processing a message returned during shutdown', async () => {
const { worker } = makeWorker();
const internal = worker as unknown as WorkerInternals;
jest.spyOn(internal, 'tryBecomeLeader').mockResolvedValue(true);
jest.spyOn(internal, 'readOne').mockImplementation(async (stream) => {
await worker.onModuleDestroy();
return { stream, message: { id: '1-0', message: {} } };
});
const process = jest.spyOn(internal, 'processEntry');
await internal.loop();
expect(process).not.toHaveBeenCalled();
});
it('acknowledges and deletes invalid stream entries', async () => {
const { worker, redisService } = makeWorker();
@@ -105,20 +216,21 @@ describe('RiotJobWorkerService', () => {
message: { job: 'not-json' },
});
expect(redisService.acknowledgeStream).toHaveBeenCalledWith(
expect(redisService.acknowledgeAndDeleteStream).toHaveBeenCalledWith(
'riot:queue:high',
RIOT_JOB_GROUP,
'bad-1',
);
expect(redisService.deleteStreamEntries).toHaveBeenCalledWith(
'riot:queue:high',
'bad-1',
);
});
it('refreshes league entries while processing user history refresh jobs', async () => {
const { worker, enrichmentService, recentMatchesService, redisService } =
makeWorker();
it('refreshes Riot identity and league entries while processing user history refresh jobs', async () => {
const {
worker,
enrichmentService,
recentMatchesService,
redisService,
jobQueueService,
} = makeWorker();
const userId = new mongoose.Types.ObjectId().toString();
const job: RiotRefreshSubJob = {
jobId: 'job-1',
@@ -146,24 +258,67 @@ describe('RiotJobWorkerService', () => {
});
expect(recentMatchesService.ensureFreshForQueue).toHaveBeenCalledTimes(2);
expect(enrichmentService.refreshRiotIdentity).toHaveBeenCalledWith({
userId: expect.any(mongoose.Types.ObjectId),
puuid: 'puuid-1',
region: 'asia',
});
expect(enrichmentService.refreshLeagueEntries).toHaveBeenCalledWith({
userId: expect.any(mongoose.Types.ObjectId),
puuid: 'puuid-1',
platform: 'kr',
});
expect(redisService.acknowledgeStream).toHaveBeenCalledWith(
expect(
enrichmentService.refreshRiotIdentity.mock.invocationCallOrder[0],
).toBeLessThan(jobQueueService.markCompleted.mock.invocationCallOrder[0]);
expect(redisService.acknowledgeAndDeleteStream).toHaveBeenCalledWith(
'riot:queue:high',
RIOT_JOB_GROUP,
'1-0',
);
expect(redisService.deleteStreamEntries).toHaveBeenCalledWith(
'riot:queue:high',
'1-0',
);
expect(
redisService.acknowledgeStream.mock.invocationCallOrder[0],
jobQueueService.markCompleted.mock.invocationCallOrder[0],
).toBeLessThan(
redisService.deleteStreamEntries.mock.invocationCallOrder[0],
redisService.acknowledgeAndDeleteStream.mock.invocationCallOrder[0],
);
});
it('completes successful match refresh work when Riot identity lookup throws', async () => {
const { worker, enrichmentService, jobQueueService, refreshGateway } =
makeWorker();
enrichmentService.refreshRiotIdentity.mockRejectedValueOnce(
new Error('Account-V1 unavailable'),
);
const job: RiotRefreshSubJob = {
jobId: 'job-1',
parentJobId: 'parent-1',
userId: new mongoose.Types.ObjectId().toString(),
puuid: 'puuid-1',
region: 'asia',
platform: 'kr',
queueGroup: 'summoners-rift',
queueIds: [420],
requestedAt: Date.now(),
priority: 'high',
};
await (
worker as unknown as {
processEntry: (
stream: string,
entry: { id: string; message: Record<string, string> },
) => Promise<void>;
}
).processEntry('riot:queue:high', {
id: '1-0',
message: { job: JSON.stringify(job) },
});
expect(enrichmentService.refreshRiotIdentity).toHaveBeenCalledTimes(1);
expect(jobQueueService.markCompleted).toHaveBeenCalledWith(job);
expect(jobQueueService.markFailed).not.toHaveBeenCalled();
expect(refreshGateway.broadcastRefreshEvent).toHaveBeenCalledWith(
expect.objectContaining({ state: 'completed' }),
);
});
@@ -196,7 +351,6 @@ describe('RiotJobWorkerService', () => {
message: { job: JSON.stringify(job) },
});
expect(redisService.acknowledgeStream).not.toHaveBeenCalled();
expect(redisService.deleteStreamEntries).not.toHaveBeenCalled();
expect(redisService.acknowledgeAndDeleteStream).not.toHaveBeenCalled();
});
});
@@ -33,7 +33,6 @@ const RIOT_JOB_WORKER_LEADER_LOCK_EXPIRATION_DURATION_MILLISECONDS = 60_000;
const RIOT_JOB_PROCESSING_LOCK_EXPIRATION_DURATION_MILLISECONDS = 30 * 60_000;
const RIOT_JOB_PROCESSING_LOCK_RENEWAL_INTERVAL_MILLISECONDS = 5 * 60_000;
const STALE_PENDING_MESSAGE_MINIMUM_IDLE_MILLISECONDS = 30 * 60_000;
const STALE_PENDING_MESSAGE_CLAIM_COUNT = 1;
@Injectable()
export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
@@ -41,6 +40,7 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
private readonly consumerIdentifier = `${process.pid}:${Math.random().toString(36).slice(2)}`;
private leaderLockOwnership: DistributedLockOwnership | undefined;
private stopped = false;
private streamReader?: RedisService;
constructor(
private readonly redisService: RedisService,
@@ -56,11 +56,14 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
public async onModuleInit() {
await this.ensureConsumerGroups();
this.streamReader = await this.redisService.createDedicatedConnection();
void this.loop();
}
public async onModuleDestroy() {
this.stopped = true;
// Interrupt a blocking read without delaying shutdown or other Redis users.
if (this.streamReader?.raw().isOpen) this.streamReader.raw().destroy();
if (!this.leaderLockOwnership) return;
await this.distributedLockService
.releaseLockIfOwned(this.leaderLockOwnership)
@@ -78,6 +81,7 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
while (!this.stopped) {
try {
const isLeader = await this.tryBecomeLeader();
if (this.stopped) break;
if (!isLeader) {
await this.sleep(1_000);
continue;
@@ -85,14 +89,14 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
await this.jobQueueService.promoteDueScheduledJobs();
const entry =
(await this.readOneStalePendingMessage(RIOT_JOB_HIGH_STREAM)) ??
(await this.readOne(RIOT_JOB_HIGH_STREAM, 100)) ??
(await this.readOneStalePendingMessage(RIOT_JOB_LOW_STREAM)) ??
(await this.readOne(RIOT_JOB_LOW_STREAM, 1_000));
if (this.stopped) break;
if (!entry) continue;
await this.processEntry(entry.stream, entry.message);
} catch (error) {
if (this.stopped) break;
this.logger.warn(
`Riot job worker loop failed: ${
error instanceof Error ? error.message : error
@@ -113,7 +117,7 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
return;
}
const didProcessJob = await this.distributedLockService.runWithRenewedLock(
const outcome = await this.distributedLockService.runWithRenewedLock(
{
lockKey: this.jobProcessingLockKey(job),
lockExpirationDurationMilliseconds:
@@ -122,19 +126,38 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
RIOT_JOB_PROCESSING_LOCK_RENEWAL_INTERVAL_MILLISECONDS,
},
async () => {
await this.processJob(job);
return true;
try {
await this.processJob(job);
return 'completed' as const;
} catch (error) {
if (!this.isTournamentResultJob(job)) throw error;
this.logger.warn(
`Retrying tournament result poll job ${job.jobId} for match ${job.matchId}: ${
error instanceof Error ? error.message : String(error)
}`,
);
// The handoff saves retry work before acknowledging the original.
// If it fails, leave the original pending for abandoned-job recovery.
await this.jobQueueService.rescheduleTournamentResultPoll({
stream,
entryId: entry.id,
job,
});
return 'rescheduled' as const;
}
},
);
if (!didProcessJob) {
if (!outcome) {
this.logger.debug(
`Skipped Riot job ${job.jobId}; another worker still owns the processing lock.`,
);
return;
}
await this.acknowledgeAndDelete(stream, entry.id);
if (outcome === 'completed') {
await this.acknowledgeAndDelete(stream, entry.id);
}
}
private async processJob(job: RiotJobPayload): Promise<void> {
@@ -156,18 +179,14 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
queueId,
});
}
await this.refreshRiotIdentity(job);
await this.refreshLeagueEntries(job);
await this.markUserFetchedAt(job);
const event = await this.jobQueueService.markCompleted(job);
this.refreshGateway.broadcastRefreshEvent(event);
} catch (error) {
if (this.isTournamentResultJob(job)) {
this.logger.warn(
`Tournament result poll job failed ${job.jobId}: ${
error instanceof Error ? error.message : error
}`,
);
return;
throw error;
}
if (this.isLegacyImportJob(job)) {
this.logger.warn(
@@ -192,19 +211,27 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
stream: string,
id: string,
): Promise<void> {
await this.redisService.acknowledgeStream(stream, RIOT_JOB_GROUP, id);
await this.deleteAcknowledgedEntry(stream, id);
await this.redisService.acknowledgeAndDeleteStream(
stream,
RIOT_JOB_GROUP,
id,
);
}
private async deleteAcknowledgedEntry(
stream: string,
id: string,
): Promise<void> {
private async refreshRiotIdentity(job: RiotRefreshSubJob): Promise<void> {
try {
await this.redisService.deleteStreamEntries(stream, id);
const result = await this.enrichmentService.refreshRiotIdentity({
userId: new mongoose.Types.ObjectId(job.userId),
puuid: job.puuid,
region: job.region,
});
if (result !== 'failed') return;
this.logger.warn(
`Riot identity refresh failed ${job.jobId}: puuid=${job.puuid}`,
);
} catch (error) {
this.logger.warn(
`Failed to delete acknowledged Riot job stream entry ${stream} ${id}: ${
`Riot identity refresh failed ${job.jobId}: ${
error instanceof Error ? error.message : error
}`,
);
@@ -273,32 +300,23 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
stream: string,
blockMs: number,
): Promise<{ stream: string; message: StreamEntry } | null> {
const result = await this.redisService.readGroup(
if (!this.streamReader)
throw new Error('Riot stream reader is not connected.');
const result = await this.streamReader.readGroup(
stream,
RIOT_JOB_GROUP,
this.consumerIdentifier,
'>',
{ count: 1, blockMs },
{
count: 1,
blockMs,
claimMinIdleMs: STALE_PENDING_MESSAGE_MINIMUM_IDLE_MILLISECONDS,
},
);
const message = result?.[0]?.messages[0];
return message ? { stream, message } : null;
}
private async readOneStalePendingMessage(
stream: string,
): Promise<{ stream: string; message: StreamEntry } | null> {
const result = await this.redisService.claimStalePendingStreamMessages({
key: stream,
group: RIOT_JOB_GROUP,
consumer: this.consumerIdentifier,
stalePendingMessageMinimumIdleMilliseconds:
STALE_PENDING_MESSAGE_MINIMUM_IDLE_MILLISECONDS,
count: STALE_PENDING_MESSAGE_CLAIM_COUNT,
});
const message = result.messages[0];
return message ? { stream, message } : null;
}
private async ensureConsumerGroups(): Promise<void> {
await Promise.all(
[RIOT_JOB_HIGH_STREAM, RIOT_JOB_LOW_STREAM].map(async (stream) => {
@@ -12,9 +12,12 @@ import { RiotLeagueService } from './riot-league.service';
import { RiotRecentMatchesService } from './riot-recent-matches.service';
import { RiotRecentStatsService } from './riot-recent-stats.service';
import { RiotSummonerService } from './riot-summoner.service';
import { type RiotPlatformRoute, type RiotRegionalRoute } from './riot.types';
interface FakeAccount {
puuid: string;
gameName: string;
tagLine: string;
profileIconId: number;
revisionDate: number;
summonerLevel: number;
@@ -56,6 +59,8 @@ interface FakeAccount {
function makeAccount(overrides: Partial<FakeAccount> = {}): FakeAccount {
return {
puuid: 'puuid-1',
gameName: 'OldName',
tagLine: 'KR1',
profileIconId: 0,
revisionDate: 0,
summonerLevel: 0,
@@ -82,6 +87,11 @@ function makeUser(account: FakeAccount) {
function makeService(overrides?: {
user?: any;
community?: {
riotPlatform?: RiotPlatformRoute;
riotRegion?: RiotRegionalRoute;
seasonStartedAt?: Date;
};
account?: Partial<RiotAccountService>;
summoner?: Partial<RiotSummonerService>;
league?: Partial<RiotLeagueService>;
@@ -98,10 +108,12 @@ function makeService(overrides?: {
select: () => ({
lean: () => ({
exec: () =>
Promise.resolve({
riotPlatform: 'kr',
riotRegion: 'asia',
}),
Promise.resolve(
overrides?.community ?? {
riotPlatform: 'kr',
riotRegion: 'asia',
},
),
}),
}),
});
@@ -130,6 +142,7 @@ function makeService(overrides?: {
...overrides?.summoner,
} as unknown as RiotSummonerService;
const accountService = {
getByPuuid: jest.fn(),
getRegionByPuuid: jest.fn(),
...overrides?.account,
} as unknown as RiotAccountService;
@@ -177,6 +190,205 @@ function makeService(overrides?: {
}
describe('RiotAccountEnrichmentService', () => {
it('updates a changed Riot ID resolved from the stored PUUID', async () => {
const account = makeAccount();
const user = makeUser(account);
const { service, accountService } = makeService({
user,
account: {
getByPuuid: jest.fn().mockResolvedValue({
puuid: 'puuid-1',
gameName: 'NewName',
tagLine: 'KR1',
}),
},
});
const result = await service.refreshRiotIdentity({
userId: user._id,
puuid: 'puuid-1',
region: 'europe',
});
expect(result).toBe('updated');
expect(account.gameName).toBe('NewName');
expect(account.tagLine).toBe('KR1');
expect(user.save).toHaveBeenCalledTimes(1);
expect(accountService.getByPuuid).toHaveBeenCalledWith('puuid-1', {
region: 'europe',
});
});
it('updates a changed Riot tag line resolved from the stored PUUID', async () => {
const account = makeAccount();
const user = makeUser(account);
const { service } = makeService({
user,
account: {
getByPuuid: jest.fn().mockResolvedValue({
puuid: 'puuid-1',
gameName: 'OldName',
tagLine: 'NEW',
}),
},
});
const result = await service.refreshRiotIdentity({
userId: user._id,
puuid: 'puuid-1',
});
expect(result).toBe('updated');
expect(account.gameName).toBe('OldName');
expect(account.tagLine).toBe('NEW');
expect(user.save).toHaveBeenCalledTimes(1);
});
it('resolves the Riot region from the user community when none is provided', async () => {
const account = makeAccount();
const user = makeUser(account);
const { service, accountService } = makeService({
user,
community: {
riotPlatform: 'na1',
riotRegion: 'americas',
},
account: {
getByPuuid: jest.fn().mockResolvedValue({
puuid: 'puuid-1',
gameName: 'NewName',
tagLine: 'NA1',
}),
},
});
await service.refreshRiotIdentity({
userId: user._id,
puuid: 'puuid-1',
});
expect(accountService.getByPuuid).toHaveBeenCalledWith('puuid-1', {
region: 'americas',
});
});
it('falls back to the default Riot region when the community has no region', async () => {
const account = makeAccount();
const user = makeUser(account);
const { service, accountService } = makeService({
user,
community: {
riotPlatform: 'kr',
},
account: {
getByPuuid: jest.fn().mockResolvedValue({
puuid: 'puuid-1',
gameName: 'NewName',
tagLine: 'KR1',
}),
},
});
await service.refreshRiotIdentity({
userId: user._id,
puuid: 'puuid-1',
});
expect(accountService.getByPuuid).toHaveBeenCalledWith('puuid-1', {
region: 'asia',
});
});
it('does not save when the Riot ID has not changed', async () => {
const account = makeAccount();
const user = makeUser(account);
const { service } = makeService({
user,
account: {
getByPuuid: jest.fn().mockResolvedValue({
puuid: 'puuid-1',
gameName: 'OldName',
tagLine: 'KR1',
}),
},
});
const result = await service.refreshRiotIdentity({
userId: user._id,
puuid: 'puuid-1',
});
expect(result).toBe('unchanged');
expect(user.save).not.toHaveBeenCalled();
});
it.each([
{
name: 'a mismatched PUUID',
response: {
puuid: 'different-puuid',
gameName: 'NewName',
tagLine: 'NEW',
},
},
{
name: 'a missing game name',
response: {
puuid: 'puuid-1',
gameName: null,
tagLine: 'NEW',
},
},
{
name: 'a blank tag line',
response: {
puuid: 'puuid-1',
gameName: 'NewName',
tagLine: ' ',
},
},
])('preserves the stored Riot ID for $name', async ({ response }) => {
const account = makeAccount();
const user = makeUser(account);
const { service } = makeService({
user,
account: {
getByPuuid: jest.fn().mockResolvedValue(response),
},
});
const result = await service.refreshRiotIdentity({
userId: user._id,
puuid: 'puuid-1',
});
expect(result).toBe('failed');
expect(account.gameName).toBe('OldName');
expect(account.tagLine).toBe('KR1');
expect(user.save).not.toHaveBeenCalled();
});
it('preserves the stored Riot ID when Account-V1 lookup fails', async () => {
const account = makeAccount();
const user = makeUser(account);
const { service } = makeService({
user,
account: {
getByPuuid: jest.fn().mockRejectedValue(new Error('Riot unavailable')),
},
});
const result = await service.refreshRiotIdentity({
userId: user._id,
puuid: 'puuid-1',
});
expect(result).toBe('failed');
expect(account.gameName).toBe('OldName');
expect(account.tagLine).toBe('KR1');
expect(user.save).not.toHaveBeenCalled();
});
it('returns failed for unknown user', async () => {
const { service } = makeService();
const result = await service.enrichRiotAccount({
@@ -59,6 +59,7 @@ export interface EnrichResult {
}
export type RefreshLeagueEntriesResult = 'updated' | 'failed';
export type RefreshRiotIdentityResult = 'updated' | 'unchanged' | 'failed';
@Injectable()
export class RiotAccountEnrichmentService {
@@ -87,6 +88,67 @@ export class RiotAccountEnrichmentService {
).exec();
}
public async refreshRiotIdentity(params: {
userId: mongoose.Types.ObjectId;
puuid: string;
region?: RiotRegionalRoute;
}): Promise<RefreshRiotIdentityResult> {
try {
const UserModel = await this.connectionService.getModel('user');
const user = await UserModel.findById(params.userId).exec();
if (!user) return 'failed';
const account = user.riotAccounts.find(
(candidate) => candidate.puuid === params.puuid,
);
if (!account) return 'failed';
let region = params.region;
if (!region) {
const CommunityModel =
await this.connectionService.getModel('community');
const community = await CommunityModel.findById(user.communityId)
.select({ riotRegion: 1 })
.lean()
.exec();
region = community?.riotRegion ?? DEFAULT_REGION;
}
const identity = await this.accountService.getByPuuid(params.puuid, {
region,
});
if (
identity.puuid !== params.puuid ||
!identity.gameName?.trim() ||
!identity.tagLine?.trim()
) {
this.logger.warn(
`Riot identity response was incomplete or mismatched for ${params.puuid}.`,
);
return 'failed';
}
if (
account.gameName === identity.gameName &&
account.tagLine === identity.tagLine
) {
return 'unchanged';
}
account.gameName = identity.gameName;
account.tagLine = identity.tagLine;
await user.save();
return 'updated';
} catch (error) {
this.logger.warn(
`Riot identity refresh failed for ${params.puuid}: ${
error instanceof Error ? error.message : String(error)
}`,
);
return 'failed';
}
}
public async enrichRiotAccount(params: {
userId: mongoose.Types.ObjectId;
puuid: string;
@@ -7,7 +7,10 @@ import mongoose from 'mongoose';
import { TournamentCodeService } from './tournament-code.service';
import { buildDoubleEliminationBracket } from '../double-elimination/double-elimination.util';
type TournamentCodeServiceInternals = TournamentCodeService & {
type TournamentCodeServiceInternals = Pick<
TournamentCodeService,
keyof TournamentCodeService
> & {
resolveRequiredSlots(match: MatchDocument): number;
resolveSeriesRefForGameNumber(
match: MatchDocument,
@@ -0,0 +1,227 @@
import mongoose from 'mongoose';
import type { MatchDocument } from '../global/database/schema';
import type { RiotJobPriority } from '../riot-job-queue/riot-job-queue.types';
import { TournamentResultService } from './tournament-result.service';
import type { PollTournamentResultJob } from './tournament-result.types';
describe('TournamentResultService poll delivery reliability', () => {
it('lets a fast consumer execute the initial poll after the scheduling lock is released', async () => {
const harness = createHarness({ consumeImmediately: true });
await harness.service.scheduleInitialPoll(harness.match._id);
expect(harness.publications[0].lockHeld).toBe(false);
expect(harness.match.resultPollState).toMatchObject({
lastPollOutcome: 'not-found',
lastPolledAt: expect.any(Date),
state: 'polling',
});
expect(harness.publications).toHaveLength(2);
expect(harness.publications[1].job.attempt).toBe(2);
expect(harness.publications[1].deferUntilMs).toEqual(expect.any(Number));
});
it('rejects a busy match lock so the caller can retain the poll for retry', async () => {
const harness = createHarness();
harness.locks.rejectAcquisition = true;
await expect(harness.service.processPollJob(harness.job)).rejects.toThrow();
expect(harness.match.resultPollState).toBeUndefined();
expect(harness.publications).toEqual([]);
});
it('does not publish a poll when the scheduling lock cannot be acquired', async () => {
const harness = createHarness();
harness.locks.rejectAcquisition = true;
await expect(
harness.service.scheduleInitialPoll(harness.match._id),
).resolves.toBeNull();
expect(harness.publications).toEqual([]);
expect(harness.match.resultPollState).toBeUndefined();
});
it('does not publish a poll until teams have been built', async () => {
const harness = createHarness();
harness.match.teamBuiltAt = undefined;
await expect(
harness.service.scheduleInitialPoll(harness.match._id),
).resolves.toBeNull();
expect(harness.publications).toEqual([]);
});
it('does not publish a poll for a completed Competition', async () => {
const harness = createHarness({ completed: true });
await expect(
harness.service.scheduleInitialPoll(harness.match._id),
).resolves.toBeNull();
expect(harness.publications).toEqual([]);
});
it('does not publish a poll when saving the prepared match fails', async () => {
const harness = createHarness();
harness.match.save.mockRejectedValueOnce(new Error('Database unavailable'));
await expect(
harness.service.scheduleInitialPoll(harness.match._id),
).rejects.toThrow('Database unavailable');
expect(harness.publications).toEqual([]);
expect(harness.locks.held.size).toBe(0);
});
});
class InMemoryLocks {
readonly held = new Set<string>();
rejectAcquisition = false;
async runWithLock<T>(
options: { lockKey: string },
operation: () => Promise<T>,
): Promise<T | null> {
if (this.rejectAcquisition || this.held.has(options.lockKey)) return null;
this.held.add(options.lockKey);
try {
return await operation();
} finally {
this.held.delete(options.lockKey);
}
}
runWithRenewedLock<T>(
options: { lockKey: string },
operation: () => Promise<T>,
): Promise<T | null> {
return this.runWithLock(options, operation);
}
}
type PollRequest = {
matchId: string;
attempt: number;
expandedToAllPuuids: boolean;
priority: RiotJobPriority;
deferUntilMs?: number;
};
function createHarness(
options: { consumeImmediately?: boolean; completed?: boolean } = {},
) {
const users = Array.from({ length: 10 }, (_, index) => ({
userId: new mongoose.Types.ObjectId(),
puuid: `poll-reliability-puuid-${index}`,
}));
const codeId = new mongoose.Types.ObjectId();
const match = {
_id: new mongoose.Types.ObjectId(),
communityId: new mongoose.Types.ObjectId(),
status: 'team-built',
teamBuiltAt: new Date(),
tournamentCodeIds: [codeId],
participants: users,
teams: [users.slice(0, 5), users.slice(5)].map((members, index) => ({
teamIndex: index + 1,
captainUserId: members[0].userId,
members: members.map(({ userId }) => ({ userId })),
})),
save: jest.fn().mockResolvedValue(undefined),
} as unknown as MatchDocument & { save: jest.Mock };
const phase = options.completed ? 'completed' : 'ready';
const competition = {
_id: new mongoose.Types.ObjectId(),
revision: 0,
phase,
teams: match.teams.map((team) => ({
teamId: new mongoose.Types.ObjectId(),
members: team.members,
})),
projection: { phase, series: [], gameSlots: [], games: [] },
};
const locks = new InMemoryLocks();
const publications: Array<{
job: PollTournamentResultJob;
lockHeld: boolean;
deferUntilMs?: number;
}> = [];
const matchLockKey = `distributed-lock:tournament-result:process-poll-job:match:${match._id.toString()}`;
const queue = {
enqueueTournamentResultPoll: async (request: PollRequest) => {
const job: PollTournamentResultJob = {
kind: 'poll-tournament-result',
jobId: `poll-delivery-${publications.length + 1}`,
matchId: request.matchId,
attempt: request.attempt,
expandedToAllPuuids: request.expandedToAllPuuids,
priority: request.priority,
enqueuedAt: Date.now(),
};
publications.push({
job,
lockHeld: locks.held.has(matchLockKey),
deferUntilMs: request.deferUntilMs,
});
if (options.consumeImmediately && request.deferUntilMs === undefined) {
await service.processPollJob(job);
}
return job;
},
};
const connection = {
getModel: (name: string) => {
switch (name) {
case 'match':
return { findById: () => Promise.resolve(match) };
case 'tournamentCode':
return {
find: () => ({
sort: () => ({
exec: () =>
Promise.resolve([
{ _id: codeId, state: 'reserved', code: 'TOURNAMENT-1' },
]),
}),
}),
};
case 'community':
return {
findById: () => ({
select: () => ({
lean: () => ({
exec: () => Promise.resolve({ riotRegion: 'asia' }),
}),
}),
}),
};
default:
throw new Error(`Unexpected model ${name}`);
}
},
};
const service = new TournamentResultService(
connection as never,
{ getMatchIdsByPuuid: () => Promise.resolve([]) } as never,
queue as never,
{} as never,
{} as never,
locks as never,
{ bootstrap: () => Promise.resolve(competition) } as never,
{} as never,
{ provisionReadyAssignments: () => Promise.resolve(undefined) } as never,
);
const job: PollTournamentResultJob = {
kind: 'poll-tournament-result',
jobId: 'retry-after-contention',
matchId: match._id.toString(),
attempt: 1,
expandedToAllPuuids: false,
priority: 'high',
enqueuedAt: Date.now(),
};
return { service, match, job, locks, publications };
}
@@ -11,6 +11,10 @@ describe('TournamentResultService Competition polling', () => {
});
await harness.service.processPollJob({
kind: 'poll-tournament-result',
jobId: 'poll-job-1',
enqueuedAt: Date.parse('2026-07-12T10:00:00.000Z'),
priority: 'high',
matchId: harness.match._id.toString(),
attempt: 1,
expandedToAllPuuids: true,
@@ -62,6 +66,10 @@ describe('TournamentResultService Competition polling', () => {
});
await harness.service.processPollJob({
kind: 'poll-tournament-result',
jobId: 'poll-job-1',
enqueuedAt: Date.parse('2026-07-12T10:00:00.000Z'),
priority: 'high',
matchId: harness.match._id.toString(),
attempt: 1,
expandedToAllPuuids: true,
@@ -99,6 +107,10 @@ describe('TournamentResultService Competition polling', () => {
});
await harness.service.processPollJob({
kind: 'poll-tournament-result',
jobId: 'poll-job-1',
enqueuedAt: Date.parse('2026-07-12T10:00:00.000Z'),
priority: 'high',
matchId: harness.match._id.toString(),
attempt: 1,
expandedToAllPuuids: true,
@@ -107,7 +107,7 @@ export class TournamentResultService {
priority: RiotJobPriority = 'high',
): Promise<EnqueueTournamentResultPollResult | null> {
const matchIdentifier = this.resolveMatchIdentifier(matchOrId);
return this.distributedLockService.runWithLock(
const preparedMatchId = await this.distributedLockService.runWithLock(
{
lockKey: this.tournamentResultPollProcessingLockKey(matchIdentifier),
lockExpirationDurationMilliseconds:
@@ -115,14 +115,22 @@ export class TournamentResultService {
lockAcquireTimeoutMilliseconds: 1_000,
lockRetryDelayMilliseconds: 100,
},
async () => this.scheduleInitialPollWhileLockOwned(matchOrId, priority),
async () => this.prepareInitialPollWhileLockOwned(matchOrId),
);
if (!preparedMatchId) return null;
// A fast worker must not see the job while its preparation owns the same lock.
return this.riotJobQueueService.enqueueTournamentResultPoll({
matchId: preparedMatchId,
attempt: 1,
expandedToAllPuuids: false,
priority,
});
}
private async scheduleInitialPollWhileLockOwned(
private async prepareInitialPollWhileLockOwned(
matchOrId: MatchDocument | mongoose.Types.ObjectId,
priority: RiotJobPriority,
): Promise<EnqueueTournamentResultPollResult | null> {
): Promise<string | null> {
const match = await this.loadMatch(matchOrId);
if (!this.isReadyToPoll(match)) return null;
let competition = await this.ensureCompetition(match);
@@ -143,12 +151,7 @@ export class TournamentResultService {
};
await match.save();
return this.riotJobQueueService.enqueueTournamentResultPoll({
matchId: match._id.toString(),
attempt: 1,
expandedToAllPuuids: false,
priority,
});
return match._id.toString();
}
public async scheduleManualPoll(params: {
@@ -260,8 +263,8 @@ export class TournamentResultService {
},
);
if (didProcess) return;
this.logger.debug(
`Skipped tournament result poll job ${job.jobId}; another worker is processing match ${job.matchId}.`,
throw new Error(
`Tournament result poll job ${job.jobId} could not acquire the processing lock for match ${job.matchId}.`,
);
}
@@ -8,6 +8,8 @@ export interface PollTournamentResultJob {
expandedToAllPuuids: boolean;
enqueuedAt: number;
priority: RiotJobPriority;
/** Delivery failures, separate from the regular polling attempt. */
retryCount?: number;
}
export interface EnqueueTournamentResultPollResult {
@@ -94,7 +94,7 @@ export async function discoverApiRoutes(rootDir: string): Promise<ApiRoute[]> {
routes.set(key, {
method,
route,
controllerFile: path.relative(rootDir, file),
controllerFile: path.relative(rootDir, file).split(path.sep).join('/'),
});
}
}
@@ -15,10 +15,7 @@ import {
ConnectionService,
resolveMongoDbName,
} from '../modules/global/database/connection.service';
import {
assertDistinctRedisInstances,
resolveRedisClientOptions,
} from '../modules/global/redis/redis.config';
import { loadRedisClientOptions } from '../modules/global/redis/redis.config';
import { SecretService } from '../modules/global/secret/secret.service';
type RedisClient = ReturnType<typeof createClient>;
@@ -59,18 +56,6 @@ function loadProjectEnv(): void {
}
}
async function readFirstSecret(
secretService: SecretService,
keys: string[],
): Promise<string | undefined> {
for (const key of keys) {
const value = await secretService.get<string>(key, '');
const trimmed = value.trim();
if (trimmed) return trimmed;
}
return undefined;
}
function requireSafeNodeEnv(): void {
if (
process.env.NODE_ENV === 'prod' &&
@@ -90,37 +75,7 @@ async function createRedisClientFromSecrets(
secretService: SecretService,
kind: 'common' | 'auction',
): Promise<RedisClient> {
const prefix = kind === 'auction' ? 'AUCTION_REDIS' : 'REDIS';
const urlKeys =
kind === 'auction' ? [`${prefix}_URL`] : ['REDIS_URL', 'GARNET_URL'];
const endpointKeys =
kind === 'auction'
? [`${prefix}_ENDPOINT`]
: ['REDIS_ENDPOINT', 'GARNET_ENDPOINT'];
const usernameKeys =
kind === 'auction'
? [`${prefix}_USERNAME`, `${prefix}_USERID`]
: ['REDIS_USERNAME', 'REDIS_USERID', 'GARNET_USERNAME', 'GARNET_USERID'];
const passwordKeys =
kind === 'auction'
? [`${prefix}_PASSWORD`]
: ['REDIS_PASSWORD', 'GARNET_PASSWORD'];
const [url, endpoint, username, password] = await Promise.all([
readFirstSecret(secretService, urlKeys),
readFirstSecret(secretService, endpointKeys),
readFirstSecret(secretService, usernameKeys),
readFirstSecret(secretService, passwordKeys),
]);
const client = createClient(
resolveRedisClientOptions({
endpoint,
endpointEnvName: `${prefix}_ENDPOINT`,
password,
url,
urlEnvName: `${prefix}_URL`,
username,
}),
);
const client = createClient(await loadRedisClientOptions(secretService));
client.on('error', (error) => {
console.error(`[auction-rehearsal] ${kind} Redis error:`, error);
});
@@ -128,31 +83,10 @@ async function createRedisClientFromSecrets(
return client;
}
async function assertRedisTopology(secretService: SecretService): Promise<{
async function connectRedisClients(secretService: SecretService): Promise<{
auctionRedisClient: RedisClient;
commonRedisClient: RedisClient;
}> {
const [redisUrl, redisEndpoint, auctionRedisUrl, auctionRedisEndpoint] =
await Promise.all([
readFirstSecret(secretService, ['REDIS_URL', 'GARNET_URL']),
readFirstSecret(secretService, ['REDIS_ENDPOINT', 'GARNET_ENDPOINT']),
readFirstSecret(secretService, ['AUCTION_REDIS_URL']),
readFirstSecret(secretService, ['AUCTION_REDIS_ENDPOINT']),
]);
const redisOptions = resolveRedisClientOptions({
endpoint: redisEndpoint,
endpointEnvName: 'REDIS_ENDPOINT',
url: redisUrl,
urlEnvName: 'REDIS_URL',
});
const auctionRedisOptions = resolveRedisClientOptions({
endpoint: auctionRedisEndpoint,
endpointEnvName: 'AUCTION_REDIS_ENDPOINT',
url: auctionRedisUrl,
urlEnvName: 'AUCTION_REDIS_URL',
});
assertDistinctRedisInstances(redisOptions.url, auctionRedisOptions.url);
const [commonRedisClient, auctionRedisClient] = await Promise.all([
createRedisClientFromSecrets(secretService, 'common'),
createRedisClientFromSecrets(secretService, 'auction'),
@@ -409,7 +343,7 @@ async function main(): Promise<void> {
);
const { auctionRedisClient, commonRedisClient } =
await assertRedisTopology(secretService);
await connectRedisClients(secretService);
const connectionService = new ConnectionService(secretService);
const auctionRedisService = new AuctionRedisService(auctionRedisClient);
const auctionRedisCommandService = new AuctionRedisCommandService(
+7
View File
@@ -0,0 +1,7 @@
{
"rootDir": "..",
"testEnvironment": "node",
"testRegex": "test/.*\\.integration-spec\\.ts$",
"transform": { "^.+\\.ts$": "ts-jest" },
"testTimeout": 15000
}
@@ -0,0 +1,662 @@
import { createClient } from 'redis';
import { RedisService } from '../src/modules/global/redis/redis.service';
import { AuctionRedisService } from '../src/modules/auction/redis/auction-redis.service';
import { AuctionRedisCommandService } from '../src/modules/auction/redis/auction-redis-command.service';
import { AuctionService } from '../src/modules/auction/auction.service';
import { buildAuctionRedisKeys } from '../src/modules/auction/redis/auction-redis.keys';
import { RiotJobQueueService } from '../src/modules/riot-job-queue/riot-job-queue.service';
import {
RIOT_JOB_HIGH_STREAM,
RIOT_JOB_LOW_STREAM,
RIOT_JOB_SCHEDULED_ZSET,
} from '../src/modules/riot-job-queue/riot-job-queue.types';
import { buildAuctionReserveActionRequestScriptInvocation } from '../src/modules/auction/redis/auction-redis.reserve-action';
import { buildAuctionApplyTransitionScriptInvocation } from '../src/modules/auction/redis/auction-redis.apply-transition';
import { DistributedLockService } from '../src/modules/global/redis/distributed-lock.service';
import { BackgroundRefreshScheduler } from '../src/modules/riot-background-refresh/background-refresh.scheduler';
import { setTimeout as delay } from 'node:timers/promises';
import {
CommunityStatsCacheKey,
CommunityStatsCacheService,
} from '../src/modules/community-stats/community-stats-cache.service';
import { CommunityStatsService } from '../src/modules/community-stats/community-stats.service';
import { PROMOTE_SCHEDULED_RIOT_JOB_SCRIPT } from '../src/modules/riot-job-queue/riot-job-queue.scripts';
import mongoose from 'mongoose';
const client = createClient({
url: process.env.REDIS_TEST_URL,
socket: { reconnectStrategy: false },
});
const redis = new RedisService(client);
const auctionRedis = new AuctionRedisService(client);
const queue = new RiotJobQueueService({} as never, redis);
beforeAll(async () => {
if (process.env.REDIS_TEST_ISOLATED !== '1' || !process.env.REDIS_TEST_URL) {
throw new Error(
'Run via pnpm --filter api test:redis to create an isolated Redis process.',
);
}
client.on('error', () => {});
await client.connect();
});
describe('Redis native operations', () => {
it('serves normal commands while a dedicated stream connection is blocked', async () => {
const reader = await redis.createDedicatedConnection();
try {
await redis.createConsumerGroup('stream', 'workers', '0');
const pending = reader.readGroup('stream', 'workers', 'reader', '>', {
blockMs: 2000,
count: 1,
});
void pending.catch(() => {}); // A failed assertion must still allow connection cleanup.
let isBlocked = false;
for (let i = 0; i < 100; i++) {
const clients = await client.sendCommand<string>(['CLIENT', 'LIST']);
if (/flags=b\b.*cmd=xreadgroup/.test(clients)) {
isBlocked = true;
break;
}
await delay(5);
}
expect(isBlocked).toBe(true);
await redis.setString('cache', 'available');
expect(await redis.getString('cache')).toBe('available');
const id = await redis.appendStream('stream', { job: 'wake' });
expect((await pending)?.[0].messages[0].id).toBe(id);
} finally {
if (reader.raw().isOpen) reader.raw().destroy();
}
});
it('claims abandoned pending messages before reading new work with the same idle threshold', async () => {
await redis.createConsumerGroup('stream', 'workers', '0');
const oldId = await redis.appendStream('stream', { job: 'old' });
await redis.readGroup('stream', 'workers', 'dead-worker', '>', {
count: 1,
});
const newId = await redis.appendStream('stream', { job: 'new' });
await client.sendCommand([
'XCLAIM',
'stream',
'workers',
'dead-worker',
'0',
oldId,
'IDLE',
'1800001',
]);
const recovered = await redis.readGroup(
'stream',
'workers',
'live-worker',
'>',
{ count: 1, claimMinIdleMs: 1800000 },
);
expect(recovered?.[0].messages[0]).toEqual(
expect.objectContaining({ id: oldId, message: { job: 'old' } }),
);
const fresh = await redis.readGroup(
'stream',
'workers',
'live-worker',
'>',
{ count: 1, claimMinIdleMs: 1800000 },
);
expect(fresh?.[0].messages[0].id).toBe(newId);
expect(
await redis.readGroup('stream', 'workers', 'other-worker', '>', {
count: 1,
claimMinIdleMs: 1800000,
}),
).toBeNull();
});
it('acknowledges atomically but retains a message until every group has processed it', async () => {
for (const group of ['workers', 'audit'])
await redis.createConsumerGroup('stream', group, '0');
const id = await redis.appendStream('stream', { job: 'one' });
await redis.readGroup('stream', 'workers', 'worker', '>', { count: 1 });
await redis.acknowledgeAndDeleteStream('stream', 'workers', id);
expect(await client.xLen('stream')).toBe(1);
expect((await client.xPending('stream', 'workers')).pending).toBe(0);
await redis.readGroup('stream', 'audit', 'auditor', '>', { count: 1 });
await redis.acknowledgeAndDeleteStream('stream', 'audit', id);
expect(await client.xLen('stream')).toBe(0);
await expect(
redis.acknowledgeAndDeleteStream('stream', 'workers', id),
).resolves.toBeUndefined();
});
it('never trims unread or pending jobs even when MAXLEN is exceeded', async () => {
await redis.createConsumerGroup('stream', 'workers', '0');
const first = await redis.appendStream(
'stream',
{ job: 'pending' },
{ maxLen: 1 },
);
await redis.readGroup('stream', 'workers', 'worker', '>', { count: 1 });
for (let i = 0; i < 220; i++)
await redis.appendStream('stream', { job: String(i) }, { maxLen: 1 });
expect(await client.xLen('stream')).toBe(221);
expect((await client.xRange('stream', first, first))[0].message).toEqual({
job: 'pending',
});
});
it('does not release, renew, or recreate a lock belonging to another owner', async () => {
const locks = new DistributedLockService(redis);
const owner = await locks.acquireLock({
lockKey: 'lock',
lockOwnershipToken: 'old',
lockExpirationDurationMilliseconds: 1000,
});
expect(owner).not.toBeNull();
expect(await locks.extendLockIfOwned(owner!, 4000)).toBe(true);
expect(await client.pTTL('lock')).toBeGreaterThan(3000);
await client.set('lock', 'new', { PX: 5000 });
expect(await locks.releaseLockIfOwned(owner!)).toBe(false);
expect(await auctionRedis.releaseTokenLock('lock', 'old')).toBe(false);
expect(await locks.extendLockIfOwned(owner!, 9000)).toBe(false);
expect(await client.get('lock')).toBe('new');
expect(await auctionRedis.releaseTokenLock('lock', 'new')).toBe(true);
expect(await locks.extendLockIfOwned(owner!)).toBe(false);
expect(await client.exists('lock')).toBe(0);
});
it('does not clear the dedup token of a newer refresh job', async () => {
const job = {
jobId: 'old',
puuid: 'player',
queueGroup: 'summoners-rift',
} as const;
const key = 'riot:job:dedup:player:summoners-rift';
await redis.setJson(
'riot:job:status:old',
{ ...job, state: 'processing' },
86400,
);
await redis.setString(key, 'new', 300);
await queue.markCompleted(job as never);
expect(await redis.getString(key)).toBe('new');
await queue.markFailed(job as never, new Error('failure'));
expect(await redis.getString(key)).toBe('new');
await redis.setString(key, 'old', 300);
await queue.markCompleted(job as never);
expect(await redis.getString(key)).toBeNull();
});
it('increments failure counts without losing concurrent updates and refreshes the TTL', async () => {
const scheduler = Object.assign(
Object.create(BackgroundRefreshScheduler.prototype),
{
redis,
logger: { warn: jest.fn() },
},
) as {
bumpFailureCounter(puuid: string): Promise<void>;
clearFailureCounter(puuid: string): Promise<void>;
};
await client.set('riot:bg:fail:player', '1', { EX: 10 });
await Promise.all(
Array.from({ length: 10 }, () => scheduler.bumpFailureCounter('player')),
);
expect(await client.get('riot:bg:fail:player')).toBe('11');
expect(await client.ttl('riot:bg:fail:player')).toBeGreaterThan(86390);
await scheduler.clearFailureCounter('player');
expect(await client.exists('riot:bg:fail:player')).toBe(0);
});
});
beforeEach(async () => {
await client.flushDb();
});
afterAll(async () => {
if (client.isOpen) await client.quit();
});
function scheduledJob(priority = 'high', suffix = '1') {
return JSON.stringify({
kind: 'poll-tournament-result',
jobId: `job-${suffix}`,
matchId: 'match-1',
attempt: 1,
expandedToAllPuuids: false,
enqueuedAt: Date.now(),
priority,
});
}
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((accept) => {
resolve = accept;
});
return { promise, resolve };
}
describe('Community Hash response cache', () => {
const cache = new CommunityStatsCacheService(redis);
it('does not share an old in-flight detail request after invalidation or overwrite the fresh response', async () => {
const service = new CommunityStatsService(
{} as never,
cache,
{} as never,
{} as never,
);
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const dataset = (title: string) => ({
matches: [
{
matchId: matchId.toString(),
title,
scheduledAt: null,
status: 'finished',
gameCount: 0,
games: [],
teams: [],
seriesResults: [],
},
],
detailsByMatchId: new Map(),
});
const oldDataset = deferred<ReturnType<typeof dataset>>();
const oldStarted = deferred<void>();
const build = jest
.spyOn(
service as unknown as {
buildBaseDataset(): Promise<ReturnType<typeof dataset>>;
},
'buildBaseDataset',
)
.mockImplementationOnce(() => {
oldStarted.resolve();
return oldDataset.promise;
})
.mockResolvedValue(dataset('fresh'));
const oldRequest = service.getMatchDetail({ communityId, matchId });
await oldStarted.promise;
await cache.invalidateCommunity(communityId.toString());
try {
const fresh = await service.getMatchDetail({ communityId, matchId });
expect(fresh.match.title).toBe('fresh');
expect(build).toHaveBeenCalledTimes(2);
} finally {
oldDataset.resolve(dataset('old'));
await oldRequest;
}
expect((await oldRequest).match.title).toBe('old');
expect(
(await service.getMatchDetail({ communityId, matchId })).match.title,
).toBe('fresh');
expect(build).toHaveBeenCalledTimes(2);
});
it('preserves independent normal, detail and incomplete-detail TTLs', async () => {
const normal = new CommunityStatsCacheKey('community', 'matches', 'page-1');
const detail = new CommunityStatsCacheKey(
'community',
'matchDetail',
'match-1',
);
const incomplete = new CommunityStatsCacheKey(
'community',
'matchDetail',
'match-2',
);
for (const key of [normal, detail, incomplete])
expect(await cache.get(key)).toBeNull();
await cache.set(normal, { matches: [] });
await cache.setDetail(detail, { games: [1] });
await cache.set(incomplete, { games: [] }, 60);
for (const [key, ttl] of [
[normal, 300],
[detail, 86400],
[incomplete, 60],
] as const) {
const [remaining] = await client.sendCommand<number[]>([
'HTTL',
key.hashKey,
'FIELDS',
'1',
key.field,
]);
expect(remaining).toBeGreaterThan(ttl - 3);
expect(remaining).toBeLessThanOrEqual(ttl);
}
expect(await cache.get(detail)).toEqual({ games: [1] });
expect(await client.ttl(detail.hashKey)).toBe(-1);
await client.sendCommand([
'HPEXPIRE',
incomplete.hashKey,
'20',
'FIELDS',
'1',
incomplete.field,
]);
await delay(50);
expect(await cache.get(incomplete)).toBeNull();
expect(await cache.get(detail)).toEqual({ games: [1] });
});
it('invalidates all scopes for one community while preserving other communities', async () => {
const entries = (
[
'matches',
'leaderboard',
'teamInsights',
'matchDetail',
'userInternal',
] as const
).map((scope) => new CommunityStatsCacheKey('one', scope, 'field'));
const other = new CommunityStatsCacheKey('two', 'matches', 'field');
for (const key of [...entries, other]) {
await cache.get(key);
await cache.set(key, { fresh: true });
}
expect(await cache.invalidateCommunity('one')).toBe(5);
for (const key of entries) expect(await cache.get(key)).toBeNull();
expect(await cache.get(other)).toEqual({ fresh: true });
expect(await cache.invalidateCommunity('one')).toBe(0);
});
it('rejects stale fills and separates in-flight identities across invalidation', async () => {
const old = new CommunityStatsCacheKey('one', 'matches', 'page');
await cache.get(old);
const oldIdentity = old.identity;
await cache.invalidateCommunity('one');
const fresh = new CommunityStatsCacheKey('one', 'matches', 'page');
await cache.get(fresh);
expect(fresh.identity).not.toBe(oldIdentity);
await cache.set(fresh, { version: 2 });
await cache.set(old, { version: 1 });
expect(await cache.get(fresh)).toEqual({ version: 2 });
await cache.invalidateCommunity('one');
await cache.set(old, { version: 0 });
expect(await client.exists(old.hashKey)).toBe(0);
});
it('treats malformed data as a miss and refreshes only the written field TTL', async () => {
const key = new CommunityStatsCacheKey('one', 'matches', 'page');
await cache.get(key);
await client.hSet(key.hashKey, key.field, 'broken-json');
expect(await cache.get(key)).toBeNull();
await cache.set(key, { ok: true }, 1);
await cache.set(key, { ok: true }, 300);
const [ttl] = await client.sendCommand<number[]>([
'HTTL',
key.hashKey,
'FIELDS',
'1',
key.field,
]);
expect(ttl).toBeGreaterThan(297);
expect(await cache.get(key)).toEqual({ ok: true });
});
});
describe('Redis correctness regressions', () => {
it('rechecks the due timestamp after selection so rescheduled work is not promoted early', async () => {
const job = scheduledJob();
const selectedAt = Date.now();
await client.zAdd(RIOT_JOB_SCHEDULED_ZSET, {
score: selectedAt + 60000,
value: job,
});
expect(
await client.sendCommand([
'EVAL',
PROMOTE_SCHEDULED_RIOT_JOB_SCRIPT,
'2',
RIOT_JOB_SCHEDULED_ZSET,
RIOT_JOB_HIGH_STREAM,
job,
String(selectedAt),
]),
).toBe(0);
expect(await client.xLen(RIOT_JOB_HIGH_STREAM)).toBe(0);
expect(await client.zCard(RIOT_JOB_SCHEDULED_ZSET)).toBe(1);
});
it('discards malformed scheduled jobs and keeps the requested promotion batch limit', async () => {
await client.zAdd(RIOT_JOB_SCHEDULED_ZSET, [
{ score: 0, value: 'invalid-json' },
{ score: 0, value: JSON.stringify({ kind: 'unsupported' }) },
...Array.from({ length: 3 }, (_, i) => ({
score: 1,
value: scheduledJob('high', String(i)),
})),
]);
expect(await queue.promoteDueScheduledJobs(2)).toBe(0);
expect(await client.zCard(RIOT_JOB_SCHEDULED_ZSET)).toBe(3);
expect(await queue.promoteDueScheduledJobs(2)).toBe(2);
expect(await client.xLen(RIOT_JOB_HIGH_STREAM)).toBe(2);
expect(await client.zCard(RIOT_JOB_SCHEDULED_ZSET)).toBe(1);
});
it('keeps a scheduled job when destination append fails', async () => {
const job = scheduledJob();
await client.zAdd(RIOT_JOB_SCHEDULED_ZSET, {
score: Date.now() - 1,
value: job,
});
await client.set(RIOT_JOB_HIGH_STREAM, 'wrong-type');
await expect(queue.promoteDueScheduledJobs()).rejects.toThrow('WRONGTYPE');
expect(await client.zScore(RIOT_JOB_SCHEDULED_ZSET, job)).not.toBeNull();
await client.del(RIOT_JOB_HIGH_STREAM);
expect(await queue.promoteDueScheduledJobs()).toBe(1);
expect(await client.xLen(RIOT_JOB_HIGH_STREAM)).toBe(1);
});
it('promotes each due job once under concurrent workers and leaves future jobs scheduled', async () => {
const jobs = Array.from({ length: 12 }, (_, i) =>
scheduledJob(i % 2 ? 'low' : 'high', String(i)),
);
await client.zAdd(
RIOT_JOB_SCHEDULED_ZSET,
jobs.map((value) => ({ score: Date.now() - 1, value })),
);
const future = scheduledJob('high', 'future');
await client.zAdd(RIOT_JOB_SCHEDULED_ZSET, {
score: Date.now() + 60_000,
value: future,
});
const counts = await Promise.all(
Array.from({ length: 4 }, () => queue.promoteDueScheduledJobs(5)),
);
await queue.promoteDueScheduledJobs();
expect(counts.reduce((sum, value) => sum + value, 0)).toBeLessThanOrEqual(
12,
);
expect(await client.xLen(RIOT_JOB_HIGH_STREAM)).toBe(6);
expect(await client.xLen(RIOT_JOB_LOW_STREAM)).toBe(6);
expect(await client.zCard(RIOT_JOB_SCHEDULED_ZSET)).toBe(1);
});
it('cleans only the requested lifecycle Hash payloads and queue references', async () => {
const keys = buildAuctionRedisKeys('match-1');
const oldKey = keys.durabilityPayloadKey('old');
const newKey = keys.durabilityPayloadKey('new');
for (const [key, lifecycle] of [
[oldKey, 'old-life'],
[newKey, 'new-life'],
]) {
await client.hSet(key, {
auctionLifecycleId: lifecycle,
payloadJson: JSON.stringify({ auctionLifecycleId: lifecycle }),
});
await client.zAdd(keys.durabilityRetryQueueKey, { score: 1, value: key });
await client.zAdd(keys.durabilityDeadLetterQueueKey, {
score: 1,
value: key,
});
}
const service = Object.assign(Object.create(AuctionService.prototype), {
auctionRedisService: auctionRedis,
}) as {
clearRedisDurabilityPayloadsForLifecycle(
keys: ReturnType<typeof buildAuctionRedisKeys>,
lifecycle: string,
): Promise<void>;
};
await service.clearRedisDurabilityPayloadsForLifecycle(keys, 'old-life');
expect(await client.exists(oldKey)).toBe(0);
expect(await client.exists(newKey)).toBe(1);
expect(await client.zRange(keys.durabilityRetryQueueKey, 0, -1)).toEqual([
newKey,
]);
expect(
await client.zRange(keys.durabilityDeadLetterQueueKey, 0, -1),
).toEqual([newKey]);
});
it('supports legacy JSON cleanup and preserves malformed or foreign payloads until an unconditional cleanup', async () => {
const keys = buildAuctionRedisKeys('legacy');
const legacy = keys.durabilityPayloadKey('old');
const foreign = keys.durabilityPayloadKey('foreign');
const malformed = keys.durabilityPayloadKey('malformed');
await client.set(
legacy,
JSON.stringify({ auctionLifecycleId: 'old-life' }),
);
await client.set(
foreign,
JSON.stringify({ auctionLifecycleId: 'new-life' }),
);
await client.set(malformed, 'broken-json');
await client.zAdd(
keys.durabilityRetryQueueKey,
[legacy, foreign, malformed].map((value) => ({ score: 1, value })),
);
const service = Object.assign(Object.create(AuctionService.prototype), {
auctionRedisService: auctionRedis,
}) as {
clearRedisDurabilityPayloadsForLifecycle(
keys: ReturnType<typeof buildAuctionRedisKeys>,
lifecycle?: string,
): Promise<void>;
};
await service.clearRedisDurabilityPayloadsForLifecycle(keys, 'old-life');
expect(await client.exists(legacy)).toBe(0);
expect(await client.exists([foreign, malformed])).toBe(2);
await service.clearRedisDurabilityPayloadsForLifecycle(keys);
expect(await client.exists([foreign, malformed])).toBe(0);
expect(await client.zCard(keys.durabilityRetryQueueKey)).toBe(0);
});
it('preserves the 500-request cap, replay window, and fingerprint conflict checks', async () => {
const keys = buildAuctionRedisKeys('retention');
const reserve = async (id: string, revision = 1) => {
const invocation = buildAuctionReserveActionRequestScriptInvocation(
keys,
{
auctionActionRequestId: id,
auctionActionType: 'next',
auctionStateTransitionId: `transition-${id}`,
clientObservedAuctionLifecycleId: 'life',
clientObservedPhase: 'sold',
clientObservedRevision: revision,
leaseDurationMS: 15000,
maximumStoredAuctionActionRequestResultCount: 500,
minimumAuctionActionRequestResultReplayWindowMS: 300000,
processingOwnerToken: 'owner',
},
);
return auctionRedis.evalScript<string[]>(
invocation.script,
invocation.keys,
invocation.values,
);
};
for (let i = 0; i < 500; i++)
expect((await reserve(String(i)))[0]).toBe('RESERVED');
expect((await reserve('0', 2)).slice(0, 2)).toEqual([
'REJECTED',
'DUPLICATE_ACTION_REQUEST_CONFLICT',
]);
expect((await reserve('501')).slice(0, 2)).toEqual([
'REJECTED',
'ACTION_REQUEST_RESULT_LIMIT',
]);
expect(await client.lLen(keys.actionRequestResultOrderKey)).toBe(500);
expect((await reserve('0'))[0]).toBe('RESERVED');
expect(await client.lLen(keys.actionRequestResultOrderKey)).toBe(500);
await client.hSet(
keys.actionRequestResultsKey,
'life:0:createdAtTimestampMS',
String(Date.now() - 300001),
);
expect((await reserve('501'))[0]).toBe('RESERVED');
expect(await client.lLen(keys.actionRequestResultOrderKey)).toBe(500);
expect(
await client.hExists(keys.actionRequestResultsKey, 'life:0:fingerprint'),
).toBe(0);
});
it('counts one order entry per reserved and applied action and still replays it', async () => {
const keys = buildAuctionRedisKeys('match-1');
const commands = new AuctionRedisCommandService(auctionRedis);
await commands.hydrateState('match-1', {
matchId: 'match-1',
auctionHistorySequence: 0,
auctionLifecycleId: 'life',
phase: 'sold',
revision: 0,
maximumBidRoundDurationSeconds: 30,
structureStateJson: '{}',
});
const reservation = buildAuctionReserveActionRequestScriptInvocation(keys, {
auctionActionRequestId: 'request',
auctionActionType: 'next',
auctionStateTransitionId: 'transition',
clientObservedAuctionLifecycleId: 'life',
clientObservedPhase: 'sold',
clientObservedRevision: 1,
leaseDurationMS: 15000,
maximumStoredAuctionActionRequestResultCount: 500,
minimumAuctionActionRequestResultReplayWindowMS: 300000,
processingOwnerToken: 'owner',
});
await auctionRedis.evalScript(
reservation.script,
reservation.keys,
reservation.values,
);
const apply = buildAuctionApplyTransitionScriptInvocation(keys, {
actionRequest: {
scopeKey: 'life:request',
processingOwnerToken: 'owner',
observedProcessingLeaseVersion: 1,
},
afterAuctionStructureStateJson: '{}',
auctionHistorySequence: 1,
auctionLifecycleId: 'life',
auctionStateTransitionId: 'transition',
broadcastStateRevision: 2,
deadline: { mode: 'none' },
durabilityPayloadJson: '{}',
expectedPhase: 'sold',
expectedRevision: 1,
liveStatePatch: { phase: 'sold' },
matchId: 'match-1',
shouldBroadcastState: false,
});
const result = await auctionRedis.evalScript<string[]>(
apply.script,
apply.keys,
apply.values,
);
expect(result[0]).toBe('OK');
expect(
await client.lRange(keys.actionRequestResultOrderKey, 0, -1),
).toEqual(['life:request']);
const replay = await auctionRedis.evalScript<string[]>(
reservation.script,
reservation.keys,
reservation.values,
);
expect(replay.slice(0, 2)).toEqual(['REPLAY', 'applied']);
});
});
+120
View File
@@ -0,0 +1,120 @@
import { spawn } from 'node:child_process';
import { createRequire } from 'node:module';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join, relative, resolve } from 'node:path';
import { createServer } from 'node:net';
import { randomUUID } from 'node:crypto';
import { setTimeout as delay } from 'node:timers/promises';
import { createClient } from 'redis';
const require = createRequire(import.meta.url);
const listener = createServer();
await new Promise((accept, reject) => {
listener.once('error', reject);
listener.listen(0, '127.0.0.1', accept);
});
const port = listener.address().port;
await new Promise((accept) => listener.close(accept));
const directory = await mkdtemp(join(tmpdir(), 'lolympus-redis-test-'));
const password = randomUUID();
const redis = spawn(
process.env.REDIS_TEST_SERVER || 'redis-server',
[
'--bind',
'127.0.0.1',
'--port',
String(port),
'--protected-mode',
'yes',
'--requirepass',
password,
'--save',
'',
'--appendonly',
'no',
'--dir',
directory.replaceAll('\\', '/'),
],
{ windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] },
);
let startupError;
const redisClosed = new Promise((accept) => redis.once('close', accept));
let output = '';
redis.on('error', (error) => {
startupError = error;
});
redis.stdout.on('data', (data) => {
output += data;
});
redis.stderr.on('data', (data) => {
output += data;
});
const url = `redis://:${password}@127.0.0.1:${port}`;
const client = createClient({
url,
socket: { reconnectStrategy: false, connectTimeout: 500 },
});
client.on('error', () => {});
try {
let connected = false;
for (let attempt = 0; attempt < 100; attempt++) {
if (startupError) throw startupError;
if (redis.exitCode !== null) throw new Error(`Redis exited: ${output}`);
try {
await client.connect();
connected = true;
break;
} catch {
await delay(100);
}
}
if (!connected) throw new Error(`Redis did not start: ${output}`);
const version = (await client.info('server')).match(
/redis_version:([^\r\n]+)/,
)?.[1];
if (!version?.startsWith('8.10.'))
throw new Error(`Expected Redis 8.10.x, got ${version}`);
console.log(
`Integration tests using isolated Redis ${version} on loopback port ${port}`,
);
const jest = spawn(
process.execPath,
[
require.resolve('jest/bin/jest'),
'--config',
'test/jest-redis.json',
'--runInBand',
...process.argv.slice(2),
],
{
cwd: resolve(import.meta.dirname, '..'),
windowsHide: true,
stdio: 'inherit',
env: {
...process.env,
NODE_ENV: 'test',
REDIS_TEST_URL: url,
REDIS_TEST_ISOLATED: '1',
},
},
);
process.exitCode = await new Promise((accept, reject) => {
jest.once('error', reject);
jest.once('exit', (code) => accept(code ?? 1));
});
} finally {
if (client.isOpen) {
await client.sendCommand(['SHUTDOWN', 'NOSAVE']).catch(() => {});
if (client.isOpen) client.destroy();
}
if (redis.pid && redis.exitCode === null) redis.kill();
await redisClosed;
const cleanupTarget = relative(resolve(tmpdir()), resolve(directory));
if (!/^lolympus-redis-test-[^\\/]+$/.test(cleanupTarget)) {
throw new Error(
'Refusing to clean up a directory outside the isolated test workspace.',
);
}
await rm(directory, { recursive: true, force: true });
}
@@ -0,0 +1,284 @@
import { createClient } from 'redis';
import { RedisService } from '../src/modules/global/redis/redis.service';
import { RiotJobQueueService } from '../src/modules/riot-job-queue/riot-job-queue.service';
import {
RIOT_JOB_GROUP,
RIOT_JOB_HIGH_STREAM,
RIOT_JOB_LOW_STREAM,
RIOT_JOB_SCHEDULED_ZSET,
} from '../src/modules/riot-job-queue/riot-job-queue.types';
import type { PollTournamentResultJob } from '../src/modules/tournament-result/tournament-result.types';
const client = createClient({
url: process.env.REDIS_TEST_URL,
socket: { reconnectStrategy: false },
});
const redis = new RedisService(client);
const queue = new RiotJobQueueService({} as never, redis);
beforeAll(async () => {
const url = process.env.REDIS_TEST_URL;
if (
process.env.REDIS_TEST_ISOLATED !== '1' ||
!url ||
!['127.0.0.1', 'localhost', '[::1]'].includes(new URL(url).hostname)
) {
throw new Error('Run with the isolated loopback Redis integration runner.');
}
client.on('error', () => {});
await client.connect();
});
beforeEach(async () => {
await client.flushDb();
});
afterAll(async () => {
if (client.isOpen) await client.quit();
});
describe('Tournament result retry delivery on Redis', () => {
it('replaces a pending poll with one durable retry and ignores repeated transfer requests', async () => {
const job = pollJob();
const entryId = await pendingPoll(RIOT_JOB_HIGH_STREAM, job);
const before = Date.now();
await queue.rescheduleTournamentResultPoll({
stream: RIOT_JOB_HIGH_STREAM,
entryId,
job,
});
const after = Date.now();
const scheduled = await client.zRangeWithScores(
RIOT_JOB_SCHEDULED_ZSET,
0,
-1,
);
expect(scheduled).toHaveLength(1);
expect(JSON.parse(scheduled[0].value)).toEqual({ ...job, retryCount: 1 });
expect(scheduled[0].score).toBeGreaterThanOrEqual(before + 30_000);
expect(scheduled[0].score).toBeLessThanOrEqual(after + 30_000);
expect(
(await client.xPending(RIOT_JOB_HIGH_STREAM, RIOT_JOB_GROUP)).pending,
).toBe(0);
expect(await client.xLen(RIOT_JOB_HIGH_STREAM)).toBe(0);
await queue.rescheduleTournamentResultPoll({
stream: RIOT_JOB_HIGH_STREAM,
entryId,
job,
});
expect(
await client.zRangeWithScores(RIOT_JOB_SCHEDULED_ZSET, 0, -1),
).toEqual(scheduled);
});
it.each([
[1, 60_000],
[2, 120_000],
[3, 240_000],
[4, 300_000],
[20, 300_000],
])(
'backs off retry count %i by %i ms without changing the poll attempt',
async (retryCount, delayMs) => {
const job = { ...pollJob(), retryCount };
const entryId = await pendingPoll(RIOT_JOB_HIGH_STREAM, job);
const before = Date.now();
await queue.rescheduleTournamentResultPoll({
stream: RIOT_JOB_HIGH_STREAM,
entryId,
job,
});
const after = Date.now();
const scheduled = await client.zRangeWithScores(
RIOT_JOB_SCHEDULED_ZSET,
0,
-1,
);
expect(scheduled).toHaveLength(1);
expect(JSON.parse(scheduled[0].value)).toEqual({
...job,
retryCount: retryCount + 1,
});
expect(scheduled[0].score).toBeGreaterThanOrEqual(before + delayMs);
expect(scheduled[0].score).toBeLessThanOrEqual(after + delayMs);
},
);
it('keeps the original pending when retry persistence fails and can recover afterward', async () => {
const job = pollJob();
const entryId = await pendingPoll(RIOT_JOB_HIGH_STREAM, job);
await client.set(RIOT_JOB_SCHEDULED_ZSET, 'wrong-type');
await expect(
queue.rescheduleTournamentResultPoll({
stream: RIOT_JOB_HIGH_STREAM,
entryId,
job,
}),
).rejects.toThrow();
expect(
(await client.xPending(RIOT_JOB_HIGH_STREAM, RIOT_JOB_GROUP)).pending,
).toBe(1);
expect(await client.xRange(RIOT_JOB_HIGH_STREAM, entryId, entryId)).toEqual(
[{ id: entryId, message: { job: JSON.stringify(job) } }],
);
await client.del(RIOT_JOB_SCHEDULED_ZSET);
await queue.rescheduleTournamentResultPoll({
stream: RIOT_JOB_HIGH_STREAM,
entryId,
job,
});
expect(
(await client.xPending(RIOT_JOB_HIGH_STREAM, RIOT_JOB_GROUP)).pending,
).toBe(0);
expect(await client.zCard(RIOT_JOB_SCHEDULED_ZSET)).toBe(1);
});
it('retains the original for another consumer group until that group acknowledges it', async () => {
const job = pollJob();
const stream = RIOT_JOB_HIGH_STREAM;
await redis.createConsumerGroup(stream, 'audit', '0');
const entryId = await pendingPoll(stream, job);
await queue.rescheduleTournamentResultPoll({ stream, entryId, job });
expect((await client.xPending(stream, RIOT_JOB_GROUP)).pending).toBe(0);
expect(await client.xLen(stream)).toBe(1);
expect(await client.zCard(RIOT_JOB_SCHEDULED_ZSET)).toBe(1);
await queue.rescheduleTournamentResultPoll({ stream, entryId, job });
expect(await client.zCard(RIOT_JOB_SCHEDULED_ZSET)).toBe(1);
const auditEntry = await redis.readGroup(stream, 'audit', 'auditor', '>', {
count: 1,
});
expect(auditEntry?.[0].messages[0].id).toBe(entryId);
await redis.acknowledgeAndDeleteStream(stream, 'audit', entryId);
expect(await client.xLen(stream)).toBe(0);
expect(await client.zCard(RIOT_JOB_SCHEDULED_ZSET)).toBe(1);
});
it.each([
['high', RIOT_JOB_HIGH_STREAM],
['low', RIOT_JOB_LOW_STREAM],
] as const)(
'promotes a due %s retry to its original priority and allows successful consumption',
async (priority, stream) => {
const job = { ...pollJob(), priority };
const entryId = await pendingPoll(stream, job);
await queue.rescheduleTournamentResultPoll({ stream, entryId, job });
const [scheduled] = await client.zRangeWithScores(
RIOT_JOB_SCHEDULED_ZSET,
0,
-1,
);
await client.zAdd(RIOT_JOB_SCHEDULED_ZSET, {
value: scheduled.value,
score: Date.now() - 1,
});
expect(await queue.promoteDueScheduledJobs()).toBe(1);
const delivery = await redis.readGroup(
stream,
RIOT_JOB_GROUP,
'recovered-worker',
'>',
{ count: 1 },
);
const retriedEntry = delivery?.[0].messages[0];
expect(retriedEntry).toBeDefined();
expect(JSON.parse(retriedEntry!.message.job)).toEqual({
...job,
retryCount: 1,
});
expect(await client.zCard(RIOT_JOB_SCHEDULED_ZSET)).toBe(0);
const otherStream =
priority === 'high' ? RIOT_JOB_LOW_STREAM : RIOT_JOB_HIGH_STREAM;
expect(await client.xLen(otherStream)).toBe(0);
await redis.acknowledgeAndDeleteStream(
stream,
RIOT_JOB_GROUP,
retriedEntry!.id,
);
expect((await client.xPending(stream, RIOT_JOB_GROUP)).pending).toBe(0);
expect(await client.xLen(stream)).toBe(0);
},
);
it('retains pending work during a disconnected retry client and recovers with a healthy connection', async () => {
const job = pollJob();
const entryId = await pendingPoll(RIOT_JOB_HIGH_STREAM, job);
const offlineClient = createClient({
url: process.env.REDIS_TEST_URL,
socket: { reconnectStrategy: false },
});
const offlineQueue = new RiotJobQueueService(
{} as never,
new RedisService(offlineClient),
);
await expect(
offlineQueue.rescheduleTournamentResultPoll({
stream: RIOT_JOB_HIGH_STREAM,
entryId,
job,
}),
).rejects.toThrow();
expect(
(await client.xPending(RIOT_JOB_HIGH_STREAM, RIOT_JOB_GROUP)).pending,
).toBe(1);
expect(await client.xLen(RIOT_JOB_HIGH_STREAM)).toBe(1);
expect(await client.zCard(RIOT_JOB_SCHEDULED_ZSET)).toBe(0);
await queue.rescheduleTournamentResultPoll({
stream: RIOT_JOB_HIGH_STREAM,
entryId,
job,
});
expect(
(await client.xPending(RIOT_JOB_HIGH_STREAM, RIOT_JOB_GROUP)).pending,
).toBe(0);
expect(await client.zCard(RIOT_JOB_SCHEDULED_ZSET)).toBe(1);
});
});
function pollJob(): PollTournamentResultJob {
return {
kind: 'poll-tournament-result',
jobId: 'original-result-job',
matchId: '6aeecacdffed1eb545b8c0f3',
attempt: 7,
expandedToAllPuuids: true,
enqueuedAt: 1_794_053_383_203,
priority: 'high',
};
}
async function pendingPoll(
stream: string,
job: PollTournamentResultJob,
): Promise<string> {
await redis.createConsumerGroup(stream, RIOT_JOB_GROUP, '0');
const entryId = await redis.appendStream(stream, {
job: JSON.stringify(job),
});
const delivery = await redis.readGroup(
stream,
RIOT_JOB_GROUP,
'original-worker',
'>',
{ count: 1 },
);
expect(delivery?.[0].messages[0].id).toBe(entryId);
return entryId;
}
+87
View File
@@ -0,0 +1,87 @@
import type { ApiAuction } from './types';
type AuctionActionState = Pick<
ApiAuction,
| 'auctionLifecycleId'
| 'currentAuctionPlayerOrderIndex'
| 'currentBidRoundPlayerUserId'
| 'phase'
| 'revision'
>;
interface AuctionActionObservation {
clientObservedAuctionLifecycleId?: string;
clientObservedCurrentAuctionPlayerOrderIndex?: number;
clientObservedCurrentBidRoundPlayerUserId?: string;
clientObservedPhase?: string;
clientObservedRevision?: number;
}
export function resolveAuctionActionRejection(
params: Parameters<typeof shouldRetryAuctionAction>[0],
): { applyServerState: boolean; retry: boolean } {
const { request, currentState, serverState } = params;
// Decide from the live screen before applying the ACK: an old response may force resync.
const applyServerState = Boolean(
currentState &&
serverState &&
request.clientObservedAuctionLifecycleId &&
currentState.auctionLifecycleId ===
request.clientObservedAuctionLifecycleId &&
(serverState.auctionLifecycleId !== currentState.auctionLifecycleId ||
(Number.isSafeInteger(serverState.revision) &&
(serverState.revision ?? -1) > (currentState.revision ?? -1))),
);
return { applyServerState, retry: shouldRetryAuctionAction(params) };
}
export function shouldRetryAuctionAction(params: {
action: string;
request: AuctionActionObservation;
serverState?: AuctionActionState | null;
currentState?: AuctionActionState | null;
resyncRecommended: boolean;
retryAttempt: number;
}): boolean {
const { action, request, serverState, currentState } = params;
if (
!params.resyncRecommended ||
params.retryAttempt >= 1 ||
!serverState ||
!currentState
) {
return false;
}
const phase = request.clientObservedPhase;
const phaseAllowsAction =
(action === 'next' && (phase === 'sold' || phase === 'passed')) ||
(action === 'open-bidding' && phase === 'presenting') ||
((action === 'sold' || action === 'passed') && phase === 'bidding');
if (
!phaseAllowsAction ||
!request.clientObservedAuctionLifecycleId ||
!request.clientObservedCurrentBidRoundPlayerUserId ||
!Number.isSafeInteger(
request.clientObservedCurrentAuctionPlayerOrderIndex,
) ||
(request.clientObservedCurrentAuctionPlayerOrderIndex ?? -1) < 0 ||
!Number.isSafeInteger(request.clientObservedRevision) ||
(request.clientObservedRevision ?? -1) < 0
) {
return false;
}
// A delayed rejection must not turn the original action into one for another player.
return [serverState, currentState].every(
(state) =>
state.auctionLifecycleId === request.clientObservedAuctionLifecycleId &&
state.currentAuctionPlayerOrderIndex ===
request.clientObservedCurrentAuctionPlayerOrderIndex &&
state.currentBidRoundPlayerUserId ===
request.clientObservedCurrentBidRoundPlayerUserId &&
state.phase === phase &&
Number.isSafeInteger(state.revision) &&
(state.revision ?? -1) >= request.clientObservedRevision!,
);
}
+7 -3
View File
@@ -14,11 +14,13 @@
const REASON_TO_USER_MESSAGE: Record<string, string> = {
// 구조 전환
AUCTION_TRANSITION_REJECTED_BECAUSE_LIVE_STATE_CHANGED_BEFORE_APPLY:
'경매 상태가 바뀌어 최신 상태로 맞췄어요. 다시 시도해 주세요.',
'경매 상태가 바뀌었어요. 현재 선수와 진행 상태를 확인해 주세요.',
AUCTION_TRANSITION_REJECTED_BECAUSE_AUCTION_NOT_IN_BIDDING_PHASE:
'이미 입찰 단계가 아니에요. 최신 상태로 맞췄어요.',
AUCTION_TRANSITION_REJECTED_BECAUSE_PHASE_DOES_NOT_ALLOW_ADVANCE:
'이미 다음 단계로 넘어간 상태예요. 최신 상태로 맞췄어요.',
'현재 단계에서는 다음 선수로 넘어갈 수 없어요. 현재 선수를 확인해 주세요.',
AUCTION_TRANSITION_REJECTED_BECAUSE_ROSTER_INVALID:
'팀 배정 상태를 확인해야 해 경매를 완료하지 못했습니다.',
AUCTION_TRANSITION_REJECTED_BECAUSE_NO_WINNING_BID_TO_MARK_SOLD:
'낙찰할 입찰이 없어요. 최신 상태로 맞췄어요.',
AUCTION_TRANSITION_REJECTED_BECAUSE_ACTIVE_BID_PRESENT:
@@ -56,7 +58,9 @@ const ENGLISH_MESSAGE_TO_USER_MESSAGE: Record<string, string> = {
'Unknown team.': '알 수 없는 팀이에요.',
'Bid request conflicts with an earlier request.': '중복된 요청이에요.',
'Cannot advance from current phase.':
'이미 다음 단계로 넘어간 상태예요. 최신 상태로 맞췄어요.',
'현재 단계에서는 다음 선수로 넘어갈 수 없어요. 현재 선수를 확인해 주세요.',
'Auction roster validation failed.':
'팀 배정 상태를 확인해야 해 경매를 완료하지 못했습니다.',
'No bid to mark sold.': '낙찰할 입찰이 없어요. 최신 상태로 맞췄어요.',
'Cannot pass a player with an active bid.':
'진행 중인 입찰이 있어 유찰할 수 없어요.',
+21 -16
View File
@@ -3,6 +3,7 @@ import { io, type Socket } from 'socket.io-client';
import { API_BASE_URL, useAuthUserId } from '../config';
import { acquireAccessToken } from '../lib/auth/token-provider';
import type { ApiAuction, ApiAuctionChatMessage, Position } from './types';
import { resolveAuctionActionRejection } from './auction-action-retry';
import {
isAuctionResyncRecommended,
resolveAuctionErrorMessage,
@@ -691,13 +692,21 @@ export function useAuctionSocket(matchId: string | undefined) {
clearPendingActionRequest(
ack?.auctionActionRequestId ?? auctionActionRequestId,
);
// 2) 자동 재시도: "낡은 화면 때문에 거부"였고 동기 rebaseline 소스(state)가
// 있을 때만 1회. assignedPosition 등 원래 payload는 유지하고 관측값/요청
// id만 새로 만든다. 재시도 시에는 중간 에러 문구를 띄우지 않는다(무음 복구).
const canAutoRetry =
Boolean(ack.state) &&
isAuctionResyncRecommended(ack) &&
retryAttempt < 1;
// 최신 화면과 거부 응답이 모두 원래 요청의 대상일 때만 한 번 재시도한다.
const { applyServerState, retry: canAutoRetry } =
resolveAuctionActionRejection({
action: eventName,
request: payload,
serverState: ack.state,
currentState: latestAuctionRef.current,
resyncRecommended: isAuctionResyncRecommended(ack),
retryAttempt,
});
if (ack.state && applyServerState) {
commitAuctionState(ack.state, 'action-reject-rebaseline');
} else if (!ack.state && isAuctionResyncRecommended(ack)) {
resyncAuctionState();
}
// 거부 시 "클라가 보낸 관측 revision"과 "서버가 동봉한 진짜 state"를 함께
// 기록한다. observedRevision < serverRevision 이면 stale-client CONFLICT 확정.
addNewRelicPageAction('AuctionClientActionRejected', {
@@ -725,18 +734,14 @@ export function useAuctionSocket(matchId: string | undefined) {
...describeAuctionForTelemetry('observed', latestAuctionRef.current),
...describeAuctionForTelemetry('server', ack?.state ?? null),
});
// 1) rebaseline: 서버가 동봉한 최신 state를 즉시 반영(없으면 join으로 재요청).
// commitAuctionState는 latestAuctionRef를 동기로 갱신하므로, 이후
// buildAuctionActionPayload는 최신 관측값(revision/phase/선수)을 읽는다.
if (ack.state) {
commitAuctionState(ack.state, 'action-reject-rebaseline');
} else if (isAuctionResyncRecommended(ack)) {
resyncAuctionState();
}
if (canAutoRetry) {
emitAuctionAction(
eventName,
{ ...payload, ...buildAuctionActionPayload() },
{
...payload,
auctionActionRequestId: createClientRequestId(),
clientObservedRevision: latestAuctionRef.current?.revision,
},
retryAttempt + 1,
);
} else {
@@ -104,7 +104,11 @@ export function SeriesScoreCard({
{presentation.label}
</span>
</header>
<div className="divide-y divide-base-content/8">
<div
className={
isBracket ? "relative" : "divide-y divide-base-content/8"
}
>
{series.entries.map((entry) => {
const team = entry.teamId ? teamById.get(entry.teamId) : undefined;
const isWinner = isSeriesEntryWinner(series, entry.teamId);
@@ -129,6 +133,13 @@ export function SeriesScoreCard({
/>
);
})}
{isBracket && (
<span
className="pointer-events-none absolute inset-x-0 border-t border-base-content/8"
style={{ top: SERIES_SCORE_CARD_GEOMETRY.entryHeight }}
aria-hidden="true"
/>
)}
</div>
</article>
);
@@ -17,6 +17,8 @@ export const DOUBLE_ELIMINATION_BRACKET_GEOMETRY = {
boardPadding: 12,
columnWidth: 228,
columnGap: 40,
// Matches the widest focused connector underlay so parallel routes stay legible.
connectorRailClearance: 5,
cardBorderWidth: SERIES_SCORE_CARD_GEOMETRY.borderWidth,
cardHeight: SERIES_SCORE_CARD_GEOMETRY.height,
cardHeaderHeight: SERIES_SCORE_CARD_GEOMETRY.headerHeight,
@@ -109,6 +111,29 @@ interface NormalizedRound {
seriesIds: SeriesId[];
}
interface ConnectorRoute {
connector: SeriesConnectorView;
key: string;
kind: BracketConnectorKind;
targetColumn: number;
targetNodeY: number;
sourceX: number;
sourceY: number;
targetX: number;
targetY: number;
}
interface SeparateWinnerRailChoice {
verticalXs: [number, number];
crossings: number;
distanceFromBaseline: number;
distanceFromCenter: number;
}
type OrthogonalSegment =
| { orientation: "horizontal"; fixed: number; start: number; end: number }
| { orientation: "vertical"; fixed: number; start: number; end: number };
const STAGE_ORDER: Record<BracketStage, number> = {
upper: 0,
lower: 1,
@@ -126,6 +151,9 @@ const CONNECTOR_SELECTION_ORDER: Record<
"slot-b": 3,
};
// A focused 5px underlay extends 2.5px from its centerline.
const CONNECTOR_RAIL_EDGE_INSET = 3;
export function createDoubleEliminationBracketLayout(
projection: DoubleEliminationCompetitionProjection,
configuration: DoubleEliminationBracketConfiguration,
@@ -540,56 +568,53 @@ function buildConnectors(
nodeById: Map<SeriesId, BracketNodeLayout>,
): BracketConnectorLayout[] | null {
const geometry = DOUBLE_ELIMINATION_BRACKET_GEOMETRY;
const connectorsByTargetColumn = new Map<
number,
Array<{
connector: SeriesConnectorView;
source: BracketNodeLayout;
target: BracketNodeLayout;
}>
>();
const routes: ConnectorRoute[] = [];
const routesByTargetColumn = new Map<number, ConnectorRoute[]>();
for (const connector of projection.connectors) {
const source = nodeById.get(connector.from.seriesId);
const target = nodeById.get(connector.to.seriesId);
if (!source || !target || target.column <= source.column) return null;
const routes = connectorsByTargetColumn.get(target.column) ?? [];
routes.push({ connector, source, target });
connectorsByTargetColumn.set(target.column, routes);
const route = {
connector,
key: connectorKey(connector),
kind: connectorKind(connector.from.select),
targetColumn: target.column,
targetNodeY: target.y,
sourceX: source.x + source.width,
sourceY: connectorAnchorY(source, connector.from.select),
targetX: target.x,
targetY: targetSlotY(target, connector.to.slot),
} satisfies ConnectorRoute;
routes.push(route);
const columnRoutes = routesByTargetColumn.get(target.column) ?? [];
columnRoutes.push(route);
routesByTargetColumn.set(target.column, columnRoutes);
}
const verticalXByConnector = new Map<string, number>();
for (const routes of connectorsByTargetColumn.values()) {
routes.sort(
for (const columnRoutes of routesByTargetColumn.values()) {
columnRoutes.sort(
(left, right) =>
connectorAnchorY(right.source, right.connector.from.select) -
connectorAnchorY(left.source, left.connector.from.select) ||
targetSlotY(right.target, right.connector.to.slot) -
targetSlotY(left.target, left.connector.to.slot) ||
connectorKey(left.connector).localeCompare(connectorKey(right.connector)),
right.sourceY - left.sourceY ||
right.targetY - left.targetY ||
left.key.localeCompare(right.key),
);
routes.forEach(({ connector, target }, index) => {
columnRoutes.forEach(({ key, targetX }, index) => {
verticalXByConnector.set(
connectorKey(connector),
target.x -
key,
targetX -
geometry.columnGap +
(geometry.columnGap * (index + 1)) / (routes.length + 1),
(geometry.columnGap * (index + 1)) / (columnRoutes.length + 1),
);
});
}
if (!alignWinnerBundleRails(routes, verticalXByConnector)) return null;
const result: BracketConnectorLayout[] = [];
for (const connector of projection.connectors) {
const source = nodeById.get(connector.from.seriesId);
const target = nodeById.get(connector.to.seriesId);
if (!source || !target || target.column <= source.column) return null;
const sourceX = source.x + source.width;
const targetX = target.x;
const sourceY = connectorAnchorY(source, connector.from.select);
const targetY = targetSlotY(target, connector.to.slot);
const verticalX = verticalXByConnector.get(connectorKey(connector));
for (const route of routes) {
const { connector, key, kind, sourceX, sourceY, targetX, targetY } = route;
const verticalX = verticalXByConnector.get(key);
if (verticalX === undefined) return null;
const kind = connectorKind(connector.from.select);
result.push({
fromSeriesId: connector.from.seriesId,
select: connector.from.select,
@@ -622,6 +647,324 @@ function buildConnectors(
);
}
function alignWinnerBundleRails(
routes: readonly ConnectorRoute[],
verticalXByConnector: Map<string, number>,
): boolean {
const winnersByTarget = new Map<SeriesId, ConnectorRoute[]>();
for (const route of routes) {
if (route.kind !== "winner") continue;
const winners = winnersByTarget.get(route.connector.to.seriesId) ?? [];
winners.push(route);
winnersByTarget.set(route.connector.to.seriesId, winners);
}
const bundles = [...winnersByTarget.values()]
.filter(
(winners) =>
winners.length === 2 &&
winners[0].connector.to.slot !== winners[1].connector.to.slot,
)
.sort(
(left, right) =>
left[0].targetColumn - right[0].targetColumn ||
left[0].targetNodeY - right[0].targetNodeY ||
left[0].key.localeCompare(right[0].key),
);
for (const bundle of bundles) {
const preferredX =
bundle[0].targetX - DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap / 2;
if (
intervalsOverlap(
bundle[0].sourceY,
bundle[0].targetY,
bundle[1].sourceY,
bundle[1].targetY,
)
) {
const assignment = chooseSeparateWinnerRails(
bundle,
routes,
verticalXByConnector,
preferredX,
);
if (!assignment) return false;
for (const [key, verticalX] of assignment) {
verticalXByConnector.set(key, verticalX);
}
continue;
}
const verticalX = chooseWinnerBundleRail(
bundle,
routes,
verticalXByConnector,
preferredX,
);
if (verticalX === null) return false;
for (const route of bundle) verticalXByConnector.set(route.key, verticalX);
}
return true;
}
function chooseWinnerBundleRail(
bundle: readonly ConnectorRoute[],
routes: readonly ConnectorRoute[],
verticalXByConnector: Map<string, number>,
preferredX: number,
): number | null {
const previousRails = bundle.map((route) =>
verticalXByConnector.get(route.key),
);
if (previousRails.some((verticalX) => verticalX === undefined)) return null;
const previousScore = connectorConflictScore(routes, verticalXByConnector);
// Keep the existing crossing budget, then favor stroke-clear rails nearest center.
let best:
| {
verticalX: number;
crossings: number;
clearanceConflicts: number;
distanceFromCenter: number;
}
| null = null;
for (const candidateX of winnerRailCandidates(preferredX)) {
for (const route of bundle) {
verticalXByConnector.set(route.key, candidateX);
}
const score = connectorConflictScore(routes, verticalXByConnector);
if (
score.overlaps !== 0 ||
score.crossings > previousScore.crossings ||
score.clearanceConflicts > previousScore.clearanceConflicts
) {
continue;
}
const distanceFromCenter = Math.abs(candidateX - preferredX);
if (
!best ||
score.clearanceConflicts < best.clearanceConflicts ||
(score.clearanceConflicts === best.clearanceConflicts &&
(score.crossings < best.crossings ||
(score.crossings === best.crossings &&
distanceFromCenter < best.distanceFromCenter)))
) {
best = {
verticalX: candidateX,
crossings: score.crossings,
clearanceConflicts: score.clearanceConflicts,
distanceFromCenter,
};
}
}
if (best) return best.verticalX;
bundle.forEach((route, index) => {
const previousX = previousRails[index];
if (previousX !== undefined) {
verticalXByConnector.set(route.key, previousX);
}
});
return null;
}
function winnerRailCandidates(preferredX: number): number[] {
const geometry = DOUBLE_ELIMINATION_BRACKET_GEOMETRY;
const maximumOffset =
geometry.columnGap / 2 - CONNECTOR_RAIL_EDGE_INSET;
const candidates = [preferredX];
for (let offset = 1; offset <= maximumOffset; offset += 1) {
candidates.push(preferredX - offset, preferredX + offset);
}
return candidates;
}
function chooseSeparateWinnerRails(
bundle: readonly ConnectorRoute[],
routes: readonly ConnectorRoute[],
verticalXByConnector: Map<string, number>,
preferredX: number,
): Map<string, number> | null {
const orderedBundle = [...bundle].sort(
(left, right) =>
left.sourceY - right.sourceY ||
left.targetY - right.targetY ||
left.key.localeCompare(right.key),
);
const previousRails: number[] = [];
for (const route of orderedBundle) {
const previousX = verticalXByConnector.get(route.key);
if (previousX === undefined) return null;
previousRails.push(previousX);
}
const previousScore = connectorConflictScore(routes, verticalXByConnector);
const bundleKeys = new Set(orderedBundle.map(({ key }) => key));
const candidates = [
...new Set([...previousRails, ...winnerRailCandidates(preferredX)]),
];
let best: SeparateWinnerRailChoice | null = null;
for (const firstX of candidates) {
for (const secondX of candidates) {
if (firstX === secondX) continue;
verticalXByConnector.set(orderedBundle[0].key, firstX);
verticalXByConnector.set(orderedBundle[1].key, secondX);
const bundleScore = connectorConflictScore(
routes,
verticalXByConnector,
bundleKeys,
);
const score = connectorConflictScore(routes, verticalXByConnector);
if (
bundleScore.overlaps !== 0 ||
bundleScore.clearanceConflicts !== 0 ||
score.overlaps !== 0 ||
score.crossings > previousScore.crossings
) {
continue;
}
const distanceFromBaseline =
Math.abs(firstX - previousRails[0]) +
Math.abs(secondX - previousRails[1]);
const distanceFromCenter =
Math.abs(firstX - preferredX) + Math.abs(secondX - preferredX);
const candidate: SeparateWinnerRailChoice = {
verticalXs: [firstX, secondX],
crossings: score.crossings,
distanceFromBaseline,
distanceFromCenter,
};
if (!best || compareSeparateWinnerRailChoices(candidate, best) < 0) {
best = candidate;
}
}
}
orderedBundle.forEach((route, index) => {
verticalXByConnector.set(route.key, previousRails[index]);
});
if (!best) return null;
return new Map(
orderedBundle.map((route, index) => [route.key, best.verticalXs[index]]),
);
}
function compareSeparateWinnerRailChoices(
left: SeparateWinnerRailChoice,
right: SeparateWinnerRailChoice,
): number {
return (
left.crossings - right.crossings ||
left.distanceFromBaseline - right.distanceFromBaseline ||
left.distanceFromCenter - right.distanceFromCenter ||
left.verticalXs[0] - right.verticalXs[0] ||
left.verticalXs[1] - right.verticalXs[1]
);
}
function connectorConflictScore(
routes: readonly ConnectorRoute[],
verticalXByConnector: ReadonlyMap<string, number>,
focusedRouteKeys?: ReadonlySet<string>,
): { crossings: number; overlaps: number; clearanceConflicts: number } {
let crossings = 0;
let overlaps = 0;
let clearanceConflicts = 0;
for (let leftIndex = 0; leftIndex < routes.length; leftIndex += 1) {
const leftX = verticalXByConnector.get(routes[leftIndex].key);
if (leftX === undefined) continue;
const leftSegments = connectorRouteSegments(routes[leftIndex], leftX);
for (
let rightIndex = leftIndex + 1;
rightIndex < routes.length;
rightIndex += 1
) {
if (
focusedRouteKeys &&
!focusedRouteKeys.has(routes[leftIndex].key) &&
!focusedRouteKeys.has(routes[rightIndex].key)
) {
continue;
}
const rightX = verticalXByConnector.get(routes[rightIndex].key);
if (rightX === undefined) continue;
const rightSegments = connectorRouteSegments(routes[rightIndex], rightX);
for (const left of leftSegments) {
for (const right of rightSegments) {
if (left.orientation === right.orientation) {
const overlapLength =
Math.min(left.end, right.end) - Math.max(left.start, right.start);
if (left.fixed === right.fixed && overlapLength > 0) {
overlaps += 1;
} else if (
left.orientation === "vertical" &&
overlapLength > 0 &&
Math.abs(left.fixed - right.fixed) <
DOUBLE_ELIMINATION_BRACKET_GEOMETRY.connectorRailClearance
) {
clearanceConflicts += 1;
}
continue;
}
const horizontal =
left.orientation === "horizontal" ? left : right;
const vertical = left.orientation === "vertical" ? left : right;
if (
vertical.fixed > horizontal.start &&
vertical.fixed < horizontal.end &&
horizontal.fixed > vertical.start &&
horizontal.fixed < vertical.end
) {
crossings += 1;
}
}
}
}
}
return { crossings, overlaps, clearanceConflicts };
}
function connectorRouteSegments(
route: ConnectorRoute,
verticalX: number,
): OrthogonalSegment[] {
return [
orthogonalSegment("horizontal", route.sourceY, route.sourceX, verticalX),
orthogonalSegment("vertical", verticalX, route.sourceY, route.targetY),
orthogonalSegment("horizontal", route.targetY, verticalX, route.targetX),
];
}
function orthogonalSegment(
orientation: OrthogonalSegment["orientation"],
fixed: number,
first: number,
second: number,
): OrthogonalSegment {
return {
orientation,
fixed,
start: Math.min(first, second),
end: Math.max(first, second),
};
}
function intervalsOverlap(
firstStart: number,
firstEnd: number,
secondStart: number,
secondEnd: number,
): boolean {
return (
Math.min(firstStart, firstEnd) < Math.max(secondStart, secondEnd) &&
Math.min(secondStart, secondEnd) < Math.max(firstStart, firstEnd)
);
}
function connectorLabel(
connector: SeriesConnectorView,
graph: ValidatedGraph,
+4 -1
View File
@@ -2144,7 +2144,10 @@ export default function AuctionPage() {
</Link>
{errorMessage && (
<div className="mb-4 border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm text-red-500">
<div
role="alert"
className="mb-4 border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm text-red-500"
>
{errorMessage}
</div>
)}
+1 -23
View File
@@ -85,7 +85,6 @@ function HistoryTableColGroup() {
<col className="w-[88px]" />
<col className="w-[132px]" />
<col className="w-[72px]" />
<col className="w-[116px]" />
</colgroup>
);
}
@@ -99,7 +98,6 @@ function HistoryTableHeader() {
<th className="py-2.5 px-4 font-semibold">상태</th>
<th className="py-2.5 px-4 font-semibold">맵</th>
<th className="py-2.5 px-4 font-semibold">참가</th>
<th className="py-2.5 px-4 font-semibold">결과</th>
</tr>
</thead>
);
@@ -156,14 +154,6 @@ function HistoryRecordsSkeleton({
10명
</SkeletonText>
</td>
<td className="py-2.5 px-4 text-xs text-base-content/50 whitespace-nowrap">
<SkeletonText
className="truncate"
skeletonClassName="h-[1em] w-14"
>
1팀 승리
</SkeletonText>
</td>
</tr>
))}
</tbody>
@@ -205,10 +195,6 @@ function HistoryRecordsSkeleton({
<SkeletonText skeletonClassName="h-[1em] w-8">
10명
</SkeletonText>
<span className="invisible text-base-content/20">·</span>
<SkeletonText skeletonClassName="h-[1em] w-14">
1팀 승리
</SkeletonText>
</div>
</div>
</div>
@@ -682,20 +668,12 @@ export default function HomePage() {
<td className="py-2.5 px-4 text-xs text-base-content/50 whitespace-nowrap">
{match.participants.length}명
</td>
<td className="py-2.5 px-4 text-xs text-base-content/50 whitespace-nowrap">
<Link
to={`/match/${match.id}`}
className="font-semibold text-base-content/45 hover:text-primary"
>
공식 결과
</Link>
</td>
</tr>
))
) : (
<tr>
<td
colSpan={6}
colSpan={5}
className="py-6 px-4 text-sm text-base-content/35 text-center"
>
아직 내전 기록이 없습니다.
-22
View File
@@ -127,21 +127,6 @@ function formatRefreshError(error: unknown) {
return error instanceof Error ? error.message : "갱신 요청에 실패했습니다.";
}
function socketStatusMeta(status: string): { tone: string; label: string } {
switch (status) {
case "connected":
return { tone: "bg-emerald-400", label: "실시간 연결됨" };
case "connecting":
return { tone: "bg-amber-400", label: "연결 중" };
case "error":
return { tone: "bg-red-400", label: "연결 오류" };
case "disconnected":
return { tone: "bg-base-content/30", label: "연결 끊김" };
default:
return { tone: "bg-base-content/20", label: "대기 중" };
}
}
function ratioClass(value: number) {
if (value >= 55) return "text-blue-400";
if (value >= 50) return "text-amber-400";
@@ -1329,7 +1314,6 @@ export default function UserHistoryPage() {
);
}
const socketStatus = socketStatusMeta(refreshSocket.connectionStatus);
const refreshNoticeIsError =
Boolean(refreshSocket.error) ||
Boolean(refreshNotice?.startsWith("갱신 실패"));
@@ -1386,12 +1370,6 @@ export default function UserHistoryPage() {
? "요청 중..."
: "정보 갱신"}
</button>
{!isInternalQueue && (
<div className="flex items-center gap-1.5 text-[11px] text-base-content/30 sm:justify-end">
<span className={`h-1.5 w-1.5 ${socketStatus.tone}`} />
{socketStatus.label}
</div>
)}
</div>
</div>
{(refreshNotice || refreshSocket.error) && (
+199
View File
@@ -0,0 +1,199 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
resolveAuctionActionRejection,
shouldRetryAuctionAction,
} from "../src/api/auction-action-retry.ts";
const request = {
clientObservedAuctionLifecycleId: "auction-1",
clientObservedCurrentAuctionPlayerOrderIndex: 11,
clientObservedCurrentBidRoundPlayerUserId: "player-11",
clientObservedPhase: "sold",
clientObservedRevision: 130,
};
const state = {
auctionLifecycleId: "auction-1",
currentAuctionPlayerOrderIndex: 11,
currentBidRoundPlayerUserId: "player-11",
phase: "sold" as const,
revision: 131,
};
const input = {
action: "next",
request,
serverState: state,
currentState: state,
resyncRecommended: true,
retryAttempt: 0,
};
test("a delayed old-lifecycle rejection cannot roll back the screen and retry", () => {
const currentState = {
...state,
auctionLifecycleId: "auction-2",
revision: 1,
};
const decision = resolveAuctionActionRejection({ ...input, currentState });
assert.deepEqual(decision, { applyServerState: false, retry: false });
});
test("an older forced-resync rejection cannot roll back an already advanced player", () => {
const serverState = { ...state, shouldForceAuctionStateResync: true };
const currentState = {
...state,
revision: 132,
currentAuctionPlayerOrderIndex: 12,
};
assert.deepEqual(
resolveAuctionActionRejection({ ...input, serverState, currentState }),
{
applyServerState: false,
retry: false,
},
);
});
test("a fresh rejection updates the screen to the new player without retrying", () => {
const serverState = {
...state,
currentAuctionPlayerOrderIndex: 12,
phase: "presenting" as const,
};
assert.deepEqual(
resolveAuctionActionRejection({
...input,
serverState,
currentState: { ...state, revision: 130 },
}),
{ applyServerState: true, retry: false },
);
});
test("a same-target revision update is applied and permits one retry", () => {
assert.deepEqual(
resolveAuctionActionRejection({
...input,
currentState: { ...state, revision: 130 },
}),
{ applyServerState: true, retry: true },
);
});
test("retries a revision conflict only while the original action target is unchanged", () => {
assert.equal(shouldRetryAuctionAction(input), true);
});
test("does not retry next for the following player after a conflict", () => {
const nextPlayer = {
...state,
currentAuctionPlayerOrderIndex: 12,
currentBidRoundPlayerUserId: "player-12",
phase: "presenting" as const,
};
assert.equal(
shouldRetryAuctionAction({
...input,
serverState: nextPlayer,
currentState: nextPlayer,
}),
false,
);
});
for (const patch of [
{ auctionLifecycleId: "auction-2" },
{ currentAuctionPlayerOrderIndex: 12 },
{ currentBidRoundPlayerUserId: "player-12" },
{ phase: "passed" as const },
]) {
test(`does not retarget a retry when ${Object.keys(patch)[0]} changes`, () => {
assert.equal(
shouldRetryAuctionAction({
...input,
serverState: { ...state, ...patch },
}),
false,
);
});
}
test("does not retry from an older acknowledgement after the live screen has advanced", () => {
assert.equal(
shouldRetryAuctionAction({
...input,
currentState: { ...state, currentAuctionPlayerOrderIndex: 12 },
}),
false,
);
});
test("does not retry with missing original target identity", () => {
for (const field of Object.keys(request)) {
assert.equal(
shouldRetryAuctionAction({
...input,
request: { ...request, [field]: undefined },
}),
false,
);
}
});
test("does not retry without a current state, a server state, or a retry recommendation", () => {
assert.equal(
shouldRetryAuctionAction({ ...input, currentState: null }),
false,
);
assert.equal(
shouldRetryAuctionAction({ ...input, serverState: undefined }),
false,
);
assert.equal(
shouldRetryAuctionAction({ ...input, resyncRecommended: false }),
false,
);
assert.equal(shouldRetryAuctionAction({ ...input, retryAttempt: 1 }), false);
});
test("does not retry next in presenting even if the target is unchanged", () => {
assert.equal(
shouldRetryAuctionAction({
...input,
request: { ...request, clientObservedPhase: "presenting" },
serverState: { ...state, phase: "presenting" },
currentState: { ...state, phase: "presenting" },
}),
false,
);
});
test("does not retry using a revision older than the original request", () => {
assert.equal(
shouldRetryAuctionAction({
...input,
serverState: { ...state, revision: 129 },
}),
false,
);
});
for (const [action, phase] of [
["open-bidding", "presenting"],
["sold", "bidding"],
["passed", "bidding"],
["next", "passed"],
] as const) {
test(`allows a same-target ${action} retry in ${phase}`, () => {
assert.equal(
shouldRetryAuctionAction({
...input,
action,
request: { ...request, clientObservedPhase: phase },
serverState: { ...state, phase },
currentState: { ...state, phase },
}),
true,
);
});
}
@@ -0,0 +1,27 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
resolveAuctionErrorMessage,
resolveAuctionRejectionMessage,
} from "../src/api/auctionRejectionMessages.ts";
const rosterMessage = "팀 배정 상태를 확인해야 해 경매를 완료하지 못했습니다.";
test("shows the common error message when roster validation blocks completion", () => {
assert.equal(
resolveAuctionRejectionMessage({
auctionRejectionReason:
"AUCTION_TRANSITION_REJECTED_BECAUSE_ROSTER_INVALID",
code: "AUCTION_ROSTER_INVALID",
message: "Auction roster validation failed.",
}),
rosterMessage,
);
});
test("shows the same roster message for the socket error event", () => {
assert.equal(
resolveAuctionErrorMessage("Auction roster validation failed."),
rosterMessage,
);
});
@@ -367,6 +367,7 @@ test("orders mobile groups as winners, losers, grand final, then reset final", (
shuffledLayout.mobileGroups.map((group) => group.seriesIds),
orderedLayout.mobileGroups.map((group) => group.seriesIds),
);
assert.deepEqual(shuffledLayout.connectors, orderedLayout.connectors);
assert.deepEqual(
shuffledLayout.mobileGroups.flatMap((group) => group.seriesIds).sort(),
shuffled.projection.series.map((series) => series.seriesId).sort(),
@@ -474,11 +475,10 @@ test("returns null instead of throwing for an unknown connector discriminator",
);
});
test("keeps connector rails distinct and outside intervening card rectangles", () => {
test("keeps connector rails finite and outside intervening card rectangles", () => {
const { projection } = eightTeamProjection();
const layout = requireLayout(projection, EIGHT_TEAM_LAYOUT);
const nodes = new Map(layout.nodes.map((node) => [node.seriesId, node]));
const routesByTargetColumn = new Map<number, number[]>();
for (const route of layout.connectors) {
const source = nodes.get(route.fromSeriesId);
@@ -511,23 +511,256 @@ test("keeps connector rails distinct and outside intervening card rectangles", (
false,
);
}
}
});
const rails = routesByTargetColumn.get(target.column) ?? [];
rails.push(route.verticalX);
routesByTargetColumn.set(target.column, rails);
test("aligns paired winner bends on one shared rail", () => {
const fourTeam = fourTeamProjection();
const fourTeamLayout = requireLayout(fourTeam.projection, FOUR_TEAM_LAYOUT);
for (const targetSeriesId of [fourTeam.ids.WB_FINAL, fourTeam.ids.GF]) {
const routes = winnerRoutesTo(fourTeamLayout, targetSeriesId);
assert.equal(routes.length, 2);
assert.equal(routes[0].verticalX, routes[1].verticalX);
}
for (const rails of routesByTargetColumn.values()) {
assert.equal(new Set(rails).size, rails.length);
const { projection, ids } = eightTeamProjection();
const layout = requireLayout(projection, EIGHT_TEAM_LAYOUT);
for (const targetSeriesId of [
ids.WB_R2_M1,
ids.WB_R2_M2,
ids.WB_FINAL,
ids.LB_R3_M1,
ids.GF,
]) {
const routes = winnerRoutesTo(layout, targetSeriesId);
assert.equal(routes.length, 2);
assert.equal(
routes[0].verticalX,
routes[1].verticalX,
`${targetSeriesId} winner routes must share one bend rail`,
);
}
});
test("keeps reversed winner slots on deterministic non-overlapping rails", () => {
const { projection, ids } = fourTeamProjection();
const reversed = cloneProjection(projection);
const firstWinner = reversed.connectors.find(
({ from, to }) =>
from.seriesId === ids.WB_R1_M1 &&
from.select === "winner" &&
to.seriesId === ids.WB_FINAL,
);
const secondWinner = reversed.connectors.find(
({ from, to }) =>
from.seriesId === ids.WB_R1_M2 &&
from.select === "winner" &&
to.seriesId === ids.WB_FINAL,
);
assert.ok(firstWinner);
assert.ok(secondWinner);
firstWinner.to = { seriesId: ids.WB_FINAL, slot: "B" };
secondWinner.to = { seriesId: ids.WB_FINAL, slot: "A" };
const orderedLayout = requireLayout(reversed, FOUR_TEAM_LAYOUT);
const shuffled = cloneProjection(reversed);
shuffled.connectors = shuffledCopy(shuffled.connectors);
const shuffledLayout = requireLayout(shuffled, FOUR_TEAM_LAYOUT);
const routes = winnerRoutesTo(orderedLayout, ids.WB_FINAL);
assert.equal(routes.length, 2);
assert.equal(new Set(routes.map(({ verticalX }) => verticalX)).size, 2);
assert.equal(countCollinearConnectorOverlaps(orderedLayout.connectors), 0);
assert.deepEqual(shuffledLayout.connectors, orderedLayout.connectors);
});
test("moves reversed winner rails clear of overlapping connector underlays", () => {
const { projection, ids } = eightTeamProjection();
const reversed = cloneProjection(projection);
const firstWinner = reversed.connectors.find(
({ from, to }) =>
from.seriesId === ids.WB_R1_M1 &&
from.select === "winner" &&
to.seriesId === ids.WB_R2_M1,
);
const secondWinner = reversed.connectors.find(
({ from, to }) =>
from.seriesId === ids.WB_R1_M2 &&
from.select === "winner" &&
to.seriesId === ids.WB_R2_M1,
);
assert.ok(firstWinner);
assert.ok(secondWinner);
firstWinner.to = { seriesId: ids.WB_R2_M1, slot: "B" };
secondWinner.to = { seriesId: ids.WB_R2_M1, slot: "A" };
const layout = requireLayout(reversed, EIGHT_TEAM_LAYOUT);
const shuffled = cloneProjection(reversed);
shuffled.connectors = shuffledCopy(shuffled.connectors);
const shuffledLayout = requireLayout(shuffled, EIGHT_TEAM_LAYOUT);
const winners = winnerRoutesTo(layout, ids.WB_R2_M1);
assert.equal(winners.length, 2);
for (const winner of winners) {
for (const route of layout.connectors) {
if (
route === winner ||
!intervalsStrictlyOverlap(
winner.sourceY,
winner.targetY,
route.sourceY,
route.targetY,
)
) {
continue;
}
assert.ok(
Math.abs(winner.verticalX - route.verticalX) >=
DOUBLE_ELIMINATION_BRACKET_GEOMETRY.connectorRailClearance,
`${winner.fromSeriesId} winner rail ${winner.verticalX} is too close to ${route.fromSeriesId} ${route.kind} rail ${route.verticalX}`,
);
}
}
assert.deepEqual(shuffledLayout.connectors, layout.connectors);
});
test("centers conflict-free paired winner bends in the routing gap", () => {
const fourTeam = fourTeamProjection();
const fourTeamLayout = requireLayout(fourTeam.projection, FOUR_TEAM_LAYOUT);
const fourTeamGrandFinal = nodeFor(fourTeamLayout, fourTeam.ids.GF);
assert.deepEqual(
winnerRoutesTo(fourTeamLayout, fourTeam.ids.GF).map(
({ verticalX }) => verticalX,
),
[
fourTeamGrandFinal.x -
DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap / 2,
fourTeamGrandFinal.x -
DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap / 2,
],
);
const { projection, ids } = eightTeamProjection();
const layout = requireLayout(projection, EIGHT_TEAM_LAYOUT);
for (const targetSeriesId of [ids.LB_R3_M1, ids.GF]) {
const target = nodeFor(layout, targetSeriesId);
const expectedVerticalX =
target.x - DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap / 2;
const routes = winnerRoutesTo(layout, targetSeriesId);
assert.equal(routes.length, 2);
assert.deepEqual(
routes.map(({ verticalX }) => verticalX),
[expectedVerticalX, expectedVerticalX],
);
}
});
test("preserves baseline rails for loser and reset paths", () => {
const { projection } = eightTeamProjection({ resetFinal: true });
const layout = requireLayout(projection, EIGHT_TEAM_RESET_LAYOUT);
const nodes = new Map(layout.nodes.map((node) => [node.seriesId, node]));
const routesByTargetColumn = new Map<number, ConnectorLayout[]>();
for (const route of layout.connectors) {
const target = nodes.get(route.toSeriesId);
assert.ok(target);
const routes = routesByTargetColumn.get(target.column) ?? [];
routes.push(route);
routesByTargetColumn.set(target.column, routes);
}
for (const routes of routesByTargetColumn.values()) {
routes.sort(
(left, right) =>
right.sourceY - left.sourceY ||
right.targetY - left.targetY ||
connectorLayoutKey(left).localeCompare(connectorLayoutKey(right)),
);
routes.forEach((route, index) => {
if (route.kind === "winner") return;
assert.equal(
route.verticalX,
route.targetX -
DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap +
(DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap * (index + 1)) /
(routes.length + 1),
);
});
}
});
test("keeps paired winner rails clear of overlapping loser paths", () => {
const fourTeam = fourTeamProjection();
const eightTeam = eightTeamProjection();
const fixtures = [
{
layout: requireLayout(fourTeam.projection, FOUR_TEAM_LAYOUT),
pairedWinnerTargets: new Set<SeriesId>([
fourTeam.ids.WB_FINAL,
fourTeam.ids.GF,
]),
},
{
layout: requireLayout(eightTeam.projection, EIGHT_TEAM_LAYOUT),
pairedWinnerTargets: new Set<SeriesId>([
eightTeam.ids.WB_R2_M1,
eightTeam.ids.WB_R2_M2,
eightTeam.ids.WB_FINAL,
eightTeam.ids.LB_R3_M1,
eightTeam.ids.GF,
]),
},
];
for (const { layout, pairedWinnerTargets } of fixtures) {
for (const winner of layout.connectors) {
if (
winner.kind !== "winner" ||
!pairedWinnerTargets.has(winner.toSeriesId)
) {
continue;
}
for (const loser of layout.connectors) {
if (
loser.kind !== "loser" ||
!intervalsStrictlyOverlap(
winner.sourceY,
winner.targetY,
loser.sourceY,
loser.targetY,
)
) {
continue;
}
assert.ok(
Math.abs(winner.verticalX - loser.verticalX) >=
DOUBLE_ELIMINATION_BRACKET_GEOMETRY.connectorRailClearance,
`${winner.fromSeriesId} winner rail ${winner.verticalX} is too close to ${loser.fromSeriesId} loser rail ${loser.verticalX}`,
);
}
}
}
});
test("minimizes connector crossings without introducing segment overlaps", () => {
const { projection } = eightTeamProjection();
const layout = requireLayout(projection, EIGHT_TEAM_LAYOUT);
const fourTeam = fourTeamProjection();
const fourTeamReset = fourTeamProjection({ resetFinal: true });
const eightTeam = eightTeamProjection();
const eightTeamReset = eightTeamProjection({ resetFinal: true });
const layouts = [
requireLayout(fourTeam.projection, FOUR_TEAM_LAYOUT),
requireLayout(fourTeamReset.projection, FOUR_TEAM_RESET_LAYOUT),
requireLayout(eightTeam.projection, EIGHT_TEAM_LAYOUT),
requireLayout(eightTeamReset.projection, EIGHT_TEAM_RESET_LAYOUT),
];
assert.equal(countStrictConnectorCrossings(layout.connectors), 12);
assert.equal(countCollinearConnectorOverlaps(layout.connectors), 0);
assert.ok(countStrictConnectorCrossings(layouts[2].connectors) <= 12);
for (const layout of layouts) {
assert.equal(countCollinearConnectorOverlaps(layout.connectors), 0);
}
});
test("aligns connector endpoints with the A and B entry row centers", () => {
@@ -921,6 +1154,18 @@ function segment(
};
}
function intervalsStrictlyOverlap(
firstStart: number,
firstEnd: number,
secondStart: number,
secondEnd: number,
): boolean {
return (
Math.min(firstStart, firstEnd) < Math.max(secondStart, secondEnd) &&
Math.min(secondStart, secondEnd) < Math.max(firstStart, firstEnd)
);
}
function countStrictConnectorCrossings(routes: readonly ConnectorLayout[]): number {
let crossings = 0;
for (let leftIndex = 0; leftIndex < routes.length; leftIndex += 1) {
@@ -1009,6 +1254,16 @@ function nodeFor(
return node;
}
function winnerRoutesTo(
layout: NonNullable<ReturnType<typeof createDoubleEliminationBracketLayout>>,
targetSeriesId: SeriesId,
) {
return layout.connectors.filter(
(route) =>
route.kind === "winner" && route.toSeriesId === targetSeriesId,
);
}
function routeFrom(
layout: NonNullable<ReturnType<typeof createDoubleEliminationBracketLayout>>,
id: SeriesId,
@@ -1036,6 +1291,10 @@ function connectorIdentity(
};
}
function connectorLayoutKey(connector: ConnectorLayout): string {
return `${connector.fromSeriesId}:${connector.select}:${connector.toSeriesId}:${connector.toSlot}`;
}
function mobileGroupKeys(
layout: NonNullable<ReturnType<typeof createDoubleEliminationBracketLayout>>,
) {
+29
View File
@@ -0,0 +1,29 @@
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import test from "node:test";
const homePageSource = await readFile(
new URL("../src/pages/HomePage.tsx", import.meta.url),
"utf8",
);
test("keeps past match history focused on the five summary columns", () => {
const colGroup = sourceForFunction("HistoryTableColGroup");
const header = sourceForFunction("HistoryTableHeader");
const skeleton = sourceForFunction("HistoryRecordsSkeleton");
assert.equal(colGroup.match(/<col(?:\s|\/|>)/g)?.length, 5);
assert.doesNotMatch(header, />결과<\/th>/);
assert.doesNotMatch(homePageSource, /공식 결과/);
assert.doesNotMatch(skeleton, /1팀 승리/);
assert.match(homePageSource, /colSpan=\{5\}/);
});
function sourceForFunction(name: string): string {
const start = homePageSource.indexOf(`function ${name}(`);
assert.notEqual(start, -1, `${name} should exist`);
const nextFunction = homePageSource.indexOf("\nfunction ", start + 1);
assert.notEqual(nextFunction, -1, `${name} should have a following function`);
return homePageSource.slice(start, nextFunction);
}
@@ -0,0 +1,33 @@
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import test from "node:test";
import { SERIES_SCORE_CARD_GEOMETRY } from "../src/components/competition/series-score-card-geometry.ts";
const component = await readFile(
new URL(
"../src/components/competition/SeriesScoreCard.tsx",
import.meta.url,
),
"utf8",
);
test("keeps bracket entry rows equal by overlaying their divider", () => {
assert.equal(
SERIES_SCORE_CARD_GEOMETRY.height -
SERIES_SCORE_CARD_GEOMETRY.borderWidth * 2 -
SERIES_SCORE_CARD_GEOMETRY.headerHeight,
SERIES_SCORE_CARD_GEOMETRY.entryHeight * 2,
);
assert.match(
component,
/className=\{\s*isBracket\s*\?\s*"relative"\s*:\s*"divide-y divide-base-content\/8"\s*\}/,
);
assert.match(
component,
/className="pointer-events-none absolute inset-x-0 border-t border-base-content\/8"/,
);
assert.match(
component,
/style=\{\{ top: SERIES_SCORE_CARD_GEOMETRY\.entryHeight \}\}/,
);
});
+13
View File
@@ -0,0 +1,13 @@
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import test from "node:test";
const userHistoryPageSource = await readFile(
new URL("../src/pages/UserHistoryPage.tsx", import.meta.url),
"utf8",
);
test("hides the temporary real-time connection status indicator", () => {
assert.doesNotMatch(userHistoryPageSource, /실시간 연결됨/);
assert.doesNotMatch(userHistoryPageSource, /refreshSocket\.connectionStatus/);
});
@@ -0,0 +1,84 @@
# Implementation Plan: Double-Elimination Connector Routing
## Overview
Replace per-edge winner rail staggering with deterministic, collision-aware winner
bundles while retaining the existing target-corridor `H-V-H` path model and the
current loser/reset routing behavior.
## Architecture Decisions
- Keep routing as a pure layout calculation; the React renderer consumes unchanged
`BracketConnectorLayout` paths.
- Allocate baseline rails first, then choose one rail for each same-target winner
bundle while leaving loser/reset coordinates unchanged.
- Score complete candidate paths by parallel-stroke clearance, strict crossings,
and distance from the corridor midpoint.
- Permit shared `verticalX` only when the participating vertical intervals do not
overlap; otherwise search the same corridor for the nearest deterministic pair
of separate rails with focused-stroke clearance.
## Task List
### Phase 1: Regression Contract
- [x] Add tests proving quiet winner bundles use the corridor midpoint and all
shareable same-target winner paths remain aligned.
- [x] Replace target-column rail uniqueness with interval-aware segment assertions.
- [x] Cover reversed A/B input where overlapping vertical spans require the
deterministic separate-rail fallback.
- [x] Confirm the focused test fails with the current allocator.
### Checkpoint: RED
- [x] The new behavioral assertion fails for the expected unequal `verticalX`.
- [x] Existing tests remain unchanged except where their invariant is obsolete.
### Phase 2: Bundle-Aware Allocator
- [x] Represent connector routing inputs with precomputed source/target anchors.
- [x] Retain stable independent rails for loser/reset routes.
- [x] Group the two winners entering each target and select the nearest safe shared
rail without card penetration, forbidden overlap, or avoidable added crossings.
- [x] Fall back to the nearest deterministic, stroke-clear separate rails only
when the pair's own vertical intervals overlap and cannot safely share a rail.
### Checkpoint: GREEN
- [x] Focused layout tests pass for four-team, eight-team, reset-final, and shuffled
input fixtures.
- [x] Strict crossing, collinear-overlap, and 5px parallel-clearance safeguards pass.
### Phase 3: Verification and Review
- [x] Run the full web suite, lint, and production build; document the unrelated
pre-existing full-lint failures while verifying changed files separately.
- [x] Inspect the diff for correctness, simplicity, security, performance, and
adherence to the approved spec.
- [x] Perform an independent review and address all required findings.
### Checkpoint: Complete
- [x] All success criteria in the spec are verified.
- [x] No unrelated files are modified.
## Risks and Mitigations
| Risk | Impact | Mitigation |
|---|---|---|
| Blind midpoint alignment adds crossings in busy upper rounds | High | Score complete candidate paths and move the winner bundle together to the nearest safe rail. |
| Shared rails create overlapping vertical segments | High | Check interval overlap before allowing a shared `verticalX`; search deterministic fallback rails with 5px clearance otherwise. |
| Visually parallel rails pass exact-coordinate tests but overlap at stroke width | High | Require 5px clearance across overlapping vertical runs and cover it for 4/8-team fixtures. |
| Routing changes depend on input array order | Medium | Sort routes and bundles by graph display order and retain shuffled-fixture equality tests. |
| A long connector bends through an intermediate card | High | Restrict every candidate to the target corridor and retain card-penetration assertions. |
| Reset-final slot carry-over is accidentally treated as a winner pair | Medium | Bundle only connectors whose computed kind is `winner`; keep reset paths independent. |
## Dependencies
```text
Regression contract -> bundle-aware rail allocator -> full verification -> review
```
## Open Questions
None.
+62
View File
@@ -0,0 +1,62 @@
# Redis 8.10 correctness and optimization
## Scope and invariants
- Fix blocking reads sharing a client, Hash payload cleanup, duplicate action-order entries, and non-atomic scheduled-job promotion.
- Preserve high-before-low consumption, the 30-minute pending recovery threshold, business processing locks, replay fingerprints, 500-request limits, and auction lifecycle fencing.
- Use XACKDEL ACKED, XREADGROUP CLAIM, conditional string deletion/renewal, and INCREX. Never trim unacknowledged work.
- Move community response caches to hashes with independent field TTLs: 300 seconds normally, 86400 for complete details, 60 for incomplete details. Preserve response shapes and in-flight coalescing. Fence cache fills across invalidation.
- Do not implement conditional Compact Hash, JSON, Array, or request-retention redesign proposals in this change.
## Implementation sequence
1. Add regression coverage and fix the four correctness defects.
2. Upgrade stream consumption/acknowledgement and protect pending entries during trimming.
3. Replace lock scripts and token-unsafe dedup deletion with Redis conditional commands.
4. Replace failure-counter increment/expiry with INCREX.
5. Introduce versioned community hash caches and generation-aware fills/invalidation.
## Validation
- Run existing API tests before changes and record baseline failures.
- Exercise actual Lua and Redis 8.10 commands in an isolated local Redis process, including concurrent promotion, pending recovery, foreign-group retention, stale lock ownership, lifecycle-specific cleanup, and cache invalidation races/field expiry.
- Add unit regressions for worker connection lifecycle, command response handling, caller cache scopes, and interrupted operations.
- Run the full API suite, API build, changed-file lint, and dependency checks. Distinguish mock-based tests from real Redis integration results.
## Environment
The repository's named workflow skills are absent. Work follows the above explicit specification, incremental implementation, regression tests, and final review. Windows has no Docker/WSL; a temporary loopback-only Redis 8.10.3 Windows community build is used for integration validation, without accessing application Redis credentials.
## Results (2026-11-09)
| Check | Result |
| --- | --- |
| API unit/regression suite | 105 suites, 704 tests passed |
| Web regression suite | 129 tests passed |
| Isolated Redis 8.10.3 integration suite | 2 suites, 31 tests passed |
| API, web, and contracts builds | Passed (`pnpm -r --workspace-concurrency=1 build`) |
| ESLint on the 20 repaired test files | Passed with zero warnings |
| Dependency regression checks | 3 tests passed |
| Integration runner syntax and missing-executable failure cleanup | Passed; no leaked temporary directory |
| Git whitespace check | Passed |
| Full API TypeScript check including test files | Passed; all 90 pre-existing diagnostics repaired |
| Contracts and web application TypeScript checks | Passed (web check runs as part of its build) |
The initial API baseline was 685 passing tests and one failure caused by Windows path separators in the performance report. The report now emits platform-independent paths and its existing test passes. The original Redis change exposed 90 pre-existing test-type diagnostics, confirmed against HEAD sources through an in-memory compiler host. The requested follow-up repairs all 90 across 20 test files. Workspace dependencies were installed from the frozen lockfile without changing package versions.
The type repairs preserve test assertions and scenarios: public service types are separated from private-method test accessors, partial database mocks are typed at the harness boundary, generic helpers retain their full element types, and Riot/Match fixtures provide required fields. Position fixtures use the domain's `SUP`/`JGL` values, optional lookup assertions still fail when the expected object is missing, and scheduler teardown is awaited. No tests were removed or skipped, no TypeScript settings were relaxed, and no suppression directives were added. The final suite also includes the concurrent tournament polling/retry changes present in the shared workspace.
Run `pnpm --filter api typecheck` to check API source and tests without emitting files or relying on incremental state. Run `pnpm -r --if-present typecheck`, `pnpm --filter api test -- --runInBand`, `pnpm --filter web test`, `pnpm --filter api test:redis`, `pnpm test:dependency-security`, and `pnpm -r --workspace-concurrency=1 build` to reproduce the workspace checks above. The web build reports a non-failing bundle-size warning.
Actual Redis coverage includes dedicated blocking reads alongside normal commands, stale pending recovery, acknowledgement retention across consumer groups, safe stream trimming, foreign-owner lock protection, compare-and-delete dedup tokens, concurrent failure-counter increments, scheduled-job failure/retry and concurrent promotion, rescheduling fences, malformed scheduled entries and batch limits, Hash/legacy payload cleanup, action reservation/apply/replay, the 500-request cap and five-minute retention, independent cache field expiry, scope isolation, and stale cache fills across invalidation. The detail-response invalidation race also exercises the real CommunityStatsService and Redis cache with only the underlying dataset loader stubbed.
MongoDB/NATS/Riot end-to-end execution, Linux production-runtime validation, and production-scale latency/memory benchmarks were not run. No measured production speedup is claimed.
## Rollout and operating behavior
- Requires Redis 8.10.x and the existing node-redis 5.12.x client. The integration runner verifies the server version before executing tests.
- Switch API instances together: old String-cache invalidation and new Hash-cache invalidation target different namespaces. Rolling with both versions serving traffic can leave the other version's cache stale. Rollback has the same constraint.
- Old cache values expire on their existing TTL, at most 24 hours. New hashes populate on cache misses; this can temporarily increase database reads after deployment. A persistent generation token per community fences slow responses across invalidation.
- Pending/unread stream entries are retained even past the approximate 10,000-entry target. Monitor stream length and pending entries; an abandoned consumer group can retain entries until that group is deliberately retired.
- Existing action-order duplicates are not rewritten during deployment. The fix prevents new duplicates; existing entries age out through the existing five-minute replay retention and count-based cleanup.
- `pnpm --filter api test:redis` starts only its own loopback server, uses a random port/password, disables persistence, and cleans up afterward. Set `REDIS_TEST_SERVER` to an installed executable if it is not on PATH.
+121
View File
@@ -0,0 +1,121 @@
# Implementation Plan: Refresh Riot ID by PUUID
## Overview
Deliver the behavior in three backend slices. First add and prove the safe
Account-V1-to-user persistence operation. Then invoke it from the existing
personal-history refresh worker before completion is broadcast. Finally reuse it
from stale-account background refresh with community-aware region resolution and
failure isolation. No database or frontend contract change is required.
## Task List
### Phase 1: Identity Refresh Boundary
- [x] Add failing tests for changed, unchanged, incomplete, mismatched, and failed
PUUID identity lookups.
- Acceptance: tests describe state outcomes and fail because the focused method
is not implemented.
- Verify:
`pnpm --filter api exec jest --runInBand riot-account-enrichment.service.spec.ts`
- Files:
`apps/api/src/modules/riot/riot-account-enrichment.service.spec.ts`
- [x] Implement `refreshRiotIdentity` using `RiotAccountService.getByPuuid`.
- Acceptance: valid changed values persist together; invalid results preserve
existing values; unchanged values avoid a write.
- Verify: the Phase 1 focused test passes.
- Files:
`apps/api/src/modules/riot/riot-account-enrichment.service.ts`
### Checkpoint: Phase 1
- [x] The enrichment service has a typed three-state result and all focused tests
pass.
- [x] No schema, endpoint, queue payload, or frontend changes exist.
### Phase 2: Refresh Worker Integration
- [x] Add a failing worker test proving that a user-history job requests identity
refresh with its user ID, PUUID, and region.
- Acceptance: the test fails before worker orchestration is updated.
- Verify:
`pnpm --filter api exec jest --runInBand riot-job-worker.service.spec.ts`
- Files: `apps/api/src/modules/riot-job-queue/riot-job-worker.service.spec.ts`
- [x] Invoke best-effort identity refresh before job completion.
- Acceptance: the worker logs identity failure without aborting successful match
refresh work, and broadcasts completion only after identity refresh returns.
- Verify: the Phase 2 focused test passes.
- Files: `apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts`
### Checkpoint: Complete
- [x] Focused API suites pass without skipped tests.
- [x] API lint and build pass.
- [x] Web lint and production build pass, confirming the existing profile
invalidation integration remains compatible.
- [x] Final diff contains only the specification, plan, enrichment service, worker,
and their tests.
### Phase 3: Background Refresh Integration
- [x] Add a failing enrichment-service test proving that an omitted region is
resolved from the user's community.
- Acceptance: a non-Asia community route reaches Account-V1 without changing the
public method signature.
- Verify:
`pnpm --filter api exec jest --runInBand riot-account-enrichment.service.spec.ts`
- Files:
`apps/api/src/modules/riot/riot-account-enrichment.service.spec.ts`
- [x] Resolve the community Riot region for region-less identity refresh calls.
- Acceptance: explicit caller regions remain unchanged; missing community routes
use the existing `asia` fallback.
- Verify: the focused enrichment-service test passes.
- Files:
`apps/api/src/modules/riot/riot-account-enrichment.service.ts`
- [x] Add failing background scheduler tests for identity refresh ordering and
failure isolation.
- Acceptance: stale accounts request identity refresh before statistics
enrichment, while identity rejection does not increment failure counters.
- Verify:
`pnpm --filter api exec jest --runInBand background-refresh.scheduler.spec.ts`
- Files:
`apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.spec.ts`
- [x] Invoke best-effort identity refresh from the stale-account loop.
- Acceptance: each processed candidate gets one PUUID identity lookup, statistics
enrichment still determines processed/failed/backoff state, and no new Redis or
database contract is added.
- Verify: the focused background scheduler tests pass.
- Files:
`apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.ts`
### Checkpoint: Background Refresh Complete
- [x] Focused identity, manual worker, and background scheduler suites pass.
- [x] API lint, full tests, and build pass.
- [x] Final diff remains limited to the existing feature documents, identity
service/tests, and background scheduler/tests.
## Risks and Mitigations
| Risk | Impact | Mitigation |
|---|---|---|
| Account-V1 returns an incomplete identity | High | Require matching PUUID and two non-empty Riot ID fields before mutation. |
| Riot Account-V1 is temporarily unavailable | Medium | Preserve stored identity, log the failure, and retain existing best-effort job semantics. |
| Multiple queue groups repeat identity lookup | Low | The personal page requests one queue group; avoid a new dedup mechanism until a measured need exists. |
| Background community uses a non-Asia Riot route | High | Resolve omitted regions from the user's community before falling back to `asia`. |
| Identity lookup failure triggers background backoff | Medium | Isolate identity exceptions and let existing statistics enrichment alone control failure counters. |
| UI keeps the stale profile cached | High | Identity update completes before the existing completion event invalidates the profile query. |
| Historical names are unexpectedly rewritten | Medium | Restrict persistence to the embedded Riot account and leave match snapshots untouched. |
## Dependencies
```text
validated Account-V1 lookup
-> focused identity persistence method
-> manual refresh worker -> existing completion event -> profile invalidation
-> background scheduler -> existing statistics enrichment and backoff policy
```
## Open Questions
None. The user approved the specification and requested implementation.
@@ -0,0 +1,134 @@
# Spec: Double-Elimination Connector Routing
## Objective
Make winner advancement lines in the desktop double-elimination bracket bend at a
consistent horizontal position. Two winner lines entering the same match should
read as one visual pair when their vertical spans can share a rail: use the center
of the 40px inter-column corridor when it is safe, and move the pair together only
when another connector would interfere. If an accepted A/B mapping reverses the
source order and makes those spans overlap, preserve separate deterministic,
stroke-clear rails instead of creating a collinear overlap.
The primary user is a participant or organizer tracing advancement through a busy
eight-team bracket. Success means the solid coral winner paths are visually
aligned without degrading the existing dashed loser paths, card placement, or
keyboard-driven connector highlighting.
## Approved Product Decisions
- Treat the two `winner` connectors entering one Series as a semantic bundle.
- Prefer `target.x - columnGap / 2` for a winner bundle.
- If the preferred rail causes crossings, collinear overlap, or less than 5px of
clearance from an overlapping parallel route, move a shareable bundle to the
nearest safe rail. Retain separate rails only when the pair's own vertical spans
overlap and therefore cannot safely share any rail; move those rails to the
nearest deterministic positions needed to preserve the same 5px clearance.
- Preserve the current loser/reset rail ordering unless moving one is required to
maintain valid geometry.
- Keep every connector as a separate `H-V-H` SVG path so focus highlighting and
accessible labels remain independent.
- Keep long-distance bends inside the corridor immediately before the target
column; do not use the midpoint between source and target cards.
## Tech Stack
- React 19, TypeScript 6, Vite 8, Tailwind CSS 4, and daisyUI under `apps/web`
- Node's built-in test runner for the pure bracket layout calculation
## Commands
- Focused layout tests: `pnpm --filter web exec node --test --experimental-strip-types test/double-elimination-bracket-layout.test.ts`
- Full web tests: `pnpm --filter web test`
- Web lint: `pnpm --filter web lint`
- Web production build: `pnpm --filter web build:prod`
- Development server: `pnpm --filter web start:dev`
## Project Structure
- `apps/web/src/components/competition/double-elimination-bracket-layout.ts`
validates the bracket graph, positions cards, assigns connector rails, and emits
SVG path geometry.
- `apps/web/src/components/competition/DoubleEliminationBracket.tsx` renders the
computed paths and must not need routing-specific changes.
- `apps/web/test/double-elimination-bracket-layout.test.ts` contains canonical
four-team, eight-team, and reset-final fixtures plus geometry assertions.
## Code Style
Keep routing deterministic and express geometry through small named helpers:
```ts
const preferredX = target.x - geometry.columnGap / 2;
const verticalX = nearestSafeRail(preferredX, bundle, occupiedRoutes);
```
Use existing layout types and semantic connector kinds. Do not add a dependency,
DOM measurement, mutable global state, or renderer-specific routing behavior.
## Testing Strategy
- Add regression tests before implementation and confirm they fail against the
current per-edge rail allocator.
- Assert observable geometry: safe winner pairs share a rail, quiet corridors use
their exact midpoint, busy corridors keep a pair aligned, and mixed
winner/loser entries remain distinguishable.
- Cover reversed A/B winner input explicitly: it remains deterministic and uses
separate rails without collinear overlap or focused-stroke clearance conflicts
because no shared H-V-H rail is safe.
- Replace the obsolete "all rails in a target column are unique" assertion with
interval-aware overlap and 5px focused-stroke clearance protection.
- Preserve deterministic output for shuffled input, finite path coordinates,
target-corridor bounds, card avoidance, endpoint alignment, and canonical graph
validation.
- Verify four-team, eight-team, and reset-final layouts; run the complete web test,
lint, and production build commands.
## Boundaries
### Always
- Keep winner, loser, and reset connectors visually distinguishable by the existing
solid/dashed patterns and brand tokens.
- Keep connector rails strictly inside the target corridor.
- Avoid strict segment crossings and collinear overlaps whenever a safe candidate
exists.
- Keep overlapping parallel winner and loser rails at least 5px apart, matching
the widest focused connector underlay.
- Produce the same layout regardless of projection input ordering.
### Ask First
- Add dependencies or change the public projection contract.
- Change bracket card dimensions, round columns, or the 40px column gap.
- Redesign mobile bracket presentation or connector interaction behavior.
### Never
- Route a connector through a match card.
- Infer routing from Series codes; use canonical graph identity and topology.
- Merge two logical connectors into one SVG path.
- Modify unrelated competition or score-card behavior.
## Success Criteria
- The two winner paths into `LB_R3_M1` bend at the corridor midpoint and share the
same `verticalX`.
- The winner paths into the grand final share the corridor midpoint when safe.
- Every same-target winner pair whose vertical spans do not overlap shares one
`verticalX`, using the nearest collision-safe rail when the midpoint is busy.
- A reversed A/B pair with overlapping vertical spans retains deterministic
separate rails, produces no collinear segment overlap, and remains at least 5px
from every overlapping vertical route.
- Loser/reset paths retain their baseline rails, and winner bundles remain at least
5px away where their vertical runs overlap.
- All rails remain inside their target corridors without card penetration or
collinear overlap.
- Canonical four-team, eight-team, reset-final, and shuffled-input tests pass.
- Full web tests and production build pass; changed-file lint passes, and any
unrelated full-lint baseline failures are documented.
## Open Questions
None. The user reviewed the proposed bundle-aware routing behavior and requested
implementation.
+175
View File
@@ -0,0 +1,175 @@
# Spec: Refresh Riot ID by PUUID
## Objective
Whenever an account is refreshed manually from the personal match-history page
or automatically by the stale-account background scheduler, resolve its current
Riot ID through Riot Account-V1 using the stored PUUID. If the player changed
either their game name or tag line, persist the latest values on the same embedded
Riot account so the profile displays the new Riot ID.
The existing refresh job remains the single user-facing operation. It continues
to refresh matches and ranked data, and additionally refreshes identity before
emitting its completion event.
## Approved Product Decisions
- Use the stored PUUID as the stable identity key; never look up the account by
the possibly stale game name and tag line.
- Query Riot Account-V1 on every manually queued user-history refresh job and
every selected stale-account background refresh rather than applying a name TTL.
- Update `gameName` and `tagLine` together only when Riot returns a matching PUUID
and both values are non-empty.
- Preserve the previous Riot ID if the Account-V1 lookup fails or returns an
incomplete or mismatched response.
- Treat identity refresh as best effort, matching the existing ranked-data refresh
policy: log a failure but allow successful match refresh work to complete.
- When a caller does not already know the Riot regional route, resolve it from the
user's community and fall back to `asia` only when the community has no route.
- Do not increment the background failure counter or enter backoff solely because
the identity lookup failed; background statistics enrichment retains its
existing success and failure semantics.
- Reuse the existing refresh completion event and profile-query invalidation; do
not add a new endpoint, response field, socket event, or frontend state path.
- Update only the embedded Riot account used by the personal profile. Historical
match snapshots retain the names recorded by Riot for those games.
## Tech Stack
- NestJS 11, TypeScript 5, Mongoose 9, and Jest under `apps/api`
- Riot Account-V1 through the existing `RiotAccountService`
- Redis stream jobs through the existing `RiotJobWorkerService`
- Scheduled stale-account refresh through `BackgroundRefreshScheduler`
- React Query profile invalidation already present in `UserHistoryPage`
## Commands
- Focused tests:
`pnpm --filter api exec jest --runInBand riot-account-enrichment.service.spec.ts riot-job-worker.service.spec.ts background-refresh.scheduler.spec.ts`
- API lint: `pnpm --filter api lint`
- API build: `pnpm --filter api build`
- Web lint: `pnpm --filter web lint`
- Web production build: `pnpm --filter web build:prod`
## Project Structure
- `apps/api/src/modules/riot/riot-account.service.ts` owns the validated
Account-V1 PUUID lookup.
- `apps/api/src/modules/riot/riot-account-enrichment.service.ts` owns the
persistence boundary for the embedded Riot account.
- `apps/api/src/modules/riot/riot-account-enrichment.service.spec.ts` verifies
update, no-op, and failure behavior.
- `apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts` orchestrates
identity, match, and ranked refresh work before completion.
- `apps/api/src/modules/riot-job-queue/riot-job-worker.service.spec.ts` verifies
that a personal-history refresh job requests the PUUID-based identity refresh.
- `apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.ts`
orchestrates best-effort identity refresh for stale accounts before statistics
enrichment.
- `apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.spec.ts`
verifies background invocation, ordering, and failure isolation.
- `apps/web/src/pages/UserHistoryPage.tsx` already invalidates the profile query
when the refresh socket reports completion and is not modified in this scope.
## Internal Contract
Add one focused method to `RiotAccountEnrichmentService`:
```ts
type RefreshRiotIdentityResult = "updated" | "unchanged" | "failed";
refreshRiotIdentity(params: {
userId: mongoose.Types.ObjectId;
puuid: string;
region?: RiotRegionalRoute;
}): Promise<RefreshRiotIdentityResult>;
```
`updated` means both persisted Riot ID fields now match Account-V1. `unchanged`
means the validated response matched the stored values and no database write was
needed. `failed` means no stored account could be resolved or the external lookup
could not safely provide a complete identity; stored values remain unchanged. If
`region` is omitted, the service resolves the user's community and uses its
configured `riotRegion`, falling back to `asia` only when unavailable.
## Code Style
Keep the external validation and persistence decision explicit:
```ts
const identity = await this.accountService.getByPuuid(puuid, { region });
if (identity.puuid !== puuid || !identity.gameName || !identity.tagLine) {
return "failed";
}
```
Use existing single quotes, NestJS logging, Mongoose document mutation, and
Prettier formatting. Do not add a generic identity abstraction or new dependency.
## Testing Strategy
- Write the enrichment-service tests first and confirm they fail before adding
the new method.
- Verify a changed game name and tag line are persisted together.
- Verify identical values return `unchanged` without saving.
- Verify missing values, PUUID mismatch, and Riot lookup errors return `failed`
without overwriting or saving the stored identity.
- Write the worker orchestration expectation before calling the new method.
- Verify a region-less identity refresh uses the user's configured community
region.
- Write background scheduler expectations before adding identity refresh to the
stale-account loop.
- Verify identity refresh happens before statistics enrichment and that a rejected
identity lookup does not increment background failure counters.
- Run focused API tests after each slice, then API lint/build and web lint/build
to verify the existing client integration remains valid.
## Boundaries
### Always
- Use the stored PUUID for Account-V1 lookup and verify the returned PUUID.
- Validate both Riot ID fields before mutating the database.
- Preserve the current Riot ID on any unsafe or failed response.
- Keep the existing refresh route, enqueue response, and socket event compatible.
- Keep background identity failures independent from enrichment failure counters.
- Run focused tests before broader lint and build verification.
### Ask First
- Add a database field or migration.
- Change refresh failure semantics so an identity lookup failure fails the whole
user-history job.
- Update historical match snapshots or active match participant display names.
- Add a new API response field, endpoint, dependency, or Redis job type.
- Commit, push, deploy, or alter CI configuration.
### Never
- Resolve identity from the stale stored Riot ID.
- Partially update only the game name or only the tag line.
- Replace a valid stored identity with empty or mismatched Account-V1 data.
- Expose Riot API errors or credentials to the browser.
- Mix the change with the separate past-history result-column PR.
## Success Criteria
- Clicking `정보 갱신` causes the queued worker to call Account-V1 by the stored
PUUID.
- Selecting a stale account for background refresh also calls Account-V1 by the
stored PUUID before statistics enrichment.
- A changed Riot game name or tag line is persisted on the matching embedded
account before the completion event is broadcast.
- The completion event triggers the existing profile-query invalidation, so the
personal history header displays the latest `gameName#tagLine`.
- Failed, incomplete, or mismatched Riot identity responses do not overwrite the
existing Riot ID and do not prevent otherwise successful match refresh work.
- Background identity lookup failures do not increment the account failure counter
or prevent otherwise successful background enrichment.
- Focused tests, API lint/build, and web lint/production build pass.
## Open Questions
None. The user approved this specification and requested implementation. The
existing queue and UI invalidation paths support the behavior without a public
contract change.
+9 -6
View File
@@ -16,7 +16,8 @@
"build:web:prod": "pnpm --filter web build:prod",
"deploy:web:staging": "node scripts/deploy-cloudflare-pages.mjs staging",
"deploy:web:prod": "node scripts/deploy-cloudflare-pages.mjs prod",
"test": "echo \"Error: no test specified\" && exit 1"
"test": "echo \"Error: no test specified\" && exit 1",
"test:dependency-security": "node --test scripts/dependency-security.test.mjs"
},
"keywords": [],
"author": "",
@@ -25,9 +26,6 @@
"node": ">=26 <27"
},
"packageManager": "pnpm@10.4.1",
"dependencies": {
"@infisical/sdk": "^5.0.2"
},
"pnpm": {
"auditConfig": {
"ignoreGhsas": [
@@ -36,18 +34,23 @@
},
"overrides": {
"@babel/core@7.29.0": "7.29.6",
"@grpc/grpc-js@>=1.14.0 <1.14.5": "1.14.7",
"body-parser@>=2.0.0 <2.4.0": "2.4.0",
"brace-expansion@1.1.13": "1.1.16",
"brace-expansion@2.0.3": "2.1.2",
"brace-expansion@5.0.5": "5.0.8",
"engine.io@6.6.6": "6.6.7",
"engine.io@>=6.6.0 <6.6.10": "6.6.11",
"fast-uri@3.1.0": "3.1.4",
"form-data@4.0.5": "4.0.6",
"js-yaml@4.1.1": "4.3.0",
"js-yaml@5.2.1": "5.2.2",
"multer@2.2.0": "2.3.0",
"multer@>=2.0.0 <2.5.0": "2.5.0",
"nanoid@3.3.16": "3.3.18",
"proxy-addr@>=2.0.0 <2.0.8": "2.0.8",
"qs@6.15.1": "6.15.2",
"socket.io-parser@4.2.6": "4.2.7",
"source-map-js@>=1.0.0 <1.2.2": "1.2.2",
"undici@>=7.0.0 <7.30.1": "7.30.2",
"ws@8.18.3": "8.21.0"
}
}
+121 -70
View File
@@ -6,27 +6,28 @@ settings:
overrides:
'@babel/core@7.29.0': 7.29.6
'@grpc/grpc-js@>=1.14.0 <1.14.5': 1.14.7
body-parser@>=2.0.0 <2.4.0: 2.4.0
brace-expansion@1.1.13: 1.1.16
brace-expansion@2.0.3: 2.1.2
brace-expansion@5.0.5: 5.0.8
engine.io@6.6.6: 6.6.7
engine.io@>=6.6.0 <6.6.10: 6.6.11
fast-uri@3.1.0: 3.1.4
form-data@4.0.5: 4.0.6
js-yaml@4.1.1: 4.3.0
js-yaml@5.2.1: 5.2.2
multer@2.2.0: 2.3.0
multer@>=2.0.0 <2.5.0: 2.5.0
nanoid@3.3.16: 3.3.18
proxy-addr@>=2.0.0 <2.0.8: 2.0.8
qs@6.15.1: 6.15.2
socket.io-parser@4.2.6: 4.2.7
source-map-js@>=1.0.0 <1.2.2: 1.2.2
undici@>=7.0.0 <7.30.1: 7.30.2
ws@8.18.3: 8.21.0
importers:
.:
dependencies:
'@infisical/sdk':
specifier: ^5.0.2
version: 5.0.2
.: {}
apps/api:
dependencies:
@@ -311,6 +312,9 @@ packages:
'@aws-sdk/core@3.977.1':
resolution: {integrity: sha512-KVtQRtc00ES/y+Sc3vYXeP6pCIcNlBJCZOwvqSy8ZpVGmbM5+IG+AfhuTKQ2oXmIVqZJewaGMMpzPkywC6xg0w==}
engines: {node: '>=20.0.0'}
deprecated: |-
Deprecated due to Document number parsing bug in JSON, see
https://github.com/aws/aws-sdk-js-v3/issues/8246. Newer version available.
'@aws-sdk/credential-provider-cognito-identity@3.972.60':
resolution: {integrity: sha512-16Fxa3veKIO6nHJr+vN76z3BkSU7725lzruc5S2SQSTUTbK4TXtmi8033WQljZj4k1+383UsMaNOHN6B76fK5A==}
@@ -890,8 +894,8 @@ packages:
resolution: {integrity: sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
'@grpc/grpc-js@1.14.4':
resolution: {integrity: sha512-k9Dj3DV/itK9D06Y8f190Qgop7/Ui+D0njFV3LHMPwPT75DpXLQohE9Wmz0QElrJnzsjB7KPWiKJbOl7IPDArQ==}
'@grpc/grpc-js@1.14.7':
resolution: {integrity: sha512-W4W/fcBMGRVtG6dW2c7cw2mnpS3hvbBd+oQXjh2iYFTZDk1JJmcNqkM5KSaPubQpamlUUurrlb7G1s9NJeERmQ==}
engines: {node: '>=12.10.0'}
'@grpc/proto-loader@0.8.1':
@@ -1061,10 +1065,6 @@ packages:
cpu: [x64]
os: [win32]
'@infisical/sdk@5.0.2':
resolution: {integrity: sha512-mkgghtmIgBOEOFj1gb2n/AoiroFvN+NqaEEwC8ezEQ87V55yf2yksHhnBMU2MiZ26n6b3sGcpDZHF1/H6JrgyA==}
engines: {node: '>=20'}
'@inquirer/ansi@1.0.2':
resolution: {integrity: sha512-S8qNSZiYzFd0wAcyG5AXCvUHC5Sr7xpZ9wZ2py9XR88jUz8wooStVx5M6dRzczbBWjic9NP7+rY0Xi7qqK/aMQ==}
engines: {node: '>=18'}
@@ -1812,6 +1812,9 @@ packages:
'@smithy/core@3.30.0':
resolution: {integrity: sha512-dl2yRglDxfzH9uJ4fSo4zTaAHa0zH7+V7BZMRWy8hEYIKT1BiqMUK/CN6T3ADQ3kbA5N1tmUulroJ2UtONS7Kw==}
engines: {node: '>=18.0.0'}
deprecated: |-
Deprecated due to a bug in custom logger data redaction. Upgrade to the latest version. If you used a custom logger with this
version, review your logs and rotate any credentials or other secrets. See https://github.com/aws/aws-sdk-js-v3/issues/8393.
'@smithy/credential-provider-imds@4.4.14':
resolution: {integrity: sha512-QgbuahIb2qxQeZQvNK0sw3aF3JH5zwH8j2lLp5DUasVXexGGMWULAR+7z0omPXFolCP/m5wN9M5lm9EGdSviTQ==}
@@ -2633,8 +2636,8 @@ packages:
blake3-wasm@2.1.5:
resolution: {integrity: sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==}
body-parser@2.3.0:
resolution: {integrity: sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==}
body-parser@2.4.0:
resolution: {integrity: sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==}
engines: {node: '>=18'}
bowser@2.14.1:
@@ -2829,6 +2832,10 @@ packages:
resolution: {integrity: sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==}
engines: {node: '>=18'}
content-type@2.1.0:
resolution: {integrity: sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==}
engines: {node: '>=18'}
convert-source-map@2.0.0:
resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==}
@@ -3035,8 +3042,8 @@ packages:
resolution: {integrity: sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==}
engines: {node: '>=10.0.0'}
engine.io@6.6.7:
resolution: {integrity: sha512-DgOngfDKM2EviOH3Mr9m7ks1q8roetLy/IMmYthAYzbpInMbYc/GS+fWFA3rl1gvwKVsQrVV61fo5emD1y3OJQ==}
engine.io@6.6.11:
resolution: {integrity: sha512-z34mGpLoY/82ZbkX1LqGMIaf3wjVMPL6gVC681QDqnmzJ26synI8qAE32P+a7UazmpJZ8UGrFIeAavgRfXzYrg==}
engines: {node: '>=10.2.0'}
enhanced-resolve@5.20.1:
@@ -4161,8 +4168,8 @@ packages:
ms@2.1.3:
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
multer@2.3.0:
resolution: {integrity: sha512-cjNbm3sttszgZeGfJR124D+jFEfkXCVAsoPBmFn9X7UxmDSFHWqE2CoEj0vrmSpuAFnqWR1Szcm9QTsiHr60Xw==}
multer@2.5.0:
resolution: {integrity: sha512-BsqOzYGVq49JcW2IzoSAxeKYRevb+dGGPPWleOR8Lrlk4igwxu1/9pwSXlByhCb7MVZDrNJFC0IBP5/O5nLYRw==}
engines: {node: '>= 10.16.0'}
mute-stream@2.0.0:
@@ -4407,8 +4414,8 @@ packages:
resolution: {integrity: sha512-/FPD0nUc9jH6rfFjji9IBqOz4pcSE3CsT1m7Ep6Mdb0LxSUMj8hgl6GomOvZzpNpAqqGaXA0P3VSrZLFzIhQrw==}
engines: {node: '>=12.0.0'}
proxy-addr@2.0.7:
resolution: {integrity: sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==}
proxy-addr@2.0.8:
resolution: {integrity: sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==}
engines: {node: '>= 0.10'}
proxy-agent-negotiate@1.1.0:
@@ -4434,8 +4441,8 @@ packages:
resolution: {integrity: sha512-Rzq0KEyX/w/tEybncDgdkZrJgVUsUMk3xjh3t5bv3S1HTAtg+uOYt72+ZfwiQwKdysThkTBdL/rTi6HDmX9Ddw==}
engines: {node: '>=0.6'}
qs@6.15.3:
resolution: {integrity: sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==}
qs@6.17.1:
resolution: {integrity: sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==}
engines: {node: '>=0.6'}
range-parser@1.3.0:
@@ -4672,8 +4679,8 @@ packages:
resolution: {integrity: sha512-2Dd78bqzzjE6KPkD5fHZmDAKRNe3J15q+YHDrIsy9WEkqttc7GY+kT9OBLSMaPbQaEd0x1BjcmtMtXkfpc+T5A==}
engines: {node: '>=10.2.0'}
source-map-js@1.2.1:
resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
source-map-js@1.2.2:
resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==}
engines: {node: '>=0.10.0'}
source-map-support@0.5.13:
@@ -5008,12 +5015,8 @@ packages:
undici-types@8.3.0:
resolution: {integrity: sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==}
undici@7.28.0:
resolution: {integrity: sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA==}
engines: {node: '>=20.18.1'}
undici@7.29.0:
resolution: {integrity: sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==}
undici@7.30.2:
resolution: {integrity: sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA==}
engines: {node: '>=20.18.1'}
unenv@2.0.0-rc.24:
@@ -5267,9 +5270,6 @@ packages:
peerDependencies:
zod: ^3.25.0 || ^4.0.0
zod@3.25.76:
resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==}
zod@4.3.6:
resolution: {integrity: sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==}
@@ -5355,22 +5355,26 @@ snapshots:
'@aws-sdk/util-locate-window': 3.965.8
'@smithy/util-utf8': 2.3.0
tslib: 2.8.1
optional: true
'@aws-crypto/sha256-js@5.2.0':
dependencies:
'@aws-crypto/util': 5.2.0
'@aws-sdk/types': 3.974.2
tslib: 2.8.1
optional: true
'@aws-crypto/supports-web-crypto@5.2.0':
dependencies:
tslib: 2.8.1
optional: true
'@aws-crypto/util@5.2.0':
dependencies:
'@aws-sdk/types': 3.974.2
'@smithy/util-utf8': 2.3.0
tslib: 2.8.1
optional: true
'@aws-sdk/client-cognito-identity@3.993.0':
dependencies:
@@ -5413,6 +5417,7 @@ snapshots:
'@smithy/util-retry': 4.5.14
'@smithy/util-utf8': 4.4.14
tslib: 2.8.1
optional: true
'@aws-sdk/core@3.977.1':
dependencies:
@@ -5424,6 +5429,7 @@ snapshots:
'@smithy/types': 4.16.1
bowser: 2.14.1
tslib: 2.8.1
optional: true
'@aws-sdk/credential-provider-cognito-identity@3.972.60':
dependencies:
@@ -5432,6 +5438,7 @@ snapshots:
'@smithy/core': 3.30.0
'@smithy/types': 4.16.1
tslib: 2.8.1
optional: true
'@aws-sdk/credential-provider-env@3.972.61':
dependencies:
@@ -5440,6 +5447,7 @@ snapshots:
'@smithy/core': 3.30.0
'@smithy/types': 4.16.1
tslib: 2.8.1
optional: true
'@aws-sdk/credential-provider-http@3.972.63':
dependencies:
@@ -5450,6 +5458,7 @@ snapshots:
'@smithy/node-http-handler': 4.9.11
'@smithy/types': 4.16.1
tslib: 2.8.1
optional: true
'@aws-sdk/credential-provider-ini@3.973.6':
dependencies:
@@ -5466,6 +5475,7 @@ snapshots:
'@smithy/credential-provider-imds': 4.4.14
'@smithy/types': 4.16.1
tslib: 2.8.1
optional: true
'@aws-sdk/credential-provider-login@3.972.68':
dependencies:
@@ -5475,6 +5485,7 @@ snapshots:
'@smithy/core': 3.30.0
'@smithy/types': 4.16.1
tslib: 2.8.1
optional: true
'@aws-sdk/credential-provider-node@3.972.72':
dependencies:
@@ -5489,6 +5500,7 @@ snapshots:
'@smithy/credential-provider-imds': 4.4.14
'@smithy/types': 4.16.1
tslib: 2.8.1
optional: true
'@aws-sdk/credential-provider-process@3.972.61':
dependencies:
@@ -5497,6 +5509,7 @@ snapshots:
'@smithy/core': 3.30.0
'@smithy/types': 4.16.1
tslib: 2.8.1
optional: true
'@aws-sdk/credential-provider-sso@3.973.5':
dependencies:
@@ -5507,6 +5520,7 @@ snapshots:
'@smithy/core': 3.30.0
'@smithy/types': 4.16.1
tslib: 2.8.1
optional: true
'@aws-sdk/credential-provider-web-identity@3.972.67':
dependencies:
@@ -5516,6 +5530,7 @@ snapshots:
'@smithy/core': 3.30.0
'@smithy/types': 4.16.1
tslib: 2.8.1
optional: true
'@aws-sdk/credential-providers@3.993.0':
dependencies:
@@ -5539,26 +5554,31 @@ snapshots:
'@smithy/property-provider': 4.4.14
'@smithy/types': 4.16.1
tslib: 2.8.1
optional: true
'@aws-sdk/middleware-host-header@3.972.36':
dependencies:
'@aws-sdk/core': 3.977.1
tslib: 2.8.1
optional: true
'@aws-sdk/middleware-logger@3.972.35':
dependencies:
'@aws-sdk/core': 3.977.1
tslib: 2.8.1
optional: true
'@aws-sdk/middleware-recursion-detection@3.972.37':
dependencies:
'@aws-sdk/core': 3.977.1
tslib: 2.8.1
optional: true
'@aws-sdk/middleware-user-agent@3.972.65':
dependencies:
'@aws-sdk/core': 3.977.1
tslib: 2.8.1
optional: true
'@aws-sdk/nested-clients@3.993.0':
dependencies:
@@ -5600,6 +5620,7 @@ snapshots:
'@smithy/util-retry': 4.5.14
'@smithy/util-utf8': 4.4.14
tslib: 2.8.1
optional: true
'@aws-sdk/nested-clients@3.997.35':
dependencies:
@@ -5611,11 +5632,13 @@ snapshots:
'@smithy/node-http-handler': 4.9.11
'@smithy/types': 4.16.1
tslib: 2.8.1
optional: true
'@aws-sdk/region-config-resolver@3.972.39':
dependencies:
'@aws-sdk/core': 3.977.1
tslib: 2.8.1
optional: true
'@aws-sdk/signature-v4-multi-region@3.996.42':
dependencies:
@@ -5623,6 +5646,7 @@ snapshots:
'@smithy/signature-v4': 5.6.10
'@smithy/types': 4.16.1
tslib: 2.8.1
optional: true
'@aws-sdk/token-providers@3.1095.0':
dependencies:
@@ -5632,11 +5656,13 @@ snapshots:
'@smithy/core': 3.30.0
'@smithy/types': 4.16.1
tslib: 2.8.1
optional: true
'@aws-sdk/types@3.974.2':
dependencies:
'@smithy/types': 4.16.1
tslib: 2.8.1
optional: true
'@aws-sdk/util-endpoints@3.993.0':
dependencies:
@@ -5645,27 +5671,33 @@ snapshots:
'@smithy/url-parser': 4.4.14
'@smithy/util-endpoints': 3.6.14
tslib: 2.8.1
optional: true
'@aws-sdk/util-locate-window@3.965.8':
dependencies:
tslib: 2.8.1
optional: true
'@aws-sdk/util-user-agent-browser@3.972.36':
dependencies:
'@aws-sdk/core': 3.977.1
tslib: 2.8.1
optional: true
'@aws-sdk/util-user-agent-node@3.973.51':
dependencies:
'@aws-sdk/core': 3.977.1
tslib: 2.8.1
optional: true
'@aws-sdk/xml-builder@3.972.37':
dependencies:
'@smithy/types': 4.16.1
tslib: 2.8.1
optional: true
'@aws/lambda-invoke-store@0.3.0': {}
'@aws/lambda-invoke-store@0.3.0':
optional: true
'@azure/msal-browser@5.8.0':
dependencies:
@@ -6085,7 +6117,7 @@ snapshots:
'@eslint/core': 0.17.0
levn: 0.4.1
'@grpc/grpc-js@1.14.4':
'@grpc/grpc-js@1.14.7':
dependencies:
'@grpc/proto-loader': 0.8.1
'@js-sdsl/ordered-map': 4.4.2
@@ -6214,15 +6246,6 @@ snapshots:
'@img/sharp-win32-x64@0.35.2':
optional: true
'@infisical/sdk@5.0.2':
dependencies:
'@aws-crypto/sha256-js': 5.2.0
'@aws-sdk/credential-providers': 3.993.0
'@smithy/protocol-http': 5.5.14
'@smithy/signature-v4': 5.6.10
typescript: 5.9.3
zod: 3.25.76
'@inquirer/ansi@1.0.2': {}
'@inquirer/checkbox@4.3.2(@types/node@26.1.1)':
@@ -6689,7 +6712,7 @@ snapshots:
'@nestjs/core': 11.1.28(@nestjs/common@11.1.28(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/platform-express@11.1.28)(@nestjs/websockets@11.1.28)(reflect-metadata@0.2.2)(rxjs@7.8.2)
cors: 2.8.6
express: 5.2.1
multer: 2.3.0
multer: 2.5.0
path-to-regexp: 8.4.2
tslib: 2.8.1
transitivePeerDependencies:
@@ -6811,7 +6834,7 @@ snapshots:
request-ip: 3.3.0
ringbufferjs: 2.0.0
semver: 7.8.5
undici: 7.29.0
undici: 7.30.2
unescape: 1.0.1
unescape-js: 1.1.4
ws: 8.21.0
@@ -7070,159 +7093,190 @@ snapshots:
dependencies:
'@smithy/core': 3.30.0
tslib: 2.8.1
optional: true
'@smithy/core@3.30.0':
dependencies:
'@smithy/types': 4.16.1
tslib: 2.8.1
optional: true
'@smithy/credential-provider-imds@4.4.14':
dependencies:
'@smithy/core': 3.30.0
'@smithy/types': 4.16.1
tslib: 2.8.1
optional: true
'@smithy/fetch-http-handler@5.6.11':
dependencies:
'@smithy/core': 3.30.0
'@smithy/types': 4.16.1
tslib: 2.8.1
optional: true
'@smithy/hash-node@4.4.14':
dependencies:
'@smithy/core': 3.30.0
tslib: 2.8.1
optional: true
'@smithy/invalid-dependency@4.4.14':
dependencies:
'@smithy/core': 3.30.0
tslib: 2.8.1
optional: true
'@smithy/is-array-buffer@2.2.0':
dependencies:
tslib: 2.8.1
optional: true
'@smithy/middleware-content-length@4.4.14':
dependencies:
'@smithy/core': 3.30.0
tslib: 2.8.1
optional: true
'@smithy/middleware-endpoint@4.6.14':
dependencies:
'@smithy/core': 3.30.0
tslib: 2.8.1
optional: true
'@smithy/middleware-retry@4.7.14':
dependencies:
'@smithy/core': 3.30.0
tslib: 2.8.1
optional: true
'@smithy/middleware-serde@4.4.14':
dependencies:
'@smithy/core': 3.30.0
tslib: 2.8.1
optional: true
'@smithy/middleware-stack@4.4.14':
dependencies:
'@smithy/core': 3.30.0
tslib: 2.8.1
optional: true
'@smithy/node-config-provider@4.5.14':
dependencies:
'@smithy/core': 3.30.0
tslib: 2.8.1
optional: true
'@smithy/node-http-handler@4.9.11':
dependencies:
'@smithy/core': 3.30.0
'@smithy/types': 4.16.1
tslib: 2.8.1
optional: true
'@smithy/property-provider@4.4.14':
dependencies:
'@smithy/core': 3.30.0
tslib: 2.8.1
optional: true
'@smithy/protocol-http@5.5.14':
dependencies:
'@smithy/core': 3.30.0
tslib: 2.8.1
optional: true
'@smithy/signature-v4@5.6.10':
dependencies:
'@smithy/core': 3.30.0
'@smithy/types': 4.16.1
tslib: 2.8.1
optional: true
'@smithy/smithy-client@4.14.14':
dependencies:
'@smithy/core': 3.30.0
'@smithy/types': 4.16.1
tslib: 2.8.1
optional: true
'@smithy/types@4.16.1':
dependencies:
tslib: 2.8.1
optional: true
'@smithy/url-parser@4.4.14':
dependencies:
'@smithy/core': 3.30.0
tslib: 2.8.1
optional: true
'@smithy/util-base64@4.5.14':
dependencies:
'@smithy/core': 3.30.0
tslib: 2.8.1
optional: true
'@smithy/util-body-length-browser@4.4.14':
dependencies:
'@smithy/core': 3.30.0
tslib: 2.8.1
optional: true
'@smithy/util-body-length-node@4.4.14':
dependencies:
'@smithy/core': 3.30.0
tslib: 2.8.1
optional: true
'@smithy/util-buffer-from@2.2.0':
dependencies:
'@smithy/is-array-buffer': 2.2.0
tslib: 2.8.1
optional: true
'@smithy/util-defaults-mode-browser@4.5.14':
dependencies:
'@smithy/core': 3.30.0
tslib: 2.8.1
optional: true
'@smithy/util-defaults-mode-node@4.4.14':
dependencies:
'@smithy/core': 3.30.0
tslib: 2.8.1
optional: true
'@smithy/util-endpoints@3.6.14':
dependencies:
'@smithy/core': 3.30.0
tslib: 2.8.1
optional: true
'@smithy/util-middleware@4.4.14':
dependencies:
'@smithy/core': 3.30.0
tslib: 2.8.1
optional: true
'@smithy/util-retry@4.5.14':
dependencies:
'@smithy/core': 3.30.0
tslib: 2.8.1
optional: true
'@smithy/util-utf8@2.3.0':
dependencies:
'@smithy/util-buffer-from': 2.2.0
tslib: 2.8.1
optional: true
'@smithy/util-utf8@4.4.14':
dependencies:
'@smithy/core': 3.30.0
tslib: 2.8.1
optional: true
'@socket.io/component-emitter@3.1.2': {}
@@ -7248,7 +7302,7 @@ snapshots:
jiti: 2.6.1
lightningcss: 1.32.0
magic-string: 0.30.21
source-map-js: 1.2.1
source-map-js: 1.2.2
tailwindcss: 4.2.2
'@tailwindcss/oxide-android-arm64@4.2.2':
@@ -8010,21 +8064,22 @@ snapshots:
blake3-wasm@2.1.5: {}
body-parser@2.3.0:
body-parser@2.4.0:
dependencies:
bytes: 3.1.2
content-type: 2.0.0
content-type: 2.1.0
debug: 4.4.3
http-errors: 2.0.1
iconv-lite: 0.7.3
on-finished: 2.4.1
qs: 6.15.3
qs: 6.17.1
raw-body: 3.0.2
type-is: 2.1.0
transitivePeerDependencies:
- supports-color
bowser@2.14.1: {}
bowser@2.14.1:
optional: true
brace-expansion@1.1.16:
dependencies:
@@ -8190,6 +8245,8 @@ snapshots:
content-type@2.0.0: {}
content-type@2.1.0: {}
convert-source-map@2.0.0: {}
cookie-es@3.1.1: {}
@@ -8350,13 +8407,12 @@ snapshots:
engine.io-parser@5.2.3: {}
engine.io@6.6.7:
engine.io@6.6.11:
dependencies:
'@types/cors': 2.8.19
'@types/node': 26.1.1
'@types/ws': 8.18.1
accepts: 1.3.8
base64id: 2.0.0
cookie: 0.7.2
cors: 2.8.6
debug: 4.4.3
@@ -8576,7 +8632,7 @@ snapshots:
express@5.2.1:
dependencies:
accepts: 2.0.0
body-parser: 2.3.0
body-parser: 2.4.0
content-disposition: 1.1.0
content-type: 1.0.5
cookie: 0.7.2
@@ -8594,7 +8650,7 @@ snapshots:
on-finished: 2.4.1
once: 1.4.0
parseurl: 1.3.3
proxy-addr: 2.0.7
proxy-addr: 2.0.8
qs: 6.15.2
range-parser: 1.3.0
router: 2.2.0
@@ -9593,7 +9649,7 @@ snapshots:
dependencies:
'@cspotcode/source-map-support': 0.8.1
sharp: 0.35.2
undici: 7.28.0
undici: 7.30.2
workerd: 1.20260722.1
ws: 8.21.0
youch: 4.1.0-beta.10
@@ -9662,11 +9718,10 @@ snapshots:
ms@2.1.3: {}
multer@2.3.0:
multer@2.5.0:
dependencies:
append-field: 1.0.0
busboy: 1.6.0
concat-stream: 2.0.0
type-is: 1.6.18
mute-stream@2.0.0: {}
@@ -9693,7 +9748,7 @@ snapshots:
newrelic@14.3.3:
dependencies:
'@apm-js-collab/tracing-hooks': 0.9.1
'@grpc/grpc-js': 1.14.4
'@grpc/grpc-js': 1.14.7
'@grpc/proto-loader': 0.8.1
'@newrelic/security-agent': 3.0.4
'@opentelemetry/api': 1.9.1
@@ -9880,7 +9935,7 @@ snapshots:
dependencies:
nanoid: 3.3.18
picocolors: 1.1.1
source-map-js: 1.2.1
source-map-js: 1.2.2
pprof-format@2.3.0:
optional: true
@@ -9923,7 +9978,7 @@ snapshots:
'@types/node': 26.1.1
long: 5.3.2
proxy-addr@2.0.7:
proxy-addr@2.0.8:
dependencies:
forwarded: 0.2.0
ipaddr.js: 1.9.1
@@ -9944,7 +9999,7 @@ snapshots:
dependencies:
side-channel: 1.1.1
qs@6.15.3:
qs@6.17.1:
dependencies:
es-define-property: 1.0.1
side-channel: 1.1.1
@@ -10264,7 +10319,7 @@ snapshots:
base64id: 2.0.0
cors: 2.8.6
debug: 4.4.3
engine.io: 6.6.7
engine.io: 6.6.11
socket.io-adapter: 2.5.6
socket.io-parser: 4.2.7
transitivePeerDependencies:
@@ -10272,7 +10327,7 @@ snapshots:
- supports-color
- utf-8-validate
source-map-js@1.2.1: {}
source-map-js@1.2.2: {}
source-map-support@0.5.13:
dependencies:
@@ -10615,9 +10670,7 @@ snapshots:
undici-types@8.3.0: {}
undici@7.28.0: {}
undici@7.29.0: {}
undici@7.30.2: {}
unenv@2.0.0-rc.24:
dependencies:
@@ -10894,6 +10947,4 @@ snapshots:
dependencies:
zod: 4.3.6
zod@3.25.76: {}
zod@4.3.6: {}
+160
View File
@@ -0,0 +1,160 @@
import assert from "node:assert/strict";
import { once } from "node:events";
import http from "node:http";
import { createRequire } from "node:module";
import { test } from "node:test";
import { gzipSync } from "node:zlib";
const apiRequire = createRequire(
new URL("../apps/api/package.json", import.meta.url),
);
const webRequire = createRequire(
new URL("../apps/web/package.json", import.meta.url),
);
const expressRequire = createRequire(
apiRequire.resolve("@nestjs/platform-express"),
);
const proxyaddr = createRequire(expressRequire.resolve("express"))(
"proxy-addr",
);
const { ExpressAdapter } = apiRequire("@nestjs/platform-express");
const { Server } = apiRequire("socket.io");
const { io } = webRequire("socket.io-client");
const engineRequire = createRequire(
createRequire(apiRequire.resolve("socket.io")).resolve("engine.io"),
);
const WebSocket = engineRequire("ws");
test("proxy trust does not accept unrelated IPv4 addresses through IPv6 subnets", () => {
for (const subnet of ["::ffff:10.0.0.0/8", "::/1"]) {
const trust = proxyaddr.compile(subnet);
assert.equal(trust("203.0.113.9"), false, subnet);
}
for (const subnet of ["10.0.0.0/8", "::ffff:10.0.0.0/104"]) {
const trust = proxyaddr.compile(subnet);
assert.equal(trust("10.1.2.3"), true);
assert.equal(trust("::ffff:10.1.2.3"), true);
assert.equal(trust("203.0.113.9"), false);
}
});
test(
"Socket.IO rejects mismatched and omitted upgrade protocol versions",
{ timeout: 10000 },
async (t) => {
const server = http.createServer();
const sockets = new Server(server);
t.after(() => new Promise((resolve) => sockets.close(resolve)));
server.listen(0, "127.0.0.1");
await once(server, "listening");
const origin = `http://127.0.0.1:${server.address().port}`;
for (const protocol of ["3", undefined]) {
const response = await fetch(
`${origin}/socket.io/?EIO=4&transport=polling`,
);
const handshake = await response.text();
assert.equal(handshake[0], "0");
const { sid } = JSON.parse(handshake.slice(1));
const query = new URLSearchParams({ transport: "websocket", sid });
if (protocol) query.set("EIO", protocol);
const status = await new Promise((resolve, reject) => {
const socket = new WebSocket(
`${origin.replace("http:", "ws:")}/socket.io/?${query}`,
);
socket.once("unexpected-response", (_, incoming) => {
incoming.resume();
resolve(incoming.statusCode);
});
socket.once("open", () => {
socket.close();
resolve(101);
});
socket.once("error", reject);
});
assert.equal(status, 400, `upgrade EIO=${protocol ?? "(omitted)"}`);
}
sockets.on("connection", (socket) =>
socket.on("echo", (value, ack) => ack(value)),
);
const client = io(origin, { autoConnect: false, reconnection: false });
t.after(() => client.disconnect());
const connected = once(client, "connect");
client.connect();
const upgraded = once(client.io.engine, "upgrade");
await connected;
await upgraded;
assert.equal(client.io.engine.transport.name, "websocket");
assert.deepEqual(
await client.timeout(2000).emitWithAck("echo", { bid: 42 }),
{ bid: 42 },
);
},
);
test(
"Nest Express preserves raw JSON and survives compressed trailing data",
{ timeout: 10000 },
async (t) => {
const adapter = new ExpressAdapter();
adapter.registerParserMiddleware("", true);
const app = adapter.getInstance();
app.post("/echo", (req, res) =>
res.json({ body: req.body, raw: req.rawBody.toString() }),
);
app.get("/health", (_, res) => res.send("ok"));
app.use((error, _req, res, _next) => res.status(error.status ?? 500).end());
const server = http.createServer(app);
t.after(
() =>
new Promise((resolve) => {
server.closeAllConnections();
server.close(resolve);
}),
);
server.listen(0, "127.0.0.1");
await once(server, "listening");
const origin = `http://127.0.0.1:${server.address().port}`;
const json = JSON.stringify({ bid: 42 });
for (const compressed of [false, true]) {
const response = await fetch(`${origin}/echo`, {
method: "POST",
headers: {
"content-type": "application/json",
...(compressed ? { "content-encoding": "gzip" } : {}),
},
body: compressed ? gzipSync(json) : json,
});
assert.equal(response.status, 200);
assert.deepEqual(await response.json(), { body: { bid: 42 }, raw: json });
}
for (const trailing of [
Buffer.from("invalid trailing bytes"),
Buffer.from([0x1f, 0x8b, 0xff]),
]) {
const payload = Buffer.concat([gzipSync(json), trailing]);
const status = await new Promise((resolve, reject) => {
const request = http.request(
`${origin}/echo`,
{
method: "POST",
headers: {
"content-type": "application/json",
"content-encoding": "gzip",
"content-length": payload.length,
},
},
(response) => {
response.resume();
response.on("end", () => resolve(response.statusCode));
},
);
request.on("error", reject);
request.end(payload);
});
assert.equal(status, 400);
assert.equal(await (await fetch(`${origin}/health`)).text(), "ok");
}
},
);