Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f526257d9c | ||
|
|
34a47c053e | ||
|
|
e3f39fd8b8 | ||
|
|
4385ba7b8b | ||
|
|
9cd5850d43 | ||
|
|
79534cf43c | ||
|
|
03be85d07b | ||
|
|
d269bdd92b | ||
|
|
2bac89d3dc | ||
|
|
760da1cbea | ||
|
|
ca786fd80a | ||
|
|
ac0d2b53f0 | ||
|
|
a4215f86fb | ||
|
|
a24726d7da | ||
|
|
bb68be14fa |
No files matched your search
@@ -29,20 +29,20 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@lolympus/contracts": "workspace:*",
|
"@lolympus/contracts": "workspace:*",
|
||||||
"@nestjs/common": "^11.0.1",
|
"@nestjs/common": "^11.1.28",
|
||||||
"@nestjs/config": "^4.0.4",
|
"@nestjs/config": "^4.0.4",
|
||||||
"@nestjs/core": "^11.0.1",
|
"@nestjs/core": "^11.1.28",
|
||||||
"@nestjs/platform-express": "^11.0.1",
|
"@nestjs/platform-express": "^11.1.28",
|
||||||
"@nestjs/platform-socket.io": "^11.1.19",
|
"@nestjs/platform-socket.io": "^11.1.28",
|
||||||
"@nestjs/swagger": "^11.2.7",
|
"@nestjs/swagger": "^11.4.6",
|
||||||
"@nestjs/websockets": "^11.1.19",
|
"@nestjs/websockets": "^11.1.28",
|
||||||
"@socket.io/redis-adapter": "^8.3.0",
|
"@socket.io/redis-adapter": "^8.3.0",
|
||||||
"class-transformer": "^0.5.1",
|
"class-transformer": "^0.5.1",
|
||||||
"class-validator": "^0.15.1",
|
"class-validator": "^0.15.1",
|
||||||
"jose": "^6.2.2",
|
"jose": "^6.2.2",
|
||||||
"mongoose": "^9.4.1",
|
"mongoose": "9.4.1",
|
||||||
"nats": "^2.29.3",
|
"nats": "^2.29.3",
|
||||||
"newrelic": "^14.3.0",
|
"newrelic": "^14.3.3",
|
||||||
"redis": "^5.12.1",
|
"redis": "^5.12.1",
|
||||||
"reflect-metadata": "^0.2.2",
|
"reflect-metadata": "^0.2.2",
|
||||||
"rxjs": "^7.8.1",
|
"rxjs": "^7.8.1",
|
||||||
|
|||||||
@@ -2,6 +2,30 @@ import mongoose from 'mongoose';
|
|||||||
import { AuctionService } from './auction.service';
|
import { AuctionService } from './auction.service';
|
||||||
|
|
||||||
describe('AuctionService', () => {
|
describe('AuctionService', () => {
|
||||||
|
function requireRecord(
|
||||||
|
value: unknown,
|
||||||
|
label: string,
|
||||||
|
): Record<string, unknown> {
|
||||||
|
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||||
|
throw new Error(`${label} must be an object.`);
|
||||||
|
}
|
||||||
|
return value as Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function requireArray(value: unknown, label: string): unknown[] {
|
||||||
|
if (!Array.isArray(value)) {
|
||||||
|
throw new Error(`${label} must be an array.`);
|
||||||
|
}
|
||||||
|
return value as unknown[];
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseJsonRecord(value: unknown, label: string) {
|
||||||
|
if (typeof value !== 'string') {
|
||||||
|
throw new Error(`${label} must be a JSON string.`);
|
||||||
|
}
|
||||||
|
return requireRecord(JSON.parse(value) as unknown, label);
|
||||||
|
}
|
||||||
|
|
||||||
function createService(models: Record<string, unknown>) {
|
function createService(models: Record<string, unknown>) {
|
||||||
const auctionHistoryModel = {
|
const auctionHistoryModel = {
|
||||||
findOne: jest.fn().mockReturnValue({
|
findOne: jest.fn().mockReturnValue({
|
||||||
@@ -1007,7 +1031,12 @@ describe('AuctionService', () => {
|
|||||||
);
|
);
|
||||||
const transitionInput =
|
const transitionInput =
|
||||||
auctionRedisCommandService.applyTransition.mock.calls[0][1];
|
auctionRedisCommandService.applyTransition.mock.calls[0][1];
|
||||||
expect(JSON.parse(transitionInput.durabilityPayloadJson)).toMatchObject({
|
expect(
|
||||||
|
parseJsonRecord(
|
||||||
|
transitionInput.durabilityPayloadJson,
|
||||||
|
'durabilityPayloadJson',
|
||||||
|
),
|
||||||
|
).toMatchObject({
|
||||||
afterAuctionMongoProjection: expect.objectContaining({
|
afterAuctionMongoProjection: expect.objectContaining({
|
||||||
phase: 'bidding',
|
phase: 'bidding',
|
||||||
revision: 2,
|
revision: 2,
|
||||||
@@ -1178,17 +1207,40 @@ describe('AuctionService', () => {
|
|||||||
|
|
||||||
const transitionInput =
|
const transitionInput =
|
||||||
auctionRedisCommandService.applyTransition.mock.calls[0][1];
|
auctionRedisCommandService.applyTransition.mock.calls[0][1];
|
||||||
const durabilityPayload = JSON.parse(transitionInput.durabilityPayloadJson);
|
const durabilityPayload = parseJsonRecord(
|
||||||
expect(durabilityPayload.snapshotBefore).toMatchObject({
|
transitionInput.durabilityPayloadJson,
|
||||||
|
'durabilityPayloadJson',
|
||||||
|
);
|
||||||
|
const snapshotBefore = requireRecord(
|
||||||
|
durabilityPayload.snapshotBefore,
|
||||||
|
'snapshotBefore',
|
||||||
|
);
|
||||||
|
const snapshotBeforeTeams = requireArray(
|
||||||
|
snapshotBefore.auctionTeams,
|
||||||
|
'snapshotBefore.auctionTeams',
|
||||||
|
);
|
||||||
|
const snapshotBeforeTeam = requireRecord(
|
||||||
|
snapshotBeforeTeams[0],
|
||||||
|
'snapshotBefore.auctionTeams[0]',
|
||||||
|
);
|
||||||
|
const afterAuctionMongoProjection = requireRecord(
|
||||||
|
durabilityPayload.afterAuctionMongoProjection,
|
||||||
|
'afterAuctionMongoProjection',
|
||||||
|
);
|
||||||
|
const projectedTeams = requireArray(
|
||||||
|
afterAuctionMongoProjection.auctionTeams,
|
||||||
|
'afterAuctionMongoProjection.auctionTeams',
|
||||||
|
);
|
||||||
|
const projectedTeam = requireRecord(
|
||||||
|
projectedTeams[0],
|
||||||
|
'afterAuctionMongoProjection.auctionTeams[0]',
|
||||||
|
);
|
||||||
|
expect(snapshotBefore).toMatchObject({
|
||||||
phase: 'bidding',
|
phase: 'bidding',
|
||||||
revision: 4,
|
revision: 4,
|
||||||
});
|
});
|
||||||
expect(durabilityPayload.snapshotBefore.auctionTeams[0].members).toEqual(
|
expect(snapshotBeforeTeam.members).toEqual([]);
|
||||||
[],
|
expect(projectedTeam.members).toEqual([
|
||||||
);
|
|
||||||
expect(
|
|
||||||
durabilityPayload.afterAuctionMongoProjection.auctionTeams[0].members,
|
|
||||||
).toEqual([
|
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
memberAcquisitionBidPointAmount: 120,
|
memberAcquisitionBidPointAmount: 120,
|
||||||
userId: playerUserId.toString(),
|
userId: playerUserId.toString(),
|
||||||
@@ -1396,7 +1448,12 @@ describe('AuctionService', () => {
|
|||||||
});
|
});
|
||||||
const [, transitionInput] =
|
const [, transitionInput] =
|
||||||
auctionRedisCommandService.applyTransition.mock.calls.at(-1) ?? [];
|
auctionRedisCommandService.applyTransition.mock.calls.at(-1) ?? [];
|
||||||
expect(JSON.parse(transitionInput.durabilityPayloadJson)).toMatchObject({
|
expect(
|
||||||
|
parseJsonRecord(
|
||||||
|
transitionInput.durabilityPayloadJson,
|
||||||
|
'durabilityPayloadJson',
|
||||||
|
),
|
||||||
|
).toMatchObject({
|
||||||
afterAuctionMongoProjection: {
|
afterAuctionMongoProjection: {
|
||||||
matchSideEffectStatus: 'pending',
|
matchSideEffectStatus: 'pending',
|
||||||
phase: 'complete',
|
phase: 'complete',
|
||||||
@@ -2567,7 +2624,10 @@ describe('AuctionService', () => {
|
|||||||
durationSeconds: 30,
|
durationSeconds: 30,
|
||||||
mode: 'set-relative',
|
mode: 'set-relative',
|
||||||
});
|
});
|
||||||
const durabilityPayload = JSON.parse(transitionInput.durabilityPayloadJson);
|
const durabilityPayload = parseJsonRecord(
|
||||||
|
transitionInput.durabilityPayloadJson,
|
||||||
|
'durabilityPayloadJson',
|
||||||
|
);
|
||||||
expect(durabilityPayload).toMatchObject({
|
expect(durabilityPayload).toMatchObject({
|
||||||
auctionActionType: 'undo',
|
auctionActionType: 'undo',
|
||||||
historyMutation: {
|
historyMutation: {
|
||||||
|
|||||||
@@ -429,8 +429,14 @@ export function applyCompetitionDomainInvariantIndexes(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type CompetitionModelName =
|
||||||
|
| 'competition'
|
||||||
|
| 'competitionFact'
|
||||||
|
| 'competitionOutbox'
|
||||||
|
| 'tournamentCodeAssignment';
|
||||||
|
|
||||||
export const competitionModelDefinitions: Array<{
|
export const competitionModelDefinitions: Array<{
|
||||||
name: string;
|
name: CompetitionModelName;
|
||||||
schema: mongoose.Schema;
|
schema: mongoose.Schema;
|
||||||
schemaName: string;
|
schemaName: string;
|
||||||
}> = [
|
}> = [
|
||||||
|
|||||||
@@ -1,4 +1,8 @@
|
|||||||
import { projectCompetition } from './competition-projector';
|
import { projectCompetition } from './competition-projector';
|
||||||
|
import {
|
||||||
|
CompetitionDomainError,
|
||||||
|
type CompetitionDomainErrorCode,
|
||||||
|
} from './domain-error';
|
||||||
import { generateSeriesGraph } from './series-graph';
|
import { generateSeriesGraph } from './series-graph';
|
||||||
|
|
||||||
describe('projectCompetition', () => {
|
describe('projectCompetition', () => {
|
||||||
@@ -323,20 +327,18 @@ describe('projectCompetition', () => {
|
|||||||
'team-1',
|
'team-1',
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(() =>
|
expectCompetitionDomainError(
|
||||||
projectCompetition({
|
() =>
|
||||||
competitionId,
|
projectCompetition({
|
||||||
revision: 1,
|
competitionId,
|
||||||
projectorVersion: 1,
|
revision: 1,
|
||||||
teams,
|
projectorVersion: 1,
|
||||||
format,
|
teams,
|
||||||
seriesGraph,
|
format,
|
||||||
facts: [{ ...accepted, seriesId: 'series-does-not-exist' }],
|
seriesGraph,
|
||||||
}),
|
facts: [{ ...accepted, seriesId: 'series-does-not-exist' }],
|
||||||
).toThrow(
|
}),
|
||||||
expect.objectContaining({
|
'GAME_SERIES_MISMATCH',
|
||||||
code: 'GAME_SERIES_MISMATCH',
|
|
||||||
}),
|
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -356,20 +358,18 @@ describe('projectCompetition', () => {
|
|||||||
'team-1',
|
'team-1',
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(() =>
|
expectCompetitionDomainError(
|
||||||
projectCompetition({
|
() =>
|
||||||
competitionId,
|
projectCompetition({
|
||||||
revision: 1,
|
competitionId,
|
||||||
projectorVersion: 1,
|
revision: 1,
|
||||||
teams,
|
projectorVersion: 1,
|
||||||
format,
|
teams,
|
||||||
seriesGraph,
|
format,
|
||||||
facts: [{ ...accepted, gameSlotId: 'slot-does-not-exist' }],
|
seriesGraph,
|
||||||
}),
|
facts: [{ ...accepted, gameSlotId: 'slot-does-not-exist' }],
|
||||||
).toThrow(
|
}),
|
||||||
expect.objectContaining({
|
'GAME_SLOT_INVALID',
|
||||||
code: 'GAME_SLOT_INVALID',
|
|
||||||
}),
|
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -382,36 +382,34 @@ describe('projectCompetition', () => {
|
|||||||
};
|
};
|
||||||
const seriesGraph = generateSeriesGraph({ competitionId, teams, format });
|
const seriesGraph = generateSeriesGraph({ competitionId, teams, format });
|
||||||
|
|
||||||
expect(() =>
|
expectCompetitionDomainError(
|
||||||
projectCompetition({
|
() =>
|
||||||
competitionId,
|
projectCompetition({
|
||||||
revision: 1,
|
competitionId,
|
||||||
projectorVersion: 1,
|
revision: 1,
|
||||||
teams,
|
projectorVersion: 1,
|
||||||
format,
|
teams,
|
||||||
seriesGraph,
|
format,
|
||||||
facts: [
|
seriesGraph,
|
||||||
{
|
facts: [
|
||||||
id: 'fact-unknown-adjudication-series',
|
{
|
||||||
type: 'series-adjudicated',
|
id: 'fact-unknown-adjudication-series',
|
||||||
competitionId,
|
type: 'series-adjudicated',
|
||||||
revision: 1,
|
competitionId,
|
||||||
ordinalWithinRevision: 1,
|
revision: 1,
|
||||||
commandId: 'command-unknown-adjudication-series',
|
ordinalWithinRevision: 1,
|
||||||
schemaVersion: 1,
|
commandId: 'command-unknown-adjudication-series',
|
||||||
actor: { type: 'user' },
|
schemaVersion: 1,
|
||||||
occurredAt: new Date('2026-07-12T00:00:01.000Z'),
|
actor: { type: 'user' },
|
||||||
recordedAt: new Date('2026-07-12T00:00:02.000Z'),
|
occurredAt: new Date('2026-07-12T00:00:01.000Z'),
|
||||||
seriesId: 'series-does-not-exist',
|
recordedAt: new Date('2026-07-12T00:00:02.000Z'),
|
||||||
decision: { type: 'administrative', winnerTeamId: 'team-1' },
|
seriesId: 'series-does-not-exist',
|
||||||
reason: 'Manual correction',
|
decision: { type: 'administrative', winnerTeamId: 'team-1' },
|
||||||
},
|
reason: 'Manual correction',
|
||||||
],
|
},
|
||||||
}),
|
],
|
||||||
).toThrow(
|
}),
|
||||||
expect.objectContaining({
|
'ADJUDICATION_INVALID',
|
||||||
code: 'ADJUDICATION_INVALID',
|
|
||||||
}),
|
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -617,3 +615,23 @@ interface GameSlotLike {
|
|||||||
id: string;
|
id: string;
|
||||||
ordinal: number;
|
ordinal: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function expectCompetitionDomainError(
|
||||||
|
action: () => unknown,
|
||||||
|
expectedCode: CompetitionDomainErrorCode,
|
||||||
|
): void {
|
||||||
|
let thrown: unknown;
|
||||||
|
try {
|
||||||
|
action();
|
||||||
|
} catch (error: unknown) {
|
||||||
|
thrown = error;
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(thrown).toBeInstanceOf(CompetitionDomainError);
|
||||||
|
if (!(thrown instanceof CompetitionDomainError)) {
|
||||||
|
throw new Error(
|
||||||
|
`Expected CompetitionDomainError, received ${String(thrown)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
expect(thrown.code).toBe(expectedCode);
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import {
|
import {
|
||||||
assertReversalPreview,
|
assertReversalPreview,
|
||||||
buildReversalFacts,
|
buildReversalFacts,
|
||||||
|
CompetitionReversalError,
|
||||||
previewSeriesReversal,
|
previewSeriesReversal,
|
||||||
} from './competition-reversal';
|
} from './competition-reversal';
|
||||||
|
|
||||||
@@ -19,18 +20,18 @@ describe('Competition reversal planning', () => {
|
|||||||
];
|
];
|
||||||
|
|
||||||
it('rejects strict reversal when a descendant has result activity', () => {
|
it('rejects strict reversal when a descendant has result activity', () => {
|
||||||
expect(() =>
|
expectCompetitionReversalError(
|
||||||
previewSeriesReversal({
|
() =>
|
||||||
competitionId: 'competition-1',
|
previewSeriesReversal({
|
||||||
revision: 2,
|
competitionId: 'competition-1',
|
||||||
seriesId: 'series-parent',
|
revision: 2,
|
||||||
mode: 'strict',
|
seriesId: 'series-parent',
|
||||||
graph,
|
mode: 'strict',
|
||||||
facts,
|
graph,
|
||||||
assignments,
|
facts,
|
||||||
}),
|
assignments,
|
||||||
).toThrow(
|
}),
|
||||||
expect.objectContaining({ code: 'REVERSAL_DESCENDANT_ACTIVITY' }),
|
'REVERSAL_DESCENDANT_ACTIVITY',
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -105,20 +106,22 @@ describe('Competition reversal planning', () => {
|
|||||||
assignments,
|
assignments,
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(() =>
|
expectCompetitionReversalError(
|
||||||
assertReversalPreview(
|
() =>
|
||||||
{
|
assertReversalPreview(
|
||||||
competitionId: 'competition-1',
|
{
|
||||||
revision: 3,
|
competitionId: 'competition-1',
|
||||||
seriesId: 'series-parent',
|
revision: 3,
|
||||||
mode: 'cascade',
|
seriesId: 'series-parent',
|
||||||
graph,
|
mode: 'cascade',
|
||||||
facts,
|
graph,
|
||||||
assignments,
|
facts,
|
||||||
},
|
assignments,
|
||||||
preview.impactHash,
|
},
|
||||||
),
|
preview.impactHash,
|
||||||
).toThrow(expect.objectContaining({ code: 'REVERSAL_PREVIEW_STALE' }));
|
),
|
||||||
|
'REVERSAL_PREVIEW_STALE',
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('emits one append-only reversal fact for every active result fact', () => {
|
it('emits one append-only reversal fact for every active result fact', () => {
|
||||||
@@ -160,6 +163,26 @@ describe('Competition reversal planning', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
function expectCompetitionReversalError(
|
||||||
|
action: () => unknown,
|
||||||
|
expectedCode: CompetitionReversalError['code'],
|
||||||
|
): void {
|
||||||
|
let thrown: unknown;
|
||||||
|
try {
|
||||||
|
action();
|
||||||
|
} catch (error: unknown) {
|
||||||
|
thrown = error;
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(thrown).toBeInstanceOf(CompetitionReversalError);
|
||||||
|
if (!(thrown instanceof CompetitionReversalError)) {
|
||||||
|
throw new Error(
|
||||||
|
`Expected CompetitionReversalError, received ${String(thrown)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
expect(thrown.code).toBe(expectedCode);
|
||||||
|
}
|
||||||
|
|
||||||
function series(id: string, sources: Array<Record<string, unknown>>) {
|
function series(id: string, sources: Array<Record<string, unknown>>) {
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
|
|||||||
@@ -22,6 +22,33 @@ function makeHandler(params: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe('MatchListHandler', () => {
|
describe('MatchListHandler', () => {
|
||||||
|
afterEach(() => {
|
||||||
|
jest.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('queries only matches scheduled at or after command processing time', async () => {
|
||||||
|
const now = new Date('2026-07-25T07:30:00.000Z');
|
||||||
|
jest.useFakeTimers().setSystemTime(now);
|
||||||
|
const communityId = objectId('111111111111111111111111');
|
||||||
|
const list = jest.fn().mockResolvedValue([]);
|
||||||
|
const handler = makeHandler({
|
||||||
|
matchService: { list },
|
||||||
|
});
|
||||||
|
|
||||||
|
await handler.handle({
|
||||||
|
communityId,
|
||||||
|
senderUserId: 'kakao-user-1',
|
||||||
|
senderNickname: '프리리',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(list).toHaveBeenCalledWith({
|
||||||
|
communityId,
|
||||||
|
status: 'recruiting',
|
||||||
|
scheduledFrom: now,
|
||||||
|
limit: 10,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
it('prints short codes, compact KST dates, and short links', async () => {
|
it('prints short codes, compact KST dates, and short links', async () => {
|
||||||
const match = {
|
const match = {
|
||||||
_id: objectId('333333333333333333333333'),
|
_id: objectId('333333333333333333333333'),
|
||||||
|
|||||||
@@ -19,9 +19,11 @@ export class MatchListHandler {
|
|||||||
senderUserId: string;
|
senderUserId: string;
|
||||||
senderNickname: string;
|
senderNickname: string;
|
||||||
}): Promise<DakaoSegment[]> {
|
}): Promise<DakaoSegment[]> {
|
||||||
|
const scheduledFrom = new Date();
|
||||||
const matches = await this.matchService.list({
|
const matches = await this.matchService.list({
|
||||||
communityId: params.communityId,
|
communityId: params.communityId,
|
||||||
status: 'recruiting',
|
status: 'recruiting',
|
||||||
|
scheduledFrom,
|
||||||
limit: 10,
|
limit: 10,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,10 @@ import { Injectable, Logger, Scope, OnModuleInit } from '@nestjs/common';
|
|||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
import { applyMongoosePerformancePlugin } from '../observability/mongoose-performance.plugin';
|
import { applyMongoosePerformancePlugin } from '../observability/mongoose-performance.plugin';
|
||||||
import { SecretService } from '../secret/secret.service';
|
import { SecretService } from '../secret/secret.service';
|
||||||
import { tournamentModelDefinitions, TournamentModelTypes } from './schema';
|
import {
|
||||||
|
tournamentModelDefinitions,
|
||||||
|
type TournamentModelTypes,
|
||||||
|
} from './schema';
|
||||||
|
|
||||||
export function resolveMongoDbName(nodeEnv = process.env.NODE_ENV): string {
|
export function resolveMongoDbName(nodeEnv = process.env.NODE_ENV): string {
|
||||||
if (nodeEnv === 'prod') return 'lolympus';
|
if (nodeEnv === 'prod') return 'lolympus';
|
||||||
@@ -42,7 +45,8 @@ export class ConnectionService implements OnModuleInit {
|
|||||||
private connectionPromise: Promise<mongoose.Connection> | null = null;
|
private connectionPromise: Promise<mongoose.Connection> | null = null;
|
||||||
constructor(private readonly secretService: SecretService) {}
|
constructor(private readonly secretService: SecretService) {}
|
||||||
|
|
||||||
private tournamentModels: Map<string, mongoose.Model<any>> | null = null;
|
private tournamentModels: Map<keyof TournamentModelTypes, unknown> | null =
|
||||||
|
null;
|
||||||
|
|
||||||
public async getConnection(): Promise<mongoose.Connection> {
|
public async getConnection(): Promise<mongoose.Connection> {
|
||||||
if (
|
if (
|
||||||
@@ -89,14 +93,18 @@ export class ConnectionService implements OnModuleInit {
|
|||||||
modelKey: K,
|
modelKey: K,
|
||||||
): Promise<mongoose.Model<TournamentModelTypes[K]>> {
|
): Promise<mongoose.Model<TournamentModelTypes[K]>> {
|
||||||
const connection = await this.getConnection();
|
const connection = await this.getConnection();
|
||||||
if (this.tournamentModels)
|
if (this.tournamentModels) {
|
||||||
return this.tournamentModels.get(modelKey) as mongoose.Model<
|
return this.requireTournamentModel(this.tournamentModels, modelKey);
|
||||||
TournamentModelTypes[K]
|
}
|
||||||
>;
|
|
||||||
|
|
||||||
const models = new Map<K, mongoose.Model<TournamentModelTypes[K]>>();
|
const models = new Map<keyof TournamentModelTypes, unknown>();
|
||||||
|
|
||||||
tournamentModelDefinitions.forEach((modelDefinition) => {
|
tournamentModelDefinitions.forEach((modelDefinition) => {
|
||||||
|
if (!(modelDefinition.schema instanceof mongoose.Schema)) {
|
||||||
|
throw new Error(
|
||||||
|
`Invalid Mongoose schema for model ${modelDefinition.name}.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
applyMongoosePerformancePlugin(modelDefinition.schema);
|
applyMongoosePerformancePlugin(modelDefinition.schema);
|
||||||
// 이미 생성된 경우 컴파일 스킵.
|
// 이미 생성된 경우 컴파일 스킵.
|
||||||
if (
|
if (
|
||||||
@@ -106,14 +114,14 @@ export class ConnectionService implements OnModuleInit {
|
|||||||
)
|
)
|
||||||
) {
|
) {
|
||||||
models.set(
|
models.set(
|
||||||
modelDefinition.name as K,
|
modelDefinition.name,
|
||||||
connection.models[modelDefinition.name],
|
connection.models[modelDefinition.name],
|
||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
} else {
|
} else {
|
||||||
models.set(
|
models.set(
|
||||||
modelDefinition.name as K,
|
modelDefinition.name,
|
||||||
connection.model<TournamentModelTypes[K]>(
|
connection.model(
|
||||||
modelDefinition.name,
|
modelDefinition.name,
|
||||||
modelDefinition.schema,
|
modelDefinition.schema,
|
||||||
modelDefinition.schemaName,
|
modelDefinition.schemaName,
|
||||||
@@ -123,7 +131,18 @@ export class ConnectionService implements OnModuleInit {
|
|||||||
});
|
});
|
||||||
|
|
||||||
this.tournamentModels = models;
|
this.tournamentModels = models;
|
||||||
return models.get(modelKey) as mongoose.Model<TournamentModelTypes[K]>;
|
return this.requireTournamentModel(models, modelKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
private requireTournamentModel<K extends keyof TournamentModelTypes>(
|
||||||
|
models: ReadonlyMap<keyof TournamentModelTypes, unknown>,
|
||||||
|
modelKey: K,
|
||||||
|
): mongoose.Model<TournamentModelTypes[K]> {
|
||||||
|
const model = models.get(modelKey);
|
||||||
|
if (model === undefined) {
|
||||||
|
throw new Error(`Mongoose model ${modelKey} is not registered.`);
|
||||||
|
}
|
||||||
|
return model as mongoose.Model<TournamentModelTypes[K]>;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async createSession(
|
public async createSession(
|
||||||
|
|||||||
@@ -253,9 +253,7 @@ function migrateResult(result: Record<string, unknown>) {
|
|||||||
seriesResults.length > 0 ? seriesResults : buildSeries(games);
|
seriesResults.length > 0 ? seriesResults : buildSeries(games);
|
||||||
|
|
||||||
if (typeof migrated.winnerTeamIndex !== 'number') {
|
if (typeof migrated.winnerTeamIndex !== 'number') {
|
||||||
const migratedSeriesResults = Array.isArray(migrated.seriesResults)
|
const migratedSeriesResults = asArray(migrated.seriesResults);
|
||||||
? migrated.seriesResults
|
|
||||||
: [];
|
|
||||||
migrated.winnerTeamIndex =
|
migrated.winnerTeamIndex =
|
||||||
resolveWinnerTeamIndex(migratedSeriesResults) ??
|
resolveWinnerTeamIndex(migratedSeriesResults) ??
|
||||||
(isSide(migrated.winnerSide)
|
(isSide(migrated.winnerSide)
|
||||||
|
|||||||
+3
-1
@@ -117,7 +117,9 @@ function createDb(params: {
|
|||||||
function matchesFilter(doc: Doc, filter: Record<string, unknown>): boolean {
|
function matchesFilter(doc: Doc, filter: Record<string, unknown>): boolean {
|
||||||
const clauses = filter.$or;
|
const clauses = filter.$or;
|
||||||
if (Array.isArray(clauses)) {
|
if (Array.isArray(clauses)) {
|
||||||
return clauses.some((clause) => matchesFilter(doc, clause));
|
return (clauses as unknown[]).some(
|
||||||
|
(clause) => isRecord(clause) && matchesFilter(doc, clause),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return Object.entries(filter).every(([key, value]) => {
|
return Object.entries(filter).every(([key, value]) => {
|
||||||
|
|||||||
+6
-2
@@ -11,7 +11,11 @@ import {
|
|||||||
} from '../../../double-elimination/double-elimination.util';
|
} from '../../../double-elimination/double-elimination.util';
|
||||||
import { TOURNAMENT_CODE_EXPIRY_MARGIN_MS } from '../../../tournament-code/tournament-code.constants';
|
import { TOURNAMENT_CODE_EXPIRY_MARGIN_MS } from '../../../tournament-code/tournament-code.constants';
|
||||||
import { ConnectionService } from '../connection.service';
|
import { ConnectionService } from '../connection.service';
|
||||||
import type { MatchDocument, TournamentCodeDocument } from '../schema';
|
import type {
|
||||||
|
MatchDocument,
|
||||||
|
TournamentCode,
|
||||||
|
TournamentCodeDocument,
|
||||||
|
} from '../schema';
|
||||||
import { SecretModule } from '../../secret/secret.module';
|
import { SecretModule } from '../../secret/secret.module';
|
||||||
|
|
||||||
interface CliOptions {
|
interface CliOptions {
|
||||||
@@ -334,7 +338,7 @@ function printPlan(plan: MatchRepairPlan) {
|
|||||||
async function applyPlan(
|
async function applyPlan(
|
||||||
match: MatchDocument,
|
match: MatchDocument,
|
||||||
plan: MatchRepairPlan,
|
plan: MatchRepairPlan,
|
||||||
TournamentCodeModel: mongoose.Model<any>,
|
TournamentCodeModel: mongoose.Model<TournamentCode>,
|
||||||
session: mongoose.ClientSession,
|
session: mongoose.ClientSession,
|
||||||
) {
|
) {
|
||||||
if (plan.skippedReason) return;
|
if (plan.skippedReason) return;
|
||||||
|
|||||||
@@ -2485,7 +2485,9 @@ MatchStatsSchema.index({ communityId: 1, userIds: 1 });
|
|||||||
MatchStatsSchema.index({ communityId: 1, userIds: 1, scheduledAt: -1 });
|
MatchStatsSchema.index({ communityId: 1, userIds: 1, scheduledAt: -1 });
|
||||||
MatchStatsSchema.index({ communityId: 1, championIds: 1 });
|
MatchStatsSchema.index({ communityId: 1, championIds: 1 });
|
||||||
|
|
||||||
export const tournamentModelDefinitions: ModelDefinition[] = [
|
export const tournamentModelDefinitions: Array<
|
||||||
|
ModelDefinition & { name: keyof TournamentModelTypes }
|
||||||
|
> = [
|
||||||
...competitionModelDefinitions,
|
...competitionModelDefinitions,
|
||||||
{ name: 'identity', schema: IdentitySchema, schemaName: 'identity' },
|
{ name: 'identity', schema: IdentitySchema, schemaName: 'identity' },
|
||||||
{ name: 'community', schema: CommunitySchema, schemaName: 'community' },
|
{ name: 'community', schema: CommunitySchema, schemaName: 'community' },
|
||||||
|
|||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
export interface ModelDefinition {
|
export interface ModelDefinition {
|
||||||
name: string;
|
name: string;
|
||||||
schema: mongoose.Schema<any>;
|
schema: unknown;
|
||||||
schemaName?: string;
|
schemaName?: string;
|
||||||
}
|
}
|
||||||
@@ -34,10 +34,13 @@ type SchemaWithPerformanceMarker = mongoose.Schema & {
|
|||||||
[PERFORMANCE_PLUGIN_APPLIED]?: boolean;
|
[PERFORMANCE_PLUGIN_APPLIED]?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function applyMongoosePerformancePlugin(schema: mongoose.Schema): void {
|
export function applyMongoosePerformancePlugin(schemaValue: unknown): void {
|
||||||
const markedSchema = schema as SchemaWithPerformanceMarker;
|
if (!(schemaValue instanceof mongoose.Schema)) {
|
||||||
if (markedSchema[PERFORMANCE_PLUGIN_APPLIED]) return;
|
throw new TypeError('Mongoose performance plugin requires a Schema.');
|
||||||
markedSchema[PERFORMANCE_PLUGIN_APPLIED] = true;
|
}
|
||||||
|
const schema = schemaValue as SchemaWithPerformanceMarker;
|
||||||
|
if (schema[PERFORMANCE_PLUGIN_APPLIED]) return;
|
||||||
|
schema[PERFORMANCE_PLUGIN_APPLIED] = true;
|
||||||
|
|
||||||
schema.pre(QUERY_OPERATION_REGEX, function () {
|
schema.pre(QUERY_OPERATION_REGEX, function () {
|
||||||
const query = this as QueryWithPerformanceState;
|
const query = this as QueryWithPerformanceState;
|
||||||
|
|||||||
@@ -5,10 +5,12 @@ describe('MatchService', () => {
|
|||||||
function createServiceWithCreateModels() {
|
function createServiceWithCreateModels() {
|
||||||
const createdPayloads: Record<string, unknown>[] = [];
|
const createdPayloads: Record<string, unknown>[] = [];
|
||||||
const MatchModel = {
|
const MatchModel = {
|
||||||
create: jest.fn().mockImplementation(async (payload) => {
|
create: jest
|
||||||
createdPayloads.push(payload);
|
.fn()
|
||||||
return payload;
|
.mockImplementation(async (payload: Record<string, unknown>) => {
|
||||||
}),
|
createdPayloads.push(payload);
|
||||||
|
return payload;
|
||||||
|
}),
|
||||||
exists: jest.fn().mockResolvedValue(null),
|
exists: jest.fn().mockResolvedValue(null),
|
||||||
};
|
};
|
||||||
const CommunityModel = {
|
const CommunityModel = {
|
||||||
|
|||||||
@@ -53,6 +53,7 @@ function makeScheduler() {
|
|||||||
} as unknown as jest.Mocked<RiotRateLimiterService>;
|
} as unknown as jest.Mocked<RiotRateLimiterService>;
|
||||||
const enrichmentService = {
|
const enrichmentService = {
|
||||||
markRefreshRequested: jest.fn().mockResolvedValue(undefined),
|
markRefreshRequested: jest.fn().mockResolvedValue(undefined),
|
||||||
|
refreshRiotIdentity: jest.fn().mockResolvedValue('unchanged'),
|
||||||
enrichRiotAccount: jest.fn().mockResolvedValue(successResult()),
|
enrichRiotAccount: jest.fn().mockResolvedValue(successResult()),
|
||||||
} as unknown as jest.Mocked<RiotAccountEnrichmentService>;
|
} as unknown as jest.Mocked<RiotAccountEnrichmentService>;
|
||||||
const staleAccountRepository = {
|
const staleAccountRepository = {
|
||||||
@@ -134,7 +135,7 @@ describe('BackgroundRefreshScheduler', () => {
|
|||||||
expect(staleAccountRepository.findStaleAccounts).not.toHaveBeenCalled();
|
expect(staleAccountRepository.findStaleAccounts).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('marks and enriches each stale candidate without background precharge', async () => {
|
it('marks, refreshes identity, and enriches each stale candidate without background precharge', async () => {
|
||||||
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z'));
|
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z'));
|
||||||
const { scheduler, enrichmentService, staleAccountRepository } =
|
const { scheduler, enrichmentService, staleAccountRepository } =
|
||||||
makeScheduler();
|
makeScheduler();
|
||||||
@@ -149,11 +150,21 @@ describe('BackgroundRefreshScheduler', () => {
|
|||||||
candidates[0].userId,
|
candidates[0].userId,
|
||||||
'puuid-1',
|
'puuid-1',
|
||||||
);
|
);
|
||||||
|
expect(enrichmentService.refreshRiotIdentity).toHaveBeenNthCalledWith(1, {
|
||||||
|
userId: candidates[0].userId,
|
||||||
|
puuid: 'puuid-1',
|
||||||
|
});
|
||||||
|
expect(enrichmentService.refreshRiotIdentity).toHaveBeenCalledTimes(2);
|
||||||
expect(enrichmentService.enrichRiotAccount).toHaveBeenNthCalledWith(2, {
|
expect(enrichmentService.enrichRiotAccount).toHaveBeenNthCalledWith(2, {
|
||||||
userId: candidates[1].userId,
|
userId: candidates[1].userId,
|
||||||
puuid: 'puuid-2',
|
puuid: 'puuid-2',
|
||||||
options: { force: false },
|
options: { force: false },
|
||||||
});
|
});
|
||||||
|
expect(
|
||||||
|
enrichmentService.refreshRiotIdentity.mock.invocationCallOrder[0],
|
||||||
|
).toBeLessThan(
|
||||||
|
enrichmentService.enrichRiotAccount.mock.invocationCallOrder[0],
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('stops the candidate loop when the refresh gate closes mid-tick', async () => {
|
it('stops the candidate loop when the refresh gate closes mid-tick', async () => {
|
||||||
@@ -202,6 +213,27 @@ describe('BackgroundRefreshScheduler', () => {
|
|||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('continues statistics enrichment without a failure counter when identity refresh fails', async () => {
|
||||||
|
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z'));
|
||||||
|
const { scheduler, rawClient, enrichmentService, staleAccountRepository } =
|
||||||
|
makeScheduler();
|
||||||
|
const account = candidate('puuid-1');
|
||||||
|
staleAccountRepository.findStaleAccounts.mockResolvedValue([account]);
|
||||||
|
enrichmentService.refreshRiotIdentity.mockResolvedValueOnce('failed');
|
||||||
|
|
||||||
|
await scheduler.tick();
|
||||||
|
|
||||||
|
expect(enrichmentService.refreshRiotIdentity).toHaveBeenCalledWith({
|
||||||
|
userId: account.userId,
|
||||||
|
puuid: 'puuid-1',
|
||||||
|
});
|
||||||
|
expect(enrichmentService.enrichRiotAccount).toHaveBeenCalledTimes(1);
|
||||||
|
expect(rawClient.sendCommand).not.toHaveBeenCalledWith([
|
||||||
|
'INCR',
|
||||||
|
'riot:bg:fail:puuid-1',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
it('skips candidates already in failure backoff', async () => {
|
it('skips candidates already in failure backoff', async () => {
|
||||||
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z'));
|
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z'));
|
||||||
const { scheduler, redis, enrichmentService, staleAccountRepository } =
|
const { scheduler, redis, enrichmentService, staleAccountRepository } =
|
||||||
@@ -217,6 +249,7 @@ describe('BackgroundRefreshScheduler', () => {
|
|||||||
await scheduler.tick();
|
await scheduler.tick();
|
||||||
|
|
||||||
expect(enrichmentService.markRefreshRequested).not.toHaveBeenCalled();
|
expect(enrichmentService.markRefreshRequested).not.toHaveBeenCalled();
|
||||||
|
expect(enrichmentService.refreshRiotIdentity).not.toHaveBeenCalled();
|
||||||
expect(enrichmentService.enrichRiotAccount).not.toHaveBeenCalled();
|
expect(enrichmentService.enrichRiotAccount).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -15,7 +15,10 @@ import {
|
|||||||
} from '../global/redis/distributed-lock.service';
|
} from '../global/redis/distributed-lock.service';
|
||||||
import { RedisService } from '../global/redis/redis.service';
|
import { RedisService } from '../global/redis/redis.service';
|
||||||
import { isInKstBackgroundWindow } from './kst-window.util';
|
import { isInKstBackgroundWindow } from './kst-window.util';
|
||||||
import { StaleAccountRepository } from './stale-account.repository';
|
import {
|
||||||
|
type StaleAccountCandidate,
|
||||||
|
StaleAccountRepository,
|
||||||
|
} from './stale-account.repository';
|
||||||
|
|
||||||
const TICK_INTERVAL_MS = 60_000;
|
const TICK_INTERVAL_MS = 60_000;
|
||||||
const LEADER_LOCK_KEY = 'distributed-lock:riot-background-refresh:leader';
|
const LEADER_LOCK_KEY = 'distributed-lock:riot-background-refresh:leader';
|
||||||
@@ -133,6 +136,7 @@ export class BackgroundRefreshScheduler
|
|||||||
candidate.userId,
|
candidate.userId,
|
||||||
candidate.puuid,
|
candidate.puuid,
|
||||||
);
|
);
|
||||||
|
await this.refreshRiotIdentity(candidate);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const result = await this.enrichmentService.enrichRiotAccount({
|
const result = await this.enrichmentService.enrichRiotAccount({
|
||||||
@@ -165,6 +169,28 @@ export class BackgroundRefreshScheduler
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async refreshRiotIdentity(
|
||||||
|
candidate: StaleAccountCandidate,
|
||||||
|
): Promise<void> {
|
||||||
|
try {
|
||||||
|
const result = await this.enrichmentService.refreshRiotIdentity({
|
||||||
|
userId: candidate.userId,
|
||||||
|
puuid: candidate.puuid,
|
||||||
|
});
|
||||||
|
if (result !== 'failed') return;
|
||||||
|
|
||||||
|
this.logger.warn(
|
||||||
|
`Background Riot identity refresh failed for ${candidate.puuid}.`,
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
this.logger.warn(
|
||||||
|
`Background Riot identity refresh failed for ${candidate.puuid}: ${
|
||||||
|
err instanceof Error ? err.message : String(err)
|
||||||
|
}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private currentRefreshGatePolicy(): RefreshGatePolicy {
|
private currentRefreshGatePolicy(): RefreshGatePolicy {
|
||||||
const isDawn = isInKstBackgroundWindow();
|
const isDawn = isInKstBackgroundWindow();
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -62,6 +62,7 @@ function makeWorker() {
|
|||||||
processMemberJob: jest.fn(),
|
processMemberJob: jest.fn(),
|
||||||
} as unknown as jest.Mocked<LegacyImportService>;
|
} as unknown as jest.Mocked<LegacyImportService>;
|
||||||
const enrichmentService = {
|
const enrichmentService = {
|
||||||
|
refreshRiotIdentity: jest.fn().mockResolvedValue('unchanged'),
|
||||||
refreshLeagueEntries: jest.fn().mockResolvedValue('updated'),
|
refreshLeagueEntries: jest.fn().mockResolvedValue('updated'),
|
||||||
} as unknown as jest.Mocked<RiotAccountEnrichmentService>;
|
} as unknown as jest.Mocked<RiotAccountEnrichmentService>;
|
||||||
|
|
||||||
@@ -116,9 +117,14 @@ describe('RiotJobWorkerService', () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('refreshes league entries while processing user history refresh jobs', async () => {
|
it('refreshes Riot identity and league entries while processing user history refresh jobs', async () => {
|
||||||
const { worker, enrichmentService, recentMatchesService, redisService } =
|
const {
|
||||||
makeWorker();
|
worker,
|
||||||
|
enrichmentService,
|
||||||
|
recentMatchesService,
|
||||||
|
redisService,
|
||||||
|
jobQueueService,
|
||||||
|
} = makeWorker();
|
||||||
const userId = new mongoose.Types.ObjectId().toString();
|
const userId = new mongoose.Types.ObjectId().toString();
|
||||||
const job: RiotRefreshSubJob = {
|
const job: RiotRefreshSubJob = {
|
||||||
jobId: 'job-1',
|
jobId: 'job-1',
|
||||||
@@ -146,11 +152,19 @@ describe('RiotJobWorkerService', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
expect(recentMatchesService.ensureFreshForQueue).toHaveBeenCalledTimes(2);
|
expect(recentMatchesService.ensureFreshForQueue).toHaveBeenCalledTimes(2);
|
||||||
|
expect(enrichmentService.refreshRiotIdentity).toHaveBeenCalledWith({
|
||||||
|
userId: expect.any(mongoose.Types.ObjectId),
|
||||||
|
puuid: 'puuid-1',
|
||||||
|
region: 'asia',
|
||||||
|
});
|
||||||
expect(enrichmentService.refreshLeagueEntries).toHaveBeenCalledWith({
|
expect(enrichmentService.refreshLeagueEntries).toHaveBeenCalledWith({
|
||||||
userId: expect.any(mongoose.Types.ObjectId),
|
userId: expect.any(mongoose.Types.ObjectId),
|
||||||
puuid: 'puuid-1',
|
puuid: 'puuid-1',
|
||||||
platform: 'kr',
|
platform: 'kr',
|
||||||
});
|
});
|
||||||
|
expect(
|
||||||
|
enrichmentService.refreshRiotIdentity.mock.invocationCallOrder[0],
|
||||||
|
).toBeLessThan(jobQueueService.markCompleted.mock.invocationCallOrder[0]);
|
||||||
expect(redisService.acknowledgeStream).toHaveBeenCalledWith(
|
expect(redisService.acknowledgeStream).toHaveBeenCalledWith(
|
||||||
'riot:queue:high',
|
'riot:queue:high',
|
||||||
RIOT_JOB_GROUP,
|
RIOT_JOB_GROUP,
|
||||||
@@ -167,6 +181,45 @@ describe('RiotJobWorkerService', () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('completes successful match refresh work when Riot identity lookup throws', async () => {
|
||||||
|
const { worker, enrichmentService, jobQueueService, refreshGateway } =
|
||||||
|
makeWorker();
|
||||||
|
enrichmentService.refreshRiotIdentity.mockRejectedValueOnce(
|
||||||
|
new Error('Account-V1 unavailable'),
|
||||||
|
);
|
||||||
|
const job: RiotRefreshSubJob = {
|
||||||
|
jobId: 'job-1',
|
||||||
|
parentJobId: 'parent-1',
|
||||||
|
userId: new mongoose.Types.ObjectId().toString(),
|
||||||
|
puuid: 'puuid-1',
|
||||||
|
region: 'asia',
|
||||||
|
platform: 'kr',
|
||||||
|
queueGroup: 'summoners-rift',
|
||||||
|
queueIds: [420],
|
||||||
|
requestedAt: Date.now(),
|
||||||
|
priority: 'high',
|
||||||
|
};
|
||||||
|
|
||||||
|
await (
|
||||||
|
worker as unknown as {
|
||||||
|
processEntry: (
|
||||||
|
stream: string,
|
||||||
|
entry: { id: string; message: Record<string, string> },
|
||||||
|
) => Promise<void>;
|
||||||
|
}
|
||||||
|
).processEntry('riot:queue:high', {
|
||||||
|
id: '1-0',
|
||||||
|
message: { job: JSON.stringify(job) },
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(enrichmentService.refreshRiotIdentity).toHaveBeenCalledTimes(1);
|
||||||
|
expect(jobQueueService.markCompleted).toHaveBeenCalledWith(job);
|
||||||
|
expect(jobQueueService.markFailed).not.toHaveBeenCalled();
|
||||||
|
expect(refreshGateway.broadcastRefreshEvent).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({ state: 'completed' }),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
it('leaves a stream entry pending when another worker owns the job processing lock', async () => {
|
it('leaves a stream entry pending when another worker owns the job processing lock', async () => {
|
||||||
const { worker, distributedLockService, redisService } = makeWorker();
|
const { worker, distributedLockService, redisService } = makeWorker();
|
||||||
distributedLockService.runWithRenewedLock.mockResolvedValueOnce(null);
|
distributedLockService.runWithRenewedLock.mockResolvedValueOnce(null);
|
||||||
|
|||||||
@@ -156,6 +156,7 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
|
|||||||
queueId,
|
queueId,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
await this.refreshRiotIdentity(job);
|
||||||
await this.refreshLeagueEntries(job);
|
await this.refreshLeagueEntries(job);
|
||||||
await this.markUserFetchedAt(job);
|
await this.markUserFetchedAt(job);
|
||||||
const event = await this.jobQueueService.markCompleted(job);
|
const event = await this.jobQueueService.markCompleted(job);
|
||||||
@@ -211,6 +212,26 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async refreshRiotIdentity(job: RiotRefreshSubJob): Promise<void> {
|
||||||
|
try {
|
||||||
|
const result = await this.enrichmentService.refreshRiotIdentity({
|
||||||
|
userId: new mongoose.Types.ObjectId(job.userId),
|
||||||
|
puuid: job.puuid,
|
||||||
|
region: job.region,
|
||||||
|
});
|
||||||
|
if (result !== 'failed') return;
|
||||||
|
this.logger.warn(
|
||||||
|
`Riot identity refresh failed ${job.jobId}: puuid=${job.puuid}`,
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.warn(
|
||||||
|
`Riot identity refresh failed ${job.jobId}: ${
|
||||||
|
error instanceof Error ? error.message : error
|
||||||
|
}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private async refreshLeagueEntries(job: RiotRefreshSubJob): Promise<void> {
|
private async refreshLeagueEntries(job: RiotRefreshSubJob): Promise<void> {
|
||||||
try {
|
try {
|
||||||
const result = await this.enrichmentService.refreshLeagueEntries({
|
const result = await this.enrichmentService.refreshLeagueEntries({
|
||||||
|
|||||||
@@ -12,9 +12,12 @@ import { RiotLeagueService } from './riot-league.service';
|
|||||||
import { RiotRecentMatchesService } from './riot-recent-matches.service';
|
import { RiotRecentMatchesService } from './riot-recent-matches.service';
|
||||||
import { RiotRecentStatsService } from './riot-recent-stats.service';
|
import { RiotRecentStatsService } from './riot-recent-stats.service';
|
||||||
import { RiotSummonerService } from './riot-summoner.service';
|
import { RiotSummonerService } from './riot-summoner.service';
|
||||||
|
import { type RiotPlatformRoute, type RiotRegionalRoute } from './riot.types';
|
||||||
|
|
||||||
interface FakeAccount {
|
interface FakeAccount {
|
||||||
puuid: string;
|
puuid: string;
|
||||||
|
gameName: string;
|
||||||
|
tagLine: string;
|
||||||
profileIconId: number;
|
profileIconId: number;
|
||||||
revisionDate: number;
|
revisionDate: number;
|
||||||
summonerLevel: number;
|
summonerLevel: number;
|
||||||
@@ -56,6 +59,8 @@ interface FakeAccount {
|
|||||||
function makeAccount(overrides: Partial<FakeAccount> = {}): FakeAccount {
|
function makeAccount(overrides: Partial<FakeAccount> = {}): FakeAccount {
|
||||||
return {
|
return {
|
||||||
puuid: 'puuid-1',
|
puuid: 'puuid-1',
|
||||||
|
gameName: 'OldName',
|
||||||
|
tagLine: 'KR1',
|
||||||
profileIconId: 0,
|
profileIconId: 0,
|
||||||
revisionDate: 0,
|
revisionDate: 0,
|
||||||
summonerLevel: 0,
|
summonerLevel: 0,
|
||||||
@@ -82,6 +87,11 @@ function makeUser(account: FakeAccount) {
|
|||||||
|
|
||||||
function makeService(overrides?: {
|
function makeService(overrides?: {
|
||||||
user?: any;
|
user?: any;
|
||||||
|
community?: {
|
||||||
|
riotPlatform?: RiotPlatformRoute;
|
||||||
|
riotRegion?: RiotRegionalRoute;
|
||||||
|
seasonStartedAt?: Date;
|
||||||
|
};
|
||||||
account?: Partial<RiotAccountService>;
|
account?: Partial<RiotAccountService>;
|
||||||
summoner?: Partial<RiotSummonerService>;
|
summoner?: Partial<RiotSummonerService>;
|
||||||
league?: Partial<RiotLeagueService>;
|
league?: Partial<RiotLeagueService>;
|
||||||
@@ -98,10 +108,12 @@ function makeService(overrides?: {
|
|||||||
select: () => ({
|
select: () => ({
|
||||||
lean: () => ({
|
lean: () => ({
|
||||||
exec: () =>
|
exec: () =>
|
||||||
Promise.resolve({
|
Promise.resolve(
|
||||||
riotPlatform: 'kr',
|
overrides?.community ?? {
|
||||||
riotRegion: 'asia',
|
riotPlatform: 'kr',
|
||||||
}),
|
riotRegion: 'asia',
|
||||||
|
},
|
||||||
|
),
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
@@ -130,6 +142,7 @@ function makeService(overrides?: {
|
|||||||
...overrides?.summoner,
|
...overrides?.summoner,
|
||||||
} as unknown as RiotSummonerService;
|
} as unknown as RiotSummonerService;
|
||||||
const accountService = {
|
const accountService = {
|
||||||
|
getByPuuid: jest.fn(),
|
||||||
getRegionByPuuid: jest.fn(),
|
getRegionByPuuid: jest.fn(),
|
||||||
...overrides?.account,
|
...overrides?.account,
|
||||||
} as unknown as RiotAccountService;
|
} as unknown as RiotAccountService;
|
||||||
@@ -177,6 +190,205 @@ function makeService(overrides?: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe('RiotAccountEnrichmentService', () => {
|
describe('RiotAccountEnrichmentService', () => {
|
||||||
|
it('updates a changed Riot ID resolved from the stored PUUID', async () => {
|
||||||
|
const account = makeAccount();
|
||||||
|
const user = makeUser(account);
|
||||||
|
const { service, accountService } = makeService({
|
||||||
|
user,
|
||||||
|
account: {
|
||||||
|
getByPuuid: jest.fn().mockResolvedValue({
|
||||||
|
puuid: 'puuid-1',
|
||||||
|
gameName: 'NewName',
|
||||||
|
tagLine: 'KR1',
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await service.refreshRiotIdentity({
|
||||||
|
userId: user._id,
|
||||||
|
puuid: 'puuid-1',
|
||||||
|
region: 'europe',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result).toBe('updated');
|
||||||
|
expect(account.gameName).toBe('NewName');
|
||||||
|
expect(account.tagLine).toBe('KR1');
|
||||||
|
expect(user.save).toHaveBeenCalledTimes(1);
|
||||||
|
expect(accountService.getByPuuid).toHaveBeenCalledWith('puuid-1', {
|
||||||
|
region: 'europe',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('updates a changed Riot tag line resolved from the stored PUUID', async () => {
|
||||||
|
const account = makeAccount();
|
||||||
|
const user = makeUser(account);
|
||||||
|
const { service } = makeService({
|
||||||
|
user,
|
||||||
|
account: {
|
||||||
|
getByPuuid: jest.fn().mockResolvedValue({
|
||||||
|
puuid: 'puuid-1',
|
||||||
|
gameName: 'OldName',
|
||||||
|
tagLine: 'NEW',
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await service.refreshRiotIdentity({
|
||||||
|
userId: user._id,
|
||||||
|
puuid: 'puuid-1',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result).toBe('updated');
|
||||||
|
expect(account.gameName).toBe('OldName');
|
||||||
|
expect(account.tagLine).toBe('NEW');
|
||||||
|
expect(user.save).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resolves the Riot region from the user community when none is provided', async () => {
|
||||||
|
const account = makeAccount();
|
||||||
|
const user = makeUser(account);
|
||||||
|
const { service, accountService } = makeService({
|
||||||
|
user,
|
||||||
|
community: {
|
||||||
|
riotPlatform: 'na1',
|
||||||
|
riotRegion: 'americas',
|
||||||
|
},
|
||||||
|
account: {
|
||||||
|
getByPuuid: jest.fn().mockResolvedValue({
|
||||||
|
puuid: 'puuid-1',
|
||||||
|
gameName: 'NewName',
|
||||||
|
tagLine: 'NA1',
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await service.refreshRiotIdentity({
|
||||||
|
userId: user._id,
|
||||||
|
puuid: 'puuid-1',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(accountService.getByPuuid).toHaveBeenCalledWith('puuid-1', {
|
||||||
|
region: 'americas',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('falls back to the default Riot region when the community has no region', async () => {
|
||||||
|
const account = makeAccount();
|
||||||
|
const user = makeUser(account);
|
||||||
|
const { service, accountService } = makeService({
|
||||||
|
user,
|
||||||
|
community: {
|
||||||
|
riotPlatform: 'kr',
|
||||||
|
},
|
||||||
|
account: {
|
||||||
|
getByPuuid: jest.fn().mockResolvedValue({
|
||||||
|
puuid: 'puuid-1',
|
||||||
|
gameName: 'NewName',
|
||||||
|
tagLine: 'KR1',
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await service.refreshRiotIdentity({
|
||||||
|
userId: user._id,
|
||||||
|
puuid: 'puuid-1',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(accountService.getByPuuid).toHaveBeenCalledWith('puuid-1', {
|
||||||
|
region: 'asia',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not save when the Riot ID has not changed', async () => {
|
||||||
|
const account = makeAccount();
|
||||||
|
const user = makeUser(account);
|
||||||
|
const { service } = makeService({
|
||||||
|
user,
|
||||||
|
account: {
|
||||||
|
getByPuuid: jest.fn().mockResolvedValue({
|
||||||
|
puuid: 'puuid-1',
|
||||||
|
gameName: 'OldName',
|
||||||
|
tagLine: 'KR1',
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await service.refreshRiotIdentity({
|
||||||
|
userId: user._id,
|
||||||
|
puuid: 'puuid-1',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result).toBe('unchanged');
|
||||||
|
expect(user.save).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
{
|
||||||
|
name: 'a mismatched PUUID',
|
||||||
|
response: {
|
||||||
|
puuid: 'different-puuid',
|
||||||
|
gameName: 'NewName',
|
||||||
|
tagLine: 'NEW',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'a missing game name',
|
||||||
|
response: {
|
||||||
|
puuid: 'puuid-1',
|
||||||
|
gameName: null,
|
||||||
|
tagLine: 'NEW',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'a blank tag line',
|
||||||
|
response: {
|
||||||
|
puuid: 'puuid-1',
|
||||||
|
gameName: 'NewName',
|
||||||
|
tagLine: ' ',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
])('preserves the stored Riot ID for $name', async ({ response }) => {
|
||||||
|
const account = makeAccount();
|
||||||
|
const user = makeUser(account);
|
||||||
|
const { service } = makeService({
|
||||||
|
user,
|
||||||
|
account: {
|
||||||
|
getByPuuid: jest.fn().mockResolvedValue(response),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await service.refreshRiotIdentity({
|
||||||
|
userId: user._id,
|
||||||
|
puuid: 'puuid-1',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result).toBe('failed');
|
||||||
|
expect(account.gameName).toBe('OldName');
|
||||||
|
expect(account.tagLine).toBe('KR1');
|
||||||
|
expect(user.save).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('preserves the stored Riot ID when Account-V1 lookup fails', async () => {
|
||||||
|
const account = makeAccount();
|
||||||
|
const user = makeUser(account);
|
||||||
|
const { service } = makeService({
|
||||||
|
user,
|
||||||
|
account: {
|
||||||
|
getByPuuid: jest.fn().mockRejectedValue(new Error('Riot unavailable')),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await service.refreshRiotIdentity({
|
||||||
|
userId: user._id,
|
||||||
|
puuid: 'puuid-1',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result).toBe('failed');
|
||||||
|
expect(account.gameName).toBe('OldName');
|
||||||
|
expect(account.tagLine).toBe('KR1');
|
||||||
|
expect(user.save).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
it('returns failed for unknown user', async () => {
|
it('returns failed for unknown user', async () => {
|
||||||
const { service } = makeService();
|
const { service } = makeService();
|
||||||
const result = await service.enrichRiotAccount({
|
const result = await service.enrichRiotAccount({
|
||||||
|
|||||||
@@ -59,6 +59,7 @@ export interface EnrichResult {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export type RefreshLeagueEntriesResult = 'updated' | 'failed';
|
export type RefreshLeagueEntriesResult = 'updated' | 'failed';
|
||||||
|
export type RefreshRiotIdentityResult = 'updated' | 'unchanged' | 'failed';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class RiotAccountEnrichmentService {
|
export class RiotAccountEnrichmentService {
|
||||||
@@ -87,6 +88,67 @@ export class RiotAccountEnrichmentService {
|
|||||||
).exec();
|
).exec();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async refreshRiotIdentity(params: {
|
||||||
|
userId: mongoose.Types.ObjectId;
|
||||||
|
puuid: string;
|
||||||
|
region?: RiotRegionalRoute;
|
||||||
|
}): Promise<RefreshRiotIdentityResult> {
|
||||||
|
try {
|
||||||
|
const UserModel = await this.connectionService.getModel('user');
|
||||||
|
const user = await UserModel.findById(params.userId).exec();
|
||||||
|
if (!user) return 'failed';
|
||||||
|
|
||||||
|
const account = user.riotAccounts.find(
|
||||||
|
(candidate) => candidate.puuid === params.puuid,
|
||||||
|
);
|
||||||
|
if (!account) return 'failed';
|
||||||
|
|
||||||
|
let region = params.region;
|
||||||
|
if (!region) {
|
||||||
|
const CommunityModel =
|
||||||
|
await this.connectionService.getModel('community');
|
||||||
|
const community = await CommunityModel.findById(user.communityId)
|
||||||
|
.select({ riotRegion: 1 })
|
||||||
|
.lean()
|
||||||
|
.exec();
|
||||||
|
region = community?.riotRegion ?? DEFAULT_REGION;
|
||||||
|
}
|
||||||
|
|
||||||
|
const identity = await this.accountService.getByPuuid(params.puuid, {
|
||||||
|
region,
|
||||||
|
});
|
||||||
|
if (
|
||||||
|
identity.puuid !== params.puuid ||
|
||||||
|
!identity.gameName?.trim() ||
|
||||||
|
!identity.tagLine?.trim()
|
||||||
|
) {
|
||||||
|
this.logger.warn(
|
||||||
|
`Riot identity response was incomplete or mismatched for ${params.puuid}.`,
|
||||||
|
);
|
||||||
|
return 'failed';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
account.gameName === identity.gameName &&
|
||||||
|
account.tagLine === identity.tagLine
|
||||||
|
) {
|
||||||
|
return 'unchanged';
|
||||||
|
}
|
||||||
|
|
||||||
|
account.gameName = identity.gameName;
|
||||||
|
account.tagLine = identity.tagLine;
|
||||||
|
await user.save();
|
||||||
|
return 'updated';
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.warn(
|
||||||
|
`Riot identity refresh failed for ${params.puuid}: ${
|
||||||
|
error instanceof Error ? error.message : String(error)
|
||||||
|
}`,
|
||||||
|
);
|
||||||
|
return 'failed';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public async enrichRiotAccount(params: {
|
public async enrichRiotAccount(params: {
|
||||||
userId: mongoose.Types.ObjectId;
|
userId: mongoose.Types.ObjectId;
|
||||||
puuid: string;
|
puuid: string;
|
||||||
|
|||||||
@@ -19,15 +19,15 @@
|
|||||||
"preview": "vite preview"
|
"preview": "vite preview"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@lolympus/contracts": "workspace:*",
|
|
||||||
"@azure/msal-browser": "^5.8.0",
|
"@azure/msal-browser": "^5.8.0",
|
||||||
"@azure/msal-react": "^5.3.1",
|
"@azure/msal-react": "^5.3.1",
|
||||||
"@newrelic/browser-agent": "^1.316.0",
|
"@lolympus/contracts": "workspace:*",
|
||||||
|
"@newrelic/browser-agent": "^1.318.0",
|
||||||
"@tanstack/react-query": "^5.100.1",
|
"@tanstack/react-query": "^5.100.1",
|
||||||
"lucide-react": "^1.14.0",
|
"lucide-react": "^1.14.0",
|
||||||
"react": "^19.2.4",
|
"react": "^19.2.8",
|
||||||
"react-dom": "^19.2.4",
|
"react-dom": "^19.2.8",
|
||||||
"react-router": "^7.14.0",
|
"react-router": "^8.3.0",
|
||||||
"recharts": "^3.8.1",
|
"recharts": "^3.8.1",
|
||||||
"socket.io-client": "^4.8.3"
|
"socket.io-client": "^4.8.3"
|
||||||
},
|
},
|
||||||
@@ -46,7 +46,7 @@
|
|||||||
"tailwindcss": "^4.2.2",
|
"tailwindcss": "^4.2.2",
|
||||||
"typescript": "~6.0.2",
|
"typescript": "~6.0.2",
|
||||||
"typescript-eslint": "^8.58.0",
|
"typescript-eslint": "^8.58.0",
|
||||||
"vite": "^8.0.4",
|
"vite": "^8.1.5",
|
||||||
"wrangler": "^4.85.0"
|
"wrangler": "^4.114.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useEffect, useRef, useState } from 'react';
|
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
import { io, type Socket } from 'socket.io-client';
|
import { io, type Socket } from 'socket.io-client';
|
||||||
import { API_BASE_URL, useAuthUserId } from '../config';
|
import { API_BASE_URL, useAuthUserId } from '../config';
|
||||||
import { acquireAccessToken } from '../lib/auth/token-provider';
|
import { acquireAccessToken } from '../lib/auth/token-provider';
|
||||||
@@ -140,6 +140,9 @@ function mergeChatMessages(
|
|||||||
|
|
||||||
export function useAuctionSocket(matchId: string | undefined) {
|
export function useAuctionSocket(matchId: string | undefined) {
|
||||||
const authUserId = useAuthUserId();
|
const authUserId = useAuthUserId();
|
||||||
|
const connectionKey = matchId
|
||||||
|
? JSON.stringify([matchId, authUserId ?? null])
|
||||||
|
: null;
|
||||||
const socketRef = useRef<Socket | null>(null);
|
const socketRef = useRef<Socket | null>(null);
|
||||||
const pendingBidTimeoutsRef = useRef<
|
const pendingBidTimeoutsRef = useRef<
|
||||||
Record<string, ReturnType<typeof setTimeout>>
|
Record<string, ReturnType<typeof setTimeout>>
|
||||||
@@ -166,9 +169,14 @@ export function useAuctionSocket(matchId: string | undefined) {
|
|||||||
Record<string, { action: string }>
|
Record<string, { action: string }>
|
||||||
>({});
|
>({});
|
||||||
const [resetAt, setResetAt] = useState<number | null>(null);
|
const [resetAt, setResetAt] = useState<number | null>(null);
|
||||||
const [connectionStatus, setConnectionStatus] =
|
const [connectionState, setConnectionState] = useState<{
|
||||||
useState<ConnectionStatus>('idle');
|
key: string;
|
||||||
const [error, setError] = useState<string | null>(null);
|
status: ConnectionStatus;
|
||||||
|
}>({ key: '', status: 'idle' });
|
||||||
|
const [errorState, setErrorState] = useState<{
|
||||||
|
key: string;
|
||||||
|
message: string | null;
|
||||||
|
}>({ key: '', message: null });
|
||||||
const [serverTimeOffsetMs, setServerTimeOffsetMs] = useState(0);
|
const [serverTimeOffsetMs, setServerTimeOffsetMs] = useState(0);
|
||||||
const [serverRoundTripMs, setServerRoundTripMs] = useState<number | null>(
|
const [serverRoundTripMs, setServerRoundTripMs] = useState<number | null>(
|
||||||
null,
|
null,
|
||||||
@@ -176,53 +184,50 @@ export function useAuctionSocket(matchId: string | undefined) {
|
|||||||
const [bidLatencyDiagnostics, setBidLatencyDiagnostics] =
|
const [bidLatencyDiagnostics, setBidLatencyDiagnostics] =
|
||||||
useState<BidLatencyDiagnostics | null>(null);
|
useState<BidLatencyDiagnostics | null>(null);
|
||||||
|
|
||||||
function syncLatestConfirmedBidPointAmountFromAuction(
|
const commitAuctionState = useCallback(
|
||||||
nextAuction: ApiAuction,
|
(nextAuction: ApiAuction, source = 'socket-state'): boolean => {
|
||||||
) {
|
const currentAuction = latestAuctionRef.current;
|
||||||
latestConfirmedBidPointAmountRef.current =
|
const applied = shouldApplyIncomingAuctionState(
|
||||||
resolveCurrentBidPointAmount(nextAuction);
|
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),
|
||||||
|
});
|
||||||
|
|
||||||
function commitAuctionState(
|
if (!applied) {
|
||||||
nextAuction: ApiAuction,
|
return false;
|
||||||
source = 'socket-state',
|
}
|
||||||
): boolean {
|
|
||||||
const currentAuction = latestAuctionRef.current;
|
|
||||||
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) {
|
latestAuctionRef.current = nextAuction;
|
||||||
return false;
|
latestConfirmedBidPointAmountRef.current =
|
||||||
}
|
resolveCurrentBidPointAmount(nextAuction);
|
||||||
|
setAuction(nextAuction);
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
[matchId],
|
||||||
|
);
|
||||||
|
|
||||||
latestAuctionRef.current = nextAuction;
|
const commitBidDelta = useCallback((payload: BidDeltaPayload): boolean => {
|
||||||
syncLatestConfirmedBidPointAmountFromAuction(nextAuction);
|
|
||||||
setAuction(nextAuction);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
function commitBidDelta(payload: BidDeltaPayload): boolean {
|
|
||||||
const currentAuction = latestAuctionRef.current;
|
const currentAuction = latestAuctionRef.current;
|
||||||
const nextAuction = applyBidDelta(currentAuction, payload);
|
const nextAuction = applyBidDelta(currentAuction, payload);
|
||||||
if (!nextAuction || nextAuction === currentAuction) {
|
if (!nextAuction || nextAuction === currentAuction) {
|
||||||
@@ -230,10 +235,18 @@ export function useAuctionSocket(matchId: string | undefined) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
latestAuctionRef.current = nextAuction;
|
latestAuctionRef.current = nextAuction;
|
||||||
syncLatestConfirmedBidPointAmountFromAuction(nextAuction);
|
latestConfirmedBidPointAmountRef.current =
|
||||||
|
resolveCurrentBidPointAmount(nextAuction);
|
||||||
setAuction(nextAuction);
|
setAuction(nextAuction);
|
||||||
return true;
|
return true;
|
||||||
}
|
}, []);
|
||||||
|
|
||||||
|
const setError = useCallback(
|
||||||
|
(message: string | null) => {
|
||||||
|
setErrorState({ key: connectionKey ?? '', message });
|
||||||
|
},
|
||||||
|
[connectionKey],
|
||||||
|
);
|
||||||
|
|
||||||
function applyFallbackServerTimestamp(currentServerTimestampMS?: number) {
|
function applyFallbackServerTimestamp(currentServerTimestampMS?: number) {
|
||||||
if (hasSyncedServerTimeRef.current) return;
|
if (hasSyncedServerTimeRef.current) return;
|
||||||
@@ -345,14 +358,47 @@ export function useAuctionSocket(matchId: string | undefined) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const clearPendingBidRequest = useCallback((bidRequestId: string) => {
|
||||||
|
const timeoutId = pendingBidTimeoutsRef.current[bidRequestId];
|
||||||
|
if (timeoutId) clearTimeout(timeoutId);
|
||||||
|
delete pendingBidTimeoutsRef.current[bidRequestId];
|
||||||
|
setPendingBidRequests((current) => {
|
||||||
|
const next = { ...current };
|
||||||
|
delete next[bidRequestId];
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const clearPendingActionRequest = useCallback(
|
||||||
|
(auctionActionRequestId: string) => {
|
||||||
|
const timeoutId =
|
||||||
|
pendingActionTimeoutsRef.current[auctionActionRequestId];
|
||||||
|
if (timeoutId) clearTimeout(timeoutId);
|
||||||
|
delete pendingActionTimeoutsRef.current[auctionActionRequestId];
|
||||||
|
setPendingActionRequests((current) => {
|
||||||
|
const next = { ...current };
|
||||||
|
delete next[auctionActionRequestId];
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
|
||||||
|
const clearPendingActionRequests = useCallback(() => {
|
||||||
|
Object.values(pendingActionTimeoutsRef.current).forEach((timeoutId) =>
|
||||||
|
clearTimeout(timeoutId),
|
||||||
|
);
|
||||||
|
pendingActionTimeoutsRef.current = {};
|
||||||
|
setPendingActionRequests({});
|
||||||
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!matchId) {
|
if (!matchId || !connectionKey) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const activeConnectionKey = connectionKey;
|
||||||
let disposed = false;
|
let disposed = false;
|
||||||
setConnectionStatus('connecting');
|
|
||||||
setError(null);
|
|
||||||
|
|
||||||
void (async () => {
|
void (async () => {
|
||||||
const accessToken = await acquireAccessToken().catch((error) => {
|
const accessToken = await acquireAccessToken().catch((error) => {
|
||||||
@@ -373,7 +419,11 @@ export function useAuctionSocket(matchId: string | undefined) {
|
|||||||
socketRef.current = socket;
|
socketRef.current = socket;
|
||||||
|
|
||||||
socket.on('connect', () => {
|
socket.on('connect', () => {
|
||||||
setConnectionStatus('connected');
|
setConnectionState({
|
||||||
|
key: activeConnectionKey,
|
||||||
|
status: 'connected',
|
||||||
|
});
|
||||||
|
setError(null);
|
||||||
socket.emit('join', { matchId });
|
socket.emit('join', { matchId });
|
||||||
requestServerTimeSync(socket);
|
requestServerTimeSync(socket);
|
||||||
if (timeSyncIntervalRef.current) {
|
if (timeSyncIntervalRef.current) {
|
||||||
@@ -387,7 +437,10 @@ export function useAuctionSocket(matchId: string | undefined) {
|
|||||||
|
|
||||||
socket.on('disconnect', () => {
|
socket.on('disconnect', () => {
|
||||||
clearTimeSyncTimers();
|
clearTimeSyncTimers();
|
||||||
setConnectionStatus('disconnected');
|
setConnectionState({
|
||||||
|
key: activeConnectionKey,
|
||||||
|
status: 'disconnected',
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
socket.on('state', (nextAuction: ApiAuction) => {
|
socket.on('state', (nextAuction: ApiAuction) => {
|
||||||
@@ -520,42 +573,20 @@ export function useAuctionSocket(matchId: string | undefined) {
|
|||||||
hasSyncedServerTimeRef.current = false;
|
hasSyncedServerTimeRef.current = false;
|
||||||
setPendingBidRequests({});
|
setPendingBidRequests({});
|
||||||
setPendingActionRequests({});
|
setPendingActionRequests({});
|
||||||
setConnectionStatus('idle');
|
|
||||||
setServerTimeOffsetMs(0);
|
setServerTimeOffsetMs(0);
|
||||||
setServerRoundTripMs(null);
|
setServerRoundTripMs(null);
|
||||||
setBidLatencyDiagnostics(null);
|
setBidLatencyDiagnostics(null);
|
||||||
};
|
};
|
||||||
}, [authUserId, matchId]);
|
}, [
|
||||||
|
authUserId,
|
||||||
function clearPendingBidRequest(bidRequestId: string) {
|
clearPendingActionRequests,
|
||||||
const timeoutId = pendingBidTimeoutsRef.current[bidRequestId];
|
clearPendingBidRequest,
|
||||||
if (timeoutId) clearTimeout(timeoutId);
|
commitAuctionState,
|
||||||
delete pendingBidTimeoutsRef.current[bidRequestId];
|
commitBidDelta,
|
||||||
setPendingBidRequests((current) => {
|
connectionKey,
|
||||||
const next = { ...current };
|
matchId,
|
||||||
delete next[bidRequestId];
|
setError,
|
||||||
return next;
|
]);
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function clearPendingActionRequest(auctionActionRequestId: string) {
|
|
||||||
const timeoutId = pendingActionTimeoutsRef.current[auctionActionRequestId];
|
|
||||||
if (timeoutId) clearTimeout(timeoutId);
|
|
||||||
delete pendingActionTimeoutsRef.current[auctionActionRequestId];
|
|
||||||
setPendingActionRequests((current) => {
|
|
||||||
const next = { ...current };
|
|
||||||
delete next[auctionActionRequestId];
|
|
||||||
return next;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function clearPendingActionRequests() {
|
|
||||||
Object.values(pendingActionTimeoutsRef.current).forEach((timeoutId) =>
|
|
||||||
clearTimeout(timeoutId),
|
|
||||||
);
|
|
||||||
pendingActionTimeoutsRef.current = {};
|
|
||||||
setPendingActionRequests({});
|
|
||||||
}
|
|
||||||
|
|
||||||
function emit(eventName: string, payload?: unknown) {
|
function emit(eventName: string, payload?: unknown) {
|
||||||
const socket = socketRef.current;
|
const socket = socketRef.current;
|
||||||
@@ -737,9 +768,16 @@ export function useAuctionSocket(matchId: string | undefined) {
|
|||||||
const currentAuction = auction;
|
const currentAuction = auction;
|
||||||
const visibleAuction =
|
const visibleAuction =
|
||||||
currentAuction && currentAuction.matchId === matchId ? currentAuction : null;
|
currentAuction && currentAuction.matchId === matchId ? currentAuction : null;
|
||||||
const visibleConnectionStatus: ConnectionStatus = matchId
|
const visibleConnectionStatus: ConnectionStatus =
|
||||||
? connectionStatus
|
connectionKey === null
|
||||||
: 'idle';
|
? 'idle'
|
||||||
|
: connectionState.key === connectionKey
|
||||||
|
? connectionState.status
|
||||||
|
: 'connecting';
|
||||||
|
const visibleError =
|
||||||
|
connectionKey !== null && errorState.key === connectionKey
|
||||||
|
? errorState.message
|
||||||
|
: null;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
auction: visibleAuction,
|
auction: visibleAuction,
|
||||||
@@ -750,7 +788,7 @@ export function useAuctionSocket(matchId: string | undefined) {
|
|||||||
pendingBidRequests,
|
pendingBidRequests,
|
||||||
resetAt,
|
resetAt,
|
||||||
connectionStatus: visibleConnectionStatus,
|
connectionStatus: visibleConnectionStatus,
|
||||||
error,
|
error: visibleError,
|
||||||
bidLatencyDiagnostics,
|
bidLatencyDiagnostics,
|
||||||
serverRoundTripMs: matchId ? serverRoundTripMs : null,
|
serverRoundTripMs: matchId ? serverRoundTripMs : null,
|
||||||
serverTimeOffsetMs: matchId ? serverTimeOffsetMs : 0,
|
serverTimeOffsetMs: matchId ? serverTimeOffsetMs : 0,
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useEffect, useRef, useState } from 'react';
|
import { useEffect, useRef, useState } from 'react';
|
||||||
import { io, type Socket } from 'socket.io-client';
|
import { io } from 'socket.io-client';
|
||||||
import { API_BASE_URL } from '../config';
|
import { API_BASE_URL } from '../config';
|
||||||
import type { ApiRiotRefreshEvent } from './types';
|
import type { ApiRiotRefreshEvent } from './types';
|
||||||
|
|
||||||
@@ -19,37 +19,43 @@ export function useRiotRefreshSocket({
|
|||||||
parentJobId?: string;
|
parentJobId?: string;
|
||||||
onEvent: (event: ApiRiotRefreshEvent) => void;
|
onEvent: (event: ApiRiotRefreshEvent) => void;
|
||||||
}) {
|
}) {
|
||||||
const socketRef = useRef<Socket | null>(null);
|
const subscriptionKey =
|
||||||
|
puuid || parentJobId ? JSON.stringify([puuid, parentJobId]) : null;
|
||||||
const onEventRef = useRef(onEvent);
|
const onEventRef = useRef(onEvent);
|
||||||
const [connectionStatus, setConnectionStatus] =
|
const [connectionState, setConnectionState] = useState<{
|
||||||
useState<ConnectionStatus>('idle');
|
key: string;
|
||||||
const [error, setError] = useState<string | null>(null);
|
status: ConnectionStatus;
|
||||||
|
error: string | null;
|
||||||
|
}>({ key: '', status: 'idle', error: null });
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
onEventRef.current = onEvent;
|
onEventRef.current = onEvent;
|
||||||
}, [onEvent]);
|
}, [onEvent]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!puuid && !parentJobId) {
|
if (!subscriptionKey) {
|
||||||
setConnectionStatus('idle');
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
setConnectionStatus('connecting');
|
|
||||||
setError(null);
|
|
||||||
|
|
||||||
const socket = io(`${API_BASE_URL}/riot-refresh`, {
|
const socket = io(`${API_BASE_URL}/riot-refresh`, {
|
||||||
transports: ['websocket'],
|
transports: ['websocket'],
|
||||||
});
|
});
|
||||||
socketRef.current = socket;
|
|
||||||
|
|
||||||
socket.on('connect', () => {
|
socket.on('connect', () => {
|
||||||
setConnectionStatus('connected');
|
setConnectionState({
|
||||||
|
key: subscriptionKey,
|
||||||
|
status: 'connected',
|
||||||
|
error: null,
|
||||||
|
});
|
||||||
socket.emit('subscribe', { puuid, parentJobId });
|
socket.emit('subscribe', { puuid, parentJobId });
|
||||||
});
|
});
|
||||||
|
|
||||||
socket.on('disconnect', () => {
|
socket.on('disconnect', () => {
|
||||||
setConnectionStatus('disconnected');
|
setConnectionState((current) => ({
|
||||||
|
key: subscriptionKey,
|
||||||
|
status: 'disconnected',
|
||||||
|
error: current.key === subscriptionKey ? current.error : null,
|
||||||
|
}));
|
||||||
});
|
});
|
||||||
|
|
||||||
socket.on('riot-refresh', (event: ApiRiotRefreshEvent) => {
|
socket.on('riot-refresh', (event: ApiRiotRefreshEvent) => {
|
||||||
@@ -57,17 +63,29 @@ export function useRiotRefreshSocket({
|
|||||||
});
|
});
|
||||||
|
|
||||||
socket.on('error', (payload: { message?: string }) => {
|
socket.on('error', (payload: { message?: string }) => {
|
||||||
setConnectionStatus('error');
|
setConnectionState({
|
||||||
setError(payload.message ?? '전적 갱신 소켓 연결 중 오류가 발생했습니다.');
|
key: subscriptionKey,
|
||||||
|
status: 'error',
|
||||||
|
error:
|
||||||
|
payload.message ?? '전적 갱신 소켓 연결 중 오류가 발생했습니다.',
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
socket.removeAllListeners();
|
socket.removeAllListeners();
|
||||||
socket.disconnect();
|
socket.disconnect();
|
||||||
socketRef.current = null;
|
|
||||||
setConnectionStatus('idle');
|
|
||||||
};
|
};
|
||||||
}, [parentJobId, puuid]);
|
}, [parentJobId, puuid, subscriptionKey]);
|
||||||
|
|
||||||
return { connectionStatus, error };
|
const hasCurrentConnection =
|
||||||
|
subscriptionKey !== null && connectionState.key === subscriptionKey;
|
||||||
|
return {
|
||||||
|
connectionStatus:
|
||||||
|
subscriptionKey === null
|
||||||
|
? 'idle'
|
||||||
|
: hasCurrentConnection
|
||||||
|
? connectionState.status
|
||||||
|
: 'connecting',
|
||||||
|
error: hasCurrentConnection ? connectionState.error : null,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
@@ -1,20 +1,30 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { useQueryClient } from '@tanstack/react-query';
|
import { useQueryClient } from '@tanstack/react-query';
|
||||||
import { setAuthUserId, useAuthUserId } from '../config';
|
import { setAuthUserId, useAuthUserId } from '../config';
|
||||||
|
|
||||||
export default function DevAuthSwitcher() {
|
export default function DevAuthSwitcher() {
|
||||||
const authUserId = useAuthUserId();
|
const authUserId = useAuthUserId();
|
||||||
const queryClient = useQueryClient();
|
|
||||||
const [inputValue, setInputValue] = useState(authUserId ?? '');
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
setInputValue(authUserId ?? '');
|
|
||||||
}, [authUserId]);
|
|
||||||
|
|
||||||
if (!import.meta.env.DEV) {
|
if (!import.meta.env.DEV) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<DevAuthSwitcherForm
|
||||||
|
key={authUserId ?? 'no-auth-user'}
|
||||||
|
authUserId={authUserId}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function DevAuthSwitcherForm({
|
||||||
|
authUserId,
|
||||||
|
}: {
|
||||||
|
authUserId: string | null;
|
||||||
|
}) {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const [inputValue, setInputValue] = useState(authUserId ?? '');
|
||||||
|
|
||||||
function updateAuthUserId(nextValue: string | null) {
|
function updateAuthUserId(nextValue: string | null) {
|
||||||
setAuthUserId(nextValue);
|
setAuthUserId(nextValue);
|
||||||
void queryClient.invalidateQueries();
|
void queryClient.invalidateQueries();
|
||||||
|
|||||||
@@ -1,21 +1,9 @@
|
|||||||
import type { ApiTierInfo } from "../api/types";
|
import type { ApiTierInfo } from "../api/types";
|
||||||
|
import { formatRankBadge, formatRankDetail } from "./rankBadgeUtils";
|
||||||
|
|
||||||
type RankBadgeSize = "sm" | "md";
|
type RankBadgeSize = "sm" | "md";
|
||||||
type RankBadgeTooltipPlacement = "left" | "bottom";
|
type RankBadgeTooltipPlacement = "left" | "bottom";
|
||||||
|
|
||||||
const TIER_NAMES: Record<string, string> = {
|
|
||||||
IRON: "아이언",
|
|
||||||
BRONZE: "브론즈",
|
|
||||||
SILVER: "실버",
|
|
||||||
GOLD: "골드",
|
|
||||||
PLATINUM: "플래티넘",
|
|
||||||
EMERALD: "에메랄드",
|
|
||||||
DIAMOND: "다이아몬드",
|
|
||||||
MASTER: "마스터",
|
|
||||||
GRANDMASTER: "그랜드마스터",
|
|
||||||
CHALLENGER: "챌린저",
|
|
||||||
};
|
|
||||||
|
|
||||||
const SIZE_CLASSES: Record<RankBadgeSize, string> = {
|
const SIZE_CLASSES: Record<RankBadgeSize, string> = {
|
||||||
sm: "h-[17px] min-w-[18px]",
|
sm: "h-[17px] min-w-[18px]",
|
||||||
md: "h-[18px] min-w-[20px]",
|
md: "h-[18px] min-w-[20px]",
|
||||||
@@ -26,21 +14,6 @@ const TOOLTIP_CLASSES: Record<RankBadgeTooltipPlacement, string> = {
|
|||||||
bottom: "tooltip-bottom",
|
bottom: "tooltip-bottom",
|
||||||
};
|
};
|
||||||
|
|
||||||
function normalizeRank(rank: string | undefined) {
|
|
||||||
switch (rank) {
|
|
||||||
case "I":
|
|
||||||
return "1";
|
|
||||||
case "II":
|
|
||||||
return "2";
|
|
||||||
case "III":
|
|
||||||
return "3";
|
|
||||||
case "IV":
|
|
||||||
return "4";
|
|
||||||
default:
|
|
||||||
return rank;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function rankBadgeClass(tier: ApiTierInfo | undefined) {
|
function rankBadgeClass(tier: ApiTierInfo | undefined) {
|
||||||
switch (tier?.tier) {
|
switch (tier?.tier) {
|
||||||
case "CHALLENGER":
|
case "CHALLENGER":
|
||||||
@@ -68,22 +41,6 @@ function rankBadgeClass(tier: ApiTierInfo | undefined) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function formatRankBadge(tier: ApiTierInfo | undefined) {
|
|
||||||
if (!tier) return "U";
|
|
||||||
const tierInitial =
|
|
||||||
tier.tier === "GRANDMASTER" ? "GM" : tier.tier.slice(0, 1);
|
|
||||||
const rank = normalizeRank(tier.rank);
|
|
||||||
return rank ? `${tierInitial}${rank}` : tierInitial;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function formatRankDetail(tier: ApiTierInfo | undefined) {
|
|
||||||
if (!tier) return "랭크 정보 없음";
|
|
||||||
const tierName = TIER_NAMES[tier.tier] ?? tier.tier;
|
|
||||||
const rank = normalizeRank(tier.rank);
|
|
||||||
const label = rank ? `${tierName} ${rank}` : tierName;
|
|
||||||
return `${label} - ${tier.leaguePoints} LP`;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function RankBadge({
|
export function RankBadge({
|
||||||
tier,
|
tier,
|
||||||
size = "md",
|
size = "md",
|
||||||
|
|||||||
@@ -67,6 +67,7 @@ const TIER_COMPACT_NAMES: Record<string, string> = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
type PeriodKey = "30" | "90" | "all";
|
type PeriodKey = "30" | "90" | "all";
|
||||||
|
type PeriodFilter = { key: PeriodKey; cutoffTimestamp: number };
|
||||||
type SummaryVariant = "footer" | "inline";
|
type SummaryVariant = "footer" | "inline";
|
||||||
type SummaryDirection = "up" | "down" | "flat";
|
type SummaryDirection = "up" | "down" | "flat";
|
||||||
|
|
||||||
@@ -314,18 +315,17 @@ export default function TierHistoryChart({
|
|||||||
const [queue, setQueue] = useState(
|
const [queue, setQueue] = useState(
|
||||||
availableQueues[0] ?? "RANKED_SOLO_5x5",
|
availableQueues[0] ?? "RANKED_SOLO_5x5",
|
||||||
);
|
);
|
||||||
const [period, setPeriod] = useState<PeriodKey>("all");
|
const [periodFilter, setPeriodFilter] = useState<PeriodFilter>({
|
||||||
|
key: "all",
|
||||||
|
cutoffTimestamp: 0,
|
||||||
|
});
|
||||||
|
const period = periodFilter.key;
|
||||||
|
|
||||||
const activeQueue = availableQueues.includes(queue)
|
const activeQueue = availableQueues.includes(queue)
|
||||||
? queue
|
? queue
|
||||||
: (availableQueues[0] ?? "RANKED_SOLO_5x5");
|
: (availableQueues[0] ?? "RANKED_SOLO_5x5");
|
||||||
|
|
||||||
const points = useMemo<ChartPoint[]>(() => {
|
const points = useMemo<ChartPoint[]>(() => {
|
||||||
const periodDays =
|
|
||||||
PERIOD_OPTIONS.find((option) => option.key === period)?.days ?? null;
|
|
||||||
const cutoff =
|
|
||||||
periodDays === null ? 0 : Date.now() - periodDays * 24 * 60 * 60 * 1000;
|
|
||||||
|
|
||||||
return entries
|
return entries
|
||||||
.filter((entry) => entry.queueType === activeQueue)
|
.filter((entry) => entry.queueType === activeQueue)
|
||||||
.map((entry) => ({
|
.map((entry) => ({
|
||||||
@@ -337,9 +337,9 @@ export default function TierHistoryChart({
|
|||||||
wins: entry.wins,
|
wins: entry.wins,
|
||||||
losses: entry.losses,
|
losses: entry.losses,
|
||||||
}))
|
}))
|
||||||
.filter((point) => point.ts >= cutoff)
|
.filter((point) => point.ts >= periodFilter.cutoffTimestamp)
|
||||||
.sort((left, right) => left.ts - right.ts);
|
.sort((left, right) => left.ts - right.ts);
|
||||||
}, [entries, activeQueue, period]);
|
}, [entries, activeQueue, periodFilter.cutoffTimestamp]);
|
||||||
|
|
||||||
// 티어 경계(가로 점선) 후보 — 데이터 범위 안에 드는 티어 floor만.
|
// 티어 경계(가로 점선) 후보 — 데이터 범위 안에 드는 티어 floor만.
|
||||||
const tierLines = useMemo(() => {
|
const tierLines = useMemo(() => {
|
||||||
@@ -408,7 +408,19 @@ export default function TierHistoryChart({
|
|||||||
<select
|
<select
|
||||||
className="h-7 border border-base-content/10 bg-base-100 px-2 text-xs text-base-content focus:border-primary/30 focus:outline-none"
|
className="h-7 border border-base-content/10 bg-base-100 px-2 text-xs text-base-content focus:border-primary/30 focus:outline-none"
|
||||||
value={period}
|
value={period}
|
||||||
onChange={(event) => setPeriod(event.target.value as PeriodKey)}
|
onChange={(event) => {
|
||||||
|
const nextPeriod = event.target.value as PeriodKey;
|
||||||
|
const days =
|
||||||
|
PERIOD_OPTIONS.find((option) => option.key === nextPeriod)
|
||||||
|
?.days ?? null;
|
||||||
|
setPeriodFilter({
|
||||||
|
key: nextPeriod,
|
||||||
|
cutoffTimestamp:
|
||||||
|
days === null
|
||||||
|
? 0
|
||||||
|
: Date.now() - days * 24 * 60 * 60 * 1000,
|
||||||
|
});
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
{PERIOD_OPTIONS.map((option) => (
|
{PERIOD_OPTIONS.map((option) => (
|
||||||
<option key={option.key} value={option.key}>
|
<option key={option.key} value={option.key}>
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import type { ApiTierInfo } from "../api/types";
|
||||||
|
|
||||||
|
const TIER_NAMES: Record<string, string> = {
|
||||||
|
IRON: "아이언",
|
||||||
|
BRONZE: "브론즈",
|
||||||
|
SILVER: "실버",
|
||||||
|
GOLD: "골드",
|
||||||
|
PLATINUM: "플래티넘",
|
||||||
|
EMERALD: "에메랄드",
|
||||||
|
DIAMOND: "다이아몬드",
|
||||||
|
MASTER: "마스터",
|
||||||
|
GRANDMASTER: "그랜드마스터",
|
||||||
|
CHALLENGER: "챌린저",
|
||||||
|
};
|
||||||
|
|
||||||
|
function normalizeRank(rank: string | undefined) {
|
||||||
|
switch (rank) {
|
||||||
|
case "I":
|
||||||
|
return "1";
|
||||||
|
case "II":
|
||||||
|
return "2";
|
||||||
|
case "III":
|
||||||
|
return "3";
|
||||||
|
case "IV":
|
||||||
|
return "4";
|
||||||
|
default:
|
||||||
|
return rank;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatRankBadge(tier: ApiTierInfo | undefined) {
|
||||||
|
if (!tier) return "U";
|
||||||
|
const tierInitial =
|
||||||
|
tier.tier === "GRANDMASTER" ? "GM" : tier.tier.slice(0, 1);
|
||||||
|
const rank = normalizeRank(tier.rank);
|
||||||
|
return rank ? `${tierInitial}${rank}` : tierInitial;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatRankDetail(tier: ApiTierInfo | undefined) {
|
||||||
|
if (!tier) return "랭크 정보 없음";
|
||||||
|
const tierName = TIER_NAMES[tier.tier] ?? tier.tier;
|
||||||
|
const rank = normalizeRank(tier.rank);
|
||||||
|
const label = rank ? `${tierName} ${rank}` : tierName;
|
||||||
|
return `${label} - ${tier.leaguePoints} LP`;
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ import {
|
|||||||
lazy,
|
lazy,
|
||||||
memo,
|
memo,
|
||||||
Suspense,
|
Suspense,
|
||||||
|
useCallback,
|
||||||
useEffect,
|
useEffect,
|
||||||
useLayoutEffect,
|
useLayoutEffect,
|
||||||
useMemo,
|
useMemo,
|
||||||
@@ -51,7 +52,8 @@ import {
|
|||||||
teamIndexLabel,
|
teamIndexLabel,
|
||||||
} from "../lib/league";
|
} from "../lib/league";
|
||||||
import { internalMatchGamePath } from "../lib/internal-match-routes";
|
import { internalMatchGamePath } from "../lib/internal-match-routes";
|
||||||
import { formatRankDetail, RankBadge } from "../components/RankBadge";
|
import { RankBadge } from "../components/RankBadge";
|
||||||
|
import { formatRankDetail } from "../components/rankBadgeUtils";
|
||||||
import type {
|
import type {
|
||||||
ApiAuction,
|
ApiAuction,
|
||||||
ApiAuctionChatMessage,
|
ApiAuctionChatMessage,
|
||||||
@@ -1616,7 +1618,6 @@ function BidControls({
|
|||||||
serverTimeOffsetMs: number;
|
serverTimeOffsetMs: number;
|
||||||
onBid: (teamIndex: number, amount: number) => void;
|
onBid: (teamIndex: number, amount: number) => void;
|
||||||
}) {
|
}) {
|
||||||
const [bidAmount, setBidAmount] = useState(100);
|
|
||||||
const minBid = state.currentBid + AUCTION_MIN_BID_POINTS;
|
const minBid = state.currentBid + AUCTION_MIN_BID_POINTS;
|
||||||
const activeTeam = captainRole
|
const activeTeam = captainRole
|
||||||
? state.teams.find((team) => team.teamIndex === captainRole.teamIndex)
|
? state.teams.find((team) => team.teamIndex === captainRole.teamIndex)
|
||||||
@@ -1627,6 +1628,23 @@ function BidControls({
|
|||||||
? getReservedPointsAfterCurrentBid(activeTeam)
|
? getReservedPointsAfterCurrentBid(activeTeam)
|
||||||
: 0;
|
: 0;
|
||||||
const maxBid = activeTeam ? getMaxBidForTeam(activeTeam) : 0;
|
const maxBid = activeTeam ? getMaxBidForTeam(activeTeam) : 0;
|
||||||
|
const defaultBidAmount = Math.max(minBid, Math.ceil(minBid / 10) * 10);
|
||||||
|
const bidContextKey = `${activeTeam?.teamIndex ?? "spectator"}:${maxBid}:${minBid}`;
|
||||||
|
const [bidDraft, setBidDraft] = useState({
|
||||||
|
contextKey: bidContextKey,
|
||||||
|
amount: activeTeam
|
||||||
|
? Math.min(maxBid, defaultBidAmount)
|
||||||
|
: defaultBidAmount,
|
||||||
|
});
|
||||||
|
const bidAmount =
|
||||||
|
bidDraft.contextKey === bidContextKey
|
||||||
|
? bidDraft.amount
|
||||||
|
: activeTeam
|
||||||
|
? Math.min(maxBid, defaultBidAmount)
|
||||||
|
: defaultBidAmount;
|
||||||
|
const setBidAmount = (amount: number) => {
|
||||||
|
setBidDraft({ contextKey: bidContextKey, amount });
|
||||||
|
};
|
||||||
const canAffordNextBid = !isActiveTeamFull && maxBid >= minBid;
|
const canAffordNextBid = !isActiveTeamFull && maxBid >= minBid;
|
||||||
const isBidExpired = useIsDeadlineExpired(
|
const isBidExpired = useIsDeadlineExpired(
|
||||||
state.deadline,
|
state.deadline,
|
||||||
@@ -1637,11 +1655,6 @@ function BidControls({
|
|||||||
? Math.min(maxBid, Math.max(minBid, bidAmount))
|
? Math.min(maxBid, Math.max(minBid, bidAmount))
|
||||||
: Math.max(minBid, bidAmount);
|
: Math.max(minBid, bidAmount);
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const nextBid = Math.max(minBid, Math.ceil(minBid / 10) * 10);
|
|
||||||
setBidAmount(activeTeam ? Math.min(maxBid, nextBid) : nextBid);
|
|
||||||
}, [activeTeam, maxBid, minBid]);
|
|
||||||
|
|
||||||
if (state.phase !== "bidding") return null;
|
if (state.phase !== "bidding") return null;
|
||||||
|
|
||||||
if (!activeTeam) {
|
if (!activeTeam) {
|
||||||
@@ -1843,7 +1856,10 @@ export default function AuctionPage() {
|
|||||||
const resetAuctionMutation = useResetAuction(DEFAULT_COMMUNITY_ID);
|
const resetAuctionMutation = useResetAuction(DEFAULT_COMMUNITY_ID);
|
||||||
const socket = useAuctionSocket(id);
|
const socket = useAuctionSocket(id);
|
||||||
const captainTeamIndex = useDevCaptainTeamIndex();
|
const captainTeamIndex = useDevCaptainTeamIndex();
|
||||||
const [assignedPosition, setAssignedPosition] = useState<Position>("MID");
|
const [assignedPositionDraft, setAssignedPositionDraft] = useState<{
|
||||||
|
playerId: string | null;
|
||||||
|
position: Position;
|
||||||
|
}>({ playerId: null, position: "MID" });
|
||||||
const [showCancelModal, setShowCancelModal] = useState(false);
|
const [showCancelModal, setShowCancelModal] = useState(false);
|
||||||
const [cancelConfirmText, setCancelConfirmText] = useState("");
|
const [cancelConfirmText, setCancelConfirmText] = useState("");
|
||||||
const [undoTargetSequence, setUndoTargetSequence] = useState<number | null>(
|
const [undoTargetSequence, setUndoTargetSequence] = useState<number | null>(
|
||||||
@@ -1853,7 +1869,7 @@ export default function AuctionPage() {
|
|||||||
const historyBackTo = `${location.pathname}${location.search}${location.hash}`;
|
const historyBackTo = `${location.pathname}${location.search}${location.hash}`;
|
||||||
const canConfirmAuctionCancel = cancelConfirmText.trim() === "예";
|
const canConfirmAuctionCancel = cancelConfirmText.trim() === "예";
|
||||||
|
|
||||||
async function clearAuctionDataAfterCancel() {
|
const clearAuctionDataAfterCancel = useCallback(async () => {
|
||||||
if (!id) return;
|
if (!id) return;
|
||||||
const auctionQueryKey = ["auction", DEFAULT_COMMUNITY_ID, id] as const;
|
const auctionQueryKey = ["auction", DEFAULT_COMMUNITY_ID, id] as const;
|
||||||
const auctionHistoryQueryKey = [
|
const auctionHistoryQueryKey = [
|
||||||
@@ -1878,7 +1894,7 @@ export default function AuctionPage() {
|
|||||||
queryKey: ["match", DEFAULT_COMMUNITY_ID, id],
|
queryKey: ["match", DEFAULT_COMMUNITY_ID, id],
|
||||||
exact: true,
|
exact: true,
|
||||||
});
|
});
|
||||||
}
|
}, [id, queryClient]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!showCancelModal) return;
|
if (!showCancelModal) return;
|
||||||
@@ -1893,6 +1909,14 @@ export default function AuctionPage() {
|
|||||||
: null,
|
: null,
|
||||||
[liveAuction, matchQuery.data],
|
[liveAuction, matchQuery.data],
|
||||||
);
|
);
|
||||||
|
const currentPlayerId = auctionState?.currentPlayer?.id ?? null;
|
||||||
|
const assignedPosition =
|
||||||
|
assignedPositionDraft.playerId === currentPlayerId
|
||||||
|
? assignedPositionDraft.position
|
||||||
|
: (auctionState?.currentPlayer?.mainPosition ?? "MID");
|
||||||
|
const setAssignedPosition = (position: Position) => {
|
||||||
|
setAssignedPositionDraft({ playerId: currentPlayerId, position });
|
||||||
|
};
|
||||||
const availableTeamIndexes = useMemo(() => {
|
const availableTeamIndexes = useMemo(() => {
|
||||||
const indexes = new Set(
|
const indexes = new Set(
|
||||||
(auctionState?.teams ?? []).map((team) => team.teamIndex),
|
(auctionState?.teams ?? []).map((team) => team.teamIndex),
|
||||||
@@ -1907,12 +1931,6 @@ export default function AuctionPage() {
|
|||||||
};
|
};
|
||||||
const chatSenderLabel = resolveChatSenderLabel(currentUser, captainRole);
|
const chatSenderLabel = resolveChatSenderLabel(currentUser, captainRole);
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (auctionState?.currentPlayer) {
|
|
||||||
setAssignedPosition(auctionState.currentPlayer.mainPosition);
|
|
||||||
}
|
|
||||||
}, [auctionState?.currentPlayer?.id]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (availableTeamIndexes.length === 0) return;
|
if (availableTeamIndexes.length === 0) return;
|
||||||
if (
|
if (
|
||||||
@@ -1928,7 +1946,7 @@ export default function AuctionPage() {
|
|||||||
void clearAuctionDataAfterCancel().finally(() => {
|
void clearAuctionDataAfterCancel().finally(() => {
|
||||||
navigate(`/match/${id}`, { replace: true });
|
navigate(`/match/${id}`, { replace: true });
|
||||||
});
|
});
|
||||||
}, [id, navigate, socket.resetAt]);
|
}, [clearAuctionDataAfterCancel, id, navigate, socket.resetAt]);
|
||||||
|
|
||||||
if (!DEFAULT_COMMUNITY_ID) {
|
if (!DEFAULT_COMMUNITY_ID) {
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -85,7 +85,6 @@ function HistoryTableColGroup() {
|
|||||||
<col className="w-[88px]" />
|
<col className="w-[88px]" />
|
||||||
<col className="w-[132px]" />
|
<col className="w-[132px]" />
|
||||||
<col className="w-[72px]" />
|
<col className="w-[72px]" />
|
||||||
<col className="w-[116px]" />
|
|
||||||
</colgroup>
|
</colgroup>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -99,7 +98,6 @@ function HistoryTableHeader() {
|
|||||||
<th className="py-2.5 px-4 font-semibold">상태</th>
|
<th className="py-2.5 px-4 font-semibold">상태</th>
|
||||||
<th className="py-2.5 px-4 font-semibold">맵</th>
|
<th className="py-2.5 px-4 font-semibold">맵</th>
|
||||||
<th className="py-2.5 px-4 font-semibold">참가</th>
|
<th className="py-2.5 px-4 font-semibold">참가</th>
|
||||||
<th className="py-2.5 px-4 font-semibold">결과</th>
|
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
);
|
);
|
||||||
@@ -156,14 +154,6 @@ function HistoryRecordsSkeleton({
|
|||||||
10명
|
10명
|
||||||
</SkeletonText>
|
</SkeletonText>
|
||||||
</td>
|
</td>
|
||||||
<td className="py-2.5 px-4 text-xs text-base-content/50 whitespace-nowrap">
|
|
||||||
<SkeletonText
|
|
||||||
className="truncate"
|
|
||||||
skeletonClassName="h-[1em] w-14"
|
|
||||||
>
|
|
||||||
1팀 승리
|
|
||||||
</SkeletonText>
|
|
||||||
</td>
|
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
@@ -205,10 +195,6 @@ function HistoryRecordsSkeleton({
|
|||||||
<SkeletonText skeletonClassName="h-[1em] w-8">
|
<SkeletonText skeletonClassName="h-[1em] w-8">
|
||||||
10명
|
10명
|
||||||
</SkeletonText>
|
</SkeletonText>
|
||||||
<span className="invisible text-base-content/20">·</span>
|
|
||||||
<SkeletonText skeletonClassName="h-[1em] w-14">
|
|
||||||
1팀 승리
|
|
||||||
</SkeletonText>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -682,20 +668,12 @@ export default function HomePage() {
|
|||||||
<td className="py-2.5 px-4 text-xs text-base-content/50 whitespace-nowrap">
|
<td className="py-2.5 px-4 text-xs text-base-content/50 whitespace-nowrap">
|
||||||
{match.participants.length}명
|
{match.participants.length}명
|
||||||
</td>
|
</td>
|
||||||
<td className="py-2.5 px-4 text-xs text-base-content/50 whitespace-nowrap">
|
|
||||||
<Link
|
|
||||||
to={`/match/${match.id}`}
|
|
||||||
className="font-semibold text-base-content/45 hover:text-primary"
|
|
||||||
>
|
|
||||||
공식 결과
|
|
||||||
</Link>
|
|
||||||
</td>
|
|
||||||
</tr>
|
</tr>
|
||||||
))
|
))
|
||||||
) : (
|
) : (
|
||||||
<tr>
|
<tr>
|
||||||
<td
|
<td
|
||||||
colSpan={6}
|
colSpan={5}
|
||||||
className="py-6 px-4 text-sm text-base-content/35 text-center"
|
className="py-6 px-4 text-sm text-base-content/35 text-center"
|
||||||
>
|
>
|
||||||
아직 내전 기록이 없습니다.
|
아직 내전 기록이 없습니다.
|
||||||
|
|||||||
@@ -127,21 +127,6 @@ function formatRefreshError(error: unknown) {
|
|||||||
return error instanceof Error ? error.message : "갱신 요청에 실패했습니다.";
|
return error instanceof Error ? error.message : "갱신 요청에 실패했습니다.";
|
||||||
}
|
}
|
||||||
|
|
||||||
function socketStatusMeta(status: string): { tone: string; label: string } {
|
|
||||||
switch (status) {
|
|
||||||
case "connected":
|
|
||||||
return { tone: "bg-emerald-400", label: "실시간 연결됨" };
|
|
||||||
case "connecting":
|
|
||||||
return { tone: "bg-amber-400", label: "연결 중" };
|
|
||||||
case "error":
|
|
||||||
return { tone: "bg-red-400", label: "연결 오류" };
|
|
||||||
case "disconnected":
|
|
||||||
return { tone: "bg-base-content/30", label: "연결 끊김" };
|
|
||||||
default:
|
|
||||||
return { tone: "bg-base-content/20", label: "대기 중" };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function ratioClass(value: number) {
|
function ratioClass(value: number) {
|
||||||
if (value >= 55) return "text-blue-400";
|
if (value >= 55) return "text-blue-400";
|
||||||
if (value >= 50) return "text-amber-400";
|
if (value >= 50) return "text-amber-400";
|
||||||
@@ -1329,7 +1314,6 @@ export default function UserHistoryPage() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const socketStatus = socketStatusMeta(refreshSocket.connectionStatus);
|
|
||||||
const refreshNoticeIsError =
|
const refreshNoticeIsError =
|
||||||
Boolean(refreshSocket.error) ||
|
Boolean(refreshSocket.error) ||
|
||||||
Boolean(refreshNotice?.startsWith("갱신 실패"));
|
Boolean(refreshNotice?.startsWith("갱신 실패"));
|
||||||
@@ -1386,12 +1370,6 @@ export default function UserHistoryPage() {
|
|||||||
? "요청 중..."
|
? "요청 중..."
|
||||||
: "정보 갱신"}
|
: "정보 갱신"}
|
||||||
</button>
|
</button>
|
||||||
{!isInternalQueue && (
|
|
||||||
<div className="flex items-center gap-1.5 text-[11px] text-base-content/30 sm:justify-end">
|
|
||||||
<span className={`h-1.5 w-1.5 ${socketStatus.tone}`} />
|
|
||||||
{socketStatus.label}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{(refreshNotice || refreshSocket.error) && (
|
{(refreshNotice || refreshSocket.error) && (
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useEffect, useMemo, useState } from 'react';
|
import { useMemo, useState } from 'react';
|
||||||
import { useQueryClient } from '@tanstack/react-query';
|
import { useQueryClient } from '@tanstack/react-query';
|
||||||
import { Link, useParams } from 'react-router';
|
import { Link, useParams } from 'react-router';
|
||||||
import {
|
import {
|
||||||
@@ -8,11 +8,17 @@ import {
|
|||||||
useMe,
|
useMe,
|
||||||
useStartLegacyImport,
|
useStartLegacyImport,
|
||||||
} from '../../api/hooks';
|
} from '../../api/hooks';
|
||||||
import type { LegacyImportJob, StartLegacyImportRequest } from '../../api/types';
|
import type {
|
||||||
|
LegacyImportJob,
|
||||||
|
LegacyImportMemberWindow,
|
||||||
|
StartLegacyImportRequest,
|
||||||
|
} from '../../api/types';
|
||||||
import { DEFAULT_COMMUNITY_ID } from '../../config';
|
import { DEFAULT_COMMUNITY_ID } from '../../config';
|
||||||
|
|
||||||
const DEFAULT_START = '2024-05-01T00:00:00.000Z';
|
const DEFAULT_START = '2024-05-01T00:00:00.000Z';
|
||||||
|
|
||||||
|
type MemberWindowOverride = { startTime: string; endTime: string };
|
||||||
|
|
||||||
function toInputValue(value: string) {
|
function toInputValue(value: string) {
|
||||||
const date = new Date(value);
|
const date = new Date(value);
|
||||||
const local = new Date(date.getTime() - date.getTimezoneOffset() * 60_000);
|
const local = new Date(date.getTime() - date.getTimezoneOffset() * 60_000);
|
||||||
@@ -44,6 +50,15 @@ function progress(job: LegacyImportJob) {
|
|||||||
return Math.round((job.processedMembers / job.totalMembers) * 100);
|
return Math.round((job.processedMembers / job.totalMembers) * 100);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function defaultMemberOverride(
|
||||||
|
member: LegacyImportMemberWindow,
|
||||||
|
): MemberWindowOverride {
|
||||||
|
return {
|
||||||
|
startTime: toInputValue(member.startTime),
|
||||||
|
endTime: toInputValue(member.endTime),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function JobCard({
|
function JobCard({
|
||||||
job,
|
job,
|
||||||
onCancel,
|
onCancel,
|
||||||
@@ -111,7 +126,7 @@ export default function LegacyImportPage() {
|
|||||||
const [windowEnd, setWindowEnd] = useState('');
|
const [windowEnd, setWindowEnd] = useState('');
|
||||||
const [message, setMessage] = useState<string | null>(null);
|
const [message, setMessage] = useState<string | null>(null);
|
||||||
const [overrides, setOverrides] = useState<
|
const [overrides, setOverrides] = useState<
|
||||||
Record<string, { startTime: string; endTime: string }>
|
Record<string, MemberWindowOverride>
|
||||||
>({});
|
>({});
|
||||||
const currentUser =
|
const currentUser =
|
||||||
meQuery.data?.memberships.find(
|
meQuery.data?.memberships.find(
|
||||||
@@ -131,20 +146,6 @@ export default function LegacyImportPage() {
|
|||||||
const cancelMutation = useCancelLegacyImport(communityId);
|
const cancelMutation = useCancelLegacyImport(communityId);
|
||||||
const members = membersQuery.data?.members ?? [];
|
const members = membersQuery.data?.members ?? [];
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
setOverrides(
|
|
||||||
Object.fromEntries(
|
|
||||||
members.map((member) => [
|
|
||||||
member.userId,
|
|
||||||
{
|
|
||||||
startTime: toInputValue(member.startTime),
|
|
||||||
endTime: toInputValue(member.endTime),
|
|
||||||
},
|
|
||||||
]),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}, [members]);
|
|
||||||
|
|
||||||
const manageableMemberships =
|
const manageableMemberships =
|
||||||
meQuery.data?.memberships.filter((membership) => {
|
meQuery.data?.memberships.filter((membership) => {
|
||||||
const role = membership.user.role;
|
const role = membership.user.role;
|
||||||
@@ -180,11 +181,15 @@ export default function LegacyImportPage() {
|
|||||||
const payload: StartLegacyImportRequest = {
|
const payload: StartLegacyImportRequest = {
|
||||||
windowStart: fromInputValue(windowStart),
|
windowStart: fromInputValue(windowStart),
|
||||||
windowEnd: fromInputValue(windowEnd),
|
windowEnd: fromInputValue(windowEnd),
|
||||||
memberOverrides: members.map((member) => ({
|
memberOverrides: members.map((member) => {
|
||||||
userId: member.userId,
|
const override =
|
||||||
startTime: fromInputValue(overrides[member.userId]?.startTime ?? ''),
|
overrides[member.userId] ?? defaultMemberOverride(member);
|
||||||
endTime: fromInputValue(overrides[member.userId]?.endTime ?? ''),
|
return {
|
||||||
})),
|
userId: member.userId,
|
||||||
|
startTime: fromInputValue(override.startTime),
|
||||||
|
endTime: fromInputValue(override.endTime),
|
||||||
|
};
|
||||||
|
}),
|
||||||
};
|
};
|
||||||
startMutation.mutate(payload, {
|
startMutation.mutate(payload, {
|
||||||
onSuccess: async (result) => {
|
onSuccess: async (result) => {
|
||||||
@@ -323,53 +328,68 @@ export default function LegacyImportPage() {
|
|||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{members.map((member) => (
|
{members.map((member) => {
|
||||||
<tr key={member.userId} className="border-b border-base-content/5">
|
const override =
|
||||||
<td className="px-3 py-2 text-sm font-bold">
|
overrides[member.userId] ?? defaultMemberOverride(member);
|
||||||
{member.displayName}
|
return (
|
||||||
</td>
|
<tr
|
||||||
<td className="px-3 py-2 text-xs text-base-content/45">
|
key={member.userId}
|
||||||
{member.gameName}#{member.tagLine}
|
className="border-b border-base-content/5"
|
||||||
</td>
|
>
|
||||||
<td className="px-3 py-2 text-xs">
|
<td className="px-3 py-2 text-sm font-bold">
|
||||||
{member.isActivated ? '활성' : '비활성'}
|
{member.displayName}
|
||||||
</td>
|
</td>
|
||||||
<td className="px-3 py-2">
|
<td className="px-3 py-2 text-xs text-base-content/45">
|
||||||
<input
|
{member.gameName}#{member.tagLine}
|
||||||
type="datetime-local"
|
</td>
|
||||||
value={overrides[member.userId]?.startTime ?? ''}
|
<td className="px-3 py-2 text-xs">
|
||||||
onChange={(event) =>
|
{member.isActivated ? '활성' : '비활성'}
|
||||||
setOverrides((current) => ({
|
</td>
|
||||||
...current,
|
<td className="px-3 py-2">
|
||||||
[member.userId]: {
|
<input
|
||||||
...current[member.userId],
|
type="datetime-local"
|
||||||
startTime: event.target.value,
|
value={override.startTime}
|
||||||
endTime: current[member.userId]?.endTime ?? '',
|
onChange={(event) =>
|
||||||
},
|
setOverrides((current) => {
|
||||||
}))
|
const currentOverride =
|
||||||
}
|
current[member.userId] ??
|
||||||
className="border border-base-content/10 bg-transparent px-2 py-1 text-xs"
|
defaultMemberOverride(member);
|
||||||
/>
|
return {
|
||||||
</td>
|
...current,
|
||||||
<td className="px-3 py-2">
|
[member.userId]: {
|
||||||
<input
|
...currentOverride,
|
||||||
type="datetime-local"
|
startTime: event.target.value,
|
||||||
value={overrides[member.userId]?.endTime ?? ''}
|
},
|
||||||
onChange={(event) =>
|
};
|
||||||
setOverrides((current) => ({
|
})
|
||||||
...current,
|
}
|
||||||
[member.userId]: {
|
className="border border-base-content/10 bg-transparent px-2 py-1 text-xs"
|
||||||
...current[member.userId],
|
/>
|
||||||
startTime: current[member.userId]?.startTime ?? '',
|
</td>
|
||||||
endTime: event.target.value,
|
<td className="px-3 py-2">
|
||||||
},
|
<input
|
||||||
}))
|
type="datetime-local"
|
||||||
}
|
value={override.endTime}
|
||||||
className="border border-base-content/10 bg-transparent px-2 py-1 text-xs"
|
onChange={(event) =>
|
||||||
/>
|
setOverrides((current) => {
|
||||||
</td>
|
const currentOverride =
|
||||||
</tr>
|
current[member.userId] ??
|
||||||
))}
|
defaultMemberOverride(member);
|
||||||
|
return {
|
||||||
|
...current,
|
||||||
|
[member.userId]: {
|
||||||
|
...currentOverride,
|
||||||
|
endTime: event.target.value,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
})
|
||||||
|
}
|
||||||
|
className="border border-base-content/10 bg-transparent px-2 py-1 text-xs"
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
);
|
||||||
|
})}
|
||||||
{members.length === 0 && (
|
{members.length === 0 && (
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan={5} className="px-4 py-8 text-center text-sm text-base-content/35">
|
<td colSpan={5} className="px-4 py-8 text-center text-sm text-base-content/35">
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { readFile } from "node:fs/promises";
|
||||||
|
import test from "node:test";
|
||||||
|
|
||||||
|
const homePageSource = await readFile(
|
||||||
|
new URL("../src/pages/HomePage.tsx", import.meta.url),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
|
||||||
|
test("keeps past match history focused on the five summary columns", () => {
|
||||||
|
const colGroup = sourceForFunction("HistoryTableColGroup");
|
||||||
|
const header = sourceForFunction("HistoryTableHeader");
|
||||||
|
const skeleton = sourceForFunction("HistoryRecordsSkeleton");
|
||||||
|
|
||||||
|
assert.equal(colGroup.match(/<col(?:\s|\/|>)/g)?.length, 5);
|
||||||
|
assert.doesNotMatch(header, />결과<\/th>/);
|
||||||
|
assert.doesNotMatch(homePageSource, /공식 결과/);
|
||||||
|
assert.doesNotMatch(skeleton, /1팀 승리/);
|
||||||
|
assert.match(homePageSource, /colSpan=\{5\}/);
|
||||||
|
});
|
||||||
|
|
||||||
|
function sourceForFunction(name: string): string {
|
||||||
|
const start = homePageSource.indexOf(`function ${name}(`);
|
||||||
|
assert.notEqual(start, -1, `${name} should exist`);
|
||||||
|
|
||||||
|
const nextFunction = homePageSource.indexOf("\nfunction ", start + 1);
|
||||||
|
assert.notEqual(nextFunction, -1, `${name} should have a following function`);
|
||||||
|
return homePageSource.slice(start, nextFunction);
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { readFile } from "node:fs/promises";
|
||||||
|
import test from "node:test";
|
||||||
|
|
||||||
|
const userHistoryPageSource = await readFile(
|
||||||
|
new URL("../src/pages/UserHistoryPage.tsx", import.meta.url),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
|
||||||
|
test("hides the temporary real-time connection status indicator", () => {
|
||||||
|
assert.doesNotMatch(userHistoryPageSource, /실시간 연결됨/);
|
||||||
|
assert.doesNotMatch(userHistoryPageSource, /refreshSocket\.connectionStatus/);
|
||||||
|
});
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
# Implementation Plan: Refresh Riot ID by PUUID
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
Deliver the behavior in three backend slices. First add and prove the safe
|
||||||
|
Account-V1-to-user persistence operation. Then invoke it from the existing
|
||||||
|
personal-history refresh worker before completion is broadcast. Finally reuse it
|
||||||
|
from stale-account background refresh with community-aware region resolution and
|
||||||
|
failure isolation. No database or frontend contract change is required.
|
||||||
|
|
||||||
|
## Task List
|
||||||
|
|
||||||
|
### Phase 1: Identity Refresh Boundary
|
||||||
|
|
||||||
|
- [x] Add failing tests for changed, unchanged, incomplete, mismatched, and failed
|
||||||
|
PUUID identity lookups.
|
||||||
|
- Acceptance: tests describe state outcomes and fail because the focused method
|
||||||
|
is not implemented.
|
||||||
|
- Verify:
|
||||||
|
`pnpm --filter api exec jest --runInBand riot-account-enrichment.service.spec.ts`
|
||||||
|
- Files:
|
||||||
|
`apps/api/src/modules/riot/riot-account-enrichment.service.spec.ts`
|
||||||
|
- [x] Implement `refreshRiotIdentity` using `RiotAccountService.getByPuuid`.
|
||||||
|
- Acceptance: valid changed values persist together; invalid results preserve
|
||||||
|
existing values; unchanged values avoid a write.
|
||||||
|
- Verify: the Phase 1 focused test passes.
|
||||||
|
- Files:
|
||||||
|
`apps/api/src/modules/riot/riot-account-enrichment.service.ts`
|
||||||
|
|
||||||
|
### Checkpoint: Phase 1
|
||||||
|
|
||||||
|
- [x] The enrichment service has a typed three-state result and all focused tests
|
||||||
|
pass.
|
||||||
|
- [x] No schema, endpoint, queue payload, or frontend changes exist.
|
||||||
|
|
||||||
|
### Phase 2: Refresh Worker Integration
|
||||||
|
|
||||||
|
- [x] Add a failing worker test proving that a user-history job requests identity
|
||||||
|
refresh with its user ID, PUUID, and region.
|
||||||
|
- Acceptance: the test fails before worker orchestration is updated.
|
||||||
|
- Verify:
|
||||||
|
`pnpm --filter api exec jest --runInBand riot-job-worker.service.spec.ts`
|
||||||
|
- Files: `apps/api/src/modules/riot-job-queue/riot-job-worker.service.spec.ts`
|
||||||
|
- [x] Invoke best-effort identity refresh before job completion.
|
||||||
|
- Acceptance: the worker logs identity failure without aborting successful match
|
||||||
|
refresh work, and broadcasts completion only after identity refresh returns.
|
||||||
|
- Verify: the Phase 2 focused test passes.
|
||||||
|
- Files: `apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts`
|
||||||
|
|
||||||
|
### Checkpoint: Complete
|
||||||
|
|
||||||
|
- [x] Focused API suites pass without skipped tests.
|
||||||
|
- [x] API lint and build pass.
|
||||||
|
- [x] Web lint and production build pass, confirming the existing profile
|
||||||
|
invalidation integration remains compatible.
|
||||||
|
- [x] Final diff contains only the specification, plan, enrichment service, worker,
|
||||||
|
and their tests.
|
||||||
|
|
||||||
|
### Phase 3: Background Refresh Integration
|
||||||
|
|
||||||
|
- [x] Add a failing enrichment-service test proving that an omitted region is
|
||||||
|
resolved from the user's community.
|
||||||
|
- Acceptance: a non-Asia community route reaches Account-V1 without changing the
|
||||||
|
public method signature.
|
||||||
|
- Verify:
|
||||||
|
`pnpm --filter api exec jest --runInBand riot-account-enrichment.service.spec.ts`
|
||||||
|
- Files:
|
||||||
|
`apps/api/src/modules/riot/riot-account-enrichment.service.spec.ts`
|
||||||
|
- [x] Resolve the community Riot region for region-less identity refresh calls.
|
||||||
|
- Acceptance: explicit caller regions remain unchanged; missing community routes
|
||||||
|
use the existing `asia` fallback.
|
||||||
|
- Verify: the focused enrichment-service test passes.
|
||||||
|
- Files:
|
||||||
|
`apps/api/src/modules/riot/riot-account-enrichment.service.ts`
|
||||||
|
- [x] Add failing background scheduler tests for identity refresh ordering and
|
||||||
|
failure isolation.
|
||||||
|
- Acceptance: stale accounts request identity refresh before statistics
|
||||||
|
enrichment, while identity rejection does not increment failure counters.
|
||||||
|
- Verify:
|
||||||
|
`pnpm --filter api exec jest --runInBand background-refresh.scheduler.spec.ts`
|
||||||
|
- Files:
|
||||||
|
`apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.spec.ts`
|
||||||
|
- [x] Invoke best-effort identity refresh from the stale-account loop.
|
||||||
|
- Acceptance: each processed candidate gets one PUUID identity lookup, statistics
|
||||||
|
enrichment still determines processed/failed/backoff state, and no new Redis or
|
||||||
|
database contract is added.
|
||||||
|
- Verify: the focused background scheduler tests pass.
|
||||||
|
- Files:
|
||||||
|
`apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.ts`
|
||||||
|
|
||||||
|
### Checkpoint: Background Refresh Complete
|
||||||
|
|
||||||
|
- [x] Focused identity, manual worker, and background scheduler suites pass.
|
||||||
|
- [x] API lint, full tests, and build pass.
|
||||||
|
- [x] Final diff remains limited to the existing feature documents, identity
|
||||||
|
service/tests, and background scheduler/tests.
|
||||||
|
|
||||||
|
## Risks and Mitigations
|
||||||
|
|
||||||
|
| Risk | Impact | Mitigation |
|
||||||
|
|---|---|---|
|
||||||
|
| Account-V1 returns an incomplete identity | High | Require matching PUUID and two non-empty Riot ID fields before mutation. |
|
||||||
|
| Riot Account-V1 is temporarily unavailable | Medium | Preserve stored identity, log the failure, and retain existing best-effort job semantics. |
|
||||||
|
| Multiple queue groups repeat identity lookup | Low | The personal page requests one queue group; avoid a new dedup mechanism until a measured need exists. |
|
||||||
|
| Background community uses a non-Asia Riot route | High | Resolve omitted regions from the user's community before falling back to `asia`. |
|
||||||
|
| Identity lookup failure triggers background backoff | Medium | Isolate identity exceptions and let existing statistics enrichment alone control failure counters. |
|
||||||
|
| UI keeps the stale profile cached | High | Identity update completes before the existing completion event invalidates the profile query. |
|
||||||
|
| Historical names are unexpectedly rewritten | Medium | Restrict persistence to the embedded Riot account and leave match snapshots untouched. |
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
```text
|
||||||
|
validated Account-V1 lookup
|
||||||
|
-> focused identity persistence method
|
||||||
|
-> manual refresh worker -> existing completion event -> profile invalidation
|
||||||
|
-> background scheduler -> existing statistics enrichment and backoff policy
|
||||||
|
```
|
||||||
|
|
||||||
|
## Open Questions
|
||||||
|
|
||||||
|
None. The user approved the specification and requested implementation.
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# Dependency Audit Exceptions
|
||||||
|
|
||||||
|
## GHSA-mh99-v99m-4gvg
|
||||||
|
|
||||||
|
- Package: `brace-expansion`
|
||||||
|
- Scope: development tooling only (`eslint`, `jest`, and `@nestjs/cli` through
|
||||||
|
`minimatch`/`glob`)
|
||||||
|
- Production exposure: none; `pnpm audit --prod --audit-level high` reports no
|
||||||
|
high or critical findings
|
||||||
|
- Reason: the only patched release is `brace-expansion@5.0.8`, whose CommonJS
|
||||||
|
API is incompatible with the affected `minimatch@3` and `minimatch@9`
|
||||||
|
consumers
|
||||||
|
- Mitigation: repository-controlled glob patterns are trusted; no
|
||||||
|
attacker-controlled input is passed to these development tools
|
||||||
|
- Review date: 2026-08-25
|
||||||
|
- Removal condition: remove the audit exception once the upstream toolchain
|
||||||
|
supports `brace-expansion@5.0.8` or publishes compatible patched releases
|
||||||
|
|
||||||
|
## Tracked remediation
|
||||||
|
|
||||||
|
### GHSA-664h-wqgq-64gw
|
||||||
|
|
||||||
|
- Package: `mongoose@9.4.1`
|
||||||
|
- Severity: moderate
|
||||||
|
- Patched version: `>=9.7.2`
|
||||||
|
- Status: not ignored; it remains visible in a full audit and does not fail the
|
||||||
|
high-severity CI gate
|
||||||
|
- Upgrade blocker: Mongoose 9.7.x tightens create and query types and currently
|
||||||
|
causes API compilation failures across the model layer
|
||||||
|
- Next action: migrate the affected model create/query types, then upgrade
|
||||||
|
Mongoose in a dedicated change
|
||||||
|
- Review date: 2026-08-25
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
# Spec: Dakao Upcoming Internal Match List
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
|
||||||
|
When a user sends `!내전 일정`, return only recruiting matches whose scheduled
|
||||||
|
start is not earlier than the command processing time. Matches that have already
|
||||||
|
started must not consume the ten-result query limit or appear in the response.
|
||||||
|
|
||||||
|
## Approved Product Decisions
|
||||||
|
|
||||||
|
- Capture the command processing time once before querying matches.
|
||||||
|
- Exclude `scheduledAt < now`.
|
||||||
|
- Include `scheduledAt === now` and future matches.
|
||||||
|
- Apply the boundary only to the Dakao `!내전 일정` command.
|
||||||
|
- Preserve the existing recruiting status, result limit, ordering, formatting,
|
||||||
|
short-code generation, and short-link behavior.
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
- Focused test:
|
||||||
|
`pnpm --filter api exec jest src/modules/dakao/handlers/match-list.handler.spec.ts --runInBand`
|
||||||
|
- API lint:
|
||||||
|
`pnpm --filter api exec eslint "{src,apps,libs,test}/**/*.ts" --max-warnings=0`
|
||||||
|
- API build: `pnpm --filter api build`
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
- `apps/api/src/modules/dakao/handlers/match-list.handler.ts` owns the command
|
||||||
|
query and response formatting.
|
||||||
|
- `apps/api/src/modules/dakao/handlers/match-list.handler.spec.ts` verifies the
|
||||||
|
command boundary and presentation.
|
||||||
|
- `apps/api/src/modules/match/match.service.ts` translates `scheduledFrom` into a
|
||||||
|
MongoDB `$gte` filter.
|
||||||
|
|
||||||
|
## Code Style
|
||||||
|
|
||||||
|
Pass the captured boundary through the existing list contract:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const scheduledFrom = new Date();
|
||||||
|
await matchService.list({ communityId, scheduledFrom });
|
||||||
|
```
|
||||||
|
|
||||||
|
## Testing Strategy
|
||||||
|
|
||||||
|
- Freeze the system clock in the handler unit test.
|
||||||
|
- Assert that the exact frozen time is passed as `scheduledFrom`.
|
||||||
|
- Rely on the existing `MatchService` test that verifies `scheduledFrom` becomes
|
||||||
|
`{ scheduledAt: { $gte: scheduledFrom } }`.
|
||||||
|
- Run the focused handler test, full API lint, and API build.
|
||||||
|
|
||||||
|
## Boundaries
|
||||||
|
|
||||||
|
- Always: filter before applying the result limit and use one captured time.
|
||||||
|
- Ask first: change ordering, statuses, limit, or response wording.
|
||||||
|
- Never: hide the requirement with an ESLint exception or filter only after the
|
||||||
|
limited database query.
|
||||||
|
|
||||||
|
## Success Criteria
|
||||||
|
|
||||||
|
- A match scheduled before command processing time is not queried.
|
||||||
|
- A match scheduled exactly at command processing time remains eligible.
|
||||||
|
- Existing command formatting and link tests continue to pass.
|
||||||
|
|
||||||
|
## Open Questions
|
||||||
|
|
||||||
|
None.
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
# Spec: Refresh Riot ID by PUUID
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
|
||||||
|
Whenever an account is refreshed manually from the personal match-history page
|
||||||
|
or automatically by the stale-account background scheduler, resolve its current
|
||||||
|
Riot ID through Riot Account-V1 using the stored PUUID. If the player changed
|
||||||
|
either their game name or tag line, persist the latest values on the same embedded
|
||||||
|
Riot account so the profile displays the new Riot ID.
|
||||||
|
|
||||||
|
The existing refresh job remains the single user-facing operation. It continues
|
||||||
|
to refresh matches and ranked data, and additionally refreshes identity before
|
||||||
|
emitting its completion event.
|
||||||
|
|
||||||
|
## Approved Product Decisions
|
||||||
|
|
||||||
|
- Use the stored PUUID as the stable identity key; never look up the account by
|
||||||
|
the possibly stale game name and tag line.
|
||||||
|
- Query Riot Account-V1 on every manually queued user-history refresh job and
|
||||||
|
every selected stale-account background refresh rather than applying a name TTL.
|
||||||
|
- Update `gameName` and `tagLine` together only when Riot returns a matching PUUID
|
||||||
|
and both values are non-empty.
|
||||||
|
- Preserve the previous Riot ID if the Account-V1 lookup fails or returns an
|
||||||
|
incomplete or mismatched response.
|
||||||
|
- Treat identity refresh as best effort, matching the existing ranked-data refresh
|
||||||
|
policy: log a failure but allow successful match refresh work to complete.
|
||||||
|
- When a caller does not already know the Riot regional route, resolve it from the
|
||||||
|
user's community and fall back to `asia` only when the community has no route.
|
||||||
|
- Do not increment the background failure counter or enter backoff solely because
|
||||||
|
the identity lookup failed; background statistics enrichment retains its
|
||||||
|
existing success and failure semantics.
|
||||||
|
- Reuse the existing refresh completion event and profile-query invalidation; do
|
||||||
|
not add a new endpoint, response field, socket event, or frontend state path.
|
||||||
|
- Update only the embedded Riot account used by the personal profile. Historical
|
||||||
|
match snapshots retain the names recorded by Riot for those games.
|
||||||
|
|
||||||
|
## Tech Stack
|
||||||
|
|
||||||
|
- NestJS 11, TypeScript 5, Mongoose 9, and Jest under `apps/api`
|
||||||
|
- Riot Account-V1 through the existing `RiotAccountService`
|
||||||
|
- Redis stream jobs through the existing `RiotJobWorkerService`
|
||||||
|
- Scheduled stale-account refresh through `BackgroundRefreshScheduler`
|
||||||
|
- React Query profile invalidation already present in `UserHistoryPage`
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
- Focused tests:
|
||||||
|
`pnpm --filter api exec jest --runInBand riot-account-enrichment.service.spec.ts riot-job-worker.service.spec.ts background-refresh.scheduler.spec.ts`
|
||||||
|
- API lint: `pnpm --filter api lint`
|
||||||
|
- API build: `pnpm --filter api build`
|
||||||
|
- Web lint: `pnpm --filter web lint`
|
||||||
|
- Web production build: `pnpm --filter web build:prod`
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
- `apps/api/src/modules/riot/riot-account.service.ts` owns the validated
|
||||||
|
Account-V1 PUUID lookup.
|
||||||
|
- `apps/api/src/modules/riot/riot-account-enrichment.service.ts` owns the
|
||||||
|
persistence boundary for the embedded Riot account.
|
||||||
|
- `apps/api/src/modules/riot/riot-account-enrichment.service.spec.ts` verifies
|
||||||
|
update, no-op, and failure behavior.
|
||||||
|
- `apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts` orchestrates
|
||||||
|
identity, match, and ranked refresh work before completion.
|
||||||
|
- `apps/api/src/modules/riot-job-queue/riot-job-worker.service.spec.ts` verifies
|
||||||
|
that a personal-history refresh job requests the PUUID-based identity refresh.
|
||||||
|
- `apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.ts`
|
||||||
|
orchestrates best-effort identity refresh for stale accounts before statistics
|
||||||
|
enrichment.
|
||||||
|
- `apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.spec.ts`
|
||||||
|
verifies background invocation, ordering, and failure isolation.
|
||||||
|
- `apps/web/src/pages/UserHistoryPage.tsx` already invalidates the profile query
|
||||||
|
when the refresh socket reports completion and is not modified in this scope.
|
||||||
|
|
||||||
|
## Internal Contract
|
||||||
|
|
||||||
|
Add one focused method to `RiotAccountEnrichmentService`:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
type RefreshRiotIdentityResult = "updated" | "unchanged" | "failed";
|
||||||
|
|
||||||
|
refreshRiotIdentity(params: {
|
||||||
|
userId: mongoose.Types.ObjectId;
|
||||||
|
puuid: string;
|
||||||
|
region?: RiotRegionalRoute;
|
||||||
|
}): Promise<RefreshRiotIdentityResult>;
|
||||||
|
```
|
||||||
|
|
||||||
|
`updated` means both persisted Riot ID fields now match Account-V1. `unchanged`
|
||||||
|
means the validated response matched the stored values and no database write was
|
||||||
|
needed. `failed` means no stored account could be resolved or the external lookup
|
||||||
|
could not safely provide a complete identity; stored values remain unchanged. If
|
||||||
|
`region` is omitted, the service resolves the user's community and uses its
|
||||||
|
configured `riotRegion`, falling back to `asia` only when unavailable.
|
||||||
|
|
||||||
|
## Code Style
|
||||||
|
|
||||||
|
Keep the external validation and persistence decision explicit:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const identity = await this.accountService.getByPuuid(puuid, { region });
|
||||||
|
if (identity.puuid !== puuid || !identity.gameName || !identity.tagLine) {
|
||||||
|
return "failed";
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Use existing single quotes, NestJS logging, Mongoose document mutation, and
|
||||||
|
Prettier formatting. Do not add a generic identity abstraction or new dependency.
|
||||||
|
|
||||||
|
## Testing Strategy
|
||||||
|
|
||||||
|
- Write the enrichment-service tests first and confirm they fail before adding
|
||||||
|
the new method.
|
||||||
|
- Verify a changed game name and tag line are persisted together.
|
||||||
|
- Verify identical values return `unchanged` without saving.
|
||||||
|
- Verify missing values, PUUID mismatch, and Riot lookup errors return `failed`
|
||||||
|
without overwriting or saving the stored identity.
|
||||||
|
- Write the worker orchestration expectation before calling the new method.
|
||||||
|
- Verify a region-less identity refresh uses the user's configured community
|
||||||
|
region.
|
||||||
|
- Write background scheduler expectations before adding identity refresh to the
|
||||||
|
stale-account loop.
|
||||||
|
- Verify identity refresh happens before statistics enrichment and that a rejected
|
||||||
|
identity lookup does not increment background failure counters.
|
||||||
|
- Run focused API tests after each slice, then API lint/build and web lint/build
|
||||||
|
to verify the existing client integration remains valid.
|
||||||
|
|
||||||
|
## Boundaries
|
||||||
|
|
||||||
|
### Always
|
||||||
|
|
||||||
|
- Use the stored PUUID for Account-V1 lookup and verify the returned PUUID.
|
||||||
|
- Validate both Riot ID fields before mutating the database.
|
||||||
|
- Preserve the current Riot ID on any unsafe or failed response.
|
||||||
|
- Keep the existing refresh route, enqueue response, and socket event compatible.
|
||||||
|
- Keep background identity failures independent from enrichment failure counters.
|
||||||
|
- Run focused tests before broader lint and build verification.
|
||||||
|
|
||||||
|
### Ask First
|
||||||
|
|
||||||
|
- Add a database field or migration.
|
||||||
|
- Change refresh failure semantics so an identity lookup failure fails the whole
|
||||||
|
user-history job.
|
||||||
|
- Update historical match snapshots or active match participant display names.
|
||||||
|
- Add a new API response field, endpoint, dependency, or Redis job type.
|
||||||
|
- Commit, push, deploy, or alter CI configuration.
|
||||||
|
|
||||||
|
### Never
|
||||||
|
|
||||||
|
- Resolve identity from the stale stored Riot ID.
|
||||||
|
- Partially update only the game name or only the tag line.
|
||||||
|
- Replace a valid stored identity with empty or mismatched Account-V1 data.
|
||||||
|
- Expose Riot API errors or credentials to the browser.
|
||||||
|
- Mix the change with the separate past-history result-column PR.
|
||||||
|
|
||||||
|
## Success Criteria
|
||||||
|
|
||||||
|
- Clicking `정보 갱신` causes the queued worker to call Account-V1 by the stored
|
||||||
|
PUUID.
|
||||||
|
- Selecting a stale account for background refresh also calls Account-V1 by the
|
||||||
|
stored PUUID before statistics enrichment.
|
||||||
|
- A changed Riot game name or tag line is persisted on the matching embedded
|
||||||
|
account before the completion event is broadcast.
|
||||||
|
- The completion event triggers the existing profile-query invalidation, so the
|
||||||
|
personal history header displays the latest `gameName#tagLine`.
|
||||||
|
- Failed, incomplete, or mismatched Riot identity responses do not overwrite the
|
||||||
|
existing Riot ID and do not prevent otherwise successful match refresh work.
|
||||||
|
- Background identity lookup failures do not increment the account failure counter
|
||||||
|
or prevent otherwise successful background enrichment.
|
||||||
|
- Focused tests, API lint/build, and web lint/production build pass.
|
||||||
|
|
||||||
|
## Open Questions
|
||||||
|
|
||||||
|
None. The user approved this specification and requested implementation. The
|
||||||
|
existing queue and UI invalidation paths support the behavior without a public
|
||||||
|
contract change.
|
||||||
+21
-1
@@ -26,6 +26,26 @@
|
|||||||
},
|
},
|
||||||
"packageManager": "pnpm@10.4.1",
|
"packageManager": "pnpm@10.4.1",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@infisical/sdk": "^5.0.0"
|
"@infisical/sdk": "^5.0.2"
|
||||||
|
},
|
||||||
|
"pnpm": {
|
||||||
|
"auditConfig": {
|
||||||
|
"ignoreGhsas": [
|
||||||
|
"GHSA-mh99-v99m-4gvg"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"overrides": {
|
||||||
|
"@babel/core@7.29.0": "7.29.6",
|
||||||
|
"brace-expansion@1.1.13": "1.1.16",
|
||||||
|
"brace-expansion@2.0.3": "2.1.2",
|
||||||
|
"brace-expansion@5.0.5": "5.0.8",
|
||||||
|
"engine.io@6.6.6": "6.6.7",
|
||||||
|
"fast-uri@3.1.0": "3.1.4",
|
||||||
|
"form-data@4.0.5": "4.0.6",
|
||||||
|
"js-yaml@4.1.1": "4.3.0",
|
||||||
|
"js-yaml@5.2.1": "5.2.2",
|
||||||
|
"qs@6.15.1": "6.15.2",
|
||||||
|
"ws@8.18.3": "8.21.0"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Generated
+1662
-1630
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user