Compare commits

..
36 changed files with 4598 additions and 917 deletions

No files matched your search

+1 -1
View File
@@ -1 +1 @@
77 83
+8 -1
View File
@@ -41,9 +41,16 @@ COPY --from=prod-deps --chown=nonroot:nonroot /app/package.json ./package.json
COPY --from=prod-deps --chown=nonroot:nonroot /app/node_modules ./node_modules COPY --from=prod-deps --chown=nonroot:nonroot /app/node_modules ./node_modules
COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/package.json ./apps/api/package.json COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/package.json ./apps/api/package.json
COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/node_modules ./apps/api/node_modules COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/node_modules ./apps/api/node_modules
COPY --chown=nonroot:nonroot apps/api/newrelic.cjs ./apps/api/newrelic.cjs
COPY --from=build --chown=nonroot:nonroot /app/apps/api/dist ./apps/api/dist COPY --from=build --chown=nonroot:nonroot /app/apps/api/dist ./apps/api/dist
COPY --chown=nonroot:nonroot apps/project.env ./project.env COPY --chown=nonroot:nonroot apps/project.env ./project.env
EXPOSE 10712 EXPOSE 10712
CMD ["apps/api/dist/main.js"] ENV NEW_RELIC_HOME=/app/apps/api \
NEW_RELIC_APP_NAME=lolympus \
NEW_RELIC_AI_MONITORING_ENABLED=true \
NEW_RELIC_CUSTOM_INSIGHTS_EVENTS_MAX_SAMPLES_STORED=100000 \
NEW_RELIC_SPAN_EVENTS_MAX_SAMPLES_STORED=10000
CMD ["--import", "/app/apps/api/node_modules/newrelic/esm-loader.mjs", "-r", "/app/apps/api/node_modules/newrelic", "apps/api/dist/main.js"]
+22 -5
View File
@@ -4,7 +4,7 @@ LOLYMPUS는 리그 오브 레전드 커뮤니티의 여러 이벤트 중 내전(
<p align="center"> <p align="center">
<video <video
src="https://git.dahyeon.us/dahyeon/lolympus-tournament-support/raw/branch/release/77/docs/screenshots/lolympus-demo.mp4" src="https://git.dahyeon.us/dahyeon/lolympus-tournament-support/raw/branch/release/83/docs/screenshots/lolympus-demo.mp4"
poster="docs/screenshots/lolympus-auction.png" poster="docs/screenshots/lolympus-auction.png"
width="960" width="960"
autoplay="autoplay" autoplay="autoplay"
@@ -13,20 +13,20 @@ LOLYMPUS는 리그 오브 레전드 커뮤니티의 여러 이벤트 중 내전(
playsinline="playsinline" playsinline="playsinline"
controls controls
> >
<a href="https://git.dahyeon.us/dahyeon/lolympus-tournament-support/raw/branch/release/77/docs/screenshots/lolympus-demo.mp4">3초 간격 데모 영상 보기</a> <a href="https://git.dahyeon.us/dahyeon/lolympus-tournament-support/raw/branch/release/83/docs/screenshots/lolympus-demo.mp4">3초 간격 데모 영상 보기</a>
</video> </video>
</p> </p>
<p align="center"> <p align="center">
<a href="https://git.dahyeon.us/dahyeon/lolympus-tournament-support/raw/branch/release/77/docs/screenshots/lolympus-demo.mp4">3초 간격 데모 영상 보기</a> <a href="https://git.dahyeon.us/dahyeon/lolympus-tournament-support/raw/branch/release/83/docs/screenshots/lolympus-demo.mp4">3초 간격 데모 영상 보기</a>
</p> </p>
## 배포 주소 ## 배포 주소
| Environment | Version | URL | | Environment | Version | URL |
| ----------- | ------- | -------------------------------------- | | ----------- | ------- | -------------------------------------- |
| Production | v77 | <https://lolympus.dahyeon.us/> | | Production | v83 | <https://lolympus.dahyeon.us/> |
| Staging | v77 | <https://890c50be.lolympus.pages.dev/> | | Staging | v83 | <https://release-83.lolympus.pages.dev/> |
## 개요 ## 개요
@@ -128,6 +128,23 @@ pnpm start:web:dev
웹 앱은 기본적으로 `apps/web/.env.development` 값을 사용합니다. API 환경값은 `apps/project.env`와 실행 환경의 시크릿 설정을 함께 확인합니다. 웹 앱은 기본적으로 `apps/web/.env.development` 값을 사용합니다. API 환경값은 `apps/project.env`와 실행 환경의 시크릿 설정을 함께 확인합니다.
### API New Relic APM
API 서버는 `newrelic` Node.js agent를 앱 코드보다 먼저 preload합니다. Docker 런타임과 `pnpm start:api:*` 스크립트 모두 `NEW_RELIC_HOME`을 API 패키지로 지정해 `apps/api/newrelic.cjs` 설정을 읽습니다.
Kubernetes에서는 Infisical이 `NEW_RELIC_LICENSE_KEY`를 프로세스 시작 전에 환경변수로 주입해야 합니다. 저장소에는 라이선스 키를 두지 않습니다.
비밀이 아닌 기본값은 Dockerfile과 `apps/api/newrelic.cjs`에 정의되어 있으며 필요하면 런타임 환경변수로 덮어쓸 수 있습니다.
```bash
NEW_RELIC_APP_NAME=lolympus
NEW_RELIC_AI_MONITORING_ENABLED=true
NEW_RELIC_CUSTOM_INSIGHTS_EVENTS_MAX_SAMPLES_STORED=100000
NEW_RELIC_SPAN_EVENTS_MAX_SAMPLES_STORED=10000
```
New Relic Node agent의 정수 환경변수는 `100k` 같은 축약형 대신 `100000`처럼 숫자 문자열을 사용합니다.
카카오톡 기반 명령어 기능은 Dakao(커스텀 카카오톡 게이트웨이) 연동이 필요합니다. Dakao가 실행 중이 아니거나 NATS를 통해 API 서버와 연결되어 있지 않으면 일정 조회, 내전 참가, 참가 취소, 계정 등록 같은 카카오톡 명령어는 사용할 수 없습니다. 카카오톡 기반 명령어 기능은 Dakao(커스텀 카카오톡 게이트웨이) 연동이 필요합니다. Dakao가 실행 중이 아니거나 NATS를 통해 API 서버와 연결되어 있지 않으면 일정 조회, 내전 참가, 참가 취소, 계정 등록 같은 카카오톡 명령어는 사용할 수 없습니다.
## 커맨드 ## 커맨드
+69
View File
@@ -0,0 +1,69 @@
'use strict';
function readBoolean(name, defaultValue) {
const value = process.env[name];
if (value == null || value === '') return defaultValue;
return !['0', 'false', 'f', 'no', 'n', 'disabled'].includes(
value.toLowerCase(),
);
}
function readInteger(name, defaultValue) {
const rawValue = process.env[name]?.trim();
if (!rawValue) return defaultValue;
if (/^\d+$/.test(rawValue)) {
return Number.parseInt(rawValue, 10);
}
process.env[name] = String(defaultValue);
return defaultValue;
}
const hasLicenseKey = Boolean(process.env.NEW_RELIC_LICENSE_KEY);
exports.config = {
app_name: [process.env.NEW_RELIC_APP_NAME || 'lolympus'],
license_key: process.env.NEW_RELIC_LICENSE_KEY || '',
agent_enabled: readBoolean('NEW_RELIC_ENABLED', hasLicenseKey),
distributed_tracing: {
enabled: true,
},
ai_monitoring: {
enabled: readBoolean('NEW_RELIC_AI_MONITORING_ENABLED', true),
},
custom_insights_events: {
max_samples_stored: readInteger(
'NEW_RELIC_CUSTOM_INSIGHTS_EVENTS_MAX_SAMPLES_STORED',
100000,
),
},
span_events: {
max_samples_stored: readInteger(
'NEW_RELIC_SPAN_EVENTS_MAX_SAMPLES_STORED',
10000,
),
},
logging: {
level: process.env.NEW_RELIC_LOG_LEVEL || 'info',
},
instrumentation: {
timers: {
enabled: false,
},
},
allow_all_headers: false,
attributes: {
exclude: [
'request.headers.cookie',
'request.headers.authorization',
'request.headers.proxyAuthorization',
'request.headers.setCookie*',
'response.headers.cookie',
'response.headers.authorization',
'response.headers.proxyAuthorization',
'response.headers.setCookie*',
],
},
};
+4 -3
View File
@@ -10,9 +10,9 @@
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"seed:dev": "ts-node src/seed.ts", "seed:dev": "ts-node src/seed.ts",
"seed:dakao-participant": "ts-node src/seed-dakao-participant.ts", "seed:dakao-participant": "ts-node src/seed-dakao-participant.ts",
"start:dev": "node -e \"process.env.NODE_ENV='dev'; require('./dist/main.js')\"", "start:dev": "NODE_ENV=dev NEW_RELIC_HOME=. node --import newrelic/esm-loader.mjs -r newrelic dist/main.js",
"start:staging": "node -e \"process.env.NODE_ENV='staging'; require('./dist/main.js')\"", "start:staging": "NODE_ENV=staging NEW_RELIC_HOME=. node --import newrelic/esm-loader.mjs -r newrelic dist/main.js",
"start:prod": "node -e \"process.env.NODE_ENV='prod'; require('./dist/main.js')\"", "start:prod": "NODE_ENV=prod NEW_RELIC_HOME=. node --import newrelic/esm-loader.mjs -r newrelic dist/main.js",
"pm2:dev": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:dev", "pm2:dev": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:dev",
"pm2:staging": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:staging", "pm2:staging": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:staging",
"pm2:prod": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:prod", "pm2:prod": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:prod",
@@ -38,6 +38,7 @@
"jose": "^6.2.2", "jose": "^6.2.2",
"mongoose": "^9.4.1", "mongoose": "^9.4.1",
"nats": "^2.29.3", "nats": "^2.29.3",
"newrelic": "^14.1.2",
"redis": "^5.12.1", "redis": "^5.12.1",
"reflect-metadata": "^0.2.2", "reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1", "rxjs": "^7.8.1",
@@ -92,7 +92,10 @@ describe('auction durability projection helpers', () => {
it.each([ it.each([
{ current: { auctionLifecycleId: 'life-1', revision: 8 }, expected: true }, { current: { auctionLifecycleId: 'life-1', revision: 8 }, expected: true },
{ current: { auctionLifecycleId: 'life-1', revision: 9 }, expected: false }, { current: { auctionLifecycleId: 'life-1', revision: 9 }, expected: false },
{ current: { auctionLifecycleId: 'new-life', revision: 1 }, expected: false }, {
current: { auctionLifecycleId: 'new-life', revision: 1 },
expected: false,
},
])('decides whether projection can apply %#', ({ current, expected }) => { ])('decides whether projection can apply %#', ({ current, expected }) => {
expect(shouldApplyAuctionProjection(current, payload)).toBe(expected); expect(shouldApplyAuctionProjection(current, payload)).toBe(expected);
}); });
@@ -100,14 +103,23 @@ describe('auction durability projection helpers', () => {
it.each([ it.each([
{ current: { auctionLifecycleId: 'life-1', revision: 8 }, expected: true }, { current: { auctionLifecycleId: 'life-1', revision: 8 }, expected: true },
{ current: { auctionLifecycleId: 'life-1', revision: 9 }, expected: true }, { current: { auctionLifecycleId: 'life-1', revision: 9 }, expected: true },
{ current: { auctionLifecycleId: 'life-1', revision: 10 }, expected: false }, {
{ current: { auctionLifecycleId: 'new-life', revision: 1 }, expected: false }, current: { auctionLifecycleId: 'life-1', revision: 10 },
expected: false,
},
{
current: { auctionLifecycleId: 'new-life', revision: 1 },
expected: false,
},
{ current: {}, expected: false }, { current: {}, expected: false },
])('decides whether a durability payload can be processed %#', ({ current, expected }) => { ])(
expect(shouldProcessAuctionDurabilityPayload(current, payload)).toBe( 'decides whether a durability payload can be processed %#',
expected, ({ current, expected }) => {
); expect(shouldProcessAuctionDurabilityPayload(current, payload)).toBe(
}); expected,
);
},
);
it('reads due durability payload keys from Redis', async () => { it('reads due durability payload keys from Redis', async () => {
const sendCommand = jest.fn().mockResolvedValue(['payload-1']); const sendCommand = jest.fn().mockResolvedValue(['payload-1']);
@@ -333,7 +345,10 @@ describe('auction durability projection helpers', () => {
createSession: jest.fn().mockResolvedValue(session), createSession: jest.fn().mockResolvedValue(session),
getModel: jest.fn((name: string) => { getModel: jest.fn((name: string) => {
if (name === 'auctionHistory') { if (name === 'auctionHistory') {
return { deleteMany: historyDeleteMany, updateOne: historyUpdateOne }; return {
deleteMany: historyDeleteMany,
updateOne: historyUpdateOne,
};
} }
if (name === 'auction') { if (name === 'auction') {
return { findById: auctionFindById, updateOne: auctionUpdateOne }; return { findById: auctionFindById, updateOne: auctionUpdateOne };
@@ -404,7 +419,10 @@ describe('auction durability projection helpers', () => {
createSession: jest.fn().mockResolvedValue(session), createSession: jest.fn().mockResolvedValue(session),
getModel: jest.fn((name: string) => { getModel: jest.fn((name: string) => {
if (name === 'auctionHistory') { if (name === 'auctionHistory') {
return { deleteMany: historyDeleteMany, updateOne: historyUpdateOne }; return {
deleteMany: historyDeleteMany,
updateOne: historyUpdateOne,
};
} }
if (name === 'auction') { if (name === 'auction') {
return { findById: auctionFindById, updateOne: auctionUpdateOne }; return { findById: auctionFindById, updateOne: auctionUpdateOne };
@@ -428,6 +446,216 @@ describe('auction durability projection helpers', () => {
expect(auctionUpdateOne).not.toHaveBeenCalled(); expect(auctionUpdateOne).not.toHaveBeenCalled();
}); });
it('recovers stale append payloads as history-only records', async () => {
const session = {
abortTransaction: jest.fn().mockResolvedValue(undefined),
commitTransaction: jest.fn().mockResolvedValue(undefined),
endSession: jest.fn().mockResolvedValue(undefined),
startTransaction: jest.fn(),
};
const historyFindOne = jest.fn().mockReturnValue({
session: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue(null),
}),
}),
});
const historyUpdateOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ upsertedCount: 1 }),
});
const auctionUpdateOne = jest.fn();
const sideEffectUpdateOne = jest.fn();
const projectionExec = jest.fn().mockResolvedValue({
auctionLifecycleId: 'life-1',
revision: 10,
});
const auctionFindById = jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
session: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({ exec: projectionExec }),
}),
}),
});
const scheduler = new AuctionDurabilityScheduler(
{
createSession: jest.fn().mockResolvedValue(session),
getModel: jest.fn((name: string) => {
if (name === 'auctionHistory') {
return {
findOne: historyFindOne,
updateOne: historyUpdateOne,
};
}
if (name === 'auction') {
return { findById: auctionFindById, updateOne: auctionUpdateOne };
}
return { updateOne: sideEffectUpdateOne };
}),
} as never,
{ raw: jest.fn() } as never,
);
await scheduler.applyDurabilityPayload({
...payload,
matchSideEffectMutation: { type: 'syncMatchTeamsAfterComplete' },
});
expect(historyFindOne).toHaveBeenCalledWith(
expect.objectContaining({
auctionId: 'auction-1',
sequence: { $gt: 4 },
}),
);
expect(historyUpdateOne).toHaveBeenCalledWith(
{
auctionId: 'auction-1',
auctionStateTransitionId: 'transition-1',
},
expect.objectContaining({
$setOnInsert: expect.objectContaining({
sequence: 4,
}),
}),
{ session, upsert: true },
);
expect(auctionUpdateOne).not.toHaveBeenCalled();
expect(sideEffectUpdateOne).not.toHaveBeenCalled();
});
it('does not resurrect stale append payloads invalidated by later undo', async () => {
const session = {
abortTransaction: jest.fn().mockResolvedValue(undefined),
commitTransaction: jest.fn().mockResolvedValue(undefined),
endSession: jest.fn().mockResolvedValue(undefined),
startTransaction: jest.fn(),
};
const historyFindOne = jest.fn().mockReturnValue({
session: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({
historyMutation: {
targetHistorySequence: 2,
type: 'deleteAfterSequenceAndAppendUndo',
},
}),
}),
}),
});
const historyUpdateOne = jest.fn();
const auctionUpdateOne = jest.fn();
const projectionExec = jest.fn().mockResolvedValue({
auctionLifecycleId: 'life-1',
revision: 10,
});
const auctionFindById = jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
session: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({ exec: projectionExec }),
}),
}),
});
const scheduler = new AuctionDurabilityScheduler(
{
createSession: jest.fn().mockResolvedValue(session),
getModel: jest.fn((name: string) => {
if (name === 'auctionHistory') {
return {
findOne: historyFindOne,
updateOne: historyUpdateOne,
};
}
if (name === 'auction') {
return { findById: auctionFindById, updateOne: auctionUpdateOne };
}
return { updateOne: jest.fn() };
}),
} as never,
{ raw: jest.fn() } as never,
);
await scheduler.applyDurabilityPayload(payload);
expect(historyFindOne).toHaveBeenCalled();
expect(historyUpdateOne).not.toHaveBeenCalled();
expect(auctionUpdateOne).not.toHaveBeenCalled();
});
it('clears stale append payloads after history-only recovery', async () => {
const sendCommand = jest
.fn()
.mockResolvedValueOnce(['payload-1'])
.mockResolvedValueOnce({
committedAtRedisTimestampMS: '1780000000000',
payloadJson: JSON.stringify({
...payload,
matchSideEffectMutation: { type: 'syncMatchTeamsAfterComplete' },
}),
})
.mockResolvedValueOnce(1)
.mockResolvedValueOnce(1);
const historyFindOne = jest.fn().mockReturnValue({
session: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue(null),
}),
}),
});
const historyUpdateOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ upsertedCount: 1 }),
});
const auctionUpdateOne = jest.fn();
const sideEffectUpdateOne = jest.fn();
const auctionFindById = jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
session: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({
auctionLifecycleId: 'life-1',
revision: 10,
}),
}),
}),
}),
});
const scheduler = new AuctionDurabilityScheduler(
{
createSession: jest.fn().mockResolvedValue(null),
getModel: jest.fn((name: string) => {
if (name === 'auctionHistory') {
return {
findOne: historyFindOne,
updateOne: historyUpdateOne,
};
}
if (name === 'auction') {
return { findById: auctionFindById, updateOne: auctionUpdateOne };
}
return { updateOne: sideEffectUpdateOne };
}),
} as never,
{
getCurrentRedisTimestampMS: jest.fn().mockResolvedValue(1000),
raw: jest.fn().mockReturnValue({ sendCommand }),
} as never,
);
await expect(scheduler.processDueDurabilityPayloads(10)).resolves.toEqual({
applied: 1,
failed: 0,
skipped: 0,
});
expect(historyUpdateOne).toHaveBeenCalledTimes(1);
expect(auctionUpdateOne).not.toHaveBeenCalled();
expect(sideEffectUpdateOne).not.toHaveBeenCalled();
expect(sendCommand).toHaveBeenNthCalledWith(3, [
'ZREM',
'auction:auctionDurabilityRetryQueue',
'payload-1',
]);
expect(sendCommand).toHaveBeenNthCalledWith(4, ['DEL', 'payload-1']);
});
it('processes due payloads and clears successful outbox entries', async () => { it('processes due payloads and clears successful outbox entries', async () => {
const sendCommand = jest const sendCommand = jest
.fn() .fn()
@@ -613,7 +841,9 @@ describe('auction durability projection helpers', () => {
.spyOn(scheduler, 'processDueDurabilityPayloads') .spyOn(scheduler, 'processDueDurabilityPayloads')
.mockResolvedValue({ applied: 0, failed: 0, skipped: 0 }); .mockResolvedValue({ applied: 0, failed: 0, skipped: 0 });
await (scheduler as unknown as { safeTick: () => Promise<void> }).safeTick(); await (
scheduler as unknown as { safeTick: () => Promise<void> }
).safeTick();
const auctionRedisService = ( const auctionRedisService = (
scheduler as unknown as { scheduler as unknown as {
@@ -649,7 +879,9 @@ describe('auction durability projection helpers', () => {
.spyOn(scheduler, 'processDueDurabilityPayloads') .spyOn(scheduler, 'processDueDurabilityPayloads')
.mockResolvedValue({ applied: 0, failed: 0, skipped: 0 }); .mockResolvedValue({ applied: 0, failed: 0, skipped: 0 });
await (scheduler as unknown as { safeTick: () => Promise<void> }).safeTick(); await (
scheduler as unknown as { safeTick: () => Promise<void> }
).safeTick();
const auctionRedisService = ( const auctionRedisService = (
scheduler as unknown as { scheduler as unknown as {
@@ -747,7 +979,8 @@ describe('auction durability projection helpers', () => {
if (name === 'auctionSideEffectApplication') { if (name === 'auctionSideEffectApplication') {
return { updateOne: sideEffectUpdateOne }; return { updateOne: sideEffectUpdateOne };
} }
if (name === 'match') return { findById: jest.fn().mockReturnValue(match) }; if (name === 'match')
return { findById: jest.fn().mockReturnValue(match) };
return {}; return {};
}), }),
} as never, } as never,
@@ -829,26 +1062,18 @@ describe('auction durability projection helpers', () => {
matchSideEffectRevision: 3, matchSideEffectRevision: 3,
matchSideEffectStatus: 'completed', matchSideEffectStatus: 'completed',
}); });
expect(broadcastMatchSideEffect).toHaveBeenNthCalledWith( expect(broadcastMatchSideEffect).toHaveBeenNthCalledWith(1, 'match-1', {
1, auctionLifecycleId: 'life-1',
'match-1', currentServerTimestampMS: 2000,
{ matchSideEffectRevision: 2,
auctionLifecycleId: 'life-1', matchSideEffectStatus: 'processing',
currentServerTimestampMS: 2000, });
matchSideEffectRevision: 2, expect(broadcastMatchSideEffect).toHaveBeenNthCalledWith(2, 'match-1', {
matchSideEffectStatus: 'processing', auctionLifecycleId: 'life-1',
}, currentServerTimestampMS: 3000,
); matchSideEffectRevision: 3,
expect(broadcastMatchSideEffect).toHaveBeenNthCalledWith( matchSideEffectStatus: 'completed',
2, });
'match-1',
{
auctionLifecycleId: 'life-1',
currentServerTimestampMS: 3000,
matchSideEffectRevision: 3,
matchSideEffectStatus: 'completed',
},
);
expect(sendCommand).toHaveBeenCalledWith([ expect(sendCommand).toHaveBeenCalledWith([
'EVAL', 'EVAL',
expect.stringContaining("redis.call('EXPIRE'"), expect.stringContaining("redis.call('EXPIRE'"),
@@ -870,6 +1095,101 @@ describe('auction durability projection helpers', () => {
]); ]);
}); });
it('fails sync match teams side effect when the completed projection has no teams', async () => {
const completePayload = {
...payload,
afterAuctionMongoProjection: {
auctionTeams: [],
matchSideEffectRevision: 1,
phase: 'complete',
revision: 10,
},
auctionActionType: 'complete',
matchSideEffectMutation: { type: 'syncMatchTeamsAfterComplete' },
revision: 10,
} as const;
const match = {
participants: [],
save: jest.fn().mockResolvedValue(undefined),
status: 'team-built',
teamBuiltAt: undefined,
teams: [],
};
const historyUpdateOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ upsertedCount: 1 }),
});
const auctionUpdateOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ modifiedCount: 1 }),
});
const auctionFindOneAndUpdate = jest
.fn()
.mockReturnValueOnce({
exec: jest.fn().mockResolvedValue({
auctionLifecycleId: 'life-1',
matchSideEffectRevision: 2,
matchSideEffectStatus: 'processing',
}),
})
.mockReturnValueOnce({
exec: jest.fn().mockResolvedValue({
auctionLifecycleId: 'life-1',
matchSideEffectRevision: 3,
matchSideEffectStatus: 'failed',
}),
});
const sideEffectUpdateOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ matchedCount: 1, modifiedCount: 1 }),
});
const reserveForMatch = jest.fn().mockResolvedValue(match);
const scheduleInitialPoll = jest.fn().mockResolvedValue(null);
const mirrorMatchSideEffectStatus = jest.fn().mockResolvedValue(true);
const broadcastMatchSideEffect = jest.fn();
const scheduler = new AuctionDurabilityScheduler(
{
createSession: jest.fn().mockResolvedValue(null),
getModel: jest.fn((name: string) => {
if (name === 'auctionHistory') return { updateOne: historyUpdateOne };
if (name === 'auction') {
return {
findOneAndUpdate: auctionFindOneAndUpdate,
updateOne: auctionUpdateOne,
};
}
if (name === 'auctionSideEffectApplication') {
return { updateOne: sideEffectUpdateOne };
}
if (name === 'match')
return { findById: jest.fn().mockReturnValue(match) };
return {};
}),
} as never,
{
getCurrentRedisTimestampMS: jest
.fn()
.mockResolvedValueOnce(2000)
.mockResolvedValueOnce(3000),
raw: jest.fn().mockReturnValue({ sendCommand: jest.fn() }),
} as never,
{ reserveForMatch } as never,
{ scheduleInitialPoll } as never,
{ mirrorMatchSideEffectStatus } as never,
{ broadcastMatchSideEffect } as never,
);
await expect(
scheduler.applyDurabilityPayload(completePayload),
).rejects.toThrow('produced no match teams');
expect(match.save).not.toHaveBeenCalled();
expect(reserveForMatch).not.toHaveBeenCalled();
expect(scheduleInitialPoll).not.toHaveBeenCalled();
expect(mirrorMatchSideEffectStatus).toHaveBeenLastCalledWith(
expect.objectContaining({
matchSideEffectStatus: 'failed',
}),
);
});
it('applies reset match side effect after durable projection', async () => { it('applies reset match side effect after durable projection', async () => {
const resetPayload = { const resetPayload = {
...payload, ...payload,
@@ -943,7 +1263,10 @@ describe('auction durability projection helpers', () => {
createSession: jest.fn().mockResolvedValue(null), createSession: jest.fn().mockResolvedValue(null),
getModel: jest.fn((name: string) => { getModel: jest.fn((name: string) => {
if (name === 'auctionHistory') { if (name === 'auctionHistory') {
return { deleteMany: historyDeleteMany, updateOne: historyUpdateOne }; return {
deleteMany: historyDeleteMany,
updateOne: historyUpdateOne,
};
} }
if (name === 'auction') { if (name === 'auction') {
return { return {
@@ -955,7 +1278,8 @@ describe('auction durability projection helpers', () => {
if (name === 'auctionSideEffectApplication') { if (name === 'auctionSideEffectApplication') {
return { updateOne: sideEffectUpdateOne }; return { updateOne: sideEffectUpdateOne };
} }
if (name === 'match') return { findById: jest.fn().mockReturnValue(match) }; if (name === 'match')
return { findById: jest.fn().mockReturnValue(match) };
return {}; return {};
}), }),
} as never, } as never,
@@ -985,7 +1309,10 @@ describe('auction durability projection helpers', () => {
teams: [], teams: [],
tournamentCodeIds: [], tournamentCodeIds: [],
}); });
expect(match.participants).toEqual([{ excluded: false }, { excluded: false }]); expect(match.participants).toEqual([
{ excluded: false },
{ excluded: false },
]);
expect(match.save).toHaveBeenCalledTimes(1); expect(match.save).toHaveBeenCalledTimes(1);
expect(sideEffectUpdateOne).toHaveBeenCalledWith( expect(sideEffectUpdateOne).toHaveBeenCalledWith(
expect.objectContaining({ expect.objectContaining({
@@ -29,6 +29,8 @@ import {
AUCTION_DURABILITY_RETRY_QUEUE_KEY, AUCTION_DURABILITY_RETRY_QUEUE_KEY,
buildAuctionRedisKeys, buildAuctionRedisKeys,
} from './redis/auction-redis.keys'; } from './redis/auction-redis.keys';
// [AUCTION-DEBUG] 경매 "중복 멤버" 조사용 임시 계측. 조사 종료 후 제거 대상.
import { recordNewRelicCustomEvent } from '../global/observability/new-relic';
const AUCTION_DURABILITY_TICK_INTERVAL_MS = 1000; const AUCTION_DURABILITY_TICK_INTERVAL_MS = 1000;
const AUCTION_DURABILITY_BATCH_LIMIT = 20; const AUCTION_DURABILITY_BATCH_LIMIT = 20;
const AUCTION_DURABILITY_RETRY_DELAY_MS = 5000; const AUCTION_DURABILITY_RETRY_DELAY_MS = 5000;
@@ -128,15 +130,17 @@ export class AuctionDurabilityScheduler
currentRedisTimestampMS: number, currentRedisTimestampMS: number,
batchLimit: number, batchLimit: number,
): Promise<string[]> { ): Promise<string[]> {
const reply = await this.auctionRedisService.raw().sendCommand([ const reply = await this.auctionRedisService
'ZRANGEBYSCORE', .raw()
AUCTION_DURABILITY_RETRY_QUEUE_KEY, .sendCommand([
'-inf', 'ZRANGEBYSCORE',
String(currentRedisTimestampMS), AUCTION_DURABILITY_RETRY_QUEUE_KEY,
'LIMIT', '-inf',
'0', String(currentRedisTimestampMS),
String(batchLimit), 'LIMIT',
]); '0',
String(batchLimit),
]);
return Array.isArray(reply) ? reply.map(String) : []; return Array.isArray(reply) ? reply.map(String) : [];
} }
@@ -165,15 +169,29 @@ export class AuctionDurabilityScheduler
} }
await this.applyDurabilityPayload(payload); await this.applyDurabilityPayload(payload);
applied += 1; applied += 1;
// [AUCTION-DEBUG] 제거 대상. 영속 지연(lag): Redis 커밋 → Mongo 영속까지 걸린 시간 + 배치 백로그.
// 사용자가 본 "되돌리기/이력이 2~3 뒤처짐"을 수치화한다(지연이 클수록 undo
// 패널이 stale 시퀀스를 보여 엉뚱한 스냅샷 복원 가능성↑).
recordNewRelicCustomEvent('AuctionServerDurability', {
matchId: typeof payload.matchId === 'string' ? payload.matchId : '',
auctionStateTransitionId: payload.auctionStateTransitionId,
auctionActionType: payload.auctionActionType,
revision: payload.revision,
auctionHistorySequence: payload.auctionHistorySequence,
persistLatencyMS:
typeof payload.committedAtRedisTimestampMS === 'number'
? currentRedisTimestampMS - payload.committedAtRedisTimestampMS
: -1,
batchBacklog: payloadKeys.length,
});
await this.clearDurabilityPayload(payloadKey); await this.clearDurabilityPayload(payloadKey);
} catch (error) { } catch (error) {
failed += 1; failed += 1;
const failureDisposition = const failureDisposition = await this.recordDurabilityPayloadFailure(
await this.recordDurabilityPayloadFailure( payloadKey,
payloadKey, currentRedisTimestampMS,
currentRedisTimestampMS, error,
error, );
);
this.logger.warn( this.logger.warn(
`Auction durability payload failed for ${payloadKey} (${failureDisposition}): ${ `Auction durability payload failed for ${payloadKey} (${failureDisposition}): ${
error instanceof Error ? error.message : error error instanceof Error ? error.message : error
@@ -195,7 +213,9 @@ export class AuctionDurabilityScheduler
const payloadJson = hash.payloadJson; const payloadJson = hash.payloadJson;
if (!payloadJson) return null; if (!payloadJson) return null;
const payload = JSON.parse(payloadJson) as AuctionDurabilityPayload; const payload = JSON.parse(payloadJson) as AuctionDurabilityPayload;
const committedAtRedisTimestampMS = Number(hash.committedAtRedisTimestampMS); const committedAtRedisTimestampMS = Number(
hash.committedAtRedisTimestampMS,
);
if (Number.isFinite(committedAtRedisTimestampMS)) { if (Number.isFinite(committedAtRedisTimestampMS)) {
payload.committedAtRedisTimestampMS = committedAtRedisTimestampMS; payload.committedAtRedisTimestampMS = committedAtRedisTimestampMS;
} }
@@ -222,13 +242,31 @@ export class AuctionDurabilityScheduler
try { try {
session?.startTransaction(); session?.startTransaction();
const historyMutation = parseAuctionHistoryMutation(
payload.historyMutation,
);
if (typeof AuctionModel.findById === 'function') { if (typeof AuctionModel.findById === 'function') {
const currentProjection = await readAuctionProjectionIdentityForMutation( const currentProjection =
AuctionModel, await readAuctionProjectionIdentityForMutation(
payload.auctionId, AuctionModel,
session, payload.auctionId,
); session,
if (!shouldProcessAuctionDurabilityPayload(currentProjection, payload)) { );
if (
!shouldProcessAuctionDurabilityPayload(currentProjection, payload)
) {
// 뒤 payload가 먼저 projection revision을 올리면 앞 append payload가 stale이 된다.
// 이때 projection/side effect는 건드리지 않고 undo용 history만 멱등 복구한다.
if (
historyMutation.type === 'append' &&
currentProjection.auctionLifecycleId === payload.auctionLifecycleId
) {
await this.applyStaleAppendHistoryRecovery({
AuctionHistoryModel,
payload,
session,
});
}
if (session) await session.commitTransaction(); if (session) await session.commitTransaction();
return; return;
} }
@@ -370,15 +408,17 @@ export class AuctionDurabilityScheduler
); );
if (!hasMatchedDocument(leaseResult)) return; if (!hasMatchedDocument(leaseResult)) return;
const processingDelta = await this.persistAndBroadcastMatchSideEffectStatus({ const processingDelta = await this.persistAndBroadcastMatchSideEffectStatus(
AuctionModel, {
currentServerTimestampMS: currentRedisTimestampMS, AuctionModel,
expectedMatchSideEffectRevision: Number( currentServerTimestampMS: currentRedisTimestampMS,
payload.afterAuctionMongoProjection.matchSideEffectRevision ?? 0, expectedMatchSideEffectRevision: Number(
), payload.afterAuctionMongoProjection.matchSideEffectRevision ?? 0,
payload, ),
status: 'processing', payload,
}); status: 'processing',
},
);
if (!processingDelta) return; if (!processingDelta) return;
let expectedMatchSideEffectRevision = let expectedMatchSideEffectRevision =
processingDelta.matchSideEffectRevision; processingDelta.matchSideEffectRevision;
@@ -396,11 +436,36 @@ export class AuctionDurabilityScheduler
teamBuiltAt?: Date; teamBuiltAt?: Date;
teams: ReturnType<typeof buildMatchTeamsFromProjection>; teams: ReturnType<typeof buildMatchTeamsFromProjection>;
} | null; } | null;
if (!match) throw new Error(`Match not found: ${String(payload.matchId)}`); if (!match)
match.teams = buildMatchTeamsFromProjection( throw new Error(`Match not found: ${String(payload.matchId)}`);
const matchTeams = buildMatchTeamsFromProjection(
payload.afterAuctionMongoProjection, payload.afterAuctionMongoProjection,
match, match,
); );
// [AUCTION-DEBUG] 제거 대상. 최종 팀에 같은 유저가 2번 들어갔는지 무조건 검사
// (출처가 markSold든 undo 복원이든 projection이든 여기서 결정적으로 잡힌다).
const allMemberUserIds = matchTeams.flatMap((team) =>
team.members.map((member) => member.userId.toString()),
);
const distinctMemberCount = new Set(allMemberUserIds).size;
recordNewRelicCustomEvent('AuctionServerTeamBuild', {
matchId: typeof payload.matchId === 'string' ? payload.matchId : '',
auctionStateTransitionId: payload.auctionStateTransitionId,
teamCount: matchTeams.length,
totalMemberCount: allMemberUserIds.length,
distinctMemberCount,
hasDuplicateMember: allMemberUserIds.length !== distinctMemberCount,
duplicateUserId:
allMemberUserIds.find(
(id, idx) => allMemberUserIds.indexOf(id) !== idx,
) ?? null,
});
if (matchTeams.length === 0) {
throw new Error(
`Auction complete side effect produced no match teams for match ${String(payload.matchId)}.`,
);
}
match.teams = matchTeams;
match.status = 'team-built'; match.status = 'team-built';
match.teamBuiltAt = match.teamBuiltAt ?? new Date(); match.teamBuiltAt = match.teamBuiltAt ?? new Date();
await match.save(); await match.save();
@@ -466,6 +531,75 @@ export class AuctionDurabilityScheduler
} }
} }
private async applyStaleAppendHistoryRecovery(params: {
AuctionHistoryModel: {
findOne?: (...args: never[]) => unknown;
updateOne: (...args: never[]) => unknown;
};
payload: AuctionDurabilityPayload;
session: mongoose.ClientSession | null | undefined;
}): Promise<void> {
const invalidated =
await this.isAppendHistoryInvalidatedByLaterDestructiveMutation(params);
if (invalidated) return;
const historyOperation = buildAuctionHistoryUpsert(params.payload).updateOne;
await execMaybe(
params.AuctionHistoryModel.updateOne(
historyOperation.filter as never,
historyOperation.update as never,
{
session: params.session,
upsert: true,
} as never,
) as Promise<unknown> | { exec(): Promise<unknown> },
);
}
private async isAppendHistoryInvalidatedByLaterDestructiveMutation(params: {
AuctionHistoryModel: {
findOne?: (...args: never[]) => unknown;
};
payload: AuctionDurabilityPayload;
session: mongoose.ClientSession | null | undefined;
}): Promise<boolean> {
if (!params.AuctionHistoryModel.findOne) return true;
// 늦게 도착한 append는 history gap을 메울 수 있지만,
// 이후 undo/reset이 의도적으로 삭제한 sequence를 되살리면 안 된다.
const query = params.AuctionHistoryModel.findOne({
auctionId: params.payload.auctionId,
sequence: { $gt: params.payload.auctionHistorySequence },
$or: [
{
'historyMutation.targetHistorySequence': {
$lt: params.payload.auctionHistorySequence,
},
'historyMutation.type': 'deleteAfterSequenceAndAppendUndo',
},
{
'historyMutation.resetMode': { $ne: 'preserve-audit' },
'historyMutation.type': 'reset',
},
],
} as never);
const scoped =
query && typeof query === 'object' && 'session' in query
? (query as { session: (...args: never[]) => unknown }).session(
params.session as never,
)
: query;
const leaned =
scoped && typeof scoped === 'object' && 'lean' in scoped
? (scoped as { lean: () => unknown }).lean()
: scoped;
const result =
leaned && typeof leaned === 'object' && 'exec' in leaned
? await (leaned as { exec: () => Promise<unknown> }).exec()
: await Promise.resolve(leaned);
return Boolean(result);
}
private async applyResetMatchSideEffect( private async applyResetMatchSideEffect(
payload: AuctionDurabilityPayload, payload: AuctionDurabilityPayload,
mutation: ParsedMatchSideEffectMutation, mutation: ParsedMatchSideEffectMutation,
@@ -553,15 +687,18 @@ export class AuctionDurabilityScheduler
); );
if (!hasMatchedDocument(leaseResult)) return; if (!hasMatchedDocument(leaseResult)) return;
const processingDelta = await this.persistAndBroadcastMatchSideEffectStatus({ const processingDelta = await this.persistAndBroadcastMatchSideEffectStatus(
AuctionModel, {
currentServerTimestampMS: currentRedisTimestampMS, AuctionModel,
expectedMatchSideEffectRevision: Number( currentServerTimestampMS: currentRedisTimestampMS,
params.payload.afterAuctionMongoProjection.matchSideEffectRevision ?? 0, expectedMatchSideEffectRevision: Number(
), params.payload.afterAuctionMongoProjection.matchSideEffectRevision ??
payload: params.payload, 0,
status: 'processing', ),
}); payload: params.payload,
status: 'processing',
},
);
if (!processingDelta) return; if (!processingDelta) return;
let expectedMatchSideEffectRevision = let expectedMatchSideEffectRevision =
processingDelta.matchSideEffectRevision; processingDelta.matchSideEffectRevision;
@@ -605,7 +742,8 @@ export class AuctionDurabilityScheduler
} catch (error) { } catch (error) {
const failureTimestampMS = const failureTimestampMS =
await this.auctionRedisService.getCurrentRedisTimestampMS(); await this.auctionRedisService.getCurrentRedisTimestampMS();
const errorMessage = error instanceof Error ? error.message : String(error); const errorMessage =
error instanceof Error ? error.message : String(error);
await execMaybe( await execMaybe(
AuctionSideEffectApplicationModel.updateOne( AuctionSideEffectApplicationModel.updateOne(
identity as never, identity as never,
@@ -658,7 +796,9 @@ export class AuctionDurabilityScheduler
payload: AuctionDurabilityPayload; payload: AuctionDurabilityPayload;
session: mongoose.ClientSession | null | undefined; session: mongoose.ClientSession | null | undefined;
}): Promise<void> { }): Promise<void> {
const mutation = parseAuctionHistoryMutation(params.payload.historyMutation); const mutation = parseAuctionHistoryMutation(
params.payload.historyMutation,
);
if (isDestructiveHistoryMutation(mutation)) { if (isDestructiveHistoryMutation(mutation)) {
if (mutation.type === 'deleteAfterSequenceAndAppendUndo') { if (mutation.type === 'deleteAfterSequenceAndAppendUndo') {
if (!params.AuctionHistoryModel.deleteMany) { if (!params.AuctionHistoryModel.deleteMany) {
@@ -689,7 +829,9 @@ export class AuctionDurabilityScheduler
} }
} }
const historyOperation = buildAuctionHistoryUpsert(params.payload).updateOne; const historyOperation = buildAuctionHistoryUpsert(
params.payload,
).updateOne;
await execMaybe( await execMaybe(
params.AuctionHistoryModel.updateOne( params.AuctionHistoryModel.updateOne(
historyOperation.filter as never, historyOperation.filter as never,
@@ -731,7 +873,9 @@ export class AuctionDurabilityScheduler
: {}), : {}),
matchSideEffectStatus: params.status, matchSideEffectStatus: params.status,
}, },
...(params.errorMessage ? {} : { $unset: { matchSideEffectError: '' } }), ...(params.errorMessage
? {}
: { $unset: { matchSideEffectError: '' } }),
} as never, } as never,
{ {
projection: { projection: {
@@ -742,13 +886,11 @@ export class AuctionDurabilityScheduler
returnDocument: 'after', returnDocument: 'after',
} as never, } as never,
), ),
)) as )) as {
| { auctionLifecycleId?: string;
auctionLifecycleId?: string; matchSideEffectRevision?: number;
matchSideEffectRevision?: number; matchSideEffectStatus?: AuctionMatchSideEffectStatus;
matchSideEffectStatus?: AuctionMatchSideEffectStatus; } | null;
}
| null;
if (!updatedAuction?.auctionLifecycleId) return null; if (!updatedAuction?.auctionLifecycleId) return null;
const delta = buildMatchSideEffectDelta({ const delta = buildMatchSideEffectDelta({
@@ -815,12 +957,14 @@ export class AuctionDurabilityScheduler
payloadKey: string, payloadKey: string,
retryAtRedisTimestampMS: number, retryAtRedisTimestampMS: number,
): Promise<void> { ): Promise<void> {
await this.auctionRedisService.raw().sendCommand([ await this.auctionRedisService
'ZADD', .raw()
AUCTION_DURABILITY_RETRY_QUEUE_KEY, .sendCommand([
String(retryAtRedisTimestampMS), 'ZADD',
payloadKey, AUCTION_DURABILITY_RETRY_QUEUE_KEY,
]); String(retryAtRedisTimestampMS),
payloadKey,
]);
} }
private async recordDurabilityPayloadFailure( private async recordDurabilityPayloadFailure(
@@ -829,43 +973,44 @@ export class AuctionDurabilityScheduler
error: unknown, error: unknown,
): Promise<'dead-lettered' | 'requeued'> { ): Promise<'dead-lettered' | 'requeued'> {
const errorMessage = formatErrorMessageForRedis(error); const errorMessage = formatErrorMessageForRedis(error);
const attemptReply = await this.auctionRedisService.raw().sendCommand([ const attemptReply = await this.auctionRedisService
'HINCRBY', .raw()
payloadKey, .sendCommand(['HINCRBY', payloadKey, 'attempts', '1']);
'attempts',
'1',
]);
const attempts = Number(attemptReply); const attempts = Number(attemptReply);
await this.auctionRedisService.raw().sendCommand([ await this.auctionRedisService
'HSET', .raw()
payloadKey, .sendCommand([
'lastError', 'HSET',
errorMessage, payloadKey,
'lastFailedAtRedisTimestampMS', 'lastError',
String(currentRedisTimestampMS), errorMessage,
]); 'lastFailedAtRedisTimestampMS',
String(currentRedisTimestampMS),
]);
if ( if (
Number.isFinite(attempts) && Number.isFinite(attempts) &&
attempts >= AUCTION_DURABILITY_MAX_ATTEMPTS attempts >= AUCTION_DURABILITY_MAX_ATTEMPTS
) { ) {
await this.auctionRedisService.raw().sendCommand([ await this.auctionRedisService
'ZREM', .raw()
AUCTION_DURABILITY_RETRY_QUEUE_KEY, .sendCommand(['ZREM', AUCTION_DURABILITY_RETRY_QUEUE_KEY, payloadKey]);
payloadKey, await this.auctionRedisService
]); .raw()
await this.auctionRedisService.raw().sendCommand([ .sendCommand([
'HSET', 'HSET',
payloadKey, payloadKey,
'deadLetteredAtRedisTimestampMS', 'deadLetteredAtRedisTimestampMS',
String(currentRedisTimestampMS), String(currentRedisTimestampMS),
]); ]);
await this.auctionRedisService.raw().sendCommand([ await this.auctionRedisService
'ZADD', .raw()
AUCTION_DURABILITY_DEAD_LETTER_QUEUE_KEY, .sendCommand([
String(currentRedisTimestampMS), 'ZADD',
payloadKey, AUCTION_DURABILITY_DEAD_LETTER_QUEUE_KEY,
]); String(currentRedisTimestampMS),
payloadKey,
]);
return 'dead-lettered'; return 'dead-lettered';
} }
@@ -881,38 +1026,40 @@ export class AuctionDurabilityScheduler
): Promise<void> { ): Promise<void> {
const matchId = String(payload.matchId); const matchId = String(payload.matchId);
const keys = buildAuctionRedisKeys(matchId); const keys = buildAuctionRedisKeys(matchId);
await this.auctionRedisService.raw().sendCommand([ await this.auctionRedisService
'EVAL', .raw()
[ .sendCommand([
"local expectedAuctionLifecycleId = ARGV[2]", 'EVAL',
"local currentAuctionLifecycleId = redis.call('HGET', KEYS[1], 'auctionLifecycleId')", [
"if currentAuctionLifecycleId ~= expectedAuctionLifecycleId then", 'local expectedAuctionLifecycleId = ARGV[2]',
' return 0', "local currentAuctionLifecycleId = redis.call('HGET', KEYS[1], 'auctionLifecycleId')",
'end', 'if currentAuctionLifecycleId ~= expectedAuctionLifecycleId then',
"redis.call('ZREM', KEYS[2], ARGV[1])", ' return 0',
'for index = 1, #KEYS do', 'end',
' if index ~= 2 then', "redis.call('ZREM', KEYS[2], ARGV[1])",
" redis.call('EXPIRE', KEYS[index], ARGV[3])", 'for index = 1, #KEYS do',
' end', ' if index ~= 2 then',
'end', " redis.call('EXPIRE', KEYS[index], ARGV[3])",
'return 1', ' end',
].join('\n'), 'end',
'11', 'return 1',
keys.liveStateKey, ].join('\n'),
keys.deadlineQueueKey, '11',
keys.structureStateKey, keys.liveStateKey,
keys.appliedTransitionIdsKey, keys.deadlineQueueKey,
keys.bidHistoryKey, keys.structureStateKey,
keys.bidRequestResultsKey, keys.appliedTransitionIdsKey,
keys.bidRequestResultOrderKey, keys.bidHistoryKey,
keys.actionRequestResultsKey, keys.bidRequestResultsKey,
keys.actionRequestResultOrderKey, keys.bidRequestResultOrderKey,
keys.rehydrateLockKey, keys.actionRequestResultsKey,
keys.stateTransitionLockKey, keys.actionRequestResultOrderKey,
matchId, keys.rehydrateLockKey,
payload.auctionLifecycleId, keys.stateTransitionLockKey,
String(AUCTION_REDIS_COMPLETED_RETAIN_SECONDS), matchId,
]); payload.auctionLifecycleId,
String(AUCTION_REDIS_COMPLETED_RETAIN_SECONDS),
]);
} }
} }
@@ -961,7 +1108,9 @@ export function parseAuctionHistoryMutation(
} }
if (record.type === 'reset') { if (record.type === 'reset') {
const resetMode = const resetMode =
record.resetMode === 'preserve-audit' ? 'preserve-audit' : 'clear-history'; record.resetMode === 'preserve-audit'
? 'preserve-audit'
: 'clear-history';
return { resetMode, type: 'reset' }; return { resetMode, type: 'reset' };
} }
return { type: 'append' }; return { type: 'append' };
@@ -1055,7 +1204,10 @@ export function buildSideEffectApplicationUpsert(
payload: AuctionDurabilityPayload, payload: AuctionDurabilityPayload,
mutation: ParsedMatchSideEffectMutation, mutation: ParsedMatchSideEffectMutation,
) { ) {
const identity = buildSideEffectApplicationIdentityFromPayload(payload, mutation); const identity = buildSideEffectApplicationIdentityFromPayload(
payload,
mutation,
);
return { return {
filter: identity, filter: identity,
update: { update: {
@@ -1100,7 +1252,12 @@ function buildSideEffectApplicationIdentityFromPayload(
function hashStableJson(value: unknown): string { function hashStableJson(value: unknown): string {
return createHash('sha256') return createHash('sha256')
.update(JSON.stringify(value, Object.keys(value as Record<string, unknown>).sort())) .update(
JSON.stringify(
value,
Object.keys(value as Record<string, unknown>).sort(),
),
)
.digest('hex'); .digest('hex');
} }
@@ -1140,13 +1297,16 @@ function buildMatchTeamsFromProjection(
const members: MatchTeamMember[] = [ const members: MatchTeamMember[] = [
{ {
assignedPosition: assignedPosition:
(captain?.preferredPositions?.[0]?.position as Position | undefined) ?? (captain?.preferredPositions?.[0]?.position as
'MID', | Position
| undefined) ?? 'MID',
cost: 0, cost: 0,
userId: captainUserId, userId: captainUserId,
}, },
...rawMembers ...rawMembers
.filter((member) => member.userId?.toString() !== captainUserId.toString()) .filter(
(member) => member.userId?.toString() !== captainUserId.toString(),
)
.map((member) => ({ .map((member) => ({
assignedPosition: (member.assignedPosition ?? 'MID') as Position, assignedPosition: (member.assignedPosition ?? 'MID') as Position,
cost: Number(member.memberAcquisitionBidPointAmount ?? 0), cost: Number(member.memberAcquisitionBidPointAmount ?? 0),
@@ -1198,7 +1358,9 @@ function calculateDurabilityRetryDelayMS(attempts: number): number {
); );
} }
async function execMaybe<T>(queryOrPromise: Promise<T> | { exec(): Promise<T> }) { async function execMaybe<T>(
queryOrPromise: Promise<T> | { exec(): Promise<T> },
) {
if ( if (
queryOrPromise && queryOrPromise &&
typeof (queryOrPromise as { exec?: unknown }).exec === 'function' typeof (queryOrPromise as { exec?: unknown }).exec === 'function'
@@ -158,11 +158,12 @@ describe('AuctionService', () => {
it('rejects non-positive or fractional bid amounts before loading auction state', async () => { it('rejects non-positive or fractional bid amounts before loading auction state', async () => {
const matchId = new mongoose.Types.ObjectId(); const matchId = new mongoose.Types.ObjectId();
const auctionFindOne = jest.fn(); const auctionFindOne = jest.fn();
const { service, auctionRedisCommandService, auctionRedisService } = createService({ const { service, auctionRedisCommandService, auctionRedisService } =
auction: { createService({
findOne: auctionFindOne, auction: {
}, findOne: auctionFindOne,
}); },
});
await expect( await expect(
service.placeBid({ service.placeBid({
@@ -266,7 +267,7 @@ describe('AuctionService', () => {
}); });
expect(match.status).toBe('team-built'); expect(match.status).toBe('team-built');
expect(match.teamBuiltAt).toBeInstanceOf(Date); expect(match.teamBuiltAt).toBeUndefined();
expect(match.save).toHaveBeenCalledTimes(1); expect(match.save).toHaveBeenCalledTimes(1);
expect(tournamentCodeService.reserveForMatch).not.toHaveBeenCalled(); expect(tournamentCodeService.reserveForMatch).not.toHaveBeenCalled();
expect(tournamentResultService.scheduleInitialPoll).not.toHaveBeenCalled(); expect(tournamentResultService.scheduleInitialPoll).not.toHaveBeenCalled();
@@ -542,44 +543,45 @@ describe('AuctionService', () => {
})); }));
const auctionDeleteOne = jest.fn().mockResolvedValue({ deletedCount: 1 }); const auctionDeleteOne = jest.fn().mockResolvedValue({ deletedCount: 1 });
const historyDeleteMany = jest.fn().mockResolvedValue({ deletedCount: 2 }); const historyDeleteMany = jest.fn().mockResolvedValue({ deletedCount: 2 });
const { service, auctionRedisCommandService, auctionRedisService } = createService({ const { service, auctionRedisCommandService, auctionRedisService } =
match: { createService({
findById: jest.fn().mockResolvedValue(match), match: {
}, findById: jest.fn().mockResolvedValue(match),
user: { },
find: jest.fn().mockResolvedValue(users), user: {
}, find: jest.fn().mockResolvedValue(users),
auction: { },
create: auctionCreate, auction: {
deleteOne: auctionDeleteOne, create: auctionCreate,
findOne: jest.fn().mockResolvedValue(existingAuction), deleteOne: auctionDeleteOne,
}, findOne: jest.fn().mockResolvedValue(existingAuction),
auctionHistory: { },
create: jest.fn().mockResolvedValue(undefined), auctionHistory: {
deleteMany: historyDeleteMany, create: jest.fn().mockResolvedValue(undefined),
findOne: jest.fn().mockReturnValue({ deleteMany: historyDeleteMany,
sort: jest.fn().mockReturnValue({ findOne: jest.fn().mockReturnValue({
sort: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue(null),
}),
}),
}),
}),
},
community: {
findById: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({ select: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({ lean: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue(null), exec: jest.fn().mockResolvedValue({
riotPlatform: 'kr',
riotRegion: 'asia',
}),
}), }),
}), }),
}), }),
}), },
}, });
community: {
findById: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({
riotPlatform: 'kr',
riotRegion: 'asia',
}),
}),
}),
}),
},
});
await service.start({ await service.start({
matchId, matchId,
@@ -800,7 +802,9 @@ describe('AuctionService', () => {
findOne: jest.fn().mockResolvedValue(auction), findOne: jest.fn().mockResolvedValue(auction),
}, },
}); });
auctionRedisStateReaderService.readLiveStateIdentity.mockResolvedValue(null); auctionRedisStateReaderService.readLiveStateIdentity.mockResolvedValue(
null,
);
auctionRedisStateReaderService.readAuctionStateView.mockResolvedValue( auctionRedisStateReaderService.readAuctionStateView.mockResolvedValue(
redisState, redisState,
); );
@@ -870,12 +874,15 @@ describe('AuctionService', () => {
phase: 'bidding', phase: 'bidding',
revision: 2, revision: 2,
}; };
const { service, auctionRedisCommandService, auctionRedisStateReaderService } = const {
createService({ service,
auction: { auctionRedisCommandService,
findOne: jest.fn().mockResolvedValue(auction), auctionRedisStateReaderService,
}, } = createService({
}); auction: {
findOne: jest.fn().mockResolvedValue(auction),
},
});
auctionRedisStateReaderService.readAuctionStateView auctionRedisStateReaderService.readAuctionStateView
.mockResolvedValueOnce(presentingState) .mockResolvedValueOnce(presentingState)
.mockResolvedValueOnce(biddingState); .mockResolvedValueOnce(biddingState);
@@ -973,12 +980,15 @@ describe('AuctionService', () => {
currentHighestBidPointAmount: 120, currentHighestBidPointAmount: 120,
revision: 3, revision: 3,
}; };
const { service, auctionRedisCommandService, auctionRedisStateReaderService } = const {
createService({ service,
auction: { auctionRedisCommandService,
findOne: jest.fn().mockResolvedValue(auction), auctionRedisStateReaderService,
}, } = createService({
}); auction: {
findOne: jest.fn().mockResolvedValue(auction),
},
});
auctionRedisStateReaderService.readAuctionStateView auctionRedisStateReaderService.readAuctionStateView
.mockResolvedValueOnce(biddingState) .mockResolvedValueOnce(biddingState)
.mockResolvedValueOnce(afterBidState); .mockResolvedValueOnce(afterBidState);
@@ -1007,6 +1017,115 @@ describe('AuctionService', () => {
); );
}); });
it('keeps Redis sold snapshotBefore isolated from the sold structure mutation', async () => {
const matchId = new mongoose.Types.ObjectId();
const captainUserId = new mongoose.Types.ObjectId();
const playerUserId = new mongoose.Types.ObjectId();
const auction = {
_id: new mongoose.Types.ObjectId(),
auctionEngineVersion: 'redis-v1',
matchId,
matchSideEffectRevision: 0,
};
const biddingState = {
auctionBidHistory: [],
auctionLifecycleId: 'life-1',
auctionPlayerOrder: [
{
userId: playerUserId.toString(),
preferredPositions: [{ position: 'MID', priority: 1 }],
},
],
auctionTeams: [
{
captainUserId: captainUserId.toString(),
members: [],
remainingBidPointAmount: 1000,
teamIndex: 1,
},
],
bidRoundExtensionSeconds: 5,
currentAuctionHistorySequence: 3,
currentAuctionPlayerOrderIndex: 0,
currentAuctionRound: 1,
currentBidRoundPlayerUserId: playerUserId.toString(),
currentHighestBidPointAmount: 120,
currentHighestBidderTeamIndex: 1,
initialTeamBidPointAmount: 1000,
maximumBidRoundDurationSeconds: 30,
passedAuctionPlayerQueue: [],
phase: 'bidding',
revision: 4,
topTierAuctionPriorityThreshold: 'NONE',
};
const soldState = {
...biddingState,
auctionTeams: [
{
...biddingState.auctionTeams[0],
members: [
{
assignedPosition: 'MID',
memberAcquisitionBidPointAmount: 120,
userId: playerUserId.toString(),
},
],
remainingBidPointAmount: 880,
},
],
currentAuctionHistorySequence: 4,
currentHighestBidPointAmount: 120,
phase: 'sold',
revision: 5,
};
const {
service,
auctionRedisCommandService,
auctionRedisStateReaderService,
} = createService({
auction: {
findOne: jest.fn().mockResolvedValue(auction),
},
});
auctionRedisStateReaderService.readAuctionStateView
.mockResolvedValueOnce(biddingState)
.mockResolvedValueOnce(soldState);
await expect(
service.markSold({
auctionActionRequestId: '00000000-0000-4000-8000-000000000061',
clientObservedAuctionLifecycleId: 'life-1',
clientObservedCurrentAuctionPlayerOrderIndex: 0,
clientObservedCurrentBidRoundPlayerUserId: playerUserId.toString(),
clientObservedPhase: 'bidding',
clientObservedRevision: 4,
matchId,
}),
).resolves.toMatchObject({
phase: 'sold',
revision: 5,
});
const transitionInput =
auctionRedisCommandService.applyTransition.mock.calls[0][1];
const durabilityPayload = JSON.parse(transitionInput.durabilityPayloadJson);
expect(durabilityPayload.snapshotBefore).toMatchObject({
phase: 'bidding',
revision: 4,
});
expect(durabilityPayload.snapshotBefore.auctionTeams[0].members).toEqual(
[],
);
expect(
durabilityPayload.afterAuctionMongoProjection.auctionTeams[0].members,
).toEqual([
expect.objectContaining({
memberAcquisitionBidPointAmount: 120,
userId: playerUserId.toString(),
}),
]);
});
it('returns bid deltas without re-reading the full Redis state', async () => { it('returns bid deltas without re-reading the full Redis state', async () => {
const matchId = new mongoose.Types.ObjectId(); const matchId = new mongoose.Types.ObjectId();
const captainUserId = new mongoose.Types.ObjectId(); const captainUserId = new mongoose.Types.ObjectId();
@@ -1189,15 +1308,14 @@ describe('AuctionService', () => {
auctionRedisStateReaderService, auctionRedisStateReaderService,
tournamentCodeService, tournamentCodeService,
tournamentResultService, tournamentResultService,
} = } = createService({
createService({ auction: {
auction: { findOne: jest.fn().mockResolvedValue(auction),
findOne: jest.fn().mockResolvedValue(auction), },
}, match: {
match: { findById: jest.fn().mockResolvedValue(match),
findById: jest.fn().mockResolvedValue(match), },
}, });
});
auctionRedisStateReaderService.readAuctionStateView auctionRedisStateReaderService.readAuctionStateView
.mockResolvedValueOnce(soldState) .mockResolvedValueOnce(soldState)
.mockResolvedValueOnce(completeState); .mockResolvedValueOnce(completeState);
@@ -1377,8 +1495,7 @@ describe('AuctionService', () => {
const signupOrder = userIds.slice(2).map((userId) => userId.toString()); const signupOrder = userIds.slice(2).map((userId) => userId.toString());
const auctionOrder = auctionCreate.mock.calls[0][0].order.map( const auctionOrder = auctionCreate.mock.calls[0][0].order.map(
(player: { userId: mongoose.Types.ObjectId }) => (player: { userId: mongoose.Types.ObjectId }) => player.userId.toString(),
player.userId.toString(),
); );
expect(auctionOrder).not.toEqual(signupOrder); expect(auctionOrder).not.toEqual(signupOrder);
@@ -1647,9 +1764,7 @@ describe('AuctionService', () => {
amount: 20, amount: 20,
}); });
expect(auction.currentDeadline).toEqual( expect(auction.currentDeadline).toEqual(new Date(now.getTime() + 12000));
new Date(now.getTime() + 12000),
);
expect(auction.save).toHaveBeenCalledTimes(1); expect(auction.save).toHaveBeenCalledTimes(1);
}); });
@@ -2151,21 +2266,25 @@ describe('AuctionService', () => {
const auctionReplaceOne = jest.fn().mockReturnValue({ const auctionReplaceOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue(undefined), exec: jest.fn().mockResolvedValue(undefined),
}); });
const { service, connectionService, tournamentCodeService, tournamentResultService } = const {
createService({ service,
auction: { connectionService,
findOne: jest.fn().mockReturnValue(auctionFindOneQuery), tournamentCodeService,
replaceOne: auctionReplaceOne, tournamentResultService,
findById: jest.fn().mockResolvedValue(restored), } = createService({
}, auction: {
auctionHistory: { findOne: jest.fn().mockReturnValue(auctionFindOneQuery),
findOne: jest.fn().mockReturnValue(historyFindOneQuery), replaceOne: auctionReplaceOne,
deleteMany: jest.fn().mockReturnValue(historyDeleteManyQuery), findById: jest.fn().mockResolvedValue(restored),
}, },
match: { auctionHistory: {
findById: jest.fn().mockReturnValue(matchFindByIdQuery), findOne: jest.fn().mockReturnValue(historyFindOneQuery),
}, deleteMany: jest.fn().mockReturnValue(historyDeleteManyQuery),
}); },
match: {
findById: jest.fn().mockReturnValue(matchFindByIdQuery),
},
});
connectionService.createSession.mockResolvedValue(session); connectionService.createSession.mockResolvedValue(session);
await expect( await expect(
@@ -2261,23 +2380,27 @@ describe('AuctionService', () => {
}), }),
}; };
const auctionReplaceOne = jest.fn(); const auctionReplaceOne = jest.fn();
const { service, connectionService, auctionRedisCommandService, auctionRedisStateReaderService } = const {
createService({ service,
auction: { connectionService,
findOne: jest.fn().mockReturnValue({ auctionRedisCommandService,
session: jest.fn().mockResolvedValue(auction), auctionRedisStateReaderService,
}), } = createService({
replaceOne: auctionReplaceOne, auction: {
}, findOne: jest.fn().mockReturnValue({
auctionHistory: { session: jest.fn().mockResolvedValue(auction),
findOne: jest.fn().mockReturnValue(historyFindOneQuery), }),
}, replaceOne: auctionReplaceOne,
match: { },
findById: jest.fn().mockReturnValue({ auctionHistory: {
session: jest.fn().mockResolvedValue(match), findOne: jest.fn().mockReturnValue(historyFindOneQuery),
}), },
}, match: {
}); findById: jest.fn().mockReturnValue({
session: jest.fn().mockResolvedValue(match),
}),
},
});
connectionService.createSession.mockResolvedValue(session); connectionService.createSession.mockResolvedValue(session);
auctionRedisStateReaderService.readAuctionStateView auctionRedisStateReaderService.readAuctionStateView
.mockResolvedValueOnce(currentRedisState) .mockResolvedValueOnce(currentRedisState)
@@ -2298,7 +2421,9 @@ describe('AuctionService', () => {
).resolves.toBe(restoredRedisState); ).resolves.toBe(restoredRedisState);
expect(auctionReplaceOne).not.toHaveBeenCalled(); expect(auctionReplaceOne).not.toHaveBeenCalled();
expect(auctionRedisCommandService.reserveActionRequest).toHaveBeenCalledWith( expect(
auctionRedisCommandService.reserveActionRequest,
).toHaveBeenCalledWith(
matchId.toString(), matchId.toString(),
expect.objectContaining({ expect.objectContaining({
auctionActionRequestId: '00000000-0000-4000-8000-000000000070', auctionActionRequestId: '00000000-0000-4000-8000-000000000070',
@@ -2319,9 +2444,7 @@ describe('AuctionService', () => {
durationSeconds: 30, durationSeconds: 30,
mode: 'set-relative', mode: 'set-relative',
}); });
const durabilityPayload = JSON.parse( const durabilityPayload = JSON.parse(transitionInput.durabilityPayloadJson);
transitionInput.durabilityPayloadJson,
);
expect(durabilityPayload).toMatchObject({ expect(durabilityPayload).toMatchObject({
auctionActionType: 'undo', auctionActionType: 'undo',
historyMutation: { historyMutation: {
+309 -181
View File
@@ -40,6 +40,8 @@ import {
import { AuctionRedisService } from './redis/auction-redis.service'; import { AuctionRedisService } from './redis/auction-redis.service';
import { AuctionRedisStateReaderService } from './redis/auction-redis-state-reader.service'; import { AuctionRedisStateReaderService } from './redis/auction-redis-state-reader.service';
import { shouldHydrateRedisAuctionState } from './redis/auction-redis.state'; import { shouldHydrateRedisAuctionState } from './redis/auction-redis.state';
// [AUCTION-DEBUG] 경매 "중복 멤버" 조사용 임시 계측. 조사 종료 후 제거 대상.
import { recordNewRelicCustomEvent } from '../global/observability/new-relic';
const AUCTION_MAX_TEAM_SIZE = 5; const AUCTION_MAX_TEAM_SIZE = 5;
const AUCTION_MIN_BID_POINTS = 10; const AUCTION_MIN_BID_POINTS = 10;
@@ -230,7 +232,9 @@ export class AuctionService {
const activeParticipants = this.applyAuctionCut(match); const activeParticipants = this.applyAuctionCut(match);
const desiredAuctionCount = activeParticipants.length; const desiredAuctionCount = activeParticipants.length;
if (desiredAuctionCount < 10) { if (desiredAuctionCount < 10) {
throw new BadRequestException('Not enough participants (need at least 10).'); throw new BadRequestException(
'Not enough participants (need at least 10).',
);
} }
const expectedCaptainCount = desiredAuctionCount / AUCTION_MAX_TEAM_SIZE; const expectedCaptainCount = desiredAuctionCount / AUCTION_MAX_TEAM_SIZE;
if (params.captains.length !== expectedCaptainCount) { if (params.captains.length !== expectedCaptainCount) {
@@ -262,7 +266,8 @@ export class AuctionService {
const enrichCooldownCutoff = Date.now() - AUCTION_ENRICHMENT_COOLDOWN_MS; const enrichCooldownCutoff = Date.now() - AUCTION_ENRICHMENT_COOLDOWN_MS;
const enrichTargets = basePlayerUsers.flatMap((user) => { const enrichTargets = basePlayerUsers.flatMap((user) => {
const account = const account =
user.riotAccounts.find((entry) => entry.isPrimary) ?? user.riotAccounts[0]; user.riotAccounts.find((entry) => entry.isPrimary) ??
user.riotAccounts[0];
if (!account?.puuid) return []; if (!account?.puuid) return [];
if (this.wasRecentlyRefreshed(account, enrichCooldownCutoff)) return []; if (this.wasRecentlyRefreshed(account, enrichCooldownCutoff)) return [];
return [{ userId: user._id, puuid: account.puuid }]; return [{ userId: user._id, puuid: account.puuid }];
@@ -316,8 +321,7 @@ export class AuctionService {
const legacyTeams = params.captains.map((c) => ({ const legacyTeams = params.captains.map((c) => ({
teamIndex: c.teamIndex, teamIndex: c.teamIndex,
captainUserId: c.userId, captainUserId: c.userId,
points: points: c.initialTeamBidPointAmount ?? params.initialTeamBidPointAmount,
c.initialTeamBidPointAmount ?? params.initialTeamBidPointAmount,
members: [], members: [],
})); }));
const auctionTeams = convertLegacyAuctionTeamsToRedisTeams(legacyTeams); const auctionTeams = convertLegacyAuctionTeamsToRedisTeams(legacyTeams);
@@ -391,26 +395,30 @@ export class AuctionService {
}); });
} catch (error) { } catch (error) {
if (!isMongoDuplicateKeyError(error)) throw error; if (!isMongoDuplicateKeyError(error)) throw error;
const raceWinner = await AuctionModel.findOne({ matchId: params.matchId }); const raceWinner = await AuctionModel.findOne({
matchId: params.matchId,
});
if (raceWinner?.startAuctionRequestId === params.startAuctionRequestId) { if (raceWinner?.startAuctionRequestId === params.startAuctionRequestId) {
return raceWinner; return raceWinner;
} }
throw new BadRequestException('Auction already exists for this match.'); throw new BadRequestException('Auction already exists for this match.');
} }
await this.recordSnapshot(auction, 'start'); await this.recordSnapshot(auction, 'start');
await this.auctionRedisCommandService.hydrateState(params.matchId.toString(), { await this.auctionRedisCommandService.hydrateState(
auctionHistorySequence: 1, params.matchId.toString(),
auctionLifecycleId, {
maximumBidRoundDurationSeconds: params.maximumBidRoundDurationSeconds, auctionHistorySequence: 1,
liveStatePatch, auctionLifecycleId,
matchId: params.matchId.toString(), maximumBidRoundDurationSeconds: params.maximumBidRoundDurationSeconds,
phase: 'presenting', liveStatePatch,
revision: 0, matchId: params.matchId.toString(),
structureStateJson, phase: 'presenting',
}); revision: 0,
structureStateJson,
},
);
match.status = 'team-built'; match.status = 'team-built';
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
await match.save(); await match.save();
this.enqueueBackgroundOrderEnrichment({ this.enqueueBackgroundOrderEnrichment({
auctionId: auction._id, auctionId: auction._id,
@@ -624,9 +632,8 @@ export class AuctionService {
params: PlaceBidParams, params: PlaceBidParams,
): Promise<AuctionBidDeltaResponse | AuctionStateResponse> { ): Promise<AuctionBidDeltaResponse | AuctionStateResponse> {
this.assertValidBidPointAmount(params.amount); this.assertValidBidPointAmount(params.amount);
const redisBidDelta = await this.tryPlaceRedisBidDeltaFromRealtimeState( const redisBidDelta =
params, await this.tryPlaceRedisBidDeltaFromRealtimeState(params);
);
if (redisBidDelta) return redisBidDelta; if (redisBidDelta) return redisBidDelta;
const auction = await this.getByMatchId(params.matchId); const auction = await this.getByMatchId(params.matchId);
@@ -712,11 +719,10 @@ export class AuctionService {
const serviceStartedAtMS = performance.now(); const serviceStartedAtMS = performance.now();
const matchId = params.matchId.toString(); const matchId = params.matchId.toString();
const bidContextReadStartedAtMS = performance.now(); const bidContextReadStartedAtMS = performance.now();
const bidContext = const bidContext = await this.auctionRedisStateReaderService.readBidContext(
await this.auctionRedisStateReaderService.readBidContext( matchId,
matchId, params.teamIndex,
params.teamIndex, );
);
const redisBidContextReadDurationMS = const redisBidContextReadDurationMS =
performance.now() - bidContextReadStartedAtMS; performance.now() - bidContextReadStartedAtMS;
if (!bidContext) return null; if (!bidContext) return null;
@@ -905,6 +911,33 @@ export class AuctionService {
return this.resolveReplayedRedisActionRequest(matchId, actionRequest); return this.resolveReplayedRedisActionRequest(matchId, actionRequest);
} }
// [AUCTION-DEBUG] 중복 멤버 버그 스모킹건: 낙찰 직전, 이 선수가 이미 어느 팀에
// 들어있는지. (markRedisSold는 검사 없이 append하므로 true면 그대로 중복) — 제거 대상
const soldUserId = String(currentPlayer.userId);
const existingTeamIndex = structureInput.auctionTeams.find((entry) =>
(entry.members ?? []).some(
(member) => String(member.userId) === soldUserId,
),
)?.teamIndex;
recordNewRelicCustomEvent('AuctionServerSold', {
matchId,
auctionActionRequestId: params.auctionActionRequestId ?? null,
auctionLifecycleId: this.stringFromState(state.auctionLifecycleId),
revision: this.numberFromState(state.revision),
currentAuctionPlayerOrderIndex:
structureInput.currentAuctionPlayerOrderIndex,
soldUserId,
winningTeamIndex,
currentBidPointAmount,
playerAlreadyInTeam: existingTeamIndex !== undefined,
existingTeamIndex:
existingTeamIndex !== undefined ? Number(existingTeamIndex) : -1,
totalAssignedMemberCount: structureInput.auctionTeams.reduce(
(sum, entry) => sum + (entry.members?.length ?? 0),
0,
),
});
const preferredPrimary = currentPlayer.preferredPositions?.[0]?.position; const preferredPrimary = currentPlayer.preferredPositions?.[0]?.position;
team.members = [ team.members = [
...(team.members ?? []), ...(team.members ?? []),
@@ -1321,12 +1354,10 @@ export class AuctionService {
if (!session) { if (!session) {
throw new InternalServerErrorException('Failed to start DB session.'); throw new InternalServerErrorException('Failed to start DB session.');
} }
let redisRuntimeToClear: let redisRuntimeToClear: {
| { auctionLifecycleId?: string;
auctionLifecycleId?: string; matchId: string;
matchId: string; } | null = null;
}
| null = null;
try { try {
session.startTransaction(); session.startTransaction();
const auction = await AuctionModel.findOne({ const auction = await AuctionModel.findOne({
@@ -1349,15 +1380,15 @@ export class AuctionService {
await AuctionSideEffectApplicationModel.deleteMany({ await AuctionSideEffectApplicationModel.deleteMany({
auctionId: auction._id, auctionId: auction._id,
}).session(session); }).session(session);
await AuctionHistoryModel.deleteMany({ auctionId: auction._id }).session( await AuctionHistoryModel.deleteMany({
session, auctionId: auction._id,
); }).session(session);
await auction.deleteOne({ session }); await auction.deleteOne({ session });
} else { } else {
await auction.deleteOne({ session }); await auction.deleteOne({ session });
await AuctionHistoryModel.deleteMany({ auctionId: auction._id }).session( await AuctionHistoryModel.deleteMany({
session, auctionId: auction._id,
); }).session(session);
if (match.status === 'team-built') { if (match.status === 'team-built') {
await this.tournamentCodeService.releaseFromMatch(match); await this.tournamentCodeService.releaseFromMatch(match);
match.status = 'recruiting'; match.status = 'recruiting';
@@ -1410,15 +1441,13 @@ export class AuctionService {
throw new InternalServerErrorException('Failed to start DB session.'); throw new InternalServerErrorException('Failed to start DB session.');
} }
let redisUndoContext: let redisUndoContext: {
| { actionRequestParams?: AuctionStructureActionRequestParams;
actionRequestParams?: AuctionStructureActionRequestParams; auction: AuctionDocument;
auction: AuctionDocument; snapshot: Record<string, unknown>;
snapshot: Record<string, unknown>; targetHistorySequence: number;
targetHistorySequence: number; undoingCompletedAuction: boolean;
undoingCompletedAuction: boolean; } | null = null;
}
| null = null;
let restored: AuctionDocument | null = null; let restored: AuctionDocument | null = null;
try { try {
@@ -1460,27 +1489,27 @@ export class AuctionService {
}; };
await session.commitTransaction(); await session.commitTransaction();
} else { } else {
if (undoingCompletedAuction) { if (undoingCompletedAuction) {
await this.tournamentCodeService.releaseFromMatch(match); await this.tournamentCodeService.releaseFromMatch(match);
await this.tournamentResultService.cancelPolling(match); await this.tournamentResultService.cancelPolling(match);
match.status = 'team-built'; match.status = 'team-built';
match.result = undefined; match.result = undefined;
await match.save({ session }); await match.save({ session });
} }
await AuctionModel.replaceOne({ _id: auction._id }, snapshot, { await AuctionModel.replaceOne({ _id: auction._id }, snapshot, {
session, session,
}).exec(); }).exec();
await AuctionHistoryModel.deleteMany({ await AuctionHistoryModel.deleteMany({
auctionId: auction._id, auctionId: auction._id,
sequence: { $gt: params.sequence }, sequence: { $gt: params.sequence },
}) })
.session(session) .session(session)
.exec(); .exec();
await session.commitTransaction(); await session.commitTransaction();
restored = await AuctionModel.findById(auction._id); restored = await AuctionModel.findById(auction._id);
if (!restored) throw new NotFoundException('Auction not found.'); if (!restored) throw new NotFoundException('Auction not found.');
} }
} catch (err) { } catch (err) {
await session.abortTransaction(); await session.abortTransaction();
@@ -1534,28 +1563,27 @@ export class AuctionService {
const processingOwnerToken = randomUUID(); const processingOwnerToken = randomUUID();
const auctionStateTransitionId = `${params.action}:${expectedAuctionLifecycleId}:${auctionActionRequestId}`; const auctionStateTransitionId = `${params.action}:${expectedAuctionLifecycleId}:${auctionActionRequestId}`;
const reserved = const reserved = await this.auctionRedisCommandService.reserveActionRequest(
await this.auctionRedisCommandService.reserveActionRequest( params.matchId,
params.matchId, {
{ auctionActionRequestId,
auctionActionRequestId, auctionActionType: params.action,
auctionActionType: params.action, auctionStateTransitionId,
auctionStateTransitionId, clientObservedAuctionLifecycleId: expectedAuctionLifecycleId,
clientObservedAuctionLifecycleId: expectedAuctionLifecycleId, clientObservedCurrentAuctionPlayerOrderIndex:
clientObservedCurrentAuctionPlayerOrderIndex: expectedCurrentAuctionPlayerOrderIndex,
expectedCurrentAuctionPlayerOrderIndex, clientObservedCurrentBidRoundPlayerUserId:
clientObservedCurrentBidRoundPlayerUserId: expectedCurrentBidRoundPlayerUserId,
expectedCurrentBidRoundPlayerUserId, clientObservedPhase: expectedPhase,
clientObservedPhase: expectedPhase, clientObservedRevision: expectedRevision,
clientObservedRevision: expectedRevision, leaseDurationMS: AUCTION_ACTION_REQUEST_LEASE_DURATION_MS,
leaseDurationMS: AUCTION_ACTION_REQUEST_LEASE_DURATION_MS, maximumStoredAuctionActionRequestResultCount:
maximumStoredAuctionActionRequestResultCount: AUCTION_MAX_STORED_ACTION_REQUEST_RESULT_COUNT,
AUCTION_MAX_STORED_ACTION_REQUEST_RESULT_COUNT, minimumAuctionActionRequestResultReplayWindowMS:
minimumAuctionActionRequestResultReplayWindowMS: AUCTION_ACTION_REQUEST_REPLAY_WINDOW_MS,
AUCTION_ACTION_REQUEST_REPLAY_WINDOW_MS, processingOwnerToken,
processingOwnerToken, },
}, );
);
if ('rejected' in reserved) { if ('rejected' in reserved) {
throw new BadRequestException( throw new BadRequestException(
@@ -1579,8 +1607,7 @@ export class AuctionService {
return { return {
actionRequest: { actionRequest: {
observedProcessingLeaseVersion: observedProcessingLeaseVersion: reserved.observedProcessingLeaseVersion,
reserved.observedProcessingLeaseVersion,
processingOwnerToken, processingOwnerToken,
scopeKey: reserved.actionRequestScopeKey, scopeKey: reserved.actionRequestScopeKey,
}, },
@@ -1627,7 +1654,10 @@ export class AuctionService {
| { durationSeconds: number; mode: 'set-relative' }; | { durationSeconds: number; mode: 'set-relative' };
expectedPhase: string; expectedPhase: string;
historyMutation?: Record<string, unknown>; historyMutation?: Record<string, unknown>;
liveStatePatch: Record<string, string | number | boolean | null | undefined>; liveStatePatch: Record<
string,
string | number | boolean | null | undefined
>;
matchSideEffectMutation?: Record<string, unknown>; matchSideEffectMutation?: Record<string, unknown>;
shouldBroadcastStateAfterDurability?: boolean; shouldBroadcastStateAfterDurability?: boolean;
shouldResetBidRuntime?: boolean; shouldResetBidRuntime?: boolean;
@@ -1644,8 +1674,7 @@ export class AuctionService {
const expectedAuctionHistorySequence = this.numberFromState( const expectedAuctionHistorySequence = this.numberFromState(
params.state.currentAuctionHistorySequence, params.state.currentAuctionHistorySequence,
); );
const auctionHistorySequence = const auctionHistorySequence = expectedAuctionHistorySequence + 1;
expectedAuctionHistorySequence + 1;
const auctionStateTransitionId = const auctionStateTransitionId =
params.actionRequest?.auctionStateTransitionId || params.actionRequest?.auctionStateTransitionId ||
params.auctionStateTransitionId || params.auctionStateTransitionId ||
@@ -1671,6 +1700,7 @@ export class AuctionService {
(params.auction.matchSideEffectRevision ?? 0) + 1; (params.auction.matchSideEffectRevision ?? 0) + 1;
afterAuctionMongoProjection.matchSideEffectError = undefined; afterAuctionMongoProjection.matchSideEffectError = undefined;
} }
const durabilityPayload = { const durabilityPayload = {
afterAuctionMongoProjection, afterAuctionMongoProjection,
auctionActionType: params.action, auctionActionType: params.action,
@@ -1695,7 +1725,8 @@ export class AuctionService {
), ),
auctionHistorySequence, auctionHistorySequence,
auctionLifecycleId: auctionLifecycleId:
params.actionRequest?.expectedAuctionLifecycleId ?? auctionLifecycleId, params.actionRequest?.expectedAuctionLifecycleId ??
auctionLifecycleId,
auctionStateTransitionId, auctionStateTransitionId,
broadcastStateRevision: expectedRevision + 1, broadcastStateRevision: expectedRevision + 1,
deadline: params.deadline, deadline: params.deadline,
@@ -1709,7 +1740,8 @@ export class AuctionService {
? this.stringFromState(params.state.currentBidRoundPlayerUserId) ? this.stringFromState(params.state.currentBidRoundPlayerUserId)
: undefined), : undefined),
expectedAuctionHistorySequence, expectedAuctionHistorySequence,
expectedPhase: params.actionRequest?.expectedPhase ?? params.expectedPhase, expectedPhase:
params.actionRequest?.expectedPhase ?? params.expectedPhase,
expectedRevision, expectedRevision,
liveStatePatch: params.liveStatePatch, liveStatePatch: params.liveStatePatch,
matchId, matchId,
@@ -1719,6 +1751,27 @@ export class AuctionService {
actionRequest: params.actionRequest?.actionRequest, actionRequest: params.actionRequest?.actionRequest,
}, },
); );
// [AUCTION-DEBUG] 제거 대상. 모든 redis 전환(sold/undo/next/open-bidding/complete)의 백본 타임라인.
// auctionStateTransitionId = `${action}:${lifecycleId}:${auctionActionRequestId}`
// 라서 클라의 auctionActionRequestId와 조인된다.
recordNewRelicCustomEvent('AuctionServerTransition', {
matchId,
action: params.action,
auctionStateTransitionId,
auctionLifecycleId,
expectedRevision,
newRevision: 'rejected' in result ? -1 : expectedRevision + 1,
auctionHistorySequence,
currentAuctionPlayerOrderIndex:
params.structureInput.currentAuctionPlayerOrderIndex,
totalAssignedMemberCount: params.structureInput.auctionTeams.reduce(
(sum, entry) => sum + (entry.members?.length ?? 0),
0,
),
rejected: 'rejected' in result,
rejectionCode: 'rejected' in result ? result.code : null,
});
if ('rejected' in result) { if ('rejected' in result) {
// 게이트웨이가 설명적 거부코드로 변환할 수 있도록 내부 code(예: CONFLICT)를 // 게이트웨이가 설명적 거부코드로 변환할 수 있도록 내부 code(예: CONFLICT)를
// 구조화해 던진다(message만 던지면 code 자리에 풀 문장이 들어가 매핑이 어렵다). // 구조화해 던진다(message만 던지면 code 자리에 풀 문장이 들어가 매핑이 어렵다).
@@ -1762,9 +1815,8 @@ export class AuctionService {
)) { )) {
const teamIndex = this.numberFromState(team.teamIndex); const teamIndex = this.numberFromState(team.teamIndex);
if (teamIndex < 1) continue; if (teamIndex < 1) continue;
clearedTeamLiveStatePatch[ clearedTeamLiveStatePatch[`team:${teamIndex}:remainingBidPointAmount`] =
`team:${teamIndex}:remainingBidPointAmount` 0;
] = 0;
clearedTeamLiveStatePatch[ clearedTeamLiveStatePatch[
`team:${teamIndex}:assignedAuctionTeamMemberCount` `team:${teamIndex}:assignedAuctionTeamMemberCount`
] = 0; ] = 0;
@@ -1829,10 +1881,40 @@ export class AuctionService {
-1, -1,
); );
const currentHighestBidPointAmount = this.numberFromState( const currentHighestBidPointAmount = this.numberFromState(
params.snapshot.currentHighestBidPointAmount ?? params.snapshot.currentBid, params.snapshot.currentHighestBidPointAmount ??
params.snapshot.currentBid,
0, 0,
); );
// [AUCTION-DEBUG] 제거 대상. undo가 "어느 시점으로" 복원하는지 + 복원된 팀 구성. 라이브 revision과
// 복원 스냅샷 revision의 간격(restoredRevisionLag)이 사용자가 본 "2~3 뒤처짐".
// 이 이벤트 직후의 AuctionServerSold가 playerAlreadyInTeam:true면 "undo가 선수를
// 안 지운 채 재낙찰 → 중복"이 한 타임라인으로 증명된다.
const liveRevisionBeforeUndo = this.numberFromState(state.revision);
const restoredRevision = this.numberFromState(params.snapshot.revision);
const restoredMemberUserIds = structureInput.auctionTeams.flatMap((entry) =>
(entry.members ?? []).map((member) => String(member.userId)),
);
recordNewRelicCustomEvent('AuctionServerUndo', {
matchId,
auctionActionRequestId:
params.actionRequestParams?.auctionActionRequestId ?? null,
auctionLifecycleId: this.stringFromState(state.auctionLifecycleId),
targetHistorySequence: params.targetHistorySequence,
liveRevisionBeforeUndo,
restoredRevision,
restoredRevisionLag: liveRevisionBeforeUndo - restoredRevision,
restoredHistorySequence: this.numberFromState(
params.snapshot.currentAuctionHistorySequence,
),
restoredPhase: phase,
restoredOrderIndex: structureInput.currentAuctionPlayerOrderIndex,
restoredAssignedMemberCount: restoredMemberUserIds.length,
restoredHasDuplicateMember:
restoredMemberUserIds.length !== new Set(restoredMemberUserIds).size,
undoingCompletedAuction: params.undoingCompletedAuction,
});
return this.applyRedisStructureTransition({ return this.applyRedisStructureTransition({
action: 'undo', action: 'undo',
actionRequest, actionRequest,
@@ -1874,8 +1956,10 @@ export class AuctionService {
state: Record<string, unknown>, state: Record<string, unknown>,
): Parameters<typeof stringifyAuctionRedisStructureState>[0] { ): Parameters<typeof stringifyAuctionRedisStructureState>[0] {
return { return {
auctionPlayerOrder: this.arrayFromState(state.auctionPlayerOrder), auctionPlayerOrder: this.cloneRedisStructureArray(
auctionTeams: this.arrayFromState(state.auctionTeams), state.auctionPlayerOrder,
),
auctionTeams: this.cloneRedisStructureArray(state.auctionTeams),
bidRoundExtensionSeconds: this.numberFromState( bidRoundExtensionSeconds: this.numberFromState(
state.bidRoundExtensionSeconds, state.bidRoundExtensionSeconds,
5, 5,
@@ -1888,34 +1972,37 @@ export class AuctionService {
state.initialTeamBidPointAmount, state.initialTeamBidPointAmount,
1000, 1000,
), ),
manualTopTierAuctionPriorityUserIds: this.arrayFromState( manualTopTierAuctionPriorityUserIds: this.cloneRedisStructureArray(
state.manualTopTierAuctionPriorityUserIds, state.manualTopTierAuctionPriorityUserIds,
), ),
maximumBidRoundDurationSeconds: this.numberFromState( maximumBidRoundDurationSeconds: this.numberFromState(
state.maximumBidRoundDurationSeconds, state.maximumBidRoundDurationSeconds,
30, 30,
), ),
passedAuctionPlayerQueue: this.arrayFromState( passedAuctionPlayerQueue: this.cloneRedisStructureArray(
state.passedAuctionPlayerQueue, state.passedAuctionPlayerQueue,
), ),
topTierAuctionPriorityThreshold: topTierAuctionPriorityThreshold: this.isAuctionTopTierThreshold(
this.isAuctionTopTierThreshold(state.topTierAuctionPriorityThreshold) state.topTierAuctionPriorityThreshold,
? state.topTierAuctionPriorityThreshold )
: 'NONE', ? state.topTierAuctionPriorityThreshold
: 'NONE',
}; };
} }
private buildRedisStructureInputFromAuctionSnapshot( private buildRedisStructureInputFromAuctionSnapshot(
snapshot: Record<string, unknown>, snapshot: Record<string, unknown>,
): Parameters<typeof stringifyAuctionRedisStructureState>[0] { ): Parameters<typeof stringifyAuctionRedisStructureState>[0] {
const legacyTeams = this.arrayFromState(snapshot.teams); const legacyTeams = this.cloneRedisStructureArray(snapshot.teams);
const auctionTeams = this.cloneRedisStructureArray(snapshot.auctionTeams);
return { return {
auctionPlayerOrder: this.arrayFromState( auctionPlayerOrder: this.cloneRedisStructureArray(
snapshot.auctionPlayerOrder ?? snapshot.order, snapshot.auctionPlayerOrder ?? snapshot.order,
), ),
auctionTeams: this.arrayFromState(snapshot.auctionTeams).length > 0 auctionTeams:
? this.arrayFromState(snapshot.auctionTeams) auctionTeams.length > 0
: convertLegacyAuctionTeamsToRedisTeams(legacyTeams as never), ? auctionTeams
: convertLegacyAuctionTeamsToRedisTeams(legacyTeams as never),
bidRoundExtensionSeconds: this.numberFromState( bidRoundExtensionSeconds: this.numberFromState(
snapshot.bidRoundExtensionSeconds ?? snapshot.bidExtensionSeconds, snapshot.bidRoundExtensionSeconds ?? snapshot.bidExtensionSeconds,
5, 5,
@@ -1931,7 +2018,7 @@ export class AuctionService {
snapshot.initialTeamBidPointAmount ?? snapshot.initialPoints, snapshot.initialTeamBidPointAmount ?? snapshot.initialPoints,
1000, 1000,
), ),
manualTopTierAuctionPriorityUserIds: this.arrayFromState( manualTopTierAuctionPriorityUserIds: this.cloneRedisStructureArray(
snapshot.manualTopTierAuctionPriorityUserIds ?? snapshot.manualTopTierAuctionPriorityUserIds ??
snapshot.manualTopTierUserIds, snapshot.manualTopTierUserIds,
), ),
@@ -1939,14 +2026,14 @@ export class AuctionService {
snapshot.maximumBidRoundDurationSeconds ?? snapshot.maxTimerSeconds, snapshot.maximumBidRoundDurationSeconds ?? snapshot.maxTimerSeconds,
30, 30,
), ),
passedAuctionPlayerQueue: this.arrayFromState( passedAuctionPlayerQueue: this.cloneRedisStructureArray(
snapshot.passedAuctionPlayerQueue ?? snapshot.passedQueue, snapshot.passedAuctionPlayerQueue ?? snapshot.passedQueue,
), ),
topTierAuctionPriorityThreshold: this.isAuctionTopTierThreshold( topTierAuctionPriorityThreshold: this.isAuctionTopTierThreshold(
snapshot.topTierAuctionPriorityThreshold ?? snapshot.topTierThreshold, snapshot.topTierAuctionPriorityThreshold ?? snapshot.topTierThreshold,
) )
? (snapshot.topTierAuctionPriorityThreshold ?? ? ((snapshot.topTierAuctionPriorityThreshold ??
snapshot.topTierThreshold) as never snapshot.topTierThreshold) as never)
: 'NONE', : 'NONE',
}; };
} }
@@ -2064,7 +2151,9 @@ export class AuctionService {
} }
private convertRedisTeamsToLegacyTeams( private convertRedisTeamsToLegacyTeams(
auctionTeams: Parameters<typeof stringifyAuctionRedisStructureState>[0]['auctionTeams'], auctionTeams: Parameters<
typeof stringifyAuctionRedisStructureState
>[0]['auctionTeams'],
): AuctionTeam[] { ): AuctionTeam[] {
return auctionTeams.map((team) => ({ return auctionTeams.map((team) => ({
captainUserId: team.captainUserId as mongoose.Types.ObjectId, captainUserId: team.captainUserId as mongoose.Types.ObjectId,
@@ -2090,13 +2179,20 @@ export class AuctionService {
return Array.isArray(value) ? (value as T[]) : []; return Array.isArray(value) ? (value as T[]) : [];
} }
private cloneRedisStructureArray<T = never>(value: unknown): T[] {
// 구조 전환 핸들러가 이 작업본을 변이하므로 snapshotBefore 원본과 참조를 공유하면 안 된다.
// structuredClone은 ObjectId를 [object Object]로 망가뜨리므로, 코드베이스 관행대로
// JSON 클론으로 깊은 복사 + ObjectId/Date 정규화를 함께 수행한다.
return JSON.parse(JSON.stringify(this.arrayFromState<T>(value))) as T[];
}
private numberFromState(value: unknown, fallback = 0): number { private numberFromState(value: unknown, fallback = 0): number {
const parsed = Number(value); const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : fallback; return Number.isFinite(parsed) ? parsed : fallback;
} }
private stringFromState(value: unknown): string { private stringFromState(value: unknown): string {
return typeof value === 'string' ? value : value?.toString() ?? ''; return typeof value === 'string' ? value : (value?.toString() ?? '');
} }
private isAuctionTopTierThreshold( private isAuctionTopTierThreshold(
@@ -2218,7 +2314,9 @@ export class AuctionService {
({ I: 4, II: 3, III: 2, IV: 1, '': 0 } as Record<string, number>)[ ({ I: 4, II: 3, III: 2, IV: 1, '': 0 } as Record<string, number>)[
solo.rank solo.rank
] ?? 0; ] ?? 0;
return tierIdx * 1000 + rankBonus * 100 + (solo.leaguePoints ?? 0) * 0.001; return (
tierIdx * 1000 + rankBonus * 100 + (solo.leaguePoints ?? 0) * 0.001
);
}; };
const top = order const top = order
@@ -2507,7 +2605,7 @@ export class AuctionService {
]), ]),
); );
match.teams = auction.teams.map((team) => { const matchTeams = auction.teams.map((team) => {
const captain = participantByUserId.get(team.captainUserId.toString()); const captain = participantByUserId.get(team.captainUserId.toString());
const members: MatchTeamMember[] = [ const members: MatchTeamMember[] = [
{ {
@@ -2531,6 +2629,12 @@ export class AuctionService {
members, members,
}; };
}); });
if (matchTeams.length === 0) {
throw new Error(
`Auction completed without teams for match ${match._id.toString()}.`,
);
}
match.teams = matchTeams;
match.status = 'team-built'; match.status = 'team-built';
match.teamBuiltAt = match.teamBuiltAt ?? new Date(); match.teamBuiltAt = match.teamBuiltAt ?? new Date();
await match.save(); await match.save();
@@ -2557,7 +2661,7 @@ export class AuctionService {
structureInput.auctionTeams, structureInput.auctionTeams,
); );
match.teams = teams.map((team) => { const matchTeams = teams.map((team) => {
const captain = participantByUserId.get(team.captainUserId.toString()); const captain = participantByUserId.get(team.captainUserId.toString());
const members: MatchTeamMember[] = [ const members: MatchTeamMember[] = [
{ {
@@ -2566,7 +2670,10 @@ export class AuctionService {
cost: 0, cost: 0,
}, },
...team.members ...team.members
.filter((member) => member.userId.toString() !== team.captainUserId.toString()) .filter(
(member) =>
member.userId.toString() !== team.captainUserId.toString(),
)
.map((member) => ({ .map((member) => ({
userId: member.userId, userId: member.userId,
assignedPosition: member.assignedPosition, assignedPosition: member.assignedPosition,
@@ -2581,6 +2688,12 @@ export class AuctionService {
members, members,
}; };
}); });
if (matchTeams.length === 0) {
throw new Error(
`Redis auction completed without teams for match ${match._id.toString()}.`,
);
}
match.teams = matchTeams;
match.status = 'team-built'; match.status = 'team-built';
match.teamBuiltAt = match.teamBuiltAt ?? new Date(); match.teamBuiltAt = match.teamBuiltAt ?? new Date();
await match.save(); await match.save();
@@ -2602,7 +2715,8 @@ export class AuctionService {
auction.bidRoundExtensionSeconds ?? auction.bidExtensionSeconds ?? 5, auction.bidRoundExtensionSeconds ?? auction.bidExtensionSeconds ?? 5,
currentAuctionPlayerOrderIndex: currentAuctionPlayerOrderIndex:
auction.currentAuctionPlayerOrderIndex ?? auction.currentIndex ?? 0, auction.currentAuctionPlayerOrderIndex ?? auction.currentIndex ?? 0,
currentAuctionRound: auction.currentAuctionRound ?? auction.auctionRound ?? 1, currentAuctionRound:
auction.currentAuctionRound ?? auction.auctionRound ?? 1,
initialTeamBidPointAmount: initialTeamBidPointAmount:
auction.initialTeamBidPointAmount ?? auction.initialPoints ?? 1000, auction.initialTeamBidPointAmount ?? auction.initialPoints ?? 1000,
manualTopTierAuctionPriorityUserIds: manualTopTierAuctionPriorityUserIds:
@@ -2614,7 +2728,9 @@ export class AuctionService {
passedAuctionPlayerQueue: passedAuctionPlayerQueue:
auction.passedAuctionPlayerQueue ?? auction.passedQueue ?? [], auction.passedAuctionPlayerQueue ?? auction.passedQueue ?? [],
topTierAuctionPriorityThreshold: topTierAuctionPriorityThreshold:
auction.topTierAuctionPriorityThreshold ?? auction.topTierThreshold ?? 'NONE', auction.topTierAuctionPriorityThreshold ??
auction.topTierThreshold ??
'NONE',
}; };
await this.auctionRedisCommandService.hydrateState( await this.auctionRedisCommandService.hydrateState(
auction.matchId.toString(), auction.matchId.toString(),
@@ -2647,35 +2763,37 @@ export class AuctionService {
expectedAuctionLifecycleId?: string, expectedAuctionLifecycleId?: string,
): Promise<void> { ): Promise<void> {
const keys = buildAuctionRedisKeys(matchId); const keys = buildAuctionRedisKeys(matchId);
const cleared = await this.auctionRedisService.raw().sendCommand([ const cleared = await this.auctionRedisService
'EVAL', .raw()
[ .sendCommand([
"local expectedAuctionLifecycleId = ARGV[2]", 'EVAL',
"if expectedAuctionLifecycleId ~= '' then", [
" local currentAuctionLifecycleId = redis.call('HGET', KEYS[1], 'auctionLifecycleId')", 'local expectedAuctionLifecycleId = ARGV[2]',
" if currentAuctionLifecycleId and currentAuctionLifecycleId ~= expectedAuctionLifecycleId then", "if expectedAuctionLifecycleId ~= '' then",
" return 0", " local currentAuctionLifecycleId = redis.call('HGET', KEYS[1], 'auctionLifecycleId')",
' end', ' if currentAuctionLifecycleId and currentAuctionLifecycleId ~= expectedAuctionLifecycleId then',
'end', ' return 0',
"redis.call('ZREM', KEYS[2], ARGV[1])", ' end',
"redis.call('DEL', KEYS[1], KEYS[3], KEYS[4], KEYS[5], KEYS[6], KEYS[7], KEYS[8], KEYS[9], KEYS[10], KEYS[11])", 'end',
'return 1', "redis.call('ZREM', KEYS[2], ARGV[1])",
].join('\n'), "redis.call('DEL', KEYS[1], KEYS[3], KEYS[4], KEYS[5], KEYS[6], KEYS[7], KEYS[8], KEYS[9], KEYS[10], KEYS[11])",
'11', 'return 1',
keys.liveStateKey, ].join('\n'),
keys.deadlineQueueKey, '11',
keys.structureStateKey, keys.liveStateKey,
keys.appliedTransitionIdsKey, keys.deadlineQueueKey,
keys.bidHistoryKey, keys.structureStateKey,
keys.bidRequestResultsKey, keys.appliedTransitionIdsKey,
keys.bidRequestResultOrderKey, keys.bidHistoryKey,
keys.actionRequestResultsKey, keys.bidRequestResultsKey,
keys.actionRequestResultOrderKey, keys.bidRequestResultOrderKey,
keys.rehydrateLockKey, keys.actionRequestResultsKey,
keys.stateTransitionLockKey, keys.actionRequestResultOrderKey,
matchId, keys.rehydrateLockKey,
expectedAuctionLifecycleId ?? '', keys.stateTransitionLockKey,
]); matchId,
expectedAuctionLifecycleId ?? '',
]);
if (Number(cleared) !== 1) return; if (Number(cleared) !== 1) return;
await this.clearRedisDurabilityPayloadsForLifecycle( await this.clearRedisDurabilityPayloadsForLifecycle(
keys, keys,
@@ -2689,14 +2807,16 @@ export class AuctionService {
): Promise<void> { ): Promise<void> {
let cursor = '0'; let cursor = '0';
do { do {
const reply = await this.auctionRedisService.raw().sendCommand([ const reply = await this.auctionRedisService
'SCAN', .raw()
cursor, .sendCommand([
'MATCH', 'SCAN',
`${keys.durabilityPayloadKeyPrefix}*`, cursor,
'COUNT', 'MATCH',
'100', `${keys.durabilityPayloadKeyPrefix}*`,
]); 'COUNT',
'100',
]);
if (!Array.isArray(reply) || reply.length < 2) return; if (!Array.isArray(reply) || reply.length < 2) return;
cursor = String(reply[0]); cursor = String(reply[0]);
const payloadKeys = Array.isArray(reply[1]) ? reply[1].map(String) : []; const payloadKeys = Array.isArray(reply[1]) ? reply[1].map(String) : [];
@@ -2714,20 +2834,23 @@ export class AuctionService {
); );
if (payloadKeysToDelete.length === 0) continue; if (payloadKeysToDelete.length === 0) continue;
await this.auctionRedisService.raw().sendCommand([ await this.auctionRedisService
'ZREM', .raw()
keys.durabilityRetryQueueKey, .sendCommand([
...payloadKeysToDelete, 'ZREM',
]); keys.durabilityRetryQueueKey,
await this.auctionRedisService.raw().sendCommand([ ...payloadKeysToDelete,
'ZREM', ]);
keys.durabilityDeadLetterQueueKey, await this.auctionRedisService
...payloadKeysToDelete, .raw()
]); .sendCommand([
await this.auctionRedisService.raw().sendCommand([ 'ZREM',
'DEL', keys.durabilityDeadLetterQueueKey,
...payloadKeysToDelete, ...payloadKeysToDelete,
]); ]);
await this.auctionRedisService
.raw()
.sendCommand(['DEL', ...payloadKeysToDelete]);
} while (cursor !== '0'); } while (cursor !== '0');
} }
@@ -2742,7 +2865,9 @@ export class AuctionService {
const payload = JSON.parse(payloadValue) as Record<string, unknown>; const payload = JSON.parse(payloadValue) as Record<string, unknown>;
return payload.auctionLifecycleId === expectedAuctionLifecycleId; return payload.auctionLifecycleId === expectedAuctionLifecycleId;
} catch { } catch {
this.logger.warn(`Failed to parse auction durability payload ${payloadKey}.`); this.logger.warn(
`Failed to parse auction durability payload ${payloadKey}.`,
);
return false; return false;
} }
} }
@@ -2855,13 +2980,16 @@ async function runWithConcurrency<T>(
if (items.length === 0) return; if (items.length === 0) return;
const queue = [...items]; const queue = [...items];
const runners = Array.from({ length: Math.min(concurrency, queue.length) }, async () => { const runners = Array.from(
while (queue.length > 0) { { length: Math.min(concurrency, queue.length) },
const item = queue.shift(); async () => {
if (item === undefined) return; while (queue.length > 0) {
await worker(item); const item = queue.shift();
} if (item === undefined) return;
}); await worker(item);
}
},
);
await Promise.allSettled(runners); await Promise.allSettled(runners);
} }
@@ -191,4 +191,54 @@ describe('CommunityStatsService', () => {
response, response,
); );
}); });
it('includes internal match route fields in user internal history matches', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const userId = new mongoose.Types.ObjectId();
const participant = record(matchId);
participant.userId = userId.toString();
participant.gameNumber = 2;
participant.riotMatchId = 'KR_1234';
const cacheService = {
get: jest.fn().mockResolvedValue(null),
set: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<CommunityStatsCacheService>;
const service = new CommunityStatsService(
{} as ConnectionService,
cacheService,
{} as MatchStatsRepository,
{} as MatchStatsService,
);
(service as unknown as { buildBaseDataset: jest.Mock }).buildBaseDataset =
jest.fn().mockResolvedValue({
season: {
id: 'all',
label: '전체',
startTime: null,
endTime: null,
},
matches: [],
records: [participant],
detailsByMatchId: new Map(),
});
const response = await service.getUserInternalHistory({
communityId,
userId,
filters: { limit: 5 },
});
expect(response.matches[0]).toMatchObject({
matchId: 'KR_1234',
internalMatchId: matchId.toString(),
gameNumber: 2,
queueLabel: '내전',
});
expect(cacheService.set).toHaveBeenCalledWith(
expect.stringContaining(`userInternal:v2:${userId.toString()}`),
response,
);
});
}); });
@@ -293,7 +293,7 @@ export class CommunityStatsService {
filters: CommunityStatsFilters; filters: CommunityStatsFilters;
}): Promise<UserInternalHistoryResponse> { }): Promise<UserInternalHistoryResponse> {
const key = this.cacheKey( const key = this.cacheKey(
`userInternal:${params.userId.toString()}`, `userInternal:v2:${params.userId.toString()}`,
params.communityId, params.communityId,
params.filters, params.filters,
); );
@@ -789,6 +789,8 @@ export class CommunityStatsService {
?.find((game) => game.riotMatchId === record.riotMatchId); ?.find((game) => game.riotMatchId === record.riotMatchId);
return { return {
matchId: record.riotMatchId, matchId: record.riotMatchId,
internalMatchId: record.matchId,
gameNumber: record.gameNumber,
queueId: 0, queueId: 0,
queueLabel: '내전', queueLabel: '내전',
gameCreation: record.gameCreation, gameCreation: record.gameCreation,
@@ -0,0 +1,39 @@
// [AUCTION-DEBUG] 경매 "중복 멤버" 조사용 서버 계측 래퍼. 조사 종료 후 호출부와 함께
// 제거 대상(범용으로 남길 거면 이 마커만 떼면 됨).
import newrelicAgent from 'newrelic';
export type NewRelicAttributeValue = string | number | boolean | null;
// newrelic 기본 export는 타입이 느슨해 unsafe-call로 잡힌다. 우리가 쓰는 부분만
// 좁게 타입을 고정한다(에이전트는 -r newrelic로 이미 preload됨).
interface NewRelicCustomEventApi {
recordCustomEvent(
eventType: string,
attributes: Record<string, NewRelicAttributeValue>,
): void;
}
const agent = newrelicAgent as unknown as NewRelicCustomEventApi;
/**
* 서버 커스텀 이벤트를 New Relic으로 보낸다(클라의 addPageAction 대응).
*
* - 에이전트는 `-r newrelic`로 이미 preload되어 있으므로 여기서 import만 하면 된다.
* - `recordCustomEvent`는 활성 트랜잭션이 없어도 동작하므로 durability 스케줄러
* tick이나 socket.io 핸들러처럼 HTTP 컨텍스트 밖에서도 그대로 호출할 수 있다.
* - 평탄한 스칼라만 받는다(중첩 객체/배열 불가). undefined 속성은 제거한다.
* - 에이전트 비활성/테스트 환경에서도 호출부가 깨지지 않도록 예외를 삼킨다.
*/
export function recordNewRelicCustomEvent(
eventType: string,
attributes: Record<string, NewRelicAttributeValue | undefined>,
): void {
try {
const flat: Record<string, NewRelicAttributeValue> = {};
for (const [key, value] of Object.entries(attributes)) {
if (value !== undefined) flat[key] = value;
}
agent.recordCustomEvent(eventType, flat);
} catch {
// 관측성 실패가 비즈니스 로직을 막아선 안 된다.
}
}
@@ -135,6 +135,8 @@ export interface RecentMatchTeamParticipantView {
export interface RecentMatchView { export interface RecentMatchView {
matchId: string; matchId: string;
internalMatchId?: string;
gameNumber?: number;
queueId: number; queueId: number;
queueLabel: string; queueLabel: string;
gameCreation: number; gameCreation: number;
@@ -1,4 +1,5 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { TournamentResultModule } from '../tournament-result/tournament-result.module';
import { TournamentCodeController } from './tournament-code.controller'; import { TournamentCodeController } from './tournament-code.controller';
import { TournamentCodeAutoProvisionService } from './tournament-code-auto-provision.service'; import { TournamentCodeAutoProvisionService } from './tournament-code-auto-provision.service';
import { TournamentCodeReplacementController } from './tournament-code-replacement.controller'; import { TournamentCodeReplacementController } from './tournament-code-replacement.controller';
@@ -7,6 +8,7 @@ import { TournamentCodeService } from './tournament-code.service';
import { TournamentCodeVendorService } from './tournament-code-vendor.service'; import { TournamentCodeVendorService } from './tournament-code-vendor.service';
@Module({ @Module({
imports: [TournamentResultModule],
controllers: [TournamentCodeController, TournamentCodeReplacementController], controllers: [TournamentCodeController, TournamentCodeReplacementController],
providers: [ providers: [
TournamentCodeService, TournamentCodeService,
@@ -0,0 +1,62 @@
import { TournamentCodeScheduler } from './tournament-code.scheduler';
describe('TournamentCodeScheduler', () => {
function createScheduler(params?: {
attachedMatches?: unknown[];
scheduleInitialPoll?: jest.Mock;
}) {
const tournamentCodeService = {
attachPendingMatchDocuments: jest
.fn()
.mockResolvedValue(params?.attachedMatches ?? []),
markExpired: jest.fn().mockResolvedValue(0),
};
const autoProvisionService = {
ensurePool: jest.fn().mockResolvedValue(undefined),
};
const tournamentResultService = {
scheduleInitialPoll:
params?.scheduleInitialPoll ?? jest.fn().mockResolvedValue(null),
};
const scheduler = new TournamentCodeScheduler(
tournamentCodeService as never,
autoProvisionService as never,
tournamentResultService as never,
) as unknown as { attachPending(): Promise<void> };
return {
scheduler,
tournamentCodeService,
tournamentResultService,
};
}
it('starts result polling after attaching delayed tournament codes', async () => {
const attachedMatches = [{ _id: 'match-1' }, { _id: 'match-2' }];
const { scheduler, tournamentResultService } = createScheduler({
attachedMatches,
});
await scheduler.attachPending();
expect(tournamentResultService.scheduleInitialPoll).toHaveBeenCalledTimes(
2,
);
expect(tournamentResultService.scheduleInitialPoll).toHaveBeenNthCalledWith(
1,
attachedMatches[0],
);
expect(tournamentResultService.scheduleInitialPoll).toHaveBeenNthCalledWith(
2,
attachedMatches[1],
);
});
it('does not schedule result polling when no match received new codes', async () => {
const { scheduler, tournamentResultService } = createScheduler();
await scheduler.attachPending();
expect(tournamentResultService.scheduleInitialPoll).not.toHaveBeenCalled();
});
});
@@ -1,4 +1,5 @@
import { Injectable, Logger, OnModuleDestroy, OnModuleInit } from '@nestjs/common'; import { Injectable, Logger, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import { TournamentResultService } from '../tournament-result/tournament-result.service';
import { TournamentCodeAutoProvisionService } from './tournament-code-auto-provision.service'; import { TournamentCodeAutoProvisionService } from './tournament-code-auto-provision.service';
import { TournamentCodeService } from './tournament-code.service'; import { TournamentCodeService } from './tournament-code.service';
@@ -12,6 +13,7 @@ export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy {
constructor( constructor(
private readonly tournamentCodeService: TournamentCodeService, private readonly tournamentCodeService: TournamentCodeService,
private readonly autoProvisionService: TournamentCodeAutoProvisionService, private readonly autoProvisionService: TournamentCodeAutoProvisionService,
private readonly tournamentResultService: TournamentResultService,
) {} ) {}
public onModuleInit() { public onModuleInit() {
@@ -45,9 +47,15 @@ export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy {
private async attachPending() { private async attachPending() {
try { try {
const touched = await this.tournamentCodeService.attachPendingMatches(); const matches =
if (touched > 0) { await this.tournamentCodeService.attachPendingMatchDocuments();
this.logger.debug(`Attached tournament codes for ${touched} matches.`); if (matches.length > 0) {
this.logger.debug(
`Attached tournament codes for ${matches.length} matches.`,
);
for (const match of matches) {
await this.tournamentResultService.scheduleInitialPoll(match);
}
} }
} catch (error) { } catch (error) {
this.logger.warn( this.logger.warn(
@@ -226,8 +226,10 @@ describe('TournamentCodeService round-robin scheduling', () => {
(game) => game.roundNumber === roundNumber, (game) => game.roundNumber === roundNumber,
); );
expect(round).toHaveLength(4); expect(round).toHaveLength(4);
expect(new Set(round.flatMap((game) => [game.teamAIndex, game.teamBIndex])).size) expect(
.toBe(8); new Set(round.flatMap((game) => [game.teamAIndex, game.teamBIndex]))
.size,
).toBe(8);
} }
}); });
@@ -405,6 +407,69 @@ describe('TournamentCodeService pool stats', () => {
}); });
}); });
describe('TournamentCodeService pending match attachment', () => {
it('does not attach tournament codes before match teams are built', async () => {
const invalidMatch = {
...createMatch({
status: 'team-built',
teams: [],
tournamentCodeIds: [],
} as unknown as MatchOverrides),
isModified: jest.fn().mockReturnValue(false),
};
const validMatch = {
...createMatch({
status: 'team-built',
teams: [
{
teamIndex: 1,
members: [{ userId: new mongoose.Types.ObjectId() }],
},
{
teamIndex: 2,
members: [{ userId: new mongoose.Types.ObjectId() }],
},
],
tournamentCodeIds: [],
} as unknown as MatchOverrides),
isModified: jest.fn().mockReturnValue(false),
};
const codeId = new mongoose.Types.ObjectId();
const MatchModel = {
find: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue([invalidMatch, validMatch]),
}),
findById: jest.fn().mockResolvedValue(validMatch),
};
const TournamentCodeModel = {
findOneAndUpdate: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ _id: codeId }),
}),
};
const connectionService = {
getModel: jest.fn().mockImplementation((modelName: string) => {
if (modelName === 'match') return Promise.resolve(MatchModel);
if (modelName === 'tournamentCode') {
return Promise.resolve(TournamentCodeModel);
}
throw new Error(`Unexpected model: ${modelName}`);
}),
};
const service = new TournamentCodeService(connectionService as never);
const matches = await service.attachPendingMatchDocuments();
expect(matches).toEqual([validMatch]);
expect(MatchModel.findById).toHaveBeenCalledTimes(1);
expect(MatchModel.findById).toHaveBeenCalledWith(validMatch._id);
expect(TournamentCodeModel.findOneAndUpdate).toHaveBeenCalledTimes(1);
expect(validMatch.tournamentCodeIds.map((id) => id.toString())).toEqual([
codeId.toString(),
]);
expect(invalidMatch.tournamentCodeIds).toEqual([]);
});
});
describe('TournamentCodeService code replacement', () => { describe('TournamentCodeService code replacement', () => {
function queryResult<T>(value: T) { function queryResult<T>(value: T) {
return { exec: jest.fn().mockResolvedValue(value) }; return { exec: jest.fn().mockResolvedValue(value) };
@@ -164,10 +164,9 @@ export class TournamentCodeService {
_id: TournamentCodeState; _id: TournamentCodeState;
count: number; count: number;
}>([{ $group: { _id: '$state', count: { $sum: 1 } } }]).exec(); }>([{ $group: { _id: '$state', count: { $sum: 1 } } }]).exec();
const byState = Object.fromEntries(states.map((state) => [state, 0])) as Record< const byState = Object.fromEntries(
TournamentCodeState, states.map((state) => [state, 0]),
number ) as Record<TournamentCodeState, number>;
>;
for (const entry of counts) byState[entry._id] = entry.count; for (const entry of counts) byState[entry._id] = entry.count;
const expiringSoon = await TournamentCodeModel.countDocuments({ const expiringSoon = await TournamentCodeModel.countDocuments({
@@ -189,7 +188,9 @@ export class TournamentCodeService {
state: 'available', state: 'available',
}).exec(); }).exec();
if (result.deletedCount === 0) { if (result.deletedCount === 0) {
throw new BadRequestException('Only available tournament codes can be deleted.'); throw new BadRequestException(
'Only available tournament codes can be deleted.',
);
} }
} }
@@ -249,7 +250,9 @@ export class TournamentCodeService {
const reservedIds: mongoose.Types.ObjectId[] = []; const reservedIds: mongoose.Types.ObjectId[] = [];
const startGameNumber = match.tournamentCodeIds.length + 1; const startGameNumber = match.tournamentCodeIds.length + 1;
const expiresAfter = new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS); const expiresAfter = new Date(
Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS,
);
for (let index = 0; index < need; index += 1) { for (let index = 0; index < need; index += 1) {
const code = await TournamentCodeModel.findOneAndUpdate( const code = await TournamentCodeModel.findOneAndUpdate(
@@ -334,10 +337,14 @@ export class TournamentCodeService {
throw new NotFoundException('Assigned tournament code not found.'); throw new NotFoundException('Assigned tournament code not found.');
} }
if (currentCode.state === 'used' || currentCode.riotMatchId) { if (currentCode.state === 'used' || currentCode.riotMatchId) {
throw new BadRequestException('Used tournament codes cannot be replaced.'); throw new BadRequestException(
'Used tournament codes cannot be replaced.',
);
} }
const expiresAfter = new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS); const expiresAfter = new Date(
Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS,
);
const replacement = await TournamentCodeModel.findOneAndUpdate( const replacement = await TournamentCodeModel.findOneAndUpdate(
{ {
state: 'available', state: 'available',
@@ -358,7 +365,9 @@ export class TournamentCodeService {
{ sort: { expiresAt: 1 }, returnDocument: 'after' }, { sort: { expiresAt: 1 }, returnDocument: 'after' },
).exec(); ).exec();
if (!replacement) { if (!replacement) {
throw new BadRequestException('No available tournament code to replace with.'); throw new BadRequestException(
'No available tournament code to replace with.',
);
} }
currentCode.state = 'released'; currentCode.state = 'released';
@@ -430,6 +439,13 @@ export class TournamentCodeService {
public async attachPendingMatches( public async attachPendingMatches(
communityId?: mongoose.Types.ObjectId, communityId?: mongoose.Types.ObjectId,
): Promise<number> { ): Promise<number> {
const matches = await this.attachPendingMatchDocuments(communityId);
return matches.length;
}
public async attachPendingMatchDocuments(
communityId?: mongoose.Types.ObjectId,
): Promise<MatchDocument[]> {
const MatchModel = await this.connectionService.getModel('match'); const MatchModel = await this.connectionService.getModel('match');
const filter: { const filter: {
status: { $in: string[] }; status: { $in: string[] };
@@ -440,20 +456,33 @@ export class TournamentCodeService {
if (communityId) filter.communityId = communityId; if (communityId) filter.communityId = communityId;
const matches = await MatchModel.find(filter).exec(); const matches = await MatchModel.find(filter).exec();
let touched = 0; const touched: MatchDocument[] = [];
for (const match of matches) { for (const match of matches) {
if ((match.tournamentCodeIds?.length ?? 0) >= this.resolveRequiredSlots(match)) { if (!this.hasBuiltTeams(match)) continue;
if (
(match.tournamentCodeIds?.length ?? 0) >=
this.resolveRequiredSlots(match)
) {
continue; continue;
} }
const before = match.tournamentCodeIds?.length ?? 0; const before = match.tournamentCodeIds?.length ?? 0;
await this.reserveForMatch(match); const updatedMatch = await this.reserveForMatch(match);
const after = match.tournamentCodeIds?.length ?? 0; const after = updatedMatch.tournamentCodeIds?.length ?? 0;
if (after > before) touched += 1; if (after > before) touched.push(updatedMatch);
} }
return touched; return touched;
} }
public async buildSlots(match: MatchDocument): Promise<TournamentCodeSlotView[]> { private hasBuiltTeams(match: MatchDocument): boolean {
return Boolean(
match.teams.length >= 2 &&
match.teams.every((team) => team.members.length > 0),
);
}
public async buildSlots(
match: MatchDocument,
): Promise<TournamentCodeSlotView[]> {
if ( if (
(match.gameMode ?? 'pair') === 'round-robin' && (match.gameMode ?? 'pair') === 'round-robin' &&
(match.gameSchedule?.length ?? 0) === 0 && (match.gameSchedule?.length ?? 0) === 0 &&
@@ -1,7 +1,11 @@
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import type { MatchDocument } from '../global/database/schema'; import type { MatchDocument } from '../global/database/schema';
import type { RiotMatchDto } from '../riot/riot.types'; import type { RiotMatchDto } from '../riot/riot.types';
import { computeGameResult, type MatchPuuidLookup } from './team-mapping.util'; import {
collectCaptainAndLimitedTeamMemberUserIds,
computeGameResult,
type MatchPuuidLookup,
} from './team-mapping.util';
function makeMatch(): { function makeMatch(): {
match: MatchDocument; match: MatchDocument;
@@ -9,8 +13,14 @@ function makeMatch(): {
blueUserIds: mongoose.Types.ObjectId[]; blueUserIds: mongoose.Types.ObjectId[];
redUserIds: mongoose.Types.ObjectId[]; redUserIds: mongoose.Types.ObjectId[];
} { } {
const blueUserIds = Array.from({ length: 5 }, () => new mongoose.Types.ObjectId()); const blueUserIds = Array.from(
const redUserIds = Array.from({ length: 5 }, () => new mongoose.Types.ObjectId()); { length: 5 },
() => new mongoose.Types.ObjectId(),
);
const redUserIds = Array.from(
{ length: 5 },
() => new mongoose.Types.ObjectId(),
);
const puuidByUserId = new Map<string, string>(); const puuidByUserId = new Map<string, string>();
const userIdByPuuid = new Map<string, mongoose.Types.ObjectId>(); const userIdByPuuid = new Map<string, mongoose.Types.ObjectId>();
@@ -47,7 +57,12 @@ function makeMatch(): {
})), })),
} as unknown as MatchDocument; } as unknown as MatchDocument;
return { match, lookup: { puuidByUserId, userIdByPuuid }, blueUserIds, redUserIds }; return {
match,
lookup: { puuidByUserId, userIdByPuuid },
blueUserIds,
redUserIds,
};
} }
function makeRiotMatch(params: { function makeRiotMatch(params: {
@@ -154,3 +169,24 @@ describe('computeGameResult', () => {
expect(result).toBeNull(); expect(result).toBeNull();
}); });
}); });
describe('collectCaptainAndLimitedTeamMemberUserIds', () => {
it('keeps captains and caps extra members per team', () => {
const { blueUserIds, match, redUserIds } = makeMatch();
match.teams[0].captainUserId = blueUserIds[0];
match.teams[1].captainUserId = redUserIds[0];
const userIds = collectCaptainAndLimitedTeamMemberUserIds(match, 2).map(
(userId) => userId.toString(),
);
expect(userIds).toEqual([
blueUserIds[0].toString(),
blueUserIds[1].toString(),
blueUserIds[2].toString(),
redUserIds[0].toString(),
redUserIds[1].toString(),
redUserIds[2].toString(),
]);
});
});
@@ -1,5 +1,9 @@
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import type { MatchDocument, MatchGameResult, TeamSide } from '../global/database/schema'; import type {
MatchDocument,
MatchGameResult,
TeamSide,
} from '../global/database/schema';
import type { RiotMatchDto } from '../riot/riot.types'; import type { RiotMatchDto } from '../riot/riot.types';
const RIOT_BLUE_TEAM_ID = 100; const RIOT_BLUE_TEAM_ID = 100;
@@ -11,19 +15,46 @@ export interface MatchPuuidLookup {
userIdByPuuid: Map<string, mongoose.Types.ObjectId>; userIdByPuuid: Map<string, mongoose.Types.ObjectId>;
} }
export function collectCaptainUserIds(match: MatchDocument): mongoose.Types.ObjectId[] { export function collectCaptainUserIds(
match: MatchDocument,
): mongoose.Types.ObjectId[] {
return match.teams return match.teams
.map((team) => team.captainUserId) .map((team) => team.captainUserId)
.filter((userId): userId is mongoose.Types.ObjectId => Boolean(userId)); .filter((userId): userId is mongoose.Types.ObjectId => Boolean(userId));
} }
export function collectMatchUserIds(match: MatchDocument): mongoose.Types.ObjectId[] { export function collectCaptainAndLimitedTeamMemberUserIds(
match: MatchDocument,
memberLimitPerTeam: number,
): mongoose.Types.ObjectId[] {
const ids = new Map<string, mongoose.Types.ObjectId>();
for (const team of match.teams) {
if (team.captainUserId) {
ids.set(team.captainUserId.toString(), team.captainUserId);
}
let memberCount = 0;
for (const member of team.members) {
if (team.captainUserId?.toString() === member.userId.toString()) {
continue;
}
if (memberCount >= memberLimitPerTeam) break;
ids.set(member.userId.toString(), member.userId);
memberCount += 1;
}
}
return [...ids.values()];
}
export function collectMatchUserIds(
match: MatchDocument,
): mongoose.Types.ObjectId[] {
const ids = new Map<string, mongoose.Types.ObjectId>(); const ids = new Map<string, mongoose.Types.ObjectId>();
for (const participant of match.participants) { for (const participant of match.participants) {
ids.set(participant.userId.toString(), participant.userId); ids.set(participant.userId.toString(), participant.userId);
} }
for (const team of match.teams) { for (const team of match.teams) {
if (team.captainUserId) ids.set(team.captainUserId.toString(), team.captainUserId); if (team.captainUserId)
ids.set(team.captainUserId.toString(), team.captainUserId);
for (const member of team.members) { for (const member of team.members) {
ids.set(member.userId.toString(), member.userId); ids.set(member.userId.toString(), member.userId);
} }
@@ -78,8 +109,10 @@ export function computeGameResult(params: {
const reversedOverlap = const reversedOverlap =
countOverlap(team100Puuids, teamBPuuids) + countOverlap(team100Puuids, teamBPuuids) +
countOverlap(team200Puuids, teamAPuuids); countOverlap(team200Puuids, teamAPuuids);
const blueTeamIndex = normalOverlap >= reversedOverlap ? teamAIndex : teamBIndex; const blueTeamIndex =
const redTeamIndex = normalOverlap >= reversedOverlap ? teamBIndex : teamAIndex; normalOverlap >= reversedOverlap ? teamAIndex : teamBIndex;
const redTeamIndex =
normalOverlap >= reversedOverlap ? teamBIndex : teamAIndex;
const teamIndexByRiotTeamId: Record<number, number> = { const teamIndexByRiotTeamId: Record<number, number> = {
[RIOT_BLUE_TEAM_ID]: blueTeamIndex, [RIOT_BLUE_TEAM_ID]: blueTeamIndex,
[RIOT_RED_TEAM_ID]: redTeamIndex, [RIOT_RED_TEAM_ID]: redTeamIndex,
@@ -4,6 +4,7 @@ import type { RiotMatchDto } from '../riot/riot.types';
import { TournamentResultService } from './tournament-result.service'; import { TournamentResultService } from './tournament-result.service';
type TournamentResultServiceInternals = TournamentResultService & { type TournamentResultServiceInternals = TournamentResultService & {
nextPollDelayMs(elapsedMs: number): number | null;
resolveRequiredGameSlots(match: MatchDocument): number; resolveRequiredGameSlots(match: MatchDocument): number;
resolveSeriesRefForGameNumber( resolveSeriesRefForGameNumber(
match: MatchDocument, match: MatchDocument,
@@ -235,7 +236,7 @@ describe('TournamentResultService tournament code polling', () => {
{ buildAndUpsert: jest.fn().mockResolvedValue(undefined) } as never, { buildAndUpsert: jest.fn().mockResolvedValue(undefined) } as never,
); );
return { service, match, code }; return { service, match, code, riotMatchService };
} }
it('matches Riot tournament codes using exact casing', async () => { it('matches Riot tournament codes using exact casing', async () => {
@@ -256,6 +257,23 @@ describe('TournamentResultService tournament code polling', () => {
expect(match.result?.games).toHaveLength(1); expect(match.result?.games).toHaveLength(1);
}); });
it('limits expanded polling to two team members per team', async () => {
const { service, match, riotMatchService } = createPollFixture({
storedCode: 'AbC-12345',
riotTournamentCode: 'AbC-12345',
});
await service.processPollJob({
matchId: match._id.toString(),
attempt: 1,
expandedToAllPuuids: true,
});
expect(
riotMatchService.getMatchIdsByPuuid.mock.calls.map(([puuid]) => puuid),
).toEqual(['poll-puuid-1', 'poll-puuid-2', 'poll-puuid-6', 'poll-puuid-7']);
});
it('does not match tournament codes when casing differs', async () => { it('does not match tournament codes when casing differs', async () => {
const { service, match, code } = createPollFixture({ const { service, match, code } = createPollFixture({
storedCode: 'ABC-12345', storedCode: 'ABC-12345',
@@ -275,6 +293,15 @@ describe('TournamentResultService tournament code polling', () => {
}); });
}); });
describe('TournamentResultService polling cadence', () => {
it('polls every two minutes during the first hour', () => {
const service = createService();
expect(service.nextPollDelayMs(0)).toBe(2 * 60_000);
expect(service.nextPollDelayMs(60 * 60_000)).toBe(2 * 60_000);
});
});
describe('TournamentResultService manual result collection', () => { describe('TournamentResultService manual result collection', () => {
function createManualFixture() { function createManualFixture() {
const communityId = new mongoose.Types.ObjectId(); const communityId = new mongoose.Types.ObjectId();
@@ -23,6 +23,7 @@ import {
resolveRoundRobinTeamCount, resolveRoundRobinTeamCount,
} from '../tournament-code/round-robin.util'; } from '../tournament-code/round-robin.util';
import { import {
collectCaptainAndLimitedTeamMemberUserIds,
collectCaptainUserIds, collectCaptainUserIds,
collectMatchUserIds, collectMatchUserIds,
computeGameResult, computeGameResult,
@@ -34,10 +35,11 @@ import type {
PollTournamentResultJob, PollTournamentResultJob,
} from './tournament-result.types'; } from './tournament-result.types';
const FIRST_HOUR_POLL_DELAY_MS = 5 * 60_000; const FIRST_HOUR_POLL_DELAY_MS = 2 * 60_000;
const LATER_POLL_DELAY_MS = 60 * 60_000; const LATER_POLL_DELAY_MS = 60 * 60_000;
const POLL_EXPIRY_MS = 24 * 60 * 60_000; const POLL_EXPIRY_MS = 24 * 60 * 60_000;
const EXPAND_AFTER_MS = 60 * 60_000; const EXPAND_AFTER_MS = 60 * 60_000;
const EXPANDED_MEMBER_LIMIT_PER_TEAM = 2;
const TOURNAMENT_LOOKUP_START_MARGIN_SECONDS = 60; const TOURNAMENT_LOOKUP_START_MARGIN_SECONDS = 60;
interface ManualGameAssignment { interface ManualGameAssignment {
@@ -216,7 +218,13 @@ export class TournamentResultService {
const region = community?.riotRegion ?? 'asia'; const region = community?.riotRegion ?? 'asia';
const lookup = await this.buildPuuidLookup(match); const lookup = await this.buildPuuidLookup(match);
const puuids = job.expandedToAllPuuids const puuids = job.expandedToAllPuuids
? this.collectPollingPuuids(collectMatchUserIds(match), lookup) ? this.collectPollingPuuids(
collectCaptainAndLimitedTeamMemberUserIds(
match,
EXPANDED_MEMBER_LIMIT_PER_TEAM,
),
lookup,
)
: this.collectPollingPuuids(collectCaptainUserIds(match), lookup); : this.collectPollingPuuids(collectCaptainUserIds(match), lookup);
const matchedGameNumbers = new Set<number>(); const matchedGameNumbers = new Set<number>();
+90
View File
@@ -0,0 +1,90 @@
import { createRequire } from 'node:module';
const CONFIG_PATH = '../newrelic.cjs';
const requireConfig = createRequire(__filename);
interface NewRelicConfig {
app_name: string[];
license_key: string;
agent_enabled: boolean;
ai_monitoring: {
enabled: boolean;
};
custom_insights_events: {
max_samples_stored: number;
};
span_events: {
max_samples_stored: number;
};
}
interface NewRelicConfigModule {
config: NewRelicConfig;
}
function loadConfig(): NewRelicConfig {
jest.resetModules();
const module = requireConfig(CONFIG_PATH) as unknown as NewRelicConfigModule;
return module.config;
}
describe('New Relic config', () => {
let originalEnv: NodeJS.ProcessEnv;
beforeEach(() => {
originalEnv = { ...process.env };
delete process.env.NEW_RELIC_ENABLED;
delete process.env.NEW_RELIC_LICENSE_KEY;
delete process.env.NEW_RELIC_APP_NAME;
delete process.env.NEW_RELIC_AI_MONITORING_ENABLED;
delete process.env.NEW_RELIC_CUSTOM_INSIGHTS_EVENTS_MAX_SAMPLES_STORED;
delete process.env.NEW_RELIC_SPAN_EVENTS_MAX_SAMPLES_STORED;
jest.resetModules();
});
afterEach(() => {
process.env = originalEnv;
jest.resetModules();
});
it('uses safe defaults and stays disabled without a license key', () => {
const config = loadConfig();
expect(config.app_name).toEqual(['lolympus']);
expect(config.agent_enabled).toBe(false);
expect(config.ai_monitoring.enabled).toBe(true);
expect(config.custom_insights_events.max_samples_stored).toBe(100000);
expect(config.span_events.max_samples_stored).toBe(10000);
});
it('enables the agent when a license key exists and honors runtime overrides', () => {
process.env.NEW_RELIC_LICENSE_KEY = 'test-license';
process.env.NEW_RELIC_APP_NAME = 'lolympus-api-test';
process.env.NEW_RELIC_AI_MONITORING_ENABLED = 'false';
process.env.NEW_RELIC_CUSTOM_INSIGHTS_EVENTS_MAX_SAMPLES_STORED = '5000';
process.env.NEW_RELIC_SPAN_EVENTS_MAX_SAMPLES_STORED = '4000';
const config = loadConfig();
expect(config.app_name).toEqual(['lolympus-api-test']);
expect(config.license_key).toBe('test-license');
expect(config.agent_enabled).toBe(true);
expect(config.ai_monitoring.enabled).toBe(false);
expect(config.custom_insights_events.max_samples_stored).toBe(5000);
expect(config.span_events.max_samples_stored).toBe(4000);
});
it('normalizes shorthand sample sizes before New Relic applies env overrides', () => {
process.env.NEW_RELIC_CUSTOM_INSIGHTS_EVENTS_MAX_SAMPLES_STORED = '100k';
process.env.NEW_RELIC_SPAN_EVENTS_MAX_SAMPLES_STORED = '10k';
const config = loadConfig();
expect(config.custom_insights_events.max_samples_stored).toBe(100000);
expect(config.span_events.max_samples_stored).toBe(10000);
expect(
process.env.NEW_RELIC_CUSTOM_INSIGHTS_EVENTS_MAX_SAMPLES_STORED,
).toBe('100000');
expect(process.env.NEW_RELIC_SPAN_EVENTS_MAX_SAMPLES_STORED).toBe('10000');
});
});
+8
View File
@@ -5,3 +5,11 @@ VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/5ef88004-e953-4b04-93db-64
VITE_MSAL_API_SCOPE=api://15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3/lolympus-tournament-support-dev VITE_MSAL_API_SCOPE=api://15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3/lolympus-tournament-support-dev
VITE_MSAL_REDIRECT_URI=http://localhost:5173/auth/callback VITE_MSAL_REDIRECT_URI=http://localhost:5173/auth/callback
VITE_MSAL_SILENT_REDIRECT_URI=http://localhost:5173/auth/silent-callback.html VITE_MSAL_SILENT_REDIRECT_URI=http://localhost:5173/auth/silent-callback.html
VITE_NEW_RELIC_ENABLED=false
VITE_NEW_RELIC_APPLICATION_ID=601654991
VITE_NEW_RELIC_ACCOUNT_ID=8100154
VITE_NEW_RELIC_AGENT_ID=601654991
VITE_NEW_RELIC_LICENSE_KEY=NRJS-caad7f6e90b92fe88de
VITE_NEW_RELIC_TRUST_KEY=8100154
VITE_NEW_RELIC_BEACON=bam.nr-data.net
VITE_NEW_RELIC_RELEASE_NAME=lolympus-web
+10
View File
@@ -5,3 +5,13 @@ VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/<tenant-id>
VITE_MSAL_API_SCOPE=api://lolympus-api/access_as_user VITE_MSAL_API_SCOPE=api://lolympus-api/access_as_user
VITE_MSAL_REDIRECT_URI=http://localhost:5173/auth/callback VITE_MSAL_REDIRECT_URI=http://localhost:5173/auth/callback
VITE_MSAL_SILENT_REDIRECT_URI=http://localhost:5173/auth/silent-callback.html VITE_MSAL_SILENT_REDIRECT_URI=http://localhost:5173/auth/silent-callback.html
VITE_NEW_RELIC_ENABLED=false
VITE_NEW_RELIC_APPLICATION_ID=
VITE_NEW_RELIC_ACCOUNT_ID=
VITE_NEW_RELIC_AGENT_ID=
VITE_NEW_RELIC_LICENSE_KEY=
VITE_NEW_RELIC_TRUST_KEY=
VITE_NEW_RELIC_BEACON=bam.nr-data.net
VITE_NEW_RELIC_APPLICATION_VERSION=
VITE_NEW_RELIC_RELEASE_ID=
VITE_NEW_RELIC_RELEASE_NAME=lolympus-web
+10 -1
View File
@@ -5,4 +5,13 @@ VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/5ef88004-e953-4b04-93db-64
VITE_MSAL_API_SCOPE=api://15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3/lolympus-tournament-support-dev VITE_MSAL_API_SCOPE=api://15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3/lolympus-tournament-support-dev
VITE_MSAL_REDIRECT_URI=https://lolympus.dahyeon.us/auth/callback VITE_MSAL_REDIRECT_URI=https://lolympus.dahyeon.us/auth/callback
VITE_MSAL_SILENT_REDIRECT_URI=https://lolympus.dahyeon.us/auth/silent-callback.html VITE_MSAL_SILENT_REDIRECT_URI=https://lolympus.dahyeon.us/auth/silent-callback.html
VITE_NEW_RELIC_ENABLED=true
VITE_NEW_RELIC_APPLICATION_ID=601654991
VITE_NEW_RELIC_ACCOUNT_ID=8100154
VITE_NEW_RELIC_AGENT_ID=601654991
VITE_NEW_RELIC_LICENSE_KEY=NRJS-caad7f6e90b92fe88de
VITE_NEW_RELIC_TRUST_KEY=8100154
VITE_NEW_RELIC_BEACON=bam.nr-data.net
VITE_NEW_RELIC_APPLICATION_VERSION=83
VITE_NEW_RELIC_RELEASE_ID=release-83
VITE_NEW_RELIC_RELEASE_NAME=lolympus-web
+12 -2
View File
@@ -1,6 +1,16 @@
VITE_API_BASE_URL=https://lolympus-api-staging.dahyeon.us VITE_API_BASE_URL=https://lolympus-api-staging.dahyeon.us
VITE_DEFAULT_COMMUNITY_ID=69ebe0adf627c11be2f020a1 VITE_DEFAULT_COMMUNITY_ID=69ebe0adf627c11be2f020a1
VITE_MSAL_CLIENT_ID=15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3 VITE_MSAL_CLIENT_ID=66dadf46-418c-43c8-a908-3c15dcc0465d
VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/5ef88004-e953-4b04-93db-64bbf49c6863 VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/5ef88004-e953-4b04-93db-64bbf49c6863
VITE_MSAL_API_SCOPE=api://15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3/lolympus-tournament-support-dev VITE_MSAL_API_SCOPE=api://15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3/lolympus-tournament-support-dev
VITE_MSAL_REDIRECT_URI=http://localhost:5173/auth/callback VITE_MSAL_REDIRECT_URI=https://release-83.lolympus.pages.dev/auth/callback
VITE_NEW_RELIC_ENABLED=true
VITE_NEW_RELIC_APPLICATION_ID=601654991
VITE_NEW_RELIC_ACCOUNT_ID=8100154
VITE_NEW_RELIC_AGENT_ID=601654991
VITE_NEW_RELIC_LICENSE_KEY=NRJS-caad7f6e90b92fe88de
VITE_NEW_RELIC_TRUST_KEY=8100154
VITE_NEW_RELIC_BEACON=bam.nr-data.net
VITE_NEW_RELIC_APPLICATION_VERSION=83
VITE_NEW_RELIC_RELEASE_ID=release-83
VITE_NEW_RELIC_RELEASE_NAME=lolympus-web
+1
View File
@@ -20,6 +20,7 @@
"dependencies": { "dependencies": {
"@azure/msal-browser": "^5.8.0", "@azure/msal-browser": "^5.8.0",
"@azure/msal-react": "^5.3.1", "@azure/msal-react": "^5.3.1",
"@newrelic/browser-agent": "^1.316.0",
"@tanstack/react-query": "^5.100.1", "@tanstack/react-query": "^5.100.1",
"lucide-react": "^1.14.0", "lucide-react": "^1.14.0",
"react": "^19.2.4", "react": "^19.2.4",
+2
View File
@@ -661,6 +661,8 @@ export interface ApiRecentMatchTeam {
export interface ApiRecentMatchView { export interface ApiRecentMatchView {
matchId: string; matchId: string;
internalMatchId?: string;
gameNumber?: number;
queueId: number; queueId: number;
queueLabel: string; queueLabel: string;
gameCreation: number; gameCreation: number;
+172 -12
View File
@@ -8,6 +8,9 @@ import {
resolveAuctionErrorMessage, resolveAuctionErrorMessage,
resolveAuctionRejectionMessage, resolveAuctionRejectionMessage,
} from './auctionRejectionMessages'; } from './auctionRejectionMessages';
// [AUCTION-DEBUG] 경매 "중복 멤버" 조사용 임시 계측. 조사 종료 후 제거 대상
// (호출부는 전부 addNewRelicPageAction / describeAuctionForTelemetry 로 grep 가능).
import { addNewRelicPageAction } from '../lib/observability/new-relic';
type ConnectionStatus = type ConnectionStatus =
| 'idle' | 'idle'
@@ -180,9 +183,36 @@ export function useAuctionSocket(matchId: string | undefined) {
resolveCurrentBidPointAmount(nextAuction); resolveCurrentBidPointAmount(nextAuction);
} }
function commitAuctionState(nextAuction: ApiAuction): boolean { function commitAuctionState(
nextAuction: ApiAuction,
source = 'socket-state',
): boolean {
const currentAuction = latestAuctionRef.current; const currentAuction = latestAuctionRef.current;
if (!shouldApplyIncomingAuctionState(currentAuction, nextAuction)) { const applied = shouldApplyIncomingAuctionState(currentAuction, nextAuction);
const currentRevision =
typeof currentAuction?.revision === 'number'
? currentAuction.revision
: -1;
const incomingRevision =
typeof nextAuction?.revision === 'number' ? nextAuction.revision : -1;
// 단조성을 깨고 적용되는 경우(=revision이 같거나 뒤로 가는데도 반영됨).
// force-resync/lifecycle 교체로만 발생하며, "2~3 버전 롤백"의 직접 증거가 된다.
const isBackwardApply =
applied &&
currentRevision >= 0 &&
incomingRevision >= 0 &&
incomingRevision <= currentRevision;
addNewRelicPageAction('AuctionClientStateApply', {
matchId: matchId ?? 'none',
source,
applied,
isBackwardApply,
revisionDelta: incomingRevision - currentRevision,
...describeAuctionForTelemetry('current', currentAuction),
...describeAuctionForTelemetry('incoming', nextAuction),
});
if (!applied) {
return false; return false;
} }
@@ -361,7 +391,7 @@ export function useAuctionSocket(matchId: string | undefined) {
}); });
socket.on('state', (nextAuction: ApiAuction) => { socket.on('state', (nextAuction: ApiAuction) => {
const didApplyState = commitAuctionState(nextAuction); const didApplyState = commitAuctionState(nextAuction, 'socket-state');
if (didApplyState) { if (didApplyState) {
clearPendingActionRequests(); clearPendingActionRequests();
} }
@@ -384,7 +414,24 @@ export function useAuctionSocket(matchId: string | undefined) {
socket.on('bid', (payload: BidDeltaPayload) => { socket.on('bid', (payload: BidDeltaPayload) => {
applyFallbackServerTimestamp(payload?.currentServerTimestampMS); applyFallbackServerTimestamp(payload?.currentServerTimestampMS);
const beforeBid = latestAuctionRef.current;
const didApplyBidDelta = commitBidDelta(payload); const didApplyBidDelta = commitBidDelta(payload);
addNewRelicPageAction('AuctionClientBidDelta', {
matchId: matchId ?? 'none',
applied: didApplyBidDelta,
deltaRevision:
typeof payload?.revision === 'number' ? payload.revision : -1,
deltaBidAmount: Number(payload?.currentHighestBidPointAmount ?? -1),
deltaBidderTeamIndex: Number(
payload?.currentHighestBidderTeamIndex ?? -1,
),
beforeRevision:
typeof beforeBid?.revision === 'number' ? beforeBid.revision : -1,
beforeBidAmount: beforeBid
? resolveCurrentBidPointAmount(beforeBid)
: -1,
beforePlayerUserId: beforeBid?.currentBidRoundPlayerUserId ?? 'none',
});
if (payload?.bidRequestId) { if (payload?.bidRequestId) {
if ( if (
didApplyBidDelta || didApplyBidDelta ||
@@ -429,6 +476,12 @@ export function useAuctionSocket(matchId: string | undefined) {
}; };
latestAuctionRef.current = nextAuction; latestAuctionRef.current = nextAuction;
setAuction(nextAuction); setAuction(nextAuction);
addNewRelicPageAction('AuctionClientSideEffect', {
matchId: matchId ?? 'none',
matchSideEffectStatus: matchSideEffectStatus ?? 'unknown',
matchSideEffectRevision,
...describeAuctionForTelemetry('current', currentAuction),
});
}); });
socket.on('reset', (payload: ResetPayload) => { socket.on('reset', (payload: ResetPayload) => {
@@ -574,6 +627,23 @@ export function useAuctionSocket(matchId: string | undefined) {
clearPendingActionRequest(auctionActionRequestId); clearPendingActionRequest(auctionActionRequestId);
setError('경매 진행 응답이 지연되어 최신 상태를 다시 확인해주세요.'); setError('경매 진행 응답이 지연되어 최신 상태를 다시 확인해주세요.');
}, 10_000); }, 10_000);
addNewRelicPageAction('AuctionClientActionSent', {
matchId: matchId ?? 'none',
action: eventName,
retryAttempt,
sentRevision:
typeof payload.clientObservedRevision === 'number'
? payload.clientObservedRevision
: -1,
sentOrderIndex:
typeof payload.clientObservedCurrentAuctionPlayerOrderIndex === 'number'
? payload.clientObservedCurrentAuctionPlayerOrderIndex
: -1,
sentPlayerUserId:
payload.clientObservedCurrentBidRoundPlayerUserId ?? 'none',
sentPhase: payload.clientObservedPhase ?? 'none',
...describeAuctionForTelemetry('observed', latestAuctionRef.current),
});
socket.emit( socket.emit(
eventName, eventName,
actionPayload, actionPayload,
@@ -590,14 +660,6 @@ export function useAuctionSocket(matchId: string | undefined) {
clearPendingActionRequest( clearPendingActionRequest(
ack?.auctionActionRequestId ?? auctionActionRequestId, ack?.auctionActionRequestId ?? auctionActionRequestId,
); );
// 1) rebaseline: 서버가 동봉한 최신 state를 즉시 반영(없으면 join으로 재요청).
// commitAuctionState는 latestAuctionRef를 동기로 갱신하므로, 이후
// buildAuctionActionPayload는 최신 관측값(revision/phase/선수)을 읽는다.
if (ack.state) {
commitAuctionState(ack.state);
} else if (isAuctionResyncRecommended(ack)) {
resyncAuctionState();
}
// 2) 자동 재시도: "낡은 화면 때문에 거부"였고 동기 rebaseline 소스(state)가 // 2) 자동 재시도: "낡은 화면 때문에 거부"였고 동기 rebaseline 소스(state)가
// 있을 때만 1회. assignedPosition 등 원래 payload는 유지하고 관측값/요청 // 있을 때만 1회. assignedPosition 등 원래 payload는 유지하고 관측값/요청
// id만 새로 만든다. 재시도 시에는 중간 에러 문구를 띄우지 않는다(무음 복구). // id만 새로 만든다. 재시도 시에는 중간 에러 문구를 띄우지 않는다(무음 복구).
@@ -605,6 +667,41 @@ export function useAuctionSocket(matchId: string | undefined) {
Boolean(ack.state) && Boolean(ack.state) &&
isAuctionResyncRecommended(ack) && isAuctionResyncRecommended(ack) &&
retryAttempt < 1; retryAttempt < 1;
// 거부 시 "클라가 보낸 관측 revision"과 "서버가 동봉한 진짜 state"를 함께
// 기록한다. observedRevision < serverRevision 이면 stale-client CONFLICT 확정.
addNewRelicPageAction('AuctionClientActionRejected', {
matchId: matchId ?? 'none',
action: eventName,
retryAttempt,
rejectionReason:
ack?.auctionRejectionReason ?? ack?.code ?? 'unknown',
rejectionCode: ack?.code ?? 'none',
resyncRecommended: isAuctionResyncRecommended(ack),
hasAckState: Boolean(ack?.state),
willAutoRetry: canAutoRetry,
sentRevision:
typeof payload.clientObservedRevision === 'number'
? payload.clientObservedRevision
: -1,
sentOrderIndex:
typeof payload.clientObservedCurrentAuctionPlayerOrderIndex ===
'number'
? payload.clientObservedCurrentAuctionPlayerOrderIndex
: -1,
sentPlayerUserId:
payload.clientObservedCurrentBidRoundPlayerUserId ?? 'none',
sentPhase: payload.clientObservedPhase ?? 'none',
...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) { if (canAutoRetry) {
emitAuctionAction( emitAuctionAction(
eventName, eventName,
@@ -621,7 +718,17 @@ export function useAuctionSocket(matchId: string | undefined) {
clearPendingActionRequest( clearPendingActionRequest(
ack.auctionActionRequestId ?? auctionActionRequestId, ack.auctionActionRequestId ?? auctionActionRequestId,
); );
commitAuctionState(ackState); addNewRelicPageAction('AuctionClientActionAck', {
matchId: matchId ?? 'none',
action: eventName,
retryAttempt,
sentRevision:
typeof payload.clientObservedRevision === 'number'
? payload.clientObservedRevision
: -1,
...describeAuctionForTelemetry('server', ackState),
});
commitAuctionState(ackState, 'action-ack');
} }
}, },
); );
@@ -754,6 +861,59 @@ function resolveCurrentBidPointAmount(auction: ApiAuction): number {
return Number.isFinite(bidPointAmount) ? bidPointAmount : 0; return Number.isFinite(bidPointAmount) ? bidPointAmount : 0;
} }
// [AUCTION-DEBUG] 아래 텔레메트리 헬퍼들과 호출부는 조사 종료 후 제거 대상.
type AuctionTelemetryAttributes = Record<string, string | number | boolean | null>;
function readAuctionHistorySequence(auction: ApiAuction | null | undefined) {
const value = (auction as { currentAuctionHistorySequence?: unknown } | null)
?.currentAuctionHistorySequence;
return typeof value === 'number' ? value : -1;
}
function summarizeAuctionTeams(auction: ApiAuction | null | undefined) {
const teams = Array.isArray(auction?.auctionTeams) ? auction.auctionTeams : [];
let assignedMemberCount = 0;
for (const team of teams) {
const members = (team as { members?: unknown[] }).members;
if (Array.isArray(members)) assignedMemberCount += members.length;
}
return { teamCount: teams.length, assignedMemberCount };
}
// New Relic로 보내기 위해 경매 상태를 평탄한 속성 집합으로 요약한다.
// prefix로 두 상태(예: 현재 vs 수신)를 한 이벤트에 같이 실어 revision 어긋남을
// 한눈에 비교할 수 있게 한다.
function describeAuctionForTelemetry(
prefix: string,
auction: ApiAuction | null | undefined,
): AuctionTelemetryAttributes {
const teamSummary = summarizeAuctionTeams(auction);
return {
[`${prefix}Revision`]:
typeof auction?.revision === 'number' ? auction.revision : -1,
[`${prefix}HistorySequence`]: readAuctionHistorySequence(auction),
[`${prefix}Phase`]: auction?.phase ?? 'unknown',
[`${prefix}LifecycleId`]: auction?.auctionLifecycleId ?? 'none',
[`${prefix}OrderIndex`]:
typeof auction?.currentAuctionPlayerOrderIndex === 'number'
? auction.currentAuctionPlayerOrderIndex
: -1,
[`${prefix}PlayerUserId`]: auction?.currentBidRoundPlayerUserId ?? 'none',
[`${prefix}BidAmount`]: auction
? resolveCurrentBidPointAmount(auction)
: -1,
[`${prefix}BidderTeamIndex`]:
typeof auction?.currentHighestBidderTeamIndex === 'number'
? auction.currentHighestBidderTeamIndex
: typeof auction?.currentBidderTeamIndex === 'number'
? auction.currentBidderTeamIndex
: -1,
[`${prefix}TeamCount`]: teamSummary.teamCount,
[`${prefix}AssignedMemberCount`]: teamSummary.assignedMemberCount,
[`${prefix}ForceResync`]: Boolean(auction?.shouldForceAuctionStateResync),
};
}
function shouldApplyIncomingAuctionState( function shouldApplyIncomingAuctionState(
current: ApiAuction | null, current: ApiAuction | null,
incoming: ApiAuction, incoming: ApiAuction,
+45
View File
@@ -122,6 +122,51 @@ body {
--color-base-300: oklch(95% 0 0); /* 구분선/보더 */ --color-base-300: oklch(95% 0 0); /* 구분선/보더 */
} }
/* ── 실시간 입찰 피드백 모션 ──
입찰가 갱신 시 pop(스케일 펄스), 내가 밀렸을 때 shake(주의 환기). */
@keyframes lts-bid-pop {
0% {
transform: scale(1);
}
35% {
transform: scale(1.14);
}
100% {
transform: scale(1);
}
}
@keyframes lts-outbid-shake {
0%,
100% {
transform: translateX(0);
}
20% {
transform: translateX(-3px);
}
40% {
transform: translateX(3px);
}
60% {
transform: translateX(-2px);
}
80% {
transform: translateX(2px);
}
}
.animate-bid-pop {
animation: lts-bid-pop 0.45s cubic-bezier(0.34, 1.56, 0.64, 1);
transform-origin: right center;
}
.animate-outbid-shake {
animation: lts-outbid-shake 0.4s ease-in-out;
}
@media (prefers-reduced-motion: reduce) {
.animate-bid-pop,
.animate-outbid-shake {
animation: none;
}
}
/* poro.gg style: 모든 모서리 각지게 */ /* poro.gg style: 모든 모서리 각지게 */
*, *,
*::before, *::before,
+160
View File
@@ -0,0 +1,160 @@
import { BrowserAgent } from '@newrelic/browser-agent/loaders/browser-agent';
import type { AgentOptions } from '@newrelic/browser-agent/loaders/agent';
type NewRelicBrowserAgent = InstanceType<typeof BrowserAgent>;
type NewRelicAttributeValue = string | number | boolean | null;
type NewRelicAttributes = Record<string, NewRelicAttributeValue>;
const DEFAULT_BEACON = 'bam.nr-data.net';
const DEFAULT_RELEASE_NAME = 'lolympus-web';
let browserAgent: NewRelicBrowserAgent | null = null;
function readEnvValue(name: string): string | undefined {
const value = import.meta.env[name];
return typeof value === 'string' && value.trim() ? value.trim() : undefined;
}
function readEnvNumber(name: string): number | undefined {
const value = Number(readEnvValue(name));
return Number.isFinite(value) ? value : undefined;
}
function isBrowserRuntime() {
return typeof window !== 'undefined';
}
export function isNewRelicBrowserMonitoringEnabled() {
return readEnvValue('VITE_NEW_RELIC_ENABLED') !== 'false';
}
export function createNewRelicBrowserAgentOptions(): AgentOptions | null {
if (!isNewRelicBrowserMonitoringEnabled()) return null;
const applicationID = readEnvValue('VITE_NEW_RELIC_APPLICATION_ID');
const accountID = readEnvNumber('VITE_NEW_RELIC_ACCOUNT_ID');
const licenseKey = readEnvValue('VITE_NEW_RELIC_LICENSE_KEY');
const beacon = readEnvValue('VITE_NEW_RELIC_BEACON') ?? DEFAULT_BEACON;
const agentID = readEnvNumber('VITE_NEW_RELIC_AGENT_ID') ?? Number(applicationID);
const applicationNumericID = Number(applicationID);
const trustKey = readEnvNumber('VITE_NEW_RELIC_TRUST_KEY') ?? accountID;
if (
!applicationID ||
!accountID ||
!licenseKey ||
!Number.isFinite(agentID) ||
!Number.isFinite(applicationNumericID)
) {
return null;
}
return {
info: {
applicationID,
beacon,
errorBeacon: beacon,
licenseKey,
sa: 1,
},
init: {
ajax: {
deny_list: [beacon],
},
browser_consent_mode: {
enabled: false,
},
distributed_tracing: {
enabled: true,
},
performance: {
capture_detail: false,
capture_marks: false,
capture_measures: true,
},
privacy: {
cookies_enabled: true,
},
session_replay: {
enabled: false,
autoStart: false,
},
},
loader_config: {
accountID,
agentID,
applicationID: applicationNumericID,
licenseKey,
trustKey,
},
};
}
function applyReleaseMetadata(agent: NewRelicBrowserAgent) {
const applicationVersion =
readEnvValue('VITE_NEW_RELIC_APPLICATION_VERSION') ??
readEnvValue('VITE_APP_VERSION') ??
readEnvValue('VITE_BUILD_NUMBER');
if (!applicationVersion) return;
agent.setApplicationVersion(applicationVersion);
agent.addRelease(
readEnvValue('VITE_NEW_RELIC_RELEASE_NAME') ?? DEFAULT_RELEASE_NAME,
readEnvValue('VITE_NEW_RELIC_RELEASE_ID') ?? applicationVersion,
);
}
export function initializeNewRelicBrowserAgent(
options = createNewRelicBrowserAgentOptions(),
) {
if (!isBrowserRuntime() || !options) return null;
if (browserAgent) return browserAgent;
// New Relic recommends instantiating the npm BrowserAgent from the earliest
// browser entry point: https://docs.newrelic.com/docs/browser/browser-monitoring/installation/install-browser-monitoring-agent/
browserAgent = new BrowserAgent(options);
applyReleaseMetadata(browserAgent);
return browserAgent;
}
export function getNewRelicBrowserAgent() {
return browserAgent;
}
export function setNewRelicUserId(userId: string | null, resetSession = false) {
browserAgent?.setUserId(userId, resetSession);
}
export function setNewRelicPageViewName(name: string, host?: string) {
browserAgent?.setPageViewName(name, host);
}
export function setNewRelicCustomAttribute(
name: string,
value: NewRelicAttributeValue,
persist = false,
) {
browserAgent?.setCustomAttribute(name, value, persist);
}
export function addNewRelicPageAction(
name: string,
attributes?: NewRelicAttributes,
) {
browserAgent?.addPageAction(name, attributes);
}
export function recordNewRelicCustomEvent(
eventType: string,
attributes?: NewRelicAttributes,
) {
browserAgent?.recordCustomEvent(eventType, attributes);
}
export function noticeNewRelicError(
error: Error | string,
attributes?: NewRelicAttributes,
) {
browserAgent?.noticeError(error, attributes);
}
+2
View File
@@ -1,3 +1,4 @@
import { initializeNewRelicBrowserAgent } from './lib/observability/new-relic.ts';
import { StrictMode } from 'react'; import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client'; import { createRoot } from 'react-dom/client';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
@@ -6,6 +7,7 @@ import App from './App.tsx';
import { MsalAppProvider } from './lib/auth/MsalAppProvider.tsx'; import { MsalAppProvider } from './lib/auth/MsalAppProvider.tsx';
import { initializeTheme } from './config.ts'; import { initializeTheme } from './config.ts';
initializeNewRelicBrowserAgent();
initializeTheme(); initializeTheme();
const queryClient = new QueryClient({ const queryClient = new QueryClient({
File diff suppressed because it is too large. Load diff
+76 -8
View File
@@ -37,6 +37,14 @@ type DdragonManifestData = ReturnType<typeof useDdragonManifest>["data"];
type RuneStyleEntry = NonNullable<DdragonManifestData>["runesReforged"][number]; type RuneStyleEntry = NonNullable<DdragonManifestData>["runesReforged"][number];
type DetailTab = "scoreboard" | "matchup" | "build"; type DetailTab = "scoreboard" | "matchup" | "build";
type TimelineMetric = "gold" | "xp"; type TimelineMetric = "gold" | "xp";
type MatchGameBackTarget = {
to: string;
label: string;
};
type MatchGameNavigationState = {
backTo: string;
backLabel: string;
};
const DETAIL_TABS: Array<{ id: DetailTab; label: string }> = [ const DETAIL_TABS: Array<{ id: DetailTab; label: string }> = [
{ id: "scoreboard", label: "스코어보드" }, { id: "scoreboard", label: "스코어보드" },
@@ -49,6 +57,46 @@ const TIMELINE_METRICS: Array<{ id: TimelineMetric; label: string }> = [
{ id: "xp", label: "경험치" }, { id: "xp", label: "경험치" },
]; ];
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
function resolveBackTarget(
state: unknown,
fallbackTo: string,
): MatchGameBackTarget {
if (
isRecord(state) &&
typeof state.backTo === "string" &&
state.backTo.startsWith("/") &&
!state.backTo.startsWith("//")
) {
return {
to: state.backTo,
label:
typeof state.backLabel === "string"
? state.backLabel
: "돌아가기",
};
}
return {
to: fallbackTo,
label: "경기 결과로 돌아가기",
};
}
function createNavigationState(
backTarget: MatchGameBackTarget,
fallbackTo: string,
): MatchGameNavigationState | undefined {
if (backTarget.to === fallbackTo) return undefined;
return {
backTo: backTarget.to,
backLabel: backTarget.label,
};
}
const SKILL_ROWS: Array<{ const SKILL_ROWS: Array<{
slot: 1 | 2 | 3 | 4; slot: 1 | 2 | 3 | 4;
label: string; label: string;
@@ -1924,9 +1972,11 @@ function GameAnalysisPanel({
function GameTabs({ function GameTabs({
detail, detail,
currentGameNumber, currentGameNumber,
navigationState,
}: { }: {
detail: ApiInternalMatchDetailResponse; detail: ApiInternalMatchDetailResponse;
currentGameNumber: number; currentGameNumber: number;
navigationState: MatchGameNavigationState | undefined;
}) { }) {
return ( return (
<nav <nav
@@ -1940,6 +1990,7 @@ function GameTabs({
<Link <Link
key={game.gameNumber} key={game.gameNumber}
to={`/match/${detail.match.matchId}/game/${game.gameNumber}`} to={`/match/${detail.match.matchId}/game/${game.gameNumber}`}
state={navigationState}
className={`min-w-[8rem] border-r border-base-content/8 px-4 py-3 text-xs transition-colors last:border-r-0 ${ className={`min-w-[8rem] border-r border-base-content/8 px-4 py-3 text-xs transition-colors last:border-r-0 ${
active active
? "bg-primary/8 text-primary" ? "bg-primary/8 text-primary"
@@ -1962,9 +2013,13 @@ function GameTabs({
function MatchScoreHero({ function MatchScoreHero({
detail, detail,
selectedGame, selectedGame,
backTarget,
navigationState,
}: { }: {
detail: ApiInternalMatchDetailResponse; detail: ApiInternalMatchDetailResponse;
selectedGame: MatchGameDetail; selectedGame: MatchGameDetail;
backTarget: MatchGameBackTarget;
navigationState: MatchGameNavigationState | undefined;
}) { }) {
const selectedSeries = resolveSelectedSeries(detail, selectedGame); const selectedSeries = resolveSelectedSeries(detail, selectedGame);
const [leftTeam, rightTeam] = selectedGame.teams; const [leftTeam, rightTeam] = selectedGame.teams;
@@ -1982,10 +2037,10 @@ function MatchScoreHero({
<div className="flex flex-col gap-5 lg:flex-row lg:items-center lg:justify-between"> <div className="flex flex-col gap-5 lg:flex-row lg:items-center lg:justify-between">
<div className="min-w-0"> <div className="min-w-0">
<Link <Link
to={`/match/${detail.match.matchId}`} to={backTarget.to}
className="text-xs text-base-content/40 hover:text-base-content" className="text-xs text-base-content/40 hover:text-base-content"
> >
← 경기 결과로 돌아가기 ← {backTarget.label}
</Link> </Link>
<h1 className="mt-4 text-2xl font-black text-base-content"> <h1 className="mt-4 text-2xl font-black text-base-content">
{detail.match.title} · {selectedGame.gameNumber}세트 {detail.match.title} · {selectedGame.gameNumber}세트
@@ -2040,18 +2095,26 @@ function MatchScoreHero({
</div> </div>
)} )}
</div> </div>
<GameTabs detail={detail} currentGameNumber={selectedGame.gameNumber} /> <GameTabs
detail={detail}
currentGameNumber={selectedGame.gameNumber}
navigationState={navigationState}
/>
</section> </section>
); );
} }
export default function MatchGameDetailPage() { export default function MatchGameDetailPage() {
const { id, gameNumber } = useParams(); const { id, gameNumber } = useParams();
const location = useLocation();
const [activeTab, setActiveTab] = useState<DetailTab>("scoreboard"); const [activeTab, setActiveTab] = useState<DetailTab>("scoreboard");
const requestedGameNumber = Number(gameNumber); const requestedGameNumber = Number(gameNumber);
const detailQuery = useInternalMatchDetail(id, DEFAULT_COMMUNITY_ID); const detailQuery = useInternalMatchDetail(id, DEFAULT_COMMUNITY_ID);
const { data: ddragon } = useDdragonManifest(); const { data: ddragon } = useDdragonManifest();
const detail = detailQuery.data; const detail = detailQuery.data;
const fallbackBackTo = `/match/${id ?? ""}`;
const backTarget = resolveBackTarget(location.state, fallbackBackTo);
const navigationState = createNavigationState(backTarget, fallbackBackTo);
if (detailQuery.isLoading) { if (detailQuery.isLoading) {
return ( return (
@@ -2065,8 +2128,8 @@ export default function MatchGameDetailPage() {
return ( return (
<main className="mx-auto max-w-6xl px-4 py-20 text-center"> <main className="mx-auto max-w-6xl px-4 py-20 text-center">
<h1 className="text-lg font-bold">세트 기록을 찾을 수 없습니다</h1> <h1 className="text-lg font-bold">세트 기록을 찾을 수 없습니다</h1>
<Link to={`/match/${id ?? ""}`} className="btn btn-ghost btn-sm mt-4"> <Link to={backTarget.to} className="btn btn-ghost btn-sm mt-4">
경기 결과로 돌아가기 {backTarget.label}
</Link> </Link>
</main> </main>
); );
@@ -2081,10 +2144,10 @@ export default function MatchGameDetailPage() {
<main className="mx-auto max-w-6xl px-4 py-20 text-center"> <main className="mx-auto max-w-6xl px-4 py-20 text-center">
<h1 className="text-lg font-bold">수집된 세트 기록이 없습니다</h1> <h1 className="text-lg font-bold">수집된 세트 기록이 없습니다</h1>
<Link <Link
to={`/match/${detail.match.matchId}`} to={backTarget.to}
className="btn btn-ghost btn-sm mt-4" className="btn btn-ghost btn-sm mt-4"
> >
경기 결과로 돌아가기 {backTarget.label}
</Link> </Link>
</main> </main>
); );
@@ -2092,7 +2155,12 @@ export default function MatchGameDetailPage() {
return ( return (
<main className="mx-auto max-w-6xl px-4 py-6 sm:px-6"> <main className="mx-auto max-w-6xl px-4 py-6 sm:px-6">
<MatchScoreHero detail={detail} selectedGame={selectedGame} /> <MatchScoreHero
detail={detail}
selectedGame={selectedGame}
backTarget={backTarget}
navigationState={navigationState}
/>
<PostgameBreakdown <PostgameBreakdown
selectedGame={selectedGame} selectedGame={selectedGame}
+890 -17
View File
File diff suppressed because it is too large. Load diff