Compare commits
8
Commits
release/82
...
release/83
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8567948084 | ||
|
|
37f1f4225d | ||
|
|
6dbc643c44 | ||
|
|
d2fc126fed | ||
|
|
ab721873f3 | ||
|
|
2984bd1604 | ||
|
|
e50a683336 | ||
|
|
9c69e35cfa |
No files matched your search
+1
-1
@@ -1 +1 @@
|
||||
77
|
||||
83
|
||||
+8
-1
@@ -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/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 --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 --chown=nonroot:nonroot apps/project.env ./project.env
|
||||
|
||||
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"]
|
||||
@@ -4,7 +4,7 @@ LOLYMPUS는 리그 오브 레전드 커뮤니티의 여러 이벤트 중 내전(
|
||||
|
||||
<p align="center">
|
||||
<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"
|
||||
width="960"
|
||||
autoplay="autoplay"
|
||||
@@ -13,20 +13,20 @@ LOLYMPUS는 리그 오브 레전드 커뮤니티의 여러 이벤트 중 내전(
|
||||
playsinline="playsinline"
|
||||
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>
|
||||
</p>
|
||||
|
||||
<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>
|
||||
|
||||
## 배포 주소
|
||||
|
||||
| Environment | Version | URL |
|
||||
| ----------- | ------- | -------------------------------------- |
|
||||
| Production | v77 | <https://lolympus.dahyeon.us/> |
|
||||
| Staging | v77 | <https://890c50be.lolympus.pages.dev/> |
|
||||
| Production | v83 | <https://lolympus.dahyeon.us/> |
|
||||
| Staging | v83 | <https://release-83.lolympus.pages.dev/> |
|
||||
|
||||
## 개요
|
||||
|
||||
@@ -128,6 +128,23 @@ pnpm start:web:dev
|
||||
|
||||
웹 앱은 기본적으로 `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 서버와 연결되어 있지 않으면 일정 조회, 내전 참가, 참가 취소, 계정 등록 같은 카카오톡 명령어는 사용할 수 없습니다.
|
||||
|
||||
## 커맨드
|
||||
|
||||
@@ -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*',
|
||||
],
|
||||
},
|
||||
};
|
||||
@@ -10,9 +10,9 @@
|
||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||
"seed:dev": "ts-node src/seed.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:staging": "node -e \"process.env.NODE_ENV='staging'; require('./dist/main.js')\"",
|
||||
"start:prod": "node -e \"process.env.NODE_ENV='prod'; 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_ENV=staging NEW_RELIC_HOME=. node --import newrelic/esm-loader.mjs -r newrelic 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: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",
|
||||
@@ -38,6 +38,7 @@
|
||||
"jose": "^6.2.2",
|
||||
"mongoose": "^9.4.1",
|
||||
"nats": "^2.29.3",
|
||||
"newrelic": "^14.1.2",
|
||||
"redis": "^5.12.1",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.1",
|
||||
|
||||
@@ -92,7 +92,10 @@ describe('auction durability projection helpers', () => {
|
||||
it.each([
|
||||
{ current: { auctionLifecycleId: 'life-1', revision: 8 }, expected: true },
|
||||
{ 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 }) => {
|
||||
expect(shouldApplyAuctionProjection(current, payload)).toBe(expected);
|
||||
});
|
||||
@@ -100,14 +103,23 @@ describe('auction durability projection helpers', () => {
|
||||
it.each([
|
||||
{ current: { auctionLifecycleId: 'life-1', revision: 8 }, 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 },
|
||||
])('decides whether a durability payload can be processed %#', ({ current, expected }) => {
|
||||
expect(shouldProcessAuctionDurabilityPayload(current, payload)).toBe(
|
||||
expected,
|
||||
);
|
||||
});
|
||||
])(
|
||||
'decides whether a durability payload can be processed %#',
|
||||
({ current, expected }) => {
|
||||
expect(shouldProcessAuctionDurabilityPayload(current, payload)).toBe(
|
||||
expected,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it('reads due durability payload keys from Redis', async () => {
|
||||
const sendCommand = jest.fn().mockResolvedValue(['payload-1']);
|
||||
@@ -333,7 +345,10 @@ describe('auction durability projection helpers', () => {
|
||||
createSession: jest.fn().mockResolvedValue(session),
|
||||
getModel: jest.fn((name: string) => {
|
||||
if (name === 'auctionHistory') {
|
||||
return { deleteMany: historyDeleteMany, updateOne: historyUpdateOne };
|
||||
return {
|
||||
deleteMany: historyDeleteMany,
|
||||
updateOne: historyUpdateOne,
|
||||
};
|
||||
}
|
||||
if (name === 'auction') {
|
||||
return { findById: auctionFindById, updateOne: auctionUpdateOne };
|
||||
@@ -404,7 +419,10 @@ describe('auction durability projection helpers', () => {
|
||||
createSession: jest.fn().mockResolvedValue(session),
|
||||
getModel: jest.fn((name: string) => {
|
||||
if (name === 'auctionHistory') {
|
||||
return { deleteMany: historyDeleteMany, updateOne: historyUpdateOne };
|
||||
return {
|
||||
deleteMany: historyDeleteMany,
|
||||
updateOne: historyUpdateOne,
|
||||
};
|
||||
}
|
||||
if (name === 'auction') {
|
||||
return { findById: auctionFindById, updateOne: auctionUpdateOne };
|
||||
@@ -428,6 +446,216 @@ describe('auction durability projection helpers', () => {
|
||||
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 () => {
|
||||
const sendCommand = jest
|
||||
.fn()
|
||||
@@ -613,7 +841,9 @@ describe('auction durability projection helpers', () => {
|
||||
.spyOn(scheduler, 'processDueDurabilityPayloads')
|
||||
.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 = (
|
||||
scheduler as unknown as {
|
||||
@@ -649,7 +879,9 @@ describe('auction durability projection helpers', () => {
|
||||
.spyOn(scheduler, 'processDueDurabilityPayloads')
|
||||
.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 = (
|
||||
scheduler as unknown as {
|
||||
@@ -747,7 +979,8 @@ describe('auction durability projection helpers', () => {
|
||||
if (name === 'auctionSideEffectApplication') {
|
||||
return { updateOne: sideEffectUpdateOne };
|
||||
}
|
||||
if (name === 'match') return { findById: jest.fn().mockReturnValue(match) };
|
||||
if (name === 'match')
|
||||
return { findById: jest.fn().mockReturnValue(match) };
|
||||
return {};
|
||||
}),
|
||||
} as never,
|
||||
@@ -829,26 +1062,18 @@ describe('auction durability projection helpers', () => {
|
||||
matchSideEffectRevision: 3,
|
||||
matchSideEffectStatus: 'completed',
|
||||
});
|
||||
expect(broadcastMatchSideEffect).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
'match-1',
|
||||
{
|
||||
auctionLifecycleId: 'life-1',
|
||||
currentServerTimestampMS: 2000,
|
||||
matchSideEffectRevision: 2,
|
||||
matchSideEffectStatus: 'processing',
|
||||
},
|
||||
);
|
||||
expect(broadcastMatchSideEffect).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
'match-1',
|
||||
{
|
||||
auctionLifecycleId: 'life-1',
|
||||
currentServerTimestampMS: 3000,
|
||||
matchSideEffectRevision: 3,
|
||||
matchSideEffectStatus: 'completed',
|
||||
},
|
||||
);
|
||||
expect(broadcastMatchSideEffect).toHaveBeenNthCalledWith(1, 'match-1', {
|
||||
auctionLifecycleId: 'life-1',
|
||||
currentServerTimestampMS: 2000,
|
||||
matchSideEffectRevision: 2,
|
||||
matchSideEffectStatus: 'processing',
|
||||
});
|
||||
expect(broadcastMatchSideEffect).toHaveBeenNthCalledWith(2, 'match-1', {
|
||||
auctionLifecycleId: 'life-1',
|
||||
currentServerTimestampMS: 3000,
|
||||
matchSideEffectRevision: 3,
|
||||
matchSideEffectStatus: 'completed',
|
||||
});
|
||||
expect(sendCommand).toHaveBeenCalledWith([
|
||||
'EVAL',
|
||||
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 () => {
|
||||
const resetPayload = {
|
||||
...payload,
|
||||
@@ -943,7 +1263,10 @@ describe('auction durability projection helpers', () => {
|
||||
createSession: jest.fn().mockResolvedValue(null),
|
||||
getModel: jest.fn((name: string) => {
|
||||
if (name === 'auctionHistory') {
|
||||
return { deleteMany: historyDeleteMany, updateOne: historyUpdateOne };
|
||||
return {
|
||||
deleteMany: historyDeleteMany,
|
||||
updateOne: historyUpdateOne,
|
||||
};
|
||||
}
|
||||
if (name === 'auction') {
|
||||
return {
|
||||
@@ -955,7 +1278,8 @@ describe('auction durability projection helpers', () => {
|
||||
if (name === 'auctionSideEffectApplication') {
|
||||
return { updateOne: sideEffectUpdateOne };
|
||||
}
|
||||
if (name === 'match') return { findById: jest.fn().mockReturnValue(match) };
|
||||
if (name === 'match')
|
||||
return { findById: jest.fn().mockReturnValue(match) };
|
||||
return {};
|
||||
}),
|
||||
} as never,
|
||||
@@ -985,7 +1309,10 @@ describe('auction durability projection helpers', () => {
|
||||
teams: [],
|
||||
tournamentCodeIds: [],
|
||||
});
|
||||
expect(match.participants).toEqual([{ excluded: false }, { excluded: false }]);
|
||||
expect(match.participants).toEqual([
|
||||
{ excluded: false },
|
||||
{ excluded: false },
|
||||
]);
|
||||
expect(match.save).toHaveBeenCalledTimes(1);
|
||||
expect(sideEffectUpdateOne).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
|
||||
@@ -29,6 +29,8 @@ import {
|
||||
AUCTION_DURABILITY_RETRY_QUEUE_KEY,
|
||||
buildAuctionRedisKeys,
|
||||
} from './redis/auction-redis.keys';
|
||||
// [AUCTION-DEBUG] 경매 "중복 멤버" 조사용 임시 계측. 조사 종료 후 제거 대상.
|
||||
import { recordNewRelicCustomEvent } from '../global/observability/new-relic';
|
||||
const AUCTION_DURABILITY_TICK_INTERVAL_MS = 1000;
|
||||
const AUCTION_DURABILITY_BATCH_LIMIT = 20;
|
||||
const AUCTION_DURABILITY_RETRY_DELAY_MS = 5000;
|
||||
@@ -128,15 +130,17 @@ export class AuctionDurabilityScheduler
|
||||
currentRedisTimestampMS: number,
|
||||
batchLimit: number,
|
||||
): Promise<string[]> {
|
||||
const reply = await this.auctionRedisService.raw().sendCommand([
|
||||
'ZRANGEBYSCORE',
|
||||
AUCTION_DURABILITY_RETRY_QUEUE_KEY,
|
||||
'-inf',
|
||||
String(currentRedisTimestampMS),
|
||||
'LIMIT',
|
||||
'0',
|
||||
String(batchLimit),
|
||||
]);
|
||||
const reply = await this.auctionRedisService
|
||||
.raw()
|
||||
.sendCommand([
|
||||
'ZRANGEBYSCORE',
|
||||
AUCTION_DURABILITY_RETRY_QUEUE_KEY,
|
||||
'-inf',
|
||||
String(currentRedisTimestampMS),
|
||||
'LIMIT',
|
||||
'0',
|
||||
String(batchLimit),
|
||||
]);
|
||||
return Array.isArray(reply) ? reply.map(String) : [];
|
||||
}
|
||||
|
||||
@@ -165,15 +169,29 @@ export class AuctionDurabilityScheduler
|
||||
}
|
||||
await this.applyDurabilityPayload(payload);
|
||||
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);
|
||||
} catch (error) {
|
||||
failed += 1;
|
||||
const failureDisposition =
|
||||
await this.recordDurabilityPayloadFailure(
|
||||
payloadKey,
|
||||
currentRedisTimestampMS,
|
||||
error,
|
||||
);
|
||||
const failureDisposition = await this.recordDurabilityPayloadFailure(
|
||||
payloadKey,
|
||||
currentRedisTimestampMS,
|
||||
error,
|
||||
);
|
||||
this.logger.warn(
|
||||
`Auction durability payload failed for ${payloadKey} (${failureDisposition}): ${
|
||||
error instanceof Error ? error.message : error
|
||||
@@ -195,7 +213,9 @@ export class AuctionDurabilityScheduler
|
||||
const payloadJson = hash.payloadJson;
|
||||
if (!payloadJson) return null;
|
||||
const payload = JSON.parse(payloadJson) as AuctionDurabilityPayload;
|
||||
const committedAtRedisTimestampMS = Number(hash.committedAtRedisTimestampMS);
|
||||
const committedAtRedisTimestampMS = Number(
|
||||
hash.committedAtRedisTimestampMS,
|
||||
);
|
||||
if (Number.isFinite(committedAtRedisTimestampMS)) {
|
||||
payload.committedAtRedisTimestampMS = committedAtRedisTimestampMS;
|
||||
}
|
||||
@@ -222,13 +242,31 @@ export class AuctionDurabilityScheduler
|
||||
|
||||
try {
|
||||
session?.startTransaction();
|
||||
const historyMutation = parseAuctionHistoryMutation(
|
||||
payload.historyMutation,
|
||||
);
|
||||
if (typeof AuctionModel.findById === 'function') {
|
||||
const currentProjection = await readAuctionProjectionIdentityForMutation(
|
||||
AuctionModel,
|
||||
payload.auctionId,
|
||||
session,
|
||||
);
|
||||
if (!shouldProcessAuctionDurabilityPayload(currentProjection, payload)) {
|
||||
const currentProjection =
|
||||
await readAuctionProjectionIdentityForMutation(
|
||||
AuctionModel,
|
||||
payload.auctionId,
|
||||
session,
|
||||
);
|
||||
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();
|
||||
return;
|
||||
}
|
||||
@@ -370,15 +408,17 @@ export class AuctionDurabilityScheduler
|
||||
);
|
||||
if (!hasMatchedDocument(leaseResult)) return;
|
||||
|
||||
const processingDelta = await this.persistAndBroadcastMatchSideEffectStatus({
|
||||
AuctionModel,
|
||||
currentServerTimestampMS: currentRedisTimestampMS,
|
||||
expectedMatchSideEffectRevision: Number(
|
||||
payload.afterAuctionMongoProjection.matchSideEffectRevision ?? 0,
|
||||
),
|
||||
payload,
|
||||
status: 'processing',
|
||||
});
|
||||
const processingDelta = await this.persistAndBroadcastMatchSideEffectStatus(
|
||||
{
|
||||
AuctionModel,
|
||||
currentServerTimestampMS: currentRedisTimestampMS,
|
||||
expectedMatchSideEffectRevision: Number(
|
||||
payload.afterAuctionMongoProjection.matchSideEffectRevision ?? 0,
|
||||
),
|
||||
payload,
|
||||
status: 'processing',
|
||||
},
|
||||
);
|
||||
if (!processingDelta) return;
|
||||
let expectedMatchSideEffectRevision =
|
||||
processingDelta.matchSideEffectRevision;
|
||||
@@ -396,11 +436,36 @@ export class AuctionDurabilityScheduler
|
||||
teamBuiltAt?: Date;
|
||||
teams: ReturnType<typeof buildMatchTeamsFromProjection>;
|
||||
} | null;
|
||||
if (!match) throw new Error(`Match not found: ${String(payload.matchId)}`);
|
||||
match.teams = buildMatchTeamsFromProjection(
|
||||
if (!match)
|
||||
throw new Error(`Match not found: ${String(payload.matchId)}`);
|
||||
const matchTeams = buildMatchTeamsFromProjection(
|
||||
payload.afterAuctionMongoProjection,
|
||||
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.teamBuiltAt = match.teamBuiltAt ?? new Date();
|
||||
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(
|
||||
payload: AuctionDurabilityPayload,
|
||||
mutation: ParsedMatchSideEffectMutation,
|
||||
@@ -553,15 +687,18 @@ export class AuctionDurabilityScheduler
|
||||
);
|
||||
if (!hasMatchedDocument(leaseResult)) return;
|
||||
|
||||
const processingDelta = await this.persistAndBroadcastMatchSideEffectStatus({
|
||||
AuctionModel,
|
||||
currentServerTimestampMS: currentRedisTimestampMS,
|
||||
expectedMatchSideEffectRevision: Number(
|
||||
params.payload.afterAuctionMongoProjection.matchSideEffectRevision ?? 0,
|
||||
),
|
||||
payload: params.payload,
|
||||
status: 'processing',
|
||||
});
|
||||
const processingDelta = await this.persistAndBroadcastMatchSideEffectStatus(
|
||||
{
|
||||
AuctionModel,
|
||||
currentServerTimestampMS: currentRedisTimestampMS,
|
||||
expectedMatchSideEffectRevision: Number(
|
||||
params.payload.afterAuctionMongoProjection.matchSideEffectRevision ??
|
||||
0,
|
||||
),
|
||||
payload: params.payload,
|
||||
status: 'processing',
|
||||
},
|
||||
);
|
||||
if (!processingDelta) return;
|
||||
let expectedMatchSideEffectRevision =
|
||||
processingDelta.matchSideEffectRevision;
|
||||
@@ -605,7 +742,8 @@ export class AuctionDurabilityScheduler
|
||||
} catch (error) {
|
||||
const failureTimestampMS =
|
||||
await this.auctionRedisService.getCurrentRedisTimestampMS();
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : String(error);
|
||||
await execMaybe(
|
||||
AuctionSideEffectApplicationModel.updateOne(
|
||||
identity as never,
|
||||
@@ -658,7 +796,9 @@ export class AuctionDurabilityScheduler
|
||||
payload: AuctionDurabilityPayload;
|
||||
session: mongoose.ClientSession | null | undefined;
|
||||
}): Promise<void> {
|
||||
const mutation = parseAuctionHistoryMutation(params.payload.historyMutation);
|
||||
const mutation = parseAuctionHistoryMutation(
|
||||
params.payload.historyMutation,
|
||||
);
|
||||
if (isDestructiveHistoryMutation(mutation)) {
|
||||
if (mutation.type === 'deleteAfterSequenceAndAppendUndo') {
|
||||
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(
|
||||
params.AuctionHistoryModel.updateOne(
|
||||
historyOperation.filter as never,
|
||||
@@ -731,7 +873,9 @@ export class AuctionDurabilityScheduler
|
||||
: {}),
|
||||
matchSideEffectStatus: params.status,
|
||||
},
|
||||
...(params.errorMessage ? {} : { $unset: { matchSideEffectError: '' } }),
|
||||
...(params.errorMessage
|
||||
? {}
|
||||
: { $unset: { matchSideEffectError: '' } }),
|
||||
} as never,
|
||||
{
|
||||
projection: {
|
||||
@@ -742,13 +886,11 @@ export class AuctionDurabilityScheduler
|
||||
returnDocument: 'after',
|
||||
} as never,
|
||||
),
|
||||
)) as
|
||||
| {
|
||||
auctionLifecycleId?: string;
|
||||
matchSideEffectRevision?: number;
|
||||
matchSideEffectStatus?: AuctionMatchSideEffectStatus;
|
||||
}
|
||||
| null;
|
||||
)) as {
|
||||
auctionLifecycleId?: string;
|
||||
matchSideEffectRevision?: number;
|
||||
matchSideEffectStatus?: AuctionMatchSideEffectStatus;
|
||||
} | null;
|
||||
if (!updatedAuction?.auctionLifecycleId) return null;
|
||||
|
||||
const delta = buildMatchSideEffectDelta({
|
||||
@@ -815,12 +957,14 @@ export class AuctionDurabilityScheduler
|
||||
payloadKey: string,
|
||||
retryAtRedisTimestampMS: number,
|
||||
): Promise<void> {
|
||||
await this.auctionRedisService.raw().sendCommand([
|
||||
'ZADD',
|
||||
AUCTION_DURABILITY_RETRY_QUEUE_KEY,
|
||||
String(retryAtRedisTimestampMS),
|
||||
payloadKey,
|
||||
]);
|
||||
await this.auctionRedisService
|
||||
.raw()
|
||||
.sendCommand([
|
||||
'ZADD',
|
||||
AUCTION_DURABILITY_RETRY_QUEUE_KEY,
|
||||
String(retryAtRedisTimestampMS),
|
||||
payloadKey,
|
||||
]);
|
||||
}
|
||||
|
||||
private async recordDurabilityPayloadFailure(
|
||||
@@ -829,43 +973,44 @@ export class AuctionDurabilityScheduler
|
||||
error: unknown,
|
||||
): Promise<'dead-lettered' | 'requeued'> {
|
||||
const errorMessage = formatErrorMessageForRedis(error);
|
||||
const attemptReply = await this.auctionRedisService.raw().sendCommand([
|
||||
'HINCRBY',
|
||||
payloadKey,
|
||||
'attempts',
|
||||
'1',
|
||||
]);
|
||||
const attemptReply = await this.auctionRedisService
|
||||
.raw()
|
||||
.sendCommand(['HINCRBY', payloadKey, 'attempts', '1']);
|
||||
const attempts = Number(attemptReply);
|
||||
await this.auctionRedisService.raw().sendCommand([
|
||||
'HSET',
|
||||
payloadKey,
|
||||
'lastError',
|
||||
errorMessage,
|
||||
'lastFailedAtRedisTimestampMS',
|
||||
String(currentRedisTimestampMS),
|
||||
]);
|
||||
await this.auctionRedisService
|
||||
.raw()
|
||||
.sendCommand([
|
||||
'HSET',
|
||||
payloadKey,
|
||||
'lastError',
|
||||
errorMessage,
|
||||
'lastFailedAtRedisTimestampMS',
|
||||
String(currentRedisTimestampMS),
|
||||
]);
|
||||
|
||||
if (
|
||||
Number.isFinite(attempts) &&
|
||||
attempts >= AUCTION_DURABILITY_MAX_ATTEMPTS
|
||||
) {
|
||||
await this.auctionRedisService.raw().sendCommand([
|
||||
'ZREM',
|
||||
AUCTION_DURABILITY_RETRY_QUEUE_KEY,
|
||||
payloadKey,
|
||||
]);
|
||||
await this.auctionRedisService.raw().sendCommand([
|
||||
'HSET',
|
||||
payloadKey,
|
||||
'deadLetteredAtRedisTimestampMS',
|
||||
String(currentRedisTimestampMS),
|
||||
]);
|
||||
await this.auctionRedisService.raw().sendCommand([
|
||||
'ZADD',
|
||||
AUCTION_DURABILITY_DEAD_LETTER_QUEUE_KEY,
|
||||
String(currentRedisTimestampMS),
|
||||
payloadKey,
|
||||
]);
|
||||
await this.auctionRedisService
|
||||
.raw()
|
||||
.sendCommand(['ZREM', AUCTION_DURABILITY_RETRY_QUEUE_KEY, payloadKey]);
|
||||
await this.auctionRedisService
|
||||
.raw()
|
||||
.sendCommand([
|
||||
'HSET',
|
||||
payloadKey,
|
||||
'deadLetteredAtRedisTimestampMS',
|
||||
String(currentRedisTimestampMS),
|
||||
]);
|
||||
await this.auctionRedisService
|
||||
.raw()
|
||||
.sendCommand([
|
||||
'ZADD',
|
||||
AUCTION_DURABILITY_DEAD_LETTER_QUEUE_KEY,
|
||||
String(currentRedisTimestampMS),
|
||||
payloadKey,
|
||||
]);
|
||||
return 'dead-lettered';
|
||||
}
|
||||
|
||||
@@ -881,38 +1026,40 @@ export class AuctionDurabilityScheduler
|
||||
): Promise<void> {
|
||||
const matchId = String(payload.matchId);
|
||||
const keys = buildAuctionRedisKeys(matchId);
|
||||
await this.auctionRedisService.raw().sendCommand([
|
||||
'EVAL',
|
||||
[
|
||||
"local expectedAuctionLifecycleId = ARGV[2]",
|
||||
"local currentAuctionLifecycleId = redis.call('HGET', KEYS[1], 'auctionLifecycleId')",
|
||||
"if currentAuctionLifecycleId ~= expectedAuctionLifecycleId then",
|
||||
' return 0',
|
||||
'end',
|
||||
"redis.call('ZREM', KEYS[2], ARGV[1])",
|
||||
'for index = 1, #KEYS do',
|
||||
' if index ~= 2 then',
|
||||
" redis.call('EXPIRE', KEYS[index], ARGV[3])",
|
||||
' end',
|
||||
'end',
|
||||
'return 1',
|
||||
].join('\n'),
|
||||
'11',
|
||||
keys.liveStateKey,
|
||||
keys.deadlineQueueKey,
|
||||
keys.structureStateKey,
|
||||
keys.appliedTransitionIdsKey,
|
||||
keys.bidHistoryKey,
|
||||
keys.bidRequestResultsKey,
|
||||
keys.bidRequestResultOrderKey,
|
||||
keys.actionRequestResultsKey,
|
||||
keys.actionRequestResultOrderKey,
|
||||
keys.rehydrateLockKey,
|
||||
keys.stateTransitionLockKey,
|
||||
matchId,
|
||||
payload.auctionLifecycleId,
|
||||
String(AUCTION_REDIS_COMPLETED_RETAIN_SECONDS),
|
||||
]);
|
||||
await this.auctionRedisService
|
||||
.raw()
|
||||
.sendCommand([
|
||||
'EVAL',
|
||||
[
|
||||
'local expectedAuctionLifecycleId = ARGV[2]',
|
||||
"local currentAuctionLifecycleId = redis.call('HGET', KEYS[1], 'auctionLifecycleId')",
|
||||
'if currentAuctionLifecycleId ~= expectedAuctionLifecycleId then',
|
||||
' return 0',
|
||||
'end',
|
||||
"redis.call('ZREM', KEYS[2], ARGV[1])",
|
||||
'for index = 1, #KEYS do',
|
||||
' if index ~= 2 then',
|
||||
" redis.call('EXPIRE', KEYS[index], ARGV[3])",
|
||||
' end',
|
||||
'end',
|
||||
'return 1',
|
||||
].join('\n'),
|
||||
'11',
|
||||
keys.liveStateKey,
|
||||
keys.deadlineQueueKey,
|
||||
keys.structureStateKey,
|
||||
keys.appliedTransitionIdsKey,
|
||||
keys.bidHistoryKey,
|
||||
keys.bidRequestResultsKey,
|
||||
keys.bidRequestResultOrderKey,
|
||||
keys.actionRequestResultsKey,
|
||||
keys.actionRequestResultOrderKey,
|
||||
keys.rehydrateLockKey,
|
||||
keys.stateTransitionLockKey,
|
||||
matchId,
|
||||
payload.auctionLifecycleId,
|
||||
String(AUCTION_REDIS_COMPLETED_RETAIN_SECONDS),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -961,7 +1108,9 @@ export function parseAuctionHistoryMutation(
|
||||
}
|
||||
if (record.type === 'reset') {
|
||||
const resetMode =
|
||||
record.resetMode === 'preserve-audit' ? 'preserve-audit' : 'clear-history';
|
||||
record.resetMode === 'preserve-audit'
|
||||
? 'preserve-audit'
|
||||
: 'clear-history';
|
||||
return { resetMode, type: 'reset' };
|
||||
}
|
||||
return { type: 'append' };
|
||||
@@ -1055,7 +1204,10 @@ export function buildSideEffectApplicationUpsert(
|
||||
payload: AuctionDurabilityPayload,
|
||||
mutation: ParsedMatchSideEffectMutation,
|
||||
) {
|
||||
const identity = buildSideEffectApplicationIdentityFromPayload(payload, mutation);
|
||||
const identity = buildSideEffectApplicationIdentityFromPayload(
|
||||
payload,
|
||||
mutation,
|
||||
);
|
||||
return {
|
||||
filter: identity,
|
||||
update: {
|
||||
@@ -1100,7 +1252,12 @@ function buildSideEffectApplicationIdentityFromPayload(
|
||||
|
||||
function hashStableJson(value: unknown): string {
|
||||
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');
|
||||
}
|
||||
|
||||
@@ -1140,13 +1297,16 @@ function buildMatchTeamsFromProjection(
|
||||
const members: MatchTeamMember[] = [
|
||||
{
|
||||
assignedPosition:
|
||||
(captain?.preferredPositions?.[0]?.position as Position | undefined) ??
|
||||
'MID',
|
||||
(captain?.preferredPositions?.[0]?.position as
|
||||
| Position
|
||||
| undefined) ?? 'MID',
|
||||
cost: 0,
|
||||
userId: captainUserId,
|
||||
},
|
||||
...rawMembers
|
||||
.filter((member) => member.userId?.toString() !== captainUserId.toString())
|
||||
.filter(
|
||||
(member) => member.userId?.toString() !== captainUserId.toString(),
|
||||
)
|
||||
.map((member) => ({
|
||||
assignedPosition: (member.assignedPosition ?? 'MID') as Position,
|
||||
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 (
|
||||
queryOrPromise &&
|
||||
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 () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const auctionFindOne = jest.fn();
|
||||
const { service, auctionRedisCommandService, auctionRedisService } = createService({
|
||||
auction: {
|
||||
findOne: auctionFindOne,
|
||||
},
|
||||
});
|
||||
const { service, auctionRedisCommandService, auctionRedisService } =
|
||||
createService({
|
||||
auction: {
|
||||
findOne: auctionFindOne,
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.placeBid({
|
||||
@@ -266,7 +267,7 @@ describe('AuctionService', () => {
|
||||
});
|
||||
|
||||
expect(match.status).toBe('team-built');
|
||||
expect(match.teamBuiltAt).toBeInstanceOf(Date);
|
||||
expect(match.teamBuiltAt).toBeUndefined();
|
||||
expect(match.save).toHaveBeenCalledTimes(1);
|
||||
expect(tournamentCodeService.reserveForMatch).not.toHaveBeenCalled();
|
||||
expect(tournamentResultService.scheduleInitialPoll).not.toHaveBeenCalled();
|
||||
@@ -542,44 +543,45 @@ describe('AuctionService', () => {
|
||||
}));
|
||||
const auctionDeleteOne = jest.fn().mockResolvedValue({ deletedCount: 1 });
|
||||
const historyDeleteMany = jest.fn().mockResolvedValue({ deletedCount: 2 });
|
||||
const { service, auctionRedisCommandService, auctionRedisService } = createService({
|
||||
match: {
|
||||
findById: jest.fn().mockResolvedValue(match),
|
||||
},
|
||||
user: {
|
||||
find: jest.fn().mockResolvedValue(users),
|
||||
},
|
||||
auction: {
|
||||
create: auctionCreate,
|
||||
deleteOne: auctionDeleteOne,
|
||||
findOne: jest.fn().mockResolvedValue(existingAuction),
|
||||
},
|
||||
auctionHistory: {
|
||||
create: jest.fn().mockResolvedValue(undefined),
|
||||
deleteMany: historyDeleteMany,
|
||||
findOne: jest.fn().mockReturnValue({
|
||||
sort: jest.fn().mockReturnValue({
|
||||
const { service, auctionRedisCommandService, auctionRedisService } =
|
||||
createService({
|
||||
match: {
|
||||
findById: jest.fn().mockResolvedValue(match),
|
||||
},
|
||||
user: {
|
||||
find: jest.fn().mockResolvedValue(users),
|
||||
},
|
||||
auction: {
|
||||
create: auctionCreate,
|
||||
deleteOne: auctionDeleteOne,
|
||||
findOne: jest.fn().mockResolvedValue(existingAuction),
|
||||
},
|
||||
auctionHistory: {
|
||||
create: jest.fn().mockResolvedValue(undefined),
|
||||
deleteMany: historyDeleteMany,
|
||||
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({
|
||||
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({
|
||||
matchId,
|
||||
@@ -800,7 +802,9 @@ describe('AuctionService', () => {
|
||||
findOne: jest.fn().mockResolvedValue(auction),
|
||||
},
|
||||
});
|
||||
auctionRedisStateReaderService.readLiveStateIdentity.mockResolvedValue(null);
|
||||
auctionRedisStateReaderService.readLiveStateIdentity.mockResolvedValue(
|
||||
null,
|
||||
);
|
||||
auctionRedisStateReaderService.readAuctionStateView.mockResolvedValue(
|
||||
redisState,
|
||||
);
|
||||
@@ -870,12 +874,15 @@ describe('AuctionService', () => {
|
||||
phase: 'bidding',
|
||||
revision: 2,
|
||||
};
|
||||
const { service, auctionRedisCommandService, auctionRedisStateReaderService } =
|
||||
createService({
|
||||
auction: {
|
||||
findOne: jest.fn().mockResolvedValue(auction),
|
||||
},
|
||||
});
|
||||
const {
|
||||
service,
|
||||
auctionRedisCommandService,
|
||||
auctionRedisStateReaderService,
|
||||
} = createService({
|
||||
auction: {
|
||||
findOne: jest.fn().mockResolvedValue(auction),
|
||||
},
|
||||
});
|
||||
auctionRedisStateReaderService.readAuctionStateView
|
||||
.mockResolvedValueOnce(presentingState)
|
||||
.mockResolvedValueOnce(biddingState);
|
||||
@@ -973,12 +980,15 @@ describe('AuctionService', () => {
|
||||
currentHighestBidPointAmount: 120,
|
||||
revision: 3,
|
||||
};
|
||||
const { service, auctionRedisCommandService, auctionRedisStateReaderService } =
|
||||
createService({
|
||||
auction: {
|
||||
findOne: jest.fn().mockResolvedValue(auction),
|
||||
},
|
||||
});
|
||||
const {
|
||||
service,
|
||||
auctionRedisCommandService,
|
||||
auctionRedisStateReaderService,
|
||||
} = createService({
|
||||
auction: {
|
||||
findOne: jest.fn().mockResolvedValue(auction),
|
||||
},
|
||||
});
|
||||
auctionRedisStateReaderService.readAuctionStateView
|
||||
.mockResolvedValueOnce(biddingState)
|
||||
.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 () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const captainUserId = new mongoose.Types.ObjectId();
|
||||
@@ -1189,15 +1308,14 @@ describe('AuctionService', () => {
|
||||
auctionRedisStateReaderService,
|
||||
tournamentCodeService,
|
||||
tournamentResultService,
|
||||
} =
|
||||
createService({
|
||||
auction: {
|
||||
findOne: jest.fn().mockResolvedValue(auction),
|
||||
},
|
||||
match: {
|
||||
findById: jest.fn().mockResolvedValue(match),
|
||||
},
|
||||
});
|
||||
} = createService({
|
||||
auction: {
|
||||
findOne: jest.fn().mockResolvedValue(auction),
|
||||
},
|
||||
match: {
|
||||
findById: jest.fn().mockResolvedValue(match),
|
||||
},
|
||||
});
|
||||
auctionRedisStateReaderService.readAuctionStateView
|
||||
.mockResolvedValueOnce(soldState)
|
||||
.mockResolvedValueOnce(completeState);
|
||||
@@ -1377,8 +1495,7 @@ describe('AuctionService', () => {
|
||||
|
||||
const signupOrder = userIds.slice(2).map((userId) => userId.toString());
|
||||
const auctionOrder = auctionCreate.mock.calls[0][0].order.map(
|
||||
(player: { userId: mongoose.Types.ObjectId }) =>
|
||||
player.userId.toString(),
|
||||
(player: { userId: mongoose.Types.ObjectId }) => player.userId.toString(),
|
||||
);
|
||||
|
||||
expect(auctionOrder).not.toEqual(signupOrder);
|
||||
@@ -1647,9 +1764,7 @@ describe('AuctionService', () => {
|
||||
amount: 20,
|
||||
});
|
||||
|
||||
expect(auction.currentDeadline).toEqual(
|
||||
new Date(now.getTime() + 12000),
|
||||
);
|
||||
expect(auction.currentDeadline).toEqual(new Date(now.getTime() + 12000));
|
||||
expect(auction.save).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
@@ -2151,21 +2266,25 @@ describe('AuctionService', () => {
|
||||
const auctionReplaceOne = jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue(undefined),
|
||||
});
|
||||
const { service, connectionService, tournamentCodeService, tournamentResultService } =
|
||||
createService({
|
||||
auction: {
|
||||
findOne: jest.fn().mockReturnValue(auctionFindOneQuery),
|
||||
replaceOne: auctionReplaceOne,
|
||||
findById: jest.fn().mockResolvedValue(restored),
|
||||
},
|
||||
auctionHistory: {
|
||||
findOne: jest.fn().mockReturnValue(historyFindOneQuery),
|
||||
deleteMany: jest.fn().mockReturnValue(historyDeleteManyQuery),
|
||||
},
|
||||
match: {
|
||||
findById: jest.fn().mockReturnValue(matchFindByIdQuery),
|
||||
},
|
||||
});
|
||||
const {
|
||||
service,
|
||||
connectionService,
|
||||
tournamentCodeService,
|
||||
tournamentResultService,
|
||||
} = createService({
|
||||
auction: {
|
||||
findOne: jest.fn().mockReturnValue(auctionFindOneQuery),
|
||||
replaceOne: auctionReplaceOne,
|
||||
findById: jest.fn().mockResolvedValue(restored),
|
||||
},
|
||||
auctionHistory: {
|
||||
findOne: jest.fn().mockReturnValue(historyFindOneQuery),
|
||||
deleteMany: jest.fn().mockReturnValue(historyDeleteManyQuery),
|
||||
},
|
||||
match: {
|
||||
findById: jest.fn().mockReturnValue(matchFindByIdQuery),
|
||||
},
|
||||
});
|
||||
connectionService.createSession.mockResolvedValue(session);
|
||||
|
||||
await expect(
|
||||
@@ -2261,23 +2380,27 @@ describe('AuctionService', () => {
|
||||
}),
|
||||
};
|
||||
const auctionReplaceOne = jest.fn();
|
||||
const { service, connectionService, auctionRedisCommandService, auctionRedisStateReaderService } =
|
||||
createService({
|
||||
auction: {
|
||||
findOne: jest.fn().mockReturnValue({
|
||||
session: jest.fn().mockResolvedValue(auction),
|
||||
}),
|
||||
replaceOne: auctionReplaceOne,
|
||||
},
|
||||
auctionHistory: {
|
||||
findOne: jest.fn().mockReturnValue(historyFindOneQuery),
|
||||
},
|
||||
match: {
|
||||
findById: jest.fn().mockReturnValue({
|
||||
session: jest.fn().mockResolvedValue(match),
|
||||
}),
|
||||
},
|
||||
});
|
||||
const {
|
||||
service,
|
||||
connectionService,
|
||||
auctionRedisCommandService,
|
||||
auctionRedisStateReaderService,
|
||||
} = createService({
|
||||
auction: {
|
||||
findOne: jest.fn().mockReturnValue({
|
||||
session: jest.fn().mockResolvedValue(auction),
|
||||
}),
|
||||
replaceOne: auctionReplaceOne,
|
||||
},
|
||||
auctionHistory: {
|
||||
findOne: jest.fn().mockReturnValue(historyFindOneQuery),
|
||||
},
|
||||
match: {
|
||||
findById: jest.fn().mockReturnValue({
|
||||
session: jest.fn().mockResolvedValue(match),
|
||||
}),
|
||||
},
|
||||
});
|
||||
connectionService.createSession.mockResolvedValue(session);
|
||||
auctionRedisStateReaderService.readAuctionStateView
|
||||
.mockResolvedValueOnce(currentRedisState)
|
||||
@@ -2298,7 +2421,9 @@ describe('AuctionService', () => {
|
||||
).resolves.toBe(restoredRedisState);
|
||||
|
||||
expect(auctionReplaceOne).not.toHaveBeenCalled();
|
||||
expect(auctionRedisCommandService.reserveActionRequest).toHaveBeenCalledWith(
|
||||
expect(
|
||||
auctionRedisCommandService.reserveActionRequest,
|
||||
).toHaveBeenCalledWith(
|
||||
matchId.toString(),
|
||||
expect.objectContaining({
|
||||
auctionActionRequestId: '00000000-0000-4000-8000-000000000070',
|
||||
@@ -2319,9 +2444,7 @@ describe('AuctionService', () => {
|
||||
durationSeconds: 30,
|
||||
mode: 'set-relative',
|
||||
});
|
||||
const durabilityPayload = JSON.parse(
|
||||
transitionInput.durabilityPayloadJson,
|
||||
);
|
||||
const durabilityPayload = JSON.parse(transitionInput.durabilityPayloadJson);
|
||||
expect(durabilityPayload).toMatchObject({
|
||||
auctionActionType: 'undo',
|
||||
historyMutation: {
|
||||
|
||||
@@ -40,6 +40,8 @@ import {
|
||||
import { AuctionRedisService } from './redis/auction-redis.service';
|
||||
import { AuctionRedisStateReaderService } from './redis/auction-redis-state-reader.service';
|
||||
import { shouldHydrateRedisAuctionState } from './redis/auction-redis.state';
|
||||
// [AUCTION-DEBUG] 경매 "중복 멤버" 조사용 임시 계측. 조사 종료 후 제거 대상.
|
||||
import { recordNewRelicCustomEvent } from '../global/observability/new-relic';
|
||||
|
||||
const AUCTION_MAX_TEAM_SIZE = 5;
|
||||
const AUCTION_MIN_BID_POINTS = 10;
|
||||
@@ -230,7 +232,9 @@ export class AuctionService {
|
||||
const activeParticipants = this.applyAuctionCut(match);
|
||||
const desiredAuctionCount = activeParticipants.length;
|
||||
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;
|
||||
if (params.captains.length !== expectedCaptainCount) {
|
||||
@@ -262,7 +266,8 @@ export class AuctionService {
|
||||
const enrichCooldownCutoff = Date.now() - AUCTION_ENRICHMENT_COOLDOWN_MS;
|
||||
const enrichTargets = basePlayerUsers.flatMap((user) => {
|
||||
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 (this.wasRecentlyRefreshed(account, enrichCooldownCutoff)) return [];
|
||||
return [{ userId: user._id, puuid: account.puuid }];
|
||||
@@ -316,8 +321,7 @@ export class AuctionService {
|
||||
const legacyTeams = params.captains.map((c) => ({
|
||||
teamIndex: c.teamIndex,
|
||||
captainUserId: c.userId,
|
||||
points:
|
||||
c.initialTeamBidPointAmount ?? params.initialTeamBidPointAmount,
|
||||
points: c.initialTeamBidPointAmount ?? params.initialTeamBidPointAmount,
|
||||
members: [],
|
||||
}));
|
||||
const auctionTeams = convertLegacyAuctionTeamsToRedisTeams(legacyTeams);
|
||||
@@ -391,26 +395,30 @@ export class AuctionService {
|
||||
});
|
||||
} catch (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) {
|
||||
return raceWinner;
|
||||
}
|
||||
throw new BadRequestException('Auction already exists for this match.');
|
||||
}
|
||||
await this.recordSnapshot(auction, 'start');
|
||||
await this.auctionRedisCommandService.hydrateState(params.matchId.toString(), {
|
||||
auctionHistorySequence: 1,
|
||||
auctionLifecycleId,
|
||||
maximumBidRoundDurationSeconds: params.maximumBidRoundDurationSeconds,
|
||||
liveStatePatch,
|
||||
matchId: params.matchId.toString(),
|
||||
phase: 'presenting',
|
||||
revision: 0,
|
||||
structureStateJson,
|
||||
});
|
||||
await this.auctionRedisCommandService.hydrateState(
|
||||
params.matchId.toString(),
|
||||
{
|
||||
auctionHistorySequence: 1,
|
||||
auctionLifecycleId,
|
||||
maximumBidRoundDurationSeconds: params.maximumBidRoundDurationSeconds,
|
||||
liveStatePatch,
|
||||
matchId: params.matchId.toString(),
|
||||
phase: 'presenting',
|
||||
revision: 0,
|
||||
structureStateJson,
|
||||
},
|
||||
);
|
||||
|
||||
match.status = 'team-built';
|
||||
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
|
||||
await match.save();
|
||||
this.enqueueBackgroundOrderEnrichment({
|
||||
auctionId: auction._id,
|
||||
@@ -624,9 +632,8 @@ export class AuctionService {
|
||||
params: PlaceBidParams,
|
||||
): Promise<AuctionBidDeltaResponse | AuctionStateResponse> {
|
||||
this.assertValidBidPointAmount(params.amount);
|
||||
const redisBidDelta = await this.tryPlaceRedisBidDeltaFromRealtimeState(
|
||||
params,
|
||||
);
|
||||
const redisBidDelta =
|
||||
await this.tryPlaceRedisBidDeltaFromRealtimeState(params);
|
||||
if (redisBidDelta) return redisBidDelta;
|
||||
|
||||
const auction = await this.getByMatchId(params.matchId);
|
||||
@@ -712,11 +719,10 @@ export class AuctionService {
|
||||
const serviceStartedAtMS = performance.now();
|
||||
const matchId = params.matchId.toString();
|
||||
const bidContextReadStartedAtMS = performance.now();
|
||||
const bidContext =
|
||||
await this.auctionRedisStateReaderService.readBidContext(
|
||||
matchId,
|
||||
params.teamIndex,
|
||||
);
|
||||
const bidContext = await this.auctionRedisStateReaderService.readBidContext(
|
||||
matchId,
|
||||
params.teamIndex,
|
||||
);
|
||||
const redisBidContextReadDurationMS =
|
||||
performance.now() - bidContextReadStartedAtMS;
|
||||
if (!bidContext) return null;
|
||||
@@ -905,6 +911,33 @@ export class AuctionService {
|
||||
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;
|
||||
team.members = [
|
||||
...(team.members ?? []),
|
||||
@@ -1321,12 +1354,10 @@ export class AuctionService {
|
||||
if (!session) {
|
||||
throw new InternalServerErrorException('Failed to start DB session.');
|
||||
}
|
||||
let redisRuntimeToClear:
|
||||
| {
|
||||
auctionLifecycleId?: string;
|
||||
matchId: string;
|
||||
}
|
||||
| null = null;
|
||||
let redisRuntimeToClear: {
|
||||
auctionLifecycleId?: string;
|
||||
matchId: string;
|
||||
} | null = null;
|
||||
try {
|
||||
session.startTransaction();
|
||||
const auction = await AuctionModel.findOne({
|
||||
@@ -1349,15 +1380,15 @@ export class AuctionService {
|
||||
await AuctionSideEffectApplicationModel.deleteMany({
|
||||
auctionId: auction._id,
|
||||
}).session(session);
|
||||
await AuctionHistoryModel.deleteMany({ auctionId: auction._id }).session(
|
||||
session,
|
||||
);
|
||||
await AuctionHistoryModel.deleteMany({
|
||||
auctionId: auction._id,
|
||||
}).session(session);
|
||||
await auction.deleteOne({ session });
|
||||
} else {
|
||||
await auction.deleteOne({ session });
|
||||
await AuctionHistoryModel.deleteMany({ auctionId: auction._id }).session(
|
||||
session,
|
||||
);
|
||||
await AuctionHistoryModel.deleteMany({
|
||||
auctionId: auction._id,
|
||||
}).session(session);
|
||||
if (match.status === 'team-built') {
|
||||
await this.tournamentCodeService.releaseFromMatch(match);
|
||||
match.status = 'recruiting';
|
||||
@@ -1410,15 +1441,13 @@ export class AuctionService {
|
||||
throw new InternalServerErrorException('Failed to start DB session.');
|
||||
}
|
||||
|
||||
let redisUndoContext:
|
||||
| {
|
||||
actionRequestParams?: AuctionStructureActionRequestParams;
|
||||
auction: AuctionDocument;
|
||||
snapshot: Record<string, unknown>;
|
||||
targetHistorySequence: number;
|
||||
undoingCompletedAuction: boolean;
|
||||
}
|
||||
| null = null;
|
||||
let redisUndoContext: {
|
||||
actionRequestParams?: AuctionStructureActionRequestParams;
|
||||
auction: AuctionDocument;
|
||||
snapshot: Record<string, unknown>;
|
||||
targetHistorySequence: number;
|
||||
undoingCompletedAuction: boolean;
|
||||
} | null = null;
|
||||
let restored: AuctionDocument | null = null;
|
||||
|
||||
try {
|
||||
@@ -1460,27 +1489,27 @@ export class AuctionService {
|
||||
};
|
||||
await session.commitTransaction();
|
||||
} else {
|
||||
if (undoingCompletedAuction) {
|
||||
await this.tournamentCodeService.releaseFromMatch(match);
|
||||
await this.tournamentResultService.cancelPolling(match);
|
||||
match.status = 'team-built';
|
||||
match.result = undefined;
|
||||
await match.save({ session });
|
||||
}
|
||||
if (undoingCompletedAuction) {
|
||||
await this.tournamentCodeService.releaseFromMatch(match);
|
||||
await this.tournamentResultService.cancelPolling(match);
|
||||
match.status = 'team-built';
|
||||
match.result = undefined;
|
||||
await match.save({ session });
|
||||
}
|
||||
|
||||
await AuctionModel.replaceOne({ _id: auction._id }, snapshot, {
|
||||
session,
|
||||
}).exec();
|
||||
await AuctionHistoryModel.deleteMany({
|
||||
auctionId: auction._id,
|
||||
sequence: { $gt: params.sequence },
|
||||
})
|
||||
.session(session)
|
||||
.exec();
|
||||
await AuctionModel.replaceOne({ _id: auction._id }, snapshot, {
|
||||
session,
|
||||
}).exec();
|
||||
await AuctionHistoryModel.deleteMany({
|
||||
auctionId: auction._id,
|
||||
sequence: { $gt: params.sequence },
|
||||
})
|
||||
.session(session)
|
||||
.exec();
|
||||
|
||||
await session.commitTransaction();
|
||||
restored = await AuctionModel.findById(auction._id);
|
||||
if (!restored) throw new NotFoundException('Auction not found.');
|
||||
await session.commitTransaction();
|
||||
restored = await AuctionModel.findById(auction._id);
|
||||
if (!restored) throw new NotFoundException('Auction not found.');
|
||||
}
|
||||
} catch (err) {
|
||||
await session.abortTransaction();
|
||||
@@ -1534,28 +1563,27 @@ export class AuctionService {
|
||||
const processingOwnerToken = randomUUID();
|
||||
const auctionStateTransitionId = `${params.action}:${expectedAuctionLifecycleId}:${auctionActionRequestId}`;
|
||||
|
||||
const reserved =
|
||||
await this.auctionRedisCommandService.reserveActionRequest(
|
||||
params.matchId,
|
||||
{
|
||||
auctionActionRequestId,
|
||||
auctionActionType: params.action,
|
||||
auctionStateTransitionId,
|
||||
clientObservedAuctionLifecycleId: expectedAuctionLifecycleId,
|
||||
clientObservedCurrentAuctionPlayerOrderIndex:
|
||||
expectedCurrentAuctionPlayerOrderIndex,
|
||||
clientObservedCurrentBidRoundPlayerUserId:
|
||||
expectedCurrentBidRoundPlayerUserId,
|
||||
clientObservedPhase: expectedPhase,
|
||||
clientObservedRevision: expectedRevision,
|
||||
leaseDurationMS: AUCTION_ACTION_REQUEST_LEASE_DURATION_MS,
|
||||
maximumStoredAuctionActionRequestResultCount:
|
||||
AUCTION_MAX_STORED_ACTION_REQUEST_RESULT_COUNT,
|
||||
minimumAuctionActionRequestResultReplayWindowMS:
|
||||
AUCTION_ACTION_REQUEST_REPLAY_WINDOW_MS,
|
||||
processingOwnerToken,
|
||||
},
|
||||
);
|
||||
const reserved = await this.auctionRedisCommandService.reserveActionRequest(
|
||||
params.matchId,
|
||||
{
|
||||
auctionActionRequestId,
|
||||
auctionActionType: params.action,
|
||||
auctionStateTransitionId,
|
||||
clientObservedAuctionLifecycleId: expectedAuctionLifecycleId,
|
||||
clientObservedCurrentAuctionPlayerOrderIndex:
|
||||
expectedCurrentAuctionPlayerOrderIndex,
|
||||
clientObservedCurrentBidRoundPlayerUserId:
|
||||
expectedCurrentBidRoundPlayerUserId,
|
||||
clientObservedPhase: expectedPhase,
|
||||
clientObservedRevision: expectedRevision,
|
||||
leaseDurationMS: AUCTION_ACTION_REQUEST_LEASE_DURATION_MS,
|
||||
maximumStoredAuctionActionRequestResultCount:
|
||||
AUCTION_MAX_STORED_ACTION_REQUEST_RESULT_COUNT,
|
||||
minimumAuctionActionRequestResultReplayWindowMS:
|
||||
AUCTION_ACTION_REQUEST_REPLAY_WINDOW_MS,
|
||||
processingOwnerToken,
|
||||
},
|
||||
);
|
||||
|
||||
if ('rejected' in reserved) {
|
||||
throw new BadRequestException(
|
||||
@@ -1579,8 +1607,7 @@ export class AuctionService {
|
||||
|
||||
return {
|
||||
actionRequest: {
|
||||
observedProcessingLeaseVersion:
|
||||
reserved.observedProcessingLeaseVersion,
|
||||
observedProcessingLeaseVersion: reserved.observedProcessingLeaseVersion,
|
||||
processingOwnerToken,
|
||||
scopeKey: reserved.actionRequestScopeKey,
|
||||
},
|
||||
@@ -1627,7 +1654,10 @@ export class AuctionService {
|
||||
| { durationSeconds: number; mode: 'set-relative' };
|
||||
expectedPhase: string;
|
||||
historyMutation?: Record<string, unknown>;
|
||||
liveStatePatch: Record<string, string | number | boolean | null | undefined>;
|
||||
liveStatePatch: Record<
|
||||
string,
|
||||
string | number | boolean | null | undefined
|
||||
>;
|
||||
matchSideEffectMutation?: Record<string, unknown>;
|
||||
shouldBroadcastStateAfterDurability?: boolean;
|
||||
shouldResetBidRuntime?: boolean;
|
||||
@@ -1644,8 +1674,7 @@ export class AuctionService {
|
||||
const expectedAuctionHistorySequence = this.numberFromState(
|
||||
params.state.currentAuctionHistorySequence,
|
||||
);
|
||||
const auctionHistorySequence =
|
||||
expectedAuctionHistorySequence + 1;
|
||||
const auctionHistorySequence = expectedAuctionHistorySequence + 1;
|
||||
const auctionStateTransitionId =
|
||||
params.actionRequest?.auctionStateTransitionId ||
|
||||
params.auctionStateTransitionId ||
|
||||
@@ -1671,6 +1700,7 @@ export class AuctionService {
|
||||
(params.auction.matchSideEffectRevision ?? 0) + 1;
|
||||
afterAuctionMongoProjection.matchSideEffectError = undefined;
|
||||
}
|
||||
|
||||
const durabilityPayload = {
|
||||
afterAuctionMongoProjection,
|
||||
auctionActionType: params.action,
|
||||
@@ -1695,7 +1725,8 @@ export class AuctionService {
|
||||
),
|
||||
auctionHistorySequence,
|
||||
auctionLifecycleId:
|
||||
params.actionRequest?.expectedAuctionLifecycleId ?? auctionLifecycleId,
|
||||
params.actionRequest?.expectedAuctionLifecycleId ??
|
||||
auctionLifecycleId,
|
||||
auctionStateTransitionId,
|
||||
broadcastStateRevision: expectedRevision + 1,
|
||||
deadline: params.deadline,
|
||||
@@ -1709,7 +1740,8 @@ export class AuctionService {
|
||||
? this.stringFromState(params.state.currentBidRoundPlayerUserId)
|
||||
: undefined),
|
||||
expectedAuctionHistorySequence,
|
||||
expectedPhase: params.actionRequest?.expectedPhase ?? params.expectedPhase,
|
||||
expectedPhase:
|
||||
params.actionRequest?.expectedPhase ?? params.expectedPhase,
|
||||
expectedRevision,
|
||||
liveStatePatch: params.liveStatePatch,
|
||||
matchId,
|
||||
@@ -1719,6 +1751,27 @@ export class AuctionService {
|
||||
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) {
|
||||
// 게이트웨이가 설명적 거부코드로 변환할 수 있도록 내부 code(예: CONFLICT)를
|
||||
// 구조화해 던진다(message만 던지면 code 자리에 풀 문장이 들어가 매핑이 어렵다).
|
||||
@@ -1762,9 +1815,8 @@ export class AuctionService {
|
||||
)) {
|
||||
const teamIndex = this.numberFromState(team.teamIndex);
|
||||
if (teamIndex < 1) continue;
|
||||
clearedTeamLiveStatePatch[
|
||||
`team:${teamIndex}:remainingBidPointAmount`
|
||||
] = 0;
|
||||
clearedTeamLiveStatePatch[`team:${teamIndex}:remainingBidPointAmount`] =
|
||||
0;
|
||||
clearedTeamLiveStatePatch[
|
||||
`team:${teamIndex}:assignedAuctionTeamMemberCount`
|
||||
] = 0;
|
||||
@@ -1829,10 +1881,40 @@ export class AuctionService {
|
||||
-1,
|
||||
);
|
||||
const currentHighestBidPointAmount = this.numberFromState(
|
||||
params.snapshot.currentHighestBidPointAmount ?? params.snapshot.currentBid,
|
||||
params.snapshot.currentHighestBidPointAmount ??
|
||||
params.snapshot.currentBid,
|
||||
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({
|
||||
action: 'undo',
|
||||
actionRequest,
|
||||
@@ -1874,8 +1956,10 @@ export class AuctionService {
|
||||
state: Record<string, unknown>,
|
||||
): Parameters<typeof stringifyAuctionRedisStructureState>[0] {
|
||||
return {
|
||||
auctionPlayerOrder: this.arrayFromState(state.auctionPlayerOrder),
|
||||
auctionTeams: this.arrayFromState(state.auctionTeams),
|
||||
auctionPlayerOrder: this.cloneRedisStructureArray(
|
||||
state.auctionPlayerOrder,
|
||||
),
|
||||
auctionTeams: this.cloneRedisStructureArray(state.auctionTeams),
|
||||
bidRoundExtensionSeconds: this.numberFromState(
|
||||
state.bidRoundExtensionSeconds,
|
||||
5,
|
||||
@@ -1888,34 +1972,37 @@ export class AuctionService {
|
||||
state.initialTeamBidPointAmount,
|
||||
1000,
|
||||
),
|
||||
manualTopTierAuctionPriorityUserIds: this.arrayFromState(
|
||||
manualTopTierAuctionPriorityUserIds: this.cloneRedisStructureArray(
|
||||
state.manualTopTierAuctionPriorityUserIds,
|
||||
),
|
||||
maximumBidRoundDurationSeconds: this.numberFromState(
|
||||
state.maximumBidRoundDurationSeconds,
|
||||
30,
|
||||
),
|
||||
passedAuctionPlayerQueue: this.arrayFromState(
|
||||
passedAuctionPlayerQueue: this.cloneRedisStructureArray(
|
||||
state.passedAuctionPlayerQueue,
|
||||
),
|
||||
topTierAuctionPriorityThreshold:
|
||||
this.isAuctionTopTierThreshold(state.topTierAuctionPriorityThreshold)
|
||||
? state.topTierAuctionPriorityThreshold
|
||||
: 'NONE',
|
||||
topTierAuctionPriorityThreshold: this.isAuctionTopTierThreshold(
|
||||
state.topTierAuctionPriorityThreshold,
|
||||
)
|
||||
? state.topTierAuctionPriorityThreshold
|
||||
: 'NONE',
|
||||
};
|
||||
}
|
||||
|
||||
private buildRedisStructureInputFromAuctionSnapshot(
|
||||
snapshot: Record<string, unknown>,
|
||||
): Parameters<typeof stringifyAuctionRedisStructureState>[0] {
|
||||
const legacyTeams = this.arrayFromState(snapshot.teams);
|
||||
const legacyTeams = this.cloneRedisStructureArray(snapshot.teams);
|
||||
const auctionTeams = this.cloneRedisStructureArray(snapshot.auctionTeams);
|
||||
return {
|
||||
auctionPlayerOrder: this.arrayFromState(
|
||||
auctionPlayerOrder: this.cloneRedisStructureArray(
|
||||
snapshot.auctionPlayerOrder ?? snapshot.order,
|
||||
),
|
||||
auctionTeams: this.arrayFromState(snapshot.auctionTeams).length > 0
|
||||
? this.arrayFromState(snapshot.auctionTeams)
|
||||
: convertLegacyAuctionTeamsToRedisTeams(legacyTeams as never),
|
||||
auctionTeams:
|
||||
auctionTeams.length > 0
|
||||
? auctionTeams
|
||||
: convertLegacyAuctionTeamsToRedisTeams(legacyTeams as never),
|
||||
bidRoundExtensionSeconds: this.numberFromState(
|
||||
snapshot.bidRoundExtensionSeconds ?? snapshot.bidExtensionSeconds,
|
||||
5,
|
||||
@@ -1931,7 +2018,7 @@ export class AuctionService {
|
||||
snapshot.initialTeamBidPointAmount ?? snapshot.initialPoints,
|
||||
1000,
|
||||
),
|
||||
manualTopTierAuctionPriorityUserIds: this.arrayFromState(
|
||||
manualTopTierAuctionPriorityUserIds: this.cloneRedisStructureArray(
|
||||
snapshot.manualTopTierAuctionPriorityUserIds ??
|
||||
snapshot.manualTopTierUserIds,
|
||||
),
|
||||
@@ -1939,14 +2026,14 @@ export class AuctionService {
|
||||
snapshot.maximumBidRoundDurationSeconds ?? snapshot.maxTimerSeconds,
|
||||
30,
|
||||
),
|
||||
passedAuctionPlayerQueue: this.arrayFromState(
|
||||
passedAuctionPlayerQueue: this.cloneRedisStructureArray(
|
||||
snapshot.passedAuctionPlayerQueue ?? snapshot.passedQueue,
|
||||
),
|
||||
topTierAuctionPriorityThreshold: this.isAuctionTopTierThreshold(
|
||||
snapshot.topTierAuctionPriorityThreshold ?? snapshot.topTierThreshold,
|
||||
)
|
||||
? (snapshot.topTierAuctionPriorityThreshold ??
|
||||
snapshot.topTierThreshold) as never
|
||||
? ((snapshot.topTierAuctionPriorityThreshold ??
|
||||
snapshot.topTierThreshold) as never)
|
||||
: 'NONE',
|
||||
};
|
||||
}
|
||||
@@ -2064,7 +2151,9 @@ export class AuctionService {
|
||||
}
|
||||
|
||||
private convertRedisTeamsToLegacyTeams(
|
||||
auctionTeams: Parameters<typeof stringifyAuctionRedisStructureState>[0]['auctionTeams'],
|
||||
auctionTeams: Parameters<
|
||||
typeof stringifyAuctionRedisStructureState
|
||||
>[0]['auctionTeams'],
|
||||
): AuctionTeam[] {
|
||||
return auctionTeams.map((team) => ({
|
||||
captainUserId: team.captainUserId as mongoose.Types.ObjectId,
|
||||
@@ -2090,13 +2179,20 @@ export class AuctionService {
|
||||
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 {
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : fallback;
|
||||
}
|
||||
|
||||
private stringFromState(value: unknown): string {
|
||||
return typeof value === 'string' ? value : value?.toString() ?? '';
|
||||
return typeof value === 'string' ? value : (value?.toString() ?? '');
|
||||
}
|
||||
|
||||
private isAuctionTopTierThreshold(
|
||||
@@ -2218,7 +2314,9 @@ export class AuctionService {
|
||||
({ I: 4, II: 3, III: 2, IV: 1, '': 0 } as Record<string, number>)[
|
||||
solo.rank
|
||||
] ?? 0;
|
||||
return tierIdx * 1000 + rankBonus * 100 + (solo.leaguePoints ?? 0) * 0.001;
|
||||
return (
|
||||
tierIdx * 1000 + rankBonus * 100 + (solo.leaguePoints ?? 0) * 0.001
|
||||
);
|
||||
};
|
||||
|
||||
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 members: MatchTeamMember[] = [
|
||||
{
|
||||
@@ -2531,6 +2629,12 @@ export class AuctionService {
|
||||
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.teamBuiltAt = match.teamBuiltAt ?? new Date();
|
||||
await match.save();
|
||||
@@ -2557,7 +2661,7 @@ export class AuctionService {
|
||||
structureInput.auctionTeams,
|
||||
);
|
||||
|
||||
match.teams = teams.map((team) => {
|
||||
const matchTeams = teams.map((team) => {
|
||||
const captain = participantByUserId.get(team.captainUserId.toString());
|
||||
const members: MatchTeamMember[] = [
|
||||
{
|
||||
@@ -2566,7 +2670,10 @@ export class AuctionService {
|
||||
cost: 0,
|
||||
},
|
||||
...team.members
|
||||
.filter((member) => member.userId.toString() !== team.captainUserId.toString())
|
||||
.filter(
|
||||
(member) =>
|
||||
member.userId.toString() !== team.captainUserId.toString(),
|
||||
)
|
||||
.map((member) => ({
|
||||
userId: member.userId,
|
||||
assignedPosition: member.assignedPosition,
|
||||
@@ -2581,6 +2688,12 @@ export class AuctionService {
|
||||
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.teamBuiltAt = match.teamBuiltAt ?? new Date();
|
||||
await match.save();
|
||||
@@ -2602,7 +2715,8 @@ export class AuctionService {
|
||||
auction.bidRoundExtensionSeconds ?? auction.bidExtensionSeconds ?? 5,
|
||||
currentAuctionPlayerOrderIndex:
|
||||
auction.currentAuctionPlayerOrderIndex ?? auction.currentIndex ?? 0,
|
||||
currentAuctionRound: auction.currentAuctionRound ?? auction.auctionRound ?? 1,
|
||||
currentAuctionRound:
|
||||
auction.currentAuctionRound ?? auction.auctionRound ?? 1,
|
||||
initialTeamBidPointAmount:
|
||||
auction.initialTeamBidPointAmount ?? auction.initialPoints ?? 1000,
|
||||
manualTopTierAuctionPriorityUserIds:
|
||||
@@ -2614,7 +2728,9 @@ export class AuctionService {
|
||||
passedAuctionPlayerQueue:
|
||||
auction.passedAuctionPlayerQueue ?? auction.passedQueue ?? [],
|
||||
topTierAuctionPriorityThreshold:
|
||||
auction.topTierAuctionPriorityThreshold ?? auction.topTierThreshold ?? 'NONE',
|
||||
auction.topTierAuctionPriorityThreshold ??
|
||||
auction.topTierThreshold ??
|
||||
'NONE',
|
||||
};
|
||||
await this.auctionRedisCommandService.hydrateState(
|
||||
auction.matchId.toString(),
|
||||
@@ -2647,35 +2763,37 @@ export class AuctionService {
|
||||
expectedAuctionLifecycleId?: string,
|
||||
): Promise<void> {
|
||||
const keys = buildAuctionRedisKeys(matchId);
|
||||
const cleared = await this.auctionRedisService.raw().sendCommand([
|
||||
'EVAL',
|
||||
[
|
||||
"local expectedAuctionLifecycleId = ARGV[2]",
|
||||
"if expectedAuctionLifecycleId ~= '' then",
|
||||
" local currentAuctionLifecycleId = redis.call('HGET', KEYS[1], 'auctionLifecycleId')",
|
||||
" if currentAuctionLifecycleId and currentAuctionLifecycleId ~= expectedAuctionLifecycleId then",
|
||||
" return 0",
|
||||
' end',
|
||||
'end',
|
||||
"redis.call('ZREM', KEYS[2], ARGV[1])",
|
||||
"redis.call('DEL', KEYS[1], KEYS[3], KEYS[4], KEYS[5], KEYS[6], KEYS[7], KEYS[8], KEYS[9], KEYS[10], KEYS[11])",
|
||||
'return 1',
|
||||
].join('\n'),
|
||||
'11',
|
||||
keys.liveStateKey,
|
||||
keys.deadlineQueueKey,
|
||||
keys.structureStateKey,
|
||||
keys.appliedTransitionIdsKey,
|
||||
keys.bidHistoryKey,
|
||||
keys.bidRequestResultsKey,
|
||||
keys.bidRequestResultOrderKey,
|
||||
keys.actionRequestResultsKey,
|
||||
keys.actionRequestResultOrderKey,
|
||||
keys.rehydrateLockKey,
|
||||
keys.stateTransitionLockKey,
|
||||
matchId,
|
||||
expectedAuctionLifecycleId ?? '',
|
||||
]);
|
||||
const cleared = await this.auctionRedisService
|
||||
.raw()
|
||||
.sendCommand([
|
||||
'EVAL',
|
||||
[
|
||||
'local expectedAuctionLifecycleId = ARGV[2]',
|
||||
"if expectedAuctionLifecycleId ~= '' then",
|
||||
" local currentAuctionLifecycleId = redis.call('HGET', KEYS[1], 'auctionLifecycleId')",
|
||||
' if currentAuctionLifecycleId and currentAuctionLifecycleId ~= expectedAuctionLifecycleId then',
|
||||
' return 0',
|
||||
' end',
|
||||
'end',
|
||||
"redis.call('ZREM', KEYS[2], ARGV[1])",
|
||||
"redis.call('DEL', KEYS[1], KEYS[3], KEYS[4], KEYS[5], KEYS[6], KEYS[7], KEYS[8], KEYS[9], KEYS[10], KEYS[11])",
|
||||
'return 1',
|
||||
].join('\n'),
|
||||
'11',
|
||||
keys.liveStateKey,
|
||||
keys.deadlineQueueKey,
|
||||
keys.structureStateKey,
|
||||
keys.appliedTransitionIdsKey,
|
||||
keys.bidHistoryKey,
|
||||
keys.bidRequestResultsKey,
|
||||
keys.bidRequestResultOrderKey,
|
||||
keys.actionRequestResultsKey,
|
||||
keys.actionRequestResultOrderKey,
|
||||
keys.rehydrateLockKey,
|
||||
keys.stateTransitionLockKey,
|
||||
matchId,
|
||||
expectedAuctionLifecycleId ?? '',
|
||||
]);
|
||||
if (Number(cleared) !== 1) return;
|
||||
await this.clearRedisDurabilityPayloadsForLifecycle(
|
||||
keys,
|
||||
@@ -2689,14 +2807,16 @@ export class AuctionService {
|
||||
): Promise<void> {
|
||||
let cursor = '0';
|
||||
do {
|
||||
const reply = await this.auctionRedisService.raw().sendCommand([
|
||||
'SCAN',
|
||||
cursor,
|
||||
'MATCH',
|
||||
`${keys.durabilityPayloadKeyPrefix}*`,
|
||||
'COUNT',
|
||||
'100',
|
||||
]);
|
||||
const reply = await this.auctionRedisService
|
||||
.raw()
|
||||
.sendCommand([
|
||||
'SCAN',
|
||||
cursor,
|
||||
'MATCH',
|
||||
`${keys.durabilityPayloadKeyPrefix}*`,
|
||||
'COUNT',
|
||||
'100',
|
||||
]);
|
||||
if (!Array.isArray(reply) || reply.length < 2) return;
|
||||
cursor = String(reply[0]);
|
||||
const payloadKeys = Array.isArray(reply[1]) ? reply[1].map(String) : [];
|
||||
@@ -2714,20 +2834,23 @@ export class AuctionService {
|
||||
);
|
||||
if (payloadKeysToDelete.length === 0) continue;
|
||||
|
||||
await this.auctionRedisService.raw().sendCommand([
|
||||
'ZREM',
|
||||
keys.durabilityRetryQueueKey,
|
||||
...payloadKeysToDelete,
|
||||
]);
|
||||
await this.auctionRedisService.raw().sendCommand([
|
||||
'ZREM',
|
||||
keys.durabilityDeadLetterQueueKey,
|
||||
...payloadKeysToDelete,
|
||||
]);
|
||||
await this.auctionRedisService.raw().sendCommand([
|
||||
'DEL',
|
||||
...payloadKeysToDelete,
|
||||
]);
|
||||
await this.auctionRedisService
|
||||
.raw()
|
||||
.sendCommand([
|
||||
'ZREM',
|
||||
keys.durabilityRetryQueueKey,
|
||||
...payloadKeysToDelete,
|
||||
]);
|
||||
await this.auctionRedisService
|
||||
.raw()
|
||||
.sendCommand([
|
||||
'ZREM',
|
||||
keys.durabilityDeadLetterQueueKey,
|
||||
...payloadKeysToDelete,
|
||||
]);
|
||||
await this.auctionRedisService
|
||||
.raw()
|
||||
.sendCommand(['DEL', ...payloadKeysToDelete]);
|
||||
} while (cursor !== '0');
|
||||
}
|
||||
|
||||
@@ -2742,7 +2865,9 @@ export class AuctionService {
|
||||
const payload = JSON.parse(payloadValue) as Record<string, unknown>;
|
||||
return payload.auctionLifecycleId === expectedAuctionLifecycleId;
|
||||
} catch {
|
||||
this.logger.warn(`Failed to parse auction durability payload ${payloadKey}.`);
|
||||
this.logger.warn(
|
||||
`Failed to parse auction durability payload ${payloadKey}.`,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -2855,13 +2980,16 @@ async function runWithConcurrency<T>(
|
||||
if (items.length === 0) return;
|
||||
|
||||
const queue = [...items];
|
||||
const runners = Array.from({ length: Math.min(concurrency, queue.length) }, async () => {
|
||||
while (queue.length > 0) {
|
||||
const item = queue.shift();
|
||||
if (item === undefined) return;
|
||||
await worker(item);
|
||||
}
|
||||
});
|
||||
const runners = Array.from(
|
||||
{ length: Math.min(concurrency, queue.length) },
|
||||
async () => {
|
||||
while (queue.length > 0) {
|
||||
const item = queue.shift();
|
||||
if (item === undefined) return;
|
||||
await worker(item);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
await Promise.allSettled(runners);
|
||||
}
|
||||
@@ -191,4 +191,54 @@ describe('CommunityStatsService', () => {
|
||||
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;
|
||||
}): Promise<UserInternalHistoryResponse> {
|
||||
const key = this.cacheKey(
|
||||
`userInternal:${params.userId.toString()}`,
|
||||
`userInternal:v2:${params.userId.toString()}`,
|
||||
params.communityId,
|
||||
params.filters,
|
||||
);
|
||||
@@ -789,6 +789,8 @@ export class CommunityStatsService {
|
||||
?.find((game) => game.riotMatchId === record.riotMatchId);
|
||||
return {
|
||||
matchId: record.riotMatchId,
|
||||
internalMatchId: record.matchId,
|
||||
gameNumber: record.gameNumber,
|
||||
queueId: 0,
|
||||
queueLabel: '내전',
|
||||
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 {
|
||||
matchId: string;
|
||||
internalMatchId?: string;
|
||||
gameNumber?: number;
|
||||
queueId: number;
|
||||
queueLabel: string;
|
||||
gameCreation: number;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TournamentResultModule } from '../tournament-result/tournament-result.module';
|
||||
import { TournamentCodeController } from './tournament-code.controller';
|
||||
import { TournamentCodeAutoProvisionService } from './tournament-code-auto-provision.service';
|
||||
import { TournamentCodeReplacementController } from './tournament-code-replacement.controller';
|
||||
@@ -7,6 +8,7 @@ import { TournamentCodeService } from './tournament-code.service';
|
||||
import { TournamentCodeVendorService } from './tournament-code-vendor.service';
|
||||
|
||||
@Module({
|
||||
imports: [TournamentResultModule],
|
||||
controllers: [TournamentCodeController, TournamentCodeReplacementController],
|
||||
providers: [
|
||||
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 { TournamentResultService } from '../tournament-result/tournament-result.service';
|
||||
import { TournamentCodeAutoProvisionService } from './tournament-code-auto-provision.service';
|
||||
import { TournamentCodeService } from './tournament-code.service';
|
||||
|
||||
@@ -12,6 +13,7 @@ export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy {
|
||||
constructor(
|
||||
private readonly tournamentCodeService: TournamentCodeService,
|
||||
private readonly autoProvisionService: TournamentCodeAutoProvisionService,
|
||||
private readonly tournamentResultService: TournamentResultService,
|
||||
) {}
|
||||
|
||||
public onModuleInit() {
|
||||
@@ -45,9 +47,15 @@ export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy {
|
||||
|
||||
private async attachPending() {
|
||||
try {
|
||||
const touched = await this.tournamentCodeService.attachPendingMatches();
|
||||
if (touched > 0) {
|
||||
this.logger.debug(`Attached tournament codes for ${touched} matches.`);
|
||||
const matches =
|
||||
await this.tournamentCodeService.attachPendingMatchDocuments();
|
||||
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) {
|
||||
this.logger.warn(
|
||||
|
||||
@@ -226,8 +226,10 @@ describe('TournamentCodeService round-robin scheduling', () => {
|
||||
(game) => game.roundNumber === roundNumber,
|
||||
);
|
||||
expect(round).toHaveLength(4);
|
||||
expect(new Set(round.flatMap((game) => [game.teamAIndex, game.teamBIndex])).size)
|
||||
.toBe(8);
|
||||
expect(
|
||||
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', () => {
|
||||
function queryResult<T>(value: T) {
|
||||
return { exec: jest.fn().mockResolvedValue(value) };
|
||||
|
||||
@@ -164,10 +164,9 @@ export class TournamentCodeService {
|
||||
_id: TournamentCodeState;
|
||||
count: number;
|
||||
}>([{ $group: { _id: '$state', count: { $sum: 1 } } }]).exec();
|
||||
const byState = Object.fromEntries(states.map((state) => [state, 0])) as Record<
|
||||
TournamentCodeState,
|
||||
number
|
||||
>;
|
||||
const byState = Object.fromEntries(
|
||||
states.map((state) => [state, 0]),
|
||||
) as Record<TournamentCodeState, number>;
|
||||
for (const entry of counts) byState[entry._id] = entry.count;
|
||||
|
||||
const expiringSoon = await TournamentCodeModel.countDocuments({
|
||||
@@ -189,7 +188,9 @@ export class TournamentCodeService {
|
||||
state: 'available',
|
||||
}).exec();
|
||||
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 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) {
|
||||
const code = await TournamentCodeModel.findOneAndUpdate(
|
||||
@@ -334,10 +337,14 @@ export class TournamentCodeService {
|
||||
throw new NotFoundException('Assigned tournament code not found.');
|
||||
}
|
||||
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(
|
||||
{
|
||||
state: 'available',
|
||||
@@ -358,7 +365,9 @@ export class TournamentCodeService {
|
||||
{ sort: { expiresAt: 1 }, returnDocument: 'after' },
|
||||
).exec();
|
||||
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';
|
||||
@@ -430,6 +439,13 @@ export class TournamentCodeService {
|
||||
public async attachPendingMatches(
|
||||
communityId?: mongoose.Types.ObjectId,
|
||||
): 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 filter: {
|
||||
status: { $in: string[] };
|
||||
@@ -440,20 +456,33 @@ export class TournamentCodeService {
|
||||
if (communityId) filter.communityId = communityId;
|
||||
|
||||
const matches = await MatchModel.find(filter).exec();
|
||||
let touched = 0;
|
||||
const touched: MatchDocument[] = [];
|
||||
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;
|
||||
}
|
||||
const before = match.tournamentCodeIds?.length ?? 0;
|
||||
await this.reserveForMatch(match);
|
||||
const after = match.tournamentCodeIds?.length ?? 0;
|
||||
if (after > before) touched += 1;
|
||||
const updatedMatch = await this.reserveForMatch(match);
|
||||
const after = updatedMatch.tournamentCodeIds?.length ?? 0;
|
||||
if (after > before) touched.push(updatedMatch);
|
||||
}
|
||||
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 (
|
||||
(match.gameMode ?? 'pair') === 'round-robin' &&
|
||||
(match.gameSchedule?.length ?? 0) === 0 &&
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import mongoose from 'mongoose';
|
||||
import type { MatchDocument } from '../global/database/schema';
|
||||
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(): {
|
||||
match: MatchDocument;
|
||||
@@ -9,8 +13,14 @@ function makeMatch(): {
|
||||
blueUserIds: mongoose.Types.ObjectId[];
|
||||
redUserIds: mongoose.Types.ObjectId[];
|
||||
} {
|
||||
const blueUserIds = Array.from({ length: 5 }, () => new mongoose.Types.ObjectId());
|
||||
const redUserIds = Array.from({ length: 5 }, () => new mongoose.Types.ObjectId());
|
||||
const blueUserIds = Array.from(
|
||||
{ length: 5 },
|
||||
() => new mongoose.Types.ObjectId(),
|
||||
);
|
||||
const redUserIds = Array.from(
|
||||
{ length: 5 },
|
||||
() => new mongoose.Types.ObjectId(),
|
||||
);
|
||||
const puuidByUserId = new Map<string, string>();
|
||||
const userIdByPuuid = new Map<string, mongoose.Types.ObjectId>();
|
||||
|
||||
@@ -47,7 +57,12 @@ function makeMatch(): {
|
||||
})),
|
||||
} as unknown as MatchDocument;
|
||||
|
||||
return { match, lookup: { puuidByUserId, userIdByPuuid }, blueUserIds, redUserIds };
|
||||
return {
|
||||
match,
|
||||
lookup: { puuidByUserId, userIdByPuuid },
|
||||
blueUserIds,
|
||||
redUserIds,
|
||||
};
|
||||
}
|
||||
|
||||
function makeRiotMatch(params: {
|
||||
@@ -154,3 +169,24 @@ describe('computeGameResult', () => {
|
||||
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 type { MatchDocument, MatchGameResult, TeamSide } from '../global/database/schema';
|
||||
import type {
|
||||
MatchDocument,
|
||||
MatchGameResult,
|
||||
TeamSide,
|
||||
} from '../global/database/schema';
|
||||
import type { RiotMatchDto } from '../riot/riot.types';
|
||||
|
||||
const RIOT_BLUE_TEAM_ID = 100;
|
||||
@@ -11,19 +15,46 @@ export interface MatchPuuidLookup {
|
||||
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
|
||||
.map((team) => team.captainUserId)
|
||||
.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>();
|
||||
for (const participant of match.participants) {
|
||||
ids.set(participant.userId.toString(), participant.userId);
|
||||
}
|
||||
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) {
|
||||
ids.set(member.userId.toString(), member.userId);
|
||||
}
|
||||
@@ -78,8 +109,10 @@ export function computeGameResult(params: {
|
||||
const reversedOverlap =
|
||||
countOverlap(team100Puuids, teamBPuuids) +
|
||||
countOverlap(team200Puuids, teamAPuuids);
|
||||
const blueTeamIndex = normalOverlap >= reversedOverlap ? teamAIndex : teamBIndex;
|
||||
const redTeamIndex = normalOverlap >= reversedOverlap ? teamBIndex : teamAIndex;
|
||||
const blueTeamIndex =
|
||||
normalOverlap >= reversedOverlap ? teamAIndex : teamBIndex;
|
||||
const redTeamIndex =
|
||||
normalOverlap >= reversedOverlap ? teamBIndex : teamAIndex;
|
||||
const teamIndexByRiotTeamId: Record<number, number> = {
|
||||
[RIOT_BLUE_TEAM_ID]: blueTeamIndex,
|
||||
[RIOT_RED_TEAM_ID]: redTeamIndex,
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { RiotMatchDto } from '../riot/riot.types';
|
||||
import { TournamentResultService } from './tournament-result.service';
|
||||
|
||||
type TournamentResultServiceInternals = TournamentResultService & {
|
||||
nextPollDelayMs(elapsedMs: number): number | null;
|
||||
resolveRequiredGameSlots(match: MatchDocument): number;
|
||||
resolveSeriesRefForGameNumber(
|
||||
match: MatchDocument,
|
||||
@@ -235,7 +236,7 @@ describe('TournamentResultService tournament code polling', () => {
|
||||
{ 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 () => {
|
||||
@@ -256,6 +257,23 @@ describe('TournamentResultService tournament code polling', () => {
|
||||
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 () => {
|
||||
const { service, match, code } = createPollFixture({
|
||||
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', () => {
|
||||
function createManualFixture() {
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
resolveRoundRobinTeamCount,
|
||||
} from '../tournament-code/round-robin.util';
|
||||
import {
|
||||
collectCaptainAndLimitedTeamMemberUserIds,
|
||||
collectCaptainUserIds,
|
||||
collectMatchUserIds,
|
||||
computeGameResult,
|
||||
@@ -34,10 +35,11 @@ import type {
|
||||
PollTournamentResultJob,
|
||||
} 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 POLL_EXPIRY_MS = 24 * 60 * 60_000;
|
||||
const EXPAND_AFTER_MS = 60 * 60_000;
|
||||
const EXPANDED_MEMBER_LIMIT_PER_TEAM = 2;
|
||||
const TOURNAMENT_LOOKUP_START_MARGIN_SECONDS = 60;
|
||||
|
||||
interface ManualGameAssignment {
|
||||
@@ -216,7 +218,13 @@ export class TournamentResultService {
|
||||
const region = community?.riotRegion ?? 'asia';
|
||||
const lookup = await this.buildPuuidLookup(match);
|
||||
const puuids = job.expandedToAllPuuids
|
||||
? this.collectPollingPuuids(collectMatchUserIds(match), lookup)
|
||||
? this.collectPollingPuuids(
|
||||
collectCaptainAndLimitedTeamMemberUserIds(
|
||||
match,
|
||||
EXPANDED_MEMBER_LIMIT_PER_TEAM,
|
||||
),
|
||||
lookup,
|
||||
)
|
||||
: this.collectPollingPuuids(collectCaptainUserIds(match), lookup);
|
||||
|
||||
const matchedGameNumbers = new Set<number>();
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -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_REDIRECT_URI=http://localhost:5173/auth/callback
|
||||
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
|
||||
@@ -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_REDIRECT_URI=http://localhost:5173/auth/callback
|
||||
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
|
||||
@@ -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_REDIRECT_URI=https://lolympus.dahyeon.us/auth/callback
|
||||
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
@@ -1,6 +1,16 @@
|
||||
VITE_API_BASE_URL=https://lolympus-api-staging.dahyeon.us
|
||||
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_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
|
||||
@@ -20,6 +20,7 @@
|
||||
"dependencies": {
|
||||
"@azure/msal-browser": "^5.8.0",
|
||||
"@azure/msal-react": "^5.3.1",
|
||||
"@newrelic/browser-agent": "^1.316.0",
|
||||
"@tanstack/react-query": "^5.100.1",
|
||||
"lucide-react": "^1.14.0",
|
||||
"react": "^19.2.4",
|
||||
|
||||
@@ -661,6 +661,8 @@ export interface ApiRecentMatchTeam {
|
||||
|
||||
export interface ApiRecentMatchView {
|
||||
matchId: string;
|
||||
internalMatchId?: string;
|
||||
gameNumber?: number;
|
||||
queueId: number;
|
||||
queueLabel: string;
|
||||
gameCreation: number;
|
||||
|
||||
@@ -8,6 +8,9 @@ import {
|
||||
resolveAuctionErrorMessage,
|
||||
resolveAuctionRejectionMessage,
|
||||
} from './auctionRejectionMessages';
|
||||
// [AUCTION-DEBUG] 경매 "중복 멤버" 조사용 임시 계측. 조사 종료 후 제거 대상
|
||||
// (호출부는 전부 addNewRelicPageAction / describeAuctionForTelemetry 로 grep 가능).
|
||||
import { addNewRelicPageAction } from '../lib/observability/new-relic';
|
||||
|
||||
type ConnectionStatus =
|
||||
| 'idle'
|
||||
@@ -180,9 +183,36 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
resolveCurrentBidPointAmount(nextAuction);
|
||||
}
|
||||
|
||||
function commitAuctionState(nextAuction: ApiAuction): boolean {
|
||||
function commitAuctionState(
|
||||
nextAuction: ApiAuction,
|
||||
source = 'socket-state',
|
||||
): boolean {
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -361,7 +391,7 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
});
|
||||
|
||||
socket.on('state', (nextAuction: ApiAuction) => {
|
||||
const didApplyState = commitAuctionState(nextAuction);
|
||||
const didApplyState = commitAuctionState(nextAuction, 'socket-state');
|
||||
if (didApplyState) {
|
||||
clearPendingActionRequests();
|
||||
}
|
||||
@@ -384,7 +414,24 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
|
||||
socket.on('bid', (payload: BidDeltaPayload) => {
|
||||
applyFallbackServerTimestamp(payload?.currentServerTimestampMS);
|
||||
const beforeBid = latestAuctionRef.current;
|
||||
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 (
|
||||
didApplyBidDelta ||
|
||||
@@ -429,6 +476,12 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
};
|
||||
latestAuctionRef.current = nextAuction;
|
||||
setAuction(nextAuction);
|
||||
addNewRelicPageAction('AuctionClientSideEffect', {
|
||||
matchId: matchId ?? 'none',
|
||||
matchSideEffectStatus: matchSideEffectStatus ?? 'unknown',
|
||||
matchSideEffectRevision,
|
||||
...describeAuctionForTelemetry('current', currentAuction),
|
||||
});
|
||||
});
|
||||
|
||||
socket.on('reset', (payload: ResetPayload) => {
|
||||
@@ -574,6 +627,23 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
clearPendingActionRequest(auctionActionRequestId);
|
||||
setError('경매 진행 응답이 지연되어 최신 상태를 다시 확인해주세요.');
|
||||
}, 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(
|
||||
eventName,
|
||||
actionPayload,
|
||||
@@ -590,14 +660,6 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
clearPendingActionRequest(
|
||||
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)가
|
||||
// 있을 때만 1회. assignedPosition 등 원래 payload는 유지하고 관측값/요청
|
||||
// id만 새로 만든다. 재시도 시에는 중간 에러 문구를 띄우지 않는다(무음 복구).
|
||||
@@ -605,6 +667,41 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
Boolean(ack.state) &&
|
||||
isAuctionResyncRecommended(ack) &&
|
||||
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) {
|
||||
emitAuctionAction(
|
||||
eventName,
|
||||
@@ -621,7 +718,17 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
clearPendingActionRequest(
|
||||
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;
|
||||
}
|
||||
|
||||
// [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(
|
||||
current: ApiAuction | null,
|
||||
incoming: ApiAuction,
|
||||
|
||||
@@ -122,6 +122,51 @@ body {
|
||||
--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: 모든 모서리 각지게 */
|
||||
*,
|
||||
*::before,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { initializeNewRelicBrowserAgent } from './lib/observability/new-relic.ts';
|
||||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
@@ -6,6 +7,7 @@ import App from './App.tsx';
|
||||
import { MsalAppProvider } from './lib/auth/MsalAppProvider.tsx';
|
||||
import { initializeTheme } from './config.ts';
|
||||
|
||||
initializeNewRelicBrowserAgent();
|
||||
initializeTheme();
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
|
||||
+1431
-385
File diff suppressed because it is too large.
Load diff
@@ -37,6 +37,14 @@ type DdragonManifestData = ReturnType<typeof useDdragonManifest>["data"];
|
||||
type RuneStyleEntry = NonNullable<DdragonManifestData>["runesReforged"][number];
|
||||
type DetailTab = "scoreboard" | "matchup" | "build";
|
||||
type TimelineMetric = "gold" | "xp";
|
||||
type MatchGameBackTarget = {
|
||||
to: string;
|
||||
label: string;
|
||||
};
|
||||
type MatchGameNavigationState = {
|
||||
backTo: string;
|
||||
backLabel: string;
|
||||
};
|
||||
|
||||
const DETAIL_TABS: Array<{ id: DetailTab; label: string }> = [
|
||||
{ id: "scoreboard", label: "스코어보드" },
|
||||
@@ -49,6 +57,46 @@ const TIMELINE_METRICS: Array<{ id: TimelineMetric; label: string }> = [
|
||||
{ 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<{
|
||||
slot: 1 | 2 | 3 | 4;
|
||||
label: string;
|
||||
@@ -1924,9 +1972,11 @@ function GameAnalysisPanel({
|
||||
function GameTabs({
|
||||
detail,
|
||||
currentGameNumber,
|
||||
navigationState,
|
||||
}: {
|
||||
detail: ApiInternalMatchDetailResponse;
|
||||
currentGameNumber: number;
|
||||
navigationState: MatchGameNavigationState | undefined;
|
||||
}) {
|
||||
return (
|
||||
<nav
|
||||
@@ -1940,6 +1990,7 @@ function GameTabs({
|
||||
<Link
|
||||
key={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 ${
|
||||
active
|
||||
? "bg-primary/8 text-primary"
|
||||
@@ -1962,9 +2013,13 @@ function GameTabs({
|
||||
function MatchScoreHero({
|
||||
detail,
|
||||
selectedGame,
|
||||
backTarget,
|
||||
navigationState,
|
||||
}: {
|
||||
detail: ApiInternalMatchDetailResponse;
|
||||
selectedGame: MatchGameDetail;
|
||||
backTarget: MatchGameBackTarget;
|
||||
navigationState: MatchGameNavigationState | undefined;
|
||||
}) {
|
||||
const selectedSeries = resolveSelectedSeries(detail, selectedGame);
|
||||
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="min-w-0">
|
||||
<Link
|
||||
to={`/match/${detail.match.matchId}`}
|
||||
to={backTarget.to}
|
||||
className="text-xs text-base-content/40 hover:text-base-content"
|
||||
>
|
||||
← 경기 결과로 돌아가기
|
||||
← {backTarget.label}
|
||||
</Link>
|
||||
<h1 className="mt-4 text-2xl font-black text-base-content">
|
||||
{detail.match.title} · {selectedGame.gameNumber}세트
|
||||
@@ -2040,18 +2095,26 @@ function MatchScoreHero({
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<GameTabs detail={detail} currentGameNumber={selectedGame.gameNumber} />
|
||||
<GameTabs
|
||||
detail={detail}
|
||||
currentGameNumber={selectedGame.gameNumber}
|
||||
navigationState={navigationState}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export default function MatchGameDetailPage() {
|
||||
const { id, gameNumber } = useParams();
|
||||
const location = useLocation();
|
||||
const [activeTab, setActiveTab] = useState<DetailTab>("scoreboard");
|
||||
const requestedGameNumber = Number(gameNumber);
|
||||
const detailQuery = useInternalMatchDetail(id, DEFAULT_COMMUNITY_ID);
|
||||
const { data: ddragon } = useDdragonManifest();
|
||||
const detail = detailQuery.data;
|
||||
const fallbackBackTo = `/match/${id ?? ""}`;
|
||||
const backTarget = resolveBackTarget(location.state, fallbackBackTo);
|
||||
const navigationState = createNavigationState(backTarget, fallbackBackTo);
|
||||
|
||||
if (detailQuery.isLoading) {
|
||||
return (
|
||||
@@ -2065,8 +2128,8 @@ export default function MatchGameDetailPage() {
|
||||
return (
|
||||
<main className="mx-auto max-w-6xl px-4 py-20 text-center">
|
||||
<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>
|
||||
</main>
|
||||
);
|
||||
@@ -2081,10 +2144,10 @@ export default function MatchGameDetailPage() {
|
||||
<main className="mx-auto max-w-6xl px-4 py-20 text-center">
|
||||
<h1 className="text-lg font-bold">수집된 세트 기록이 없습니다</h1>
|
||||
<Link
|
||||
to={`/match/${detail.match.matchId}`}
|
||||
to={backTarget.to}
|
||||
className="btn btn-ghost btn-sm mt-4"
|
||||
>
|
||||
경기 결과로 돌아가기
|
||||
{backTarget.label}
|
||||
</Link>
|
||||
</main>
|
||||
);
|
||||
@@ -2092,7 +2155,12 @@ export default function MatchGameDetailPage() {
|
||||
|
||||
return (
|
||||
<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
|
||||
selectedGame={selectedGame}
|
||||
|
||||
Generated
+890
-17
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user