Compare commits
17
Commits
release/87
...
904f1fc4a4
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
904f1fc4a4 | ||
|
|
f526257d9c | ||
|
|
34a47c053e | ||
|
|
e3f39fd8b8 | ||
|
|
4385ba7b8b | ||
|
|
9cd5850d43 | ||
|
|
79534cf43c | ||
|
|
03be85d07b | ||
|
|
d269bdd92b | ||
|
|
760da1cbea | ||
|
|
ac0d2b53f0 | ||
|
|
a24726d7da | ||
|
|
9e2f2c61e7 | ||
|
|
1f75c6318a | ||
|
|
8ec9edc35f | ||
|
|
61f1db0e6a | ||
|
|
c155f26272 |
No files matched your search
@@ -28,6 +28,8 @@ website/LICENSE
|
|||||||
!AGENTS.md
|
!AGENTS.md
|
||||||
!docs/specs/internal-match-game-analysis.md
|
!docs/specs/internal-match-game-analysis.md
|
||||||
!docs/plans/internal-match-game-analysis-p0-p1.md
|
!docs/plans/internal-match-game-analysis-p0-p1.md
|
||||||
|
!docs/specs/double-elimination-connector-routing.md
|
||||||
|
!docs/plans/double-elimination-connector-routing.md
|
||||||
!agents/**/*.md
|
!agents/**/*.md
|
||||||
!skills/**/*.md
|
!skills/**/*.md
|
||||||
/tmp/
|
/tmp/
|
||||||
|
|||||||
@@ -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;
|
||||||
|
|||||||
@@ -104,7 +104,11 @@ export function SeriesScoreCard({
|
|||||||
{presentation.label}
|
{presentation.label}
|
||||||
</span>
|
</span>
|
||||||
</header>
|
</header>
|
||||||
<div className="divide-y divide-base-content/8">
|
<div
|
||||||
|
className={
|
||||||
|
isBracket ? "relative" : "divide-y divide-base-content/8"
|
||||||
|
}
|
||||||
|
>
|
||||||
{series.entries.map((entry) => {
|
{series.entries.map((entry) => {
|
||||||
const team = entry.teamId ? teamById.get(entry.teamId) : undefined;
|
const team = entry.teamId ? teamById.get(entry.teamId) : undefined;
|
||||||
const isWinner = isSeriesEntryWinner(series, entry.teamId);
|
const isWinner = isSeriesEntryWinner(series, entry.teamId);
|
||||||
@@ -129,6 +133,13 @@ export function SeriesScoreCard({
|
|||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
{isBracket && (
|
||||||
|
<span
|
||||||
|
className="pointer-events-none absolute inset-x-0 border-t border-base-content/8"
|
||||||
|
style={{ top: SERIES_SCORE_CARD_GEOMETRY.entryHeight }}
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</article>
|
</article>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -17,6 +17,8 @@ export const DOUBLE_ELIMINATION_BRACKET_GEOMETRY = {
|
|||||||
boardPadding: 12,
|
boardPadding: 12,
|
||||||
columnWidth: 228,
|
columnWidth: 228,
|
||||||
columnGap: 40,
|
columnGap: 40,
|
||||||
|
// Matches the widest focused connector underlay so parallel routes stay legible.
|
||||||
|
connectorRailClearance: 5,
|
||||||
cardBorderWidth: SERIES_SCORE_CARD_GEOMETRY.borderWidth,
|
cardBorderWidth: SERIES_SCORE_CARD_GEOMETRY.borderWidth,
|
||||||
cardHeight: SERIES_SCORE_CARD_GEOMETRY.height,
|
cardHeight: SERIES_SCORE_CARD_GEOMETRY.height,
|
||||||
cardHeaderHeight: SERIES_SCORE_CARD_GEOMETRY.headerHeight,
|
cardHeaderHeight: SERIES_SCORE_CARD_GEOMETRY.headerHeight,
|
||||||
@@ -109,6 +111,29 @@ interface NormalizedRound {
|
|||||||
seriesIds: SeriesId[];
|
seriesIds: SeriesId[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface ConnectorRoute {
|
||||||
|
connector: SeriesConnectorView;
|
||||||
|
key: string;
|
||||||
|
kind: BracketConnectorKind;
|
||||||
|
targetColumn: number;
|
||||||
|
targetNodeY: number;
|
||||||
|
sourceX: number;
|
||||||
|
sourceY: number;
|
||||||
|
targetX: number;
|
||||||
|
targetY: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SeparateWinnerRailChoice {
|
||||||
|
verticalXs: [number, number];
|
||||||
|
crossings: number;
|
||||||
|
distanceFromBaseline: number;
|
||||||
|
distanceFromCenter: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
type OrthogonalSegment =
|
||||||
|
| { orientation: "horizontal"; fixed: number; start: number; end: number }
|
||||||
|
| { orientation: "vertical"; fixed: number; start: number; end: number };
|
||||||
|
|
||||||
const STAGE_ORDER: Record<BracketStage, number> = {
|
const STAGE_ORDER: Record<BracketStage, number> = {
|
||||||
upper: 0,
|
upper: 0,
|
||||||
lower: 1,
|
lower: 1,
|
||||||
@@ -126,6 +151,9 @@ const CONNECTOR_SELECTION_ORDER: Record<
|
|||||||
"slot-b": 3,
|
"slot-b": 3,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// A focused 5px underlay extends 2.5px from its centerline.
|
||||||
|
const CONNECTOR_RAIL_EDGE_INSET = 3;
|
||||||
|
|
||||||
export function createDoubleEliminationBracketLayout(
|
export function createDoubleEliminationBracketLayout(
|
||||||
projection: DoubleEliminationCompetitionProjection,
|
projection: DoubleEliminationCompetitionProjection,
|
||||||
configuration: DoubleEliminationBracketConfiguration,
|
configuration: DoubleEliminationBracketConfiguration,
|
||||||
@@ -540,56 +568,53 @@ function buildConnectors(
|
|||||||
nodeById: Map<SeriesId, BracketNodeLayout>,
|
nodeById: Map<SeriesId, BracketNodeLayout>,
|
||||||
): BracketConnectorLayout[] | null {
|
): BracketConnectorLayout[] | null {
|
||||||
const geometry = DOUBLE_ELIMINATION_BRACKET_GEOMETRY;
|
const geometry = DOUBLE_ELIMINATION_BRACKET_GEOMETRY;
|
||||||
const connectorsByTargetColumn = new Map<
|
const routes: ConnectorRoute[] = [];
|
||||||
number,
|
const routesByTargetColumn = new Map<number, ConnectorRoute[]>();
|
||||||
Array<{
|
|
||||||
connector: SeriesConnectorView;
|
|
||||||
source: BracketNodeLayout;
|
|
||||||
target: BracketNodeLayout;
|
|
||||||
}>
|
|
||||||
>();
|
|
||||||
for (const connector of projection.connectors) {
|
for (const connector of projection.connectors) {
|
||||||
const source = nodeById.get(connector.from.seriesId);
|
const source = nodeById.get(connector.from.seriesId);
|
||||||
const target = nodeById.get(connector.to.seriesId);
|
const target = nodeById.get(connector.to.seriesId);
|
||||||
if (!source || !target || target.column <= source.column) return null;
|
if (!source || !target || target.column <= source.column) return null;
|
||||||
const routes = connectorsByTargetColumn.get(target.column) ?? [];
|
const route = {
|
||||||
routes.push({ connector, source, target });
|
connector,
|
||||||
connectorsByTargetColumn.set(target.column, routes);
|
key: connectorKey(connector),
|
||||||
|
kind: connectorKind(connector.from.select),
|
||||||
|
targetColumn: target.column,
|
||||||
|
targetNodeY: target.y,
|
||||||
|
sourceX: source.x + source.width,
|
||||||
|
sourceY: connectorAnchorY(source, connector.from.select),
|
||||||
|
targetX: target.x,
|
||||||
|
targetY: targetSlotY(target, connector.to.slot),
|
||||||
|
} satisfies ConnectorRoute;
|
||||||
|
routes.push(route);
|
||||||
|
const columnRoutes = routesByTargetColumn.get(target.column) ?? [];
|
||||||
|
columnRoutes.push(route);
|
||||||
|
routesByTargetColumn.set(target.column, columnRoutes);
|
||||||
}
|
}
|
||||||
|
|
||||||
const verticalXByConnector = new Map<string, number>();
|
const verticalXByConnector = new Map<string, number>();
|
||||||
for (const routes of connectorsByTargetColumn.values()) {
|
for (const columnRoutes of routesByTargetColumn.values()) {
|
||||||
routes.sort(
|
columnRoutes.sort(
|
||||||
(left, right) =>
|
(left, right) =>
|
||||||
connectorAnchorY(right.source, right.connector.from.select) -
|
right.sourceY - left.sourceY ||
|
||||||
connectorAnchorY(left.source, left.connector.from.select) ||
|
right.targetY - left.targetY ||
|
||||||
targetSlotY(right.target, right.connector.to.slot) -
|
left.key.localeCompare(right.key),
|
||||||
targetSlotY(left.target, left.connector.to.slot) ||
|
|
||||||
connectorKey(left.connector).localeCompare(connectorKey(right.connector)),
|
|
||||||
);
|
);
|
||||||
routes.forEach(({ connector, target }, index) => {
|
columnRoutes.forEach(({ key, targetX }, index) => {
|
||||||
verticalXByConnector.set(
|
verticalXByConnector.set(
|
||||||
connectorKey(connector),
|
key,
|
||||||
target.x -
|
targetX -
|
||||||
geometry.columnGap +
|
geometry.columnGap +
|
||||||
(geometry.columnGap * (index + 1)) / (routes.length + 1),
|
(geometry.columnGap * (index + 1)) / (columnRoutes.length + 1),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
if (!alignWinnerBundleRails(routes, verticalXByConnector)) return null;
|
||||||
|
|
||||||
const result: BracketConnectorLayout[] = [];
|
const result: BracketConnectorLayout[] = [];
|
||||||
for (const connector of projection.connectors) {
|
for (const route of routes) {
|
||||||
const source = nodeById.get(connector.from.seriesId);
|
const { connector, key, kind, sourceX, sourceY, targetX, targetY } = route;
|
||||||
const target = nodeById.get(connector.to.seriesId);
|
const verticalX = verticalXByConnector.get(key);
|
||||||
if (!source || !target || target.column <= source.column) return null;
|
|
||||||
|
|
||||||
const sourceX = source.x + source.width;
|
|
||||||
const targetX = target.x;
|
|
||||||
const sourceY = connectorAnchorY(source, connector.from.select);
|
|
||||||
const targetY = targetSlotY(target, connector.to.slot);
|
|
||||||
const verticalX = verticalXByConnector.get(connectorKey(connector));
|
|
||||||
if (verticalX === undefined) return null;
|
if (verticalX === undefined) return null;
|
||||||
const kind = connectorKind(connector.from.select);
|
|
||||||
result.push({
|
result.push({
|
||||||
fromSeriesId: connector.from.seriesId,
|
fromSeriesId: connector.from.seriesId,
|
||||||
select: connector.from.select,
|
select: connector.from.select,
|
||||||
@@ -622,6 +647,324 @@ function buildConnectors(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function alignWinnerBundleRails(
|
||||||
|
routes: readonly ConnectorRoute[],
|
||||||
|
verticalXByConnector: Map<string, number>,
|
||||||
|
): boolean {
|
||||||
|
const winnersByTarget = new Map<SeriesId, ConnectorRoute[]>();
|
||||||
|
for (const route of routes) {
|
||||||
|
if (route.kind !== "winner") continue;
|
||||||
|
const winners = winnersByTarget.get(route.connector.to.seriesId) ?? [];
|
||||||
|
winners.push(route);
|
||||||
|
winnersByTarget.set(route.connector.to.seriesId, winners);
|
||||||
|
}
|
||||||
|
|
||||||
|
const bundles = [...winnersByTarget.values()]
|
||||||
|
.filter(
|
||||||
|
(winners) =>
|
||||||
|
winners.length === 2 &&
|
||||||
|
winners[0].connector.to.slot !== winners[1].connector.to.slot,
|
||||||
|
)
|
||||||
|
.sort(
|
||||||
|
(left, right) =>
|
||||||
|
left[0].targetColumn - right[0].targetColumn ||
|
||||||
|
left[0].targetNodeY - right[0].targetNodeY ||
|
||||||
|
left[0].key.localeCompare(right[0].key),
|
||||||
|
);
|
||||||
|
|
||||||
|
for (const bundle of bundles) {
|
||||||
|
const preferredX =
|
||||||
|
bundle[0].targetX - DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap / 2;
|
||||||
|
if (
|
||||||
|
intervalsOverlap(
|
||||||
|
bundle[0].sourceY,
|
||||||
|
bundle[0].targetY,
|
||||||
|
bundle[1].sourceY,
|
||||||
|
bundle[1].targetY,
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
const assignment = chooseSeparateWinnerRails(
|
||||||
|
bundle,
|
||||||
|
routes,
|
||||||
|
verticalXByConnector,
|
||||||
|
preferredX,
|
||||||
|
);
|
||||||
|
if (!assignment) return false;
|
||||||
|
for (const [key, verticalX] of assignment) {
|
||||||
|
verticalXByConnector.set(key, verticalX);
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const verticalX = chooseWinnerBundleRail(
|
||||||
|
bundle,
|
||||||
|
routes,
|
||||||
|
verticalXByConnector,
|
||||||
|
preferredX,
|
||||||
|
);
|
||||||
|
if (verticalX === null) return false;
|
||||||
|
for (const route of bundle) verticalXByConnector.set(route.key, verticalX);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function chooseWinnerBundleRail(
|
||||||
|
bundle: readonly ConnectorRoute[],
|
||||||
|
routes: readonly ConnectorRoute[],
|
||||||
|
verticalXByConnector: Map<string, number>,
|
||||||
|
preferredX: number,
|
||||||
|
): number | null {
|
||||||
|
const previousRails = bundle.map((route) =>
|
||||||
|
verticalXByConnector.get(route.key),
|
||||||
|
);
|
||||||
|
if (previousRails.some((verticalX) => verticalX === undefined)) return null;
|
||||||
|
const previousScore = connectorConflictScore(routes, verticalXByConnector);
|
||||||
|
// Keep the existing crossing budget, then favor stroke-clear rails nearest center.
|
||||||
|
let best:
|
||||||
|
| {
|
||||||
|
verticalX: number;
|
||||||
|
crossings: number;
|
||||||
|
clearanceConflicts: number;
|
||||||
|
distanceFromCenter: number;
|
||||||
|
}
|
||||||
|
| null = null;
|
||||||
|
|
||||||
|
for (const candidateX of winnerRailCandidates(preferredX)) {
|
||||||
|
for (const route of bundle) {
|
||||||
|
verticalXByConnector.set(route.key, candidateX);
|
||||||
|
}
|
||||||
|
const score = connectorConflictScore(routes, verticalXByConnector);
|
||||||
|
if (
|
||||||
|
score.overlaps !== 0 ||
|
||||||
|
score.crossings > previousScore.crossings ||
|
||||||
|
score.clearanceConflicts > previousScore.clearanceConflicts
|
||||||
|
) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const distanceFromCenter = Math.abs(candidateX - preferredX);
|
||||||
|
if (
|
||||||
|
!best ||
|
||||||
|
score.clearanceConflicts < best.clearanceConflicts ||
|
||||||
|
(score.clearanceConflicts === best.clearanceConflicts &&
|
||||||
|
(score.crossings < best.crossings ||
|
||||||
|
(score.crossings === best.crossings &&
|
||||||
|
distanceFromCenter < best.distanceFromCenter)))
|
||||||
|
) {
|
||||||
|
best = {
|
||||||
|
verticalX: candidateX,
|
||||||
|
crossings: score.crossings,
|
||||||
|
clearanceConflicts: score.clearanceConflicts,
|
||||||
|
distanceFromCenter,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (best) return best.verticalX;
|
||||||
|
|
||||||
|
bundle.forEach((route, index) => {
|
||||||
|
const previousX = previousRails[index];
|
||||||
|
if (previousX !== undefined) {
|
||||||
|
verticalXByConnector.set(route.key, previousX);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function winnerRailCandidates(preferredX: number): number[] {
|
||||||
|
const geometry = DOUBLE_ELIMINATION_BRACKET_GEOMETRY;
|
||||||
|
const maximumOffset =
|
||||||
|
geometry.columnGap / 2 - CONNECTOR_RAIL_EDGE_INSET;
|
||||||
|
const candidates = [preferredX];
|
||||||
|
for (let offset = 1; offset <= maximumOffset; offset += 1) {
|
||||||
|
candidates.push(preferredX - offset, preferredX + offset);
|
||||||
|
}
|
||||||
|
return candidates;
|
||||||
|
}
|
||||||
|
|
||||||
|
function chooseSeparateWinnerRails(
|
||||||
|
bundle: readonly ConnectorRoute[],
|
||||||
|
routes: readonly ConnectorRoute[],
|
||||||
|
verticalXByConnector: Map<string, number>,
|
||||||
|
preferredX: number,
|
||||||
|
): Map<string, number> | null {
|
||||||
|
const orderedBundle = [...bundle].sort(
|
||||||
|
(left, right) =>
|
||||||
|
left.sourceY - right.sourceY ||
|
||||||
|
left.targetY - right.targetY ||
|
||||||
|
left.key.localeCompare(right.key),
|
||||||
|
);
|
||||||
|
const previousRails: number[] = [];
|
||||||
|
for (const route of orderedBundle) {
|
||||||
|
const previousX = verticalXByConnector.get(route.key);
|
||||||
|
if (previousX === undefined) return null;
|
||||||
|
previousRails.push(previousX);
|
||||||
|
}
|
||||||
|
|
||||||
|
const previousScore = connectorConflictScore(routes, verticalXByConnector);
|
||||||
|
const bundleKeys = new Set(orderedBundle.map(({ key }) => key));
|
||||||
|
const candidates = [
|
||||||
|
...new Set([...previousRails, ...winnerRailCandidates(preferredX)]),
|
||||||
|
];
|
||||||
|
let best: SeparateWinnerRailChoice | null = null;
|
||||||
|
|
||||||
|
for (const firstX of candidates) {
|
||||||
|
for (const secondX of candidates) {
|
||||||
|
if (firstX === secondX) continue;
|
||||||
|
verticalXByConnector.set(orderedBundle[0].key, firstX);
|
||||||
|
verticalXByConnector.set(orderedBundle[1].key, secondX);
|
||||||
|
|
||||||
|
const bundleScore = connectorConflictScore(
|
||||||
|
routes,
|
||||||
|
verticalXByConnector,
|
||||||
|
bundleKeys,
|
||||||
|
);
|
||||||
|
const score = connectorConflictScore(routes, verticalXByConnector);
|
||||||
|
if (
|
||||||
|
bundleScore.overlaps !== 0 ||
|
||||||
|
bundleScore.clearanceConflicts !== 0 ||
|
||||||
|
score.overlaps !== 0 ||
|
||||||
|
score.crossings > previousScore.crossings
|
||||||
|
) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const distanceFromBaseline =
|
||||||
|
Math.abs(firstX - previousRails[0]) +
|
||||||
|
Math.abs(secondX - previousRails[1]);
|
||||||
|
const distanceFromCenter =
|
||||||
|
Math.abs(firstX - preferredX) + Math.abs(secondX - preferredX);
|
||||||
|
const candidate: SeparateWinnerRailChoice = {
|
||||||
|
verticalXs: [firstX, secondX],
|
||||||
|
crossings: score.crossings,
|
||||||
|
distanceFromBaseline,
|
||||||
|
distanceFromCenter,
|
||||||
|
};
|
||||||
|
if (!best || compareSeparateWinnerRailChoices(candidate, best) < 0) {
|
||||||
|
best = candidate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
orderedBundle.forEach((route, index) => {
|
||||||
|
verticalXByConnector.set(route.key, previousRails[index]);
|
||||||
|
});
|
||||||
|
if (!best) return null;
|
||||||
|
return new Map(
|
||||||
|
orderedBundle.map((route, index) => [route.key, best.verticalXs[index]]),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function compareSeparateWinnerRailChoices(
|
||||||
|
left: SeparateWinnerRailChoice,
|
||||||
|
right: SeparateWinnerRailChoice,
|
||||||
|
): number {
|
||||||
|
return (
|
||||||
|
left.crossings - right.crossings ||
|
||||||
|
left.distanceFromBaseline - right.distanceFromBaseline ||
|
||||||
|
left.distanceFromCenter - right.distanceFromCenter ||
|
||||||
|
left.verticalXs[0] - right.verticalXs[0] ||
|
||||||
|
left.verticalXs[1] - right.verticalXs[1]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function connectorConflictScore(
|
||||||
|
routes: readonly ConnectorRoute[],
|
||||||
|
verticalXByConnector: ReadonlyMap<string, number>,
|
||||||
|
focusedRouteKeys?: ReadonlySet<string>,
|
||||||
|
): { crossings: number; overlaps: number; clearanceConflicts: number } {
|
||||||
|
let crossings = 0;
|
||||||
|
let overlaps = 0;
|
||||||
|
let clearanceConflicts = 0;
|
||||||
|
for (let leftIndex = 0; leftIndex < routes.length; leftIndex += 1) {
|
||||||
|
const leftX = verticalXByConnector.get(routes[leftIndex].key);
|
||||||
|
if (leftX === undefined) continue;
|
||||||
|
const leftSegments = connectorRouteSegments(routes[leftIndex], leftX);
|
||||||
|
for (
|
||||||
|
let rightIndex = leftIndex + 1;
|
||||||
|
rightIndex < routes.length;
|
||||||
|
rightIndex += 1
|
||||||
|
) {
|
||||||
|
if (
|
||||||
|
focusedRouteKeys &&
|
||||||
|
!focusedRouteKeys.has(routes[leftIndex].key) &&
|
||||||
|
!focusedRouteKeys.has(routes[rightIndex].key)
|
||||||
|
) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const rightX = verticalXByConnector.get(routes[rightIndex].key);
|
||||||
|
if (rightX === undefined) continue;
|
||||||
|
const rightSegments = connectorRouteSegments(routes[rightIndex], rightX);
|
||||||
|
for (const left of leftSegments) {
|
||||||
|
for (const right of rightSegments) {
|
||||||
|
if (left.orientation === right.orientation) {
|
||||||
|
const overlapLength =
|
||||||
|
Math.min(left.end, right.end) - Math.max(left.start, right.start);
|
||||||
|
if (left.fixed === right.fixed && overlapLength > 0) {
|
||||||
|
overlaps += 1;
|
||||||
|
} else if (
|
||||||
|
left.orientation === "vertical" &&
|
||||||
|
overlapLength > 0 &&
|
||||||
|
Math.abs(left.fixed - right.fixed) <
|
||||||
|
DOUBLE_ELIMINATION_BRACKET_GEOMETRY.connectorRailClearance
|
||||||
|
) {
|
||||||
|
clearanceConflicts += 1;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const horizontal =
|
||||||
|
left.orientation === "horizontal" ? left : right;
|
||||||
|
const vertical = left.orientation === "vertical" ? left : right;
|
||||||
|
if (
|
||||||
|
vertical.fixed > horizontal.start &&
|
||||||
|
vertical.fixed < horizontal.end &&
|
||||||
|
horizontal.fixed > vertical.start &&
|
||||||
|
horizontal.fixed < vertical.end
|
||||||
|
) {
|
||||||
|
crossings += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { crossings, overlaps, clearanceConflicts };
|
||||||
|
}
|
||||||
|
|
||||||
|
function connectorRouteSegments(
|
||||||
|
route: ConnectorRoute,
|
||||||
|
verticalX: number,
|
||||||
|
): OrthogonalSegment[] {
|
||||||
|
return [
|
||||||
|
orthogonalSegment("horizontal", route.sourceY, route.sourceX, verticalX),
|
||||||
|
orthogonalSegment("vertical", verticalX, route.sourceY, route.targetY),
|
||||||
|
orthogonalSegment("horizontal", route.targetY, verticalX, route.targetX),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function orthogonalSegment(
|
||||||
|
orientation: OrthogonalSegment["orientation"],
|
||||||
|
fixed: number,
|
||||||
|
first: number,
|
||||||
|
second: number,
|
||||||
|
): OrthogonalSegment {
|
||||||
|
return {
|
||||||
|
orientation,
|
||||||
|
fixed,
|
||||||
|
start: Math.min(first, second),
|
||||||
|
end: Math.max(first, second),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function intervalsOverlap(
|
||||||
|
firstStart: number,
|
||||||
|
firstEnd: number,
|
||||||
|
secondStart: number,
|
||||||
|
secondEnd: number,
|
||||||
|
): boolean {
|
||||||
|
return (
|
||||||
|
Math.min(firstStart, firstEnd) < Math.max(secondStart, secondEnd) &&
|
||||||
|
Math.min(secondStart, secondEnd) < Math.max(firstStart, firstEnd)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function connectorLabel(
|
function connectorLabel(
|
||||||
connector: SeriesConnectorView,
|
connector: SeriesConnectorView,
|
||||||
graph: ValidatedGraph,
|
graph: ValidatedGraph,
|
||||||
|
|||||||
@@ -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) && (
|
||||||
|
|||||||
@@ -367,6 +367,7 @@ test("orders mobile groups as winners, losers, grand final, then reset final", (
|
|||||||
shuffledLayout.mobileGroups.map((group) => group.seriesIds),
|
shuffledLayout.mobileGroups.map((group) => group.seriesIds),
|
||||||
orderedLayout.mobileGroups.map((group) => group.seriesIds),
|
orderedLayout.mobileGroups.map((group) => group.seriesIds),
|
||||||
);
|
);
|
||||||
|
assert.deepEqual(shuffledLayout.connectors, orderedLayout.connectors);
|
||||||
assert.deepEqual(
|
assert.deepEqual(
|
||||||
shuffledLayout.mobileGroups.flatMap((group) => group.seriesIds).sort(),
|
shuffledLayout.mobileGroups.flatMap((group) => group.seriesIds).sort(),
|
||||||
shuffled.projection.series.map((series) => series.seriesId).sort(),
|
shuffled.projection.series.map((series) => series.seriesId).sort(),
|
||||||
@@ -474,11 +475,10 @@ test("returns null instead of throwing for an unknown connector discriminator",
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("keeps connector rails distinct and outside intervening card rectangles", () => {
|
test("keeps connector rails finite and outside intervening card rectangles", () => {
|
||||||
const { projection } = eightTeamProjection();
|
const { projection } = eightTeamProjection();
|
||||||
const layout = requireLayout(projection, EIGHT_TEAM_LAYOUT);
|
const layout = requireLayout(projection, EIGHT_TEAM_LAYOUT);
|
||||||
const nodes = new Map(layout.nodes.map((node) => [node.seriesId, node]));
|
const nodes = new Map(layout.nodes.map((node) => [node.seriesId, node]));
|
||||||
const routesByTargetColumn = new Map<number, number[]>();
|
|
||||||
|
|
||||||
for (const route of layout.connectors) {
|
for (const route of layout.connectors) {
|
||||||
const source = nodes.get(route.fromSeriesId);
|
const source = nodes.get(route.fromSeriesId);
|
||||||
@@ -511,23 +511,256 @@ test("keeps connector rails distinct and outside intervening card rectangles", (
|
|||||||
false,
|
false,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
const rails = routesByTargetColumn.get(target.column) ?? [];
|
test("aligns paired winner bends on one shared rail", () => {
|
||||||
rails.push(route.verticalX);
|
const fourTeam = fourTeamProjection();
|
||||||
routesByTargetColumn.set(target.column, rails);
|
const fourTeamLayout = requireLayout(fourTeam.projection, FOUR_TEAM_LAYOUT);
|
||||||
|
for (const targetSeriesId of [fourTeam.ids.WB_FINAL, fourTeam.ids.GF]) {
|
||||||
|
const routes = winnerRoutesTo(fourTeamLayout, targetSeriesId);
|
||||||
|
assert.equal(routes.length, 2);
|
||||||
|
assert.equal(routes[0].verticalX, routes[1].verticalX);
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const rails of routesByTargetColumn.values()) {
|
const { projection, ids } = eightTeamProjection();
|
||||||
assert.equal(new Set(rails).size, rails.length);
|
const layout = requireLayout(projection, EIGHT_TEAM_LAYOUT);
|
||||||
|
|
||||||
|
for (const targetSeriesId of [
|
||||||
|
ids.WB_R2_M1,
|
||||||
|
ids.WB_R2_M2,
|
||||||
|
ids.WB_FINAL,
|
||||||
|
ids.LB_R3_M1,
|
||||||
|
ids.GF,
|
||||||
|
]) {
|
||||||
|
const routes = winnerRoutesTo(layout, targetSeriesId);
|
||||||
|
assert.equal(routes.length, 2);
|
||||||
|
assert.equal(
|
||||||
|
routes[0].verticalX,
|
||||||
|
routes[1].verticalX,
|
||||||
|
`${targetSeriesId} winner routes must share one bend rail`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("keeps reversed winner slots on deterministic non-overlapping rails", () => {
|
||||||
|
const { projection, ids } = fourTeamProjection();
|
||||||
|
const reversed = cloneProjection(projection);
|
||||||
|
const firstWinner = reversed.connectors.find(
|
||||||
|
({ from, to }) =>
|
||||||
|
from.seriesId === ids.WB_R1_M1 &&
|
||||||
|
from.select === "winner" &&
|
||||||
|
to.seriesId === ids.WB_FINAL,
|
||||||
|
);
|
||||||
|
const secondWinner = reversed.connectors.find(
|
||||||
|
({ from, to }) =>
|
||||||
|
from.seriesId === ids.WB_R1_M2 &&
|
||||||
|
from.select === "winner" &&
|
||||||
|
to.seriesId === ids.WB_FINAL,
|
||||||
|
);
|
||||||
|
assert.ok(firstWinner);
|
||||||
|
assert.ok(secondWinner);
|
||||||
|
firstWinner.to = { seriesId: ids.WB_FINAL, slot: "B" };
|
||||||
|
secondWinner.to = { seriesId: ids.WB_FINAL, slot: "A" };
|
||||||
|
|
||||||
|
const orderedLayout = requireLayout(reversed, FOUR_TEAM_LAYOUT);
|
||||||
|
const shuffled = cloneProjection(reversed);
|
||||||
|
shuffled.connectors = shuffledCopy(shuffled.connectors);
|
||||||
|
const shuffledLayout = requireLayout(shuffled, FOUR_TEAM_LAYOUT);
|
||||||
|
const routes = winnerRoutesTo(orderedLayout, ids.WB_FINAL);
|
||||||
|
|
||||||
|
assert.equal(routes.length, 2);
|
||||||
|
assert.equal(new Set(routes.map(({ verticalX }) => verticalX)).size, 2);
|
||||||
|
assert.equal(countCollinearConnectorOverlaps(orderedLayout.connectors), 0);
|
||||||
|
assert.deepEqual(shuffledLayout.connectors, orderedLayout.connectors);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("moves reversed winner rails clear of overlapping connector underlays", () => {
|
||||||
|
const { projection, ids } = eightTeamProjection();
|
||||||
|
const reversed = cloneProjection(projection);
|
||||||
|
const firstWinner = reversed.connectors.find(
|
||||||
|
({ from, to }) =>
|
||||||
|
from.seriesId === ids.WB_R1_M1 &&
|
||||||
|
from.select === "winner" &&
|
||||||
|
to.seriesId === ids.WB_R2_M1,
|
||||||
|
);
|
||||||
|
const secondWinner = reversed.connectors.find(
|
||||||
|
({ from, to }) =>
|
||||||
|
from.seriesId === ids.WB_R1_M2 &&
|
||||||
|
from.select === "winner" &&
|
||||||
|
to.seriesId === ids.WB_R2_M1,
|
||||||
|
);
|
||||||
|
assert.ok(firstWinner);
|
||||||
|
assert.ok(secondWinner);
|
||||||
|
firstWinner.to = { seriesId: ids.WB_R2_M1, slot: "B" };
|
||||||
|
secondWinner.to = { seriesId: ids.WB_R2_M1, slot: "A" };
|
||||||
|
|
||||||
|
const layout = requireLayout(reversed, EIGHT_TEAM_LAYOUT);
|
||||||
|
const shuffled = cloneProjection(reversed);
|
||||||
|
shuffled.connectors = shuffledCopy(shuffled.connectors);
|
||||||
|
const shuffledLayout = requireLayout(shuffled, EIGHT_TEAM_LAYOUT);
|
||||||
|
const winners = winnerRoutesTo(layout, ids.WB_R2_M1);
|
||||||
|
|
||||||
|
assert.equal(winners.length, 2);
|
||||||
|
for (const winner of winners) {
|
||||||
|
for (const route of layout.connectors) {
|
||||||
|
if (
|
||||||
|
route === winner ||
|
||||||
|
!intervalsStrictlyOverlap(
|
||||||
|
winner.sourceY,
|
||||||
|
winner.targetY,
|
||||||
|
route.sourceY,
|
||||||
|
route.targetY,
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
assert.ok(
|
||||||
|
Math.abs(winner.verticalX - route.verticalX) >=
|
||||||
|
DOUBLE_ELIMINATION_BRACKET_GEOMETRY.connectorRailClearance,
|
||||||
|
`${winner.fromSeriesId} winner rail ${winner.verticalX} is too close to ${route.fromSeriesId} ${route.kind} rail ${route.verticalX}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert.deepEqual(shuffledLayout.connectors, layout.connectors);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("centers conflict-free paired winner bends in the routing gap", () => {
|
||||||
|
const fourTeam = fourTeamProjection();
|
||||||
|
const fourTeamLayout = requireLayout(fourTeam.projection, FOUR_TEAM_LAYOUT);
|
||||||
|
const fourTeamGrandFinal = nodeFor(fourTeamLayout, fourTeam.ids.GF);
|
||||||
|
assert.deepEqual(
|
||||||
|
winnerRoutesTo(fourTeamLayout, fourTeam.ids.GF).map(
|
||||||
|
({ verticalX }) => verticalX,
|
||||||
|
),
|
||||||
|
[
|
||||||
|
fourTeamGrandFinal.x -
|
||||||
|
DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap / 2,
|
||||||
|
fourTeamGrandFinal.x -
|
||||||
|
DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap / 2,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
const { projection, ids } = eightTeamProjection();
|
||||||
|
const layout = requireLayout(projection, EIGHT_TEAM_LAYOUT);
|
||||||
|
|
||||||
|
for (const targetSeriesId of [ids.LB_R3_M1, ids.GF]) {
|
||||||
|
const target = nodeFor(layout, targetSeriesId);
|
||||||
|
const expectedVerticalX =
|
||||||
|
target.x - DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap / 2;
|
||||||
|
const routes = winnerRoutesTo(layout, targetSeriesId);
|
||||||
|
|
||||||
|
assert.equal(routes.length, 2);
|
||||||
|
assert.deepEqual(
|
||||||
|
routes.map(({ verticalX }) => verticalX),
|
||||||
|
[expectedVerticalX, expectedVerticalX],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("preserves baseline rails for loser and reset paths", () => {
|
||||||
|
const { projection } = eightTeamProjection({ resetFinal: true });
|
||||||
|
const layout = requireLayout(projection, EIGHT_TEAM_RESET_LAYOUT);
|
||||||
|
const nodes = new Map(layout.nodes.map((node) => [node.seriesId, node]));
|
||||||
|
const routesByTargetColumn = new Map<number, ConnectorLayout[]>();
|
||||||
|
|
||||||
|
for (const route of layout.connectors) {
|
||||||
|
const target = nodes.get(route.toSeriesId);
|
||||||
|
assert.ok(target);
|
||||||
|
const routes = routesByTargetColumn.get(target.column) ?? [];
|
||||||
|
routes.push(route);
|
||||||
|
routesByTargetColumn.set(target.column, routes);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const routes of routesByTargetColumn.values()) {
|
||||||
|
routes.sort(
|
||||||
|
(left, right) =>
|
||||||
|
right.sourceY - left.sourceY ||
|
||||||
|
right.targetY - left.targetY ||
|
||||||
|
connectorLayoutKey(left).localeCompare(connectorLayoutKey(right)),
|
||||||
|
);
|
||||||
|
routes.forEach((route, index) => {
|
||||||
|
if (route.kind === "winner") return;
|
||||||
|
assert.equal(
|
||||||
|
route.verticalX,
|
||||||
|
route.targetX -
|
||||||
|
DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap +
|
||||||
|
(DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap * (index + 1)) /
|
||||||
|
(routes.length + 1),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("keeps paired winner rails clear of overlapping loser paths", () => {
|
||||||
|
const fourTeam = fourTeamProjection();
|
||||||
|
const eightTeam = eightTeamProjection();
|
||||||
|
const fixtures = [
|
||||||
|
{
|
||||||
|
layout: requireLayout(fourTeam.projection, FOUR_TEAM_LAYOUT),
|
||||||
|
pairedWinnerTargets: new Set<SeriesId>([
|
||||||
|
fourTeam.ids.WB_FINAL,
|
||||||
|
fourTeam.ids.GF,
|
||||||
|
]),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
layout: requireLayout(eightTeam.projection, EIGHT_TEAM_LAYOUT),
|
||||||
|
pairedWinnerTargets: new Set<SeriesId>([
|
||||||
|
eightTeam.ids.WB_R2_M1,
|
||||||
|
eightTeam.ids.WB_R2_M2,
|
||||||
|
eightTeam.ids.WB_FINAL,
|
||||||
|
eightTeam.ids.LB_R3_M1,
|
||||||
|
eightTeam.ids.GF,
|
||||||
|
]),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const { layout, pairedWinnerTargets } of fixtures) {
|
||||||
|
for (const winner of layout.connectors) {
|
||||||
|
if (
|
||||||
|
winner.kind !== "winner" ||
|
||||||
|
!pairedWinnerTargets.has(winner.toSeriesId)
|
||||||
|
) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (const loser of layout.connectors) {
|
||||||
|
if (
|
||||||
|
loser.kind !== "loser" ||
|
||||||
|
!intervalsStrictlyOverlap(
|
||||||
|
winner.sourceY,
|
||||||
|
winner.targetY,
|
||||||
|
loser.sourceY,
|
||||||
|
loser.targetY,
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
assert.ok(
|
||||||
|
Math.abs(winner.verticalX - loser.verticalX) >=
|
||||||
|
DOUBLE_ELIMINATION_BRACKET_GEOMETRY.connectorRailClearance,
|
||||||
|
`${winner.fromSeriesId} winner rail ${winner.verticalX} is too close to ${loser.fromSeriesId} loser rail ${loser.verticalX}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test("minimizes connector crossings without introducing segment overlaps", () => {
|
test("minimizes connector crossings without introducing segment overlaps", () => {
|
||||||
const { projection } = eightTeamProjection();
|
const fourTeam = fourTeamProjection();
|
||||||
const layout = requireLayout(projection, EIGHT_TEAM_LAYOUT);
|
const fourTeamReset = fourTeamProjection({ resetFinal: true });
|
||||||
|
const eightTeam = eightTeamProjection();
|
||||||
|
const eightTeamReset = eightTeamProjection({ resetFinal: true });
|
||||||
|
const layouts = [
|
||||||
|
requireLayout(fourTeam.projection, FOUR_TEAM_LAYOUT),
|
||||||
|
requireLayout(fourTeamReset.projection, FOUR_TEAM_RESET_LAYOUT),
|
||||||
|
requireLayout(eightTeam.projection, EIGHT_TEAM_LAYOUT),
|
||||||
|
requireLayout(eightTeamReset.projection, EIGHT_TEAM_RESET_LAYOUT),
|
||||||
|
];
|
||||||
|
|
||||||
assert.equal(countStrictConnectorCrossings(layout.connectors), 12);
|
assert.ok(countStrictConnectorCrossings(layouts[2].connectors) <= 12);
|
||||||
assert.equal(countCollinearConnectorOverlaps(layout.connectors), 0);
|
for (const layout of layouts) {
|
||||||
|
assert.equal(countCollinearConnectorOverlaps(layout.connectors), 0);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test("aligns connector endpoints with the A and B entry row centers", () => {
|
test("aligns connector endpoints with the A and B entry row centers", () => {
|
||||||
@@ -921,6 +1154,18 @@ function segment(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function intervalsStrictlyOverlap(
|
||||||
|
firstStart: number,
|
||||||
|
firstEnd: number,
|
||||||
|
secondStart: number,
|
||||||
|
secondEnd: number,
|
||||||
|
): boolean {
|
||||||
|
return (
|
||||||
|
Math.min(firstStart, firstEnd) < Math.max(secondStart, secondEnd) &&
|
||||||
|
Math.min(secondStart, secondEnd) < Math.max(firstStart, firstEnd)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function countStrictConnectorCrossings(routes: readonly ConnectorLayout[]): number {
|
function countStrictConnectorCrossings(routes: readonly ConnectorLayout[]): number {
|
||||||
let crossings = 0;
|
let crossings = 0;
|
||||||
for (let leftIndex = 0; leftIndex < routes.length; leftIndex += 1) {
|
for (let leftIndex = 0; leftIndex < routes.length; leftIndex += 1) {
|
||||||
@@ -1009,6 +1254,16 @@ function nodeFor(
|
|||||||
return node;
|
return node;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function winnerRoutesTo(
|
||||||
|
layout: NonNullable<ReturnType<typeof createDoubleEliminationBracketLayout>>,
|
||||||
|
targetSeriesId: SeriesId,
|
||||||
|
) {
|
||||||
|
return layout.connectors.filter(
|
||||||
|
(route) =>
|
||||||
|
route.kind === "winner" && route.toSeriesId === targetSeriesId,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function routeFrom(
|
function routeFrom(
|
||||||
layout: NonNullable<ReturnType<typeof createDoubleEliminationBracketLayout>>,
|
layout: NonNullable<ReturnType<typeof createDoubleEliminationBracketLayout>>,
|
||||||
id: SeriesId,
|
id: SeriesId,
|
||||||
@@ -1036,6 +1291,10 @@ function connectorIdentity(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function connectorLayoutKey(connector: ConnectorLayout): string {
|
||||||
|
return `${connector.fromSeriesId}:${connector.select}:${connector.toSeriesId}:${connector.toSlot}`;
|
||||||
|
}
|
||||||
|
|
||||||
function mobileGroupKeys(
|
function mobileGroupKeys(
|
||||||
layout: NonNullable<ReturnType<typeof createDoubleEliminationBracketLayout>>,
|
layout: NonNullable<ReturnType<typeof createDoubleEliminationBracketLayout>>,
|
||||||
) {
|
) {
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { readFile } from "node:fs/promises";
|
||||||
|
import test from "node:test";
|
||||||
|
|
||||||
|
const homePageSource = await readFile(
|
||||||
|
new URL("../src/pages/HomePage.tsx", import.meta.url),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
|
||||||
|
test("keeps past match history focused on the five summary columns", () => {
|
||||||
|
const colGroup = sourceForFunction("HistoryTableColGroup");
|
||||||
|
const header = sourceForFunction("HistoryTableHeader");
|
||||||
|
const skeleton = sourceForFunction("HistoryRecordsSkeleton");
|
||||||
|
|
||||||
|
assert.equal(colGroup.match(/<col(?:\s|\/|>)/g)?.length, 5);
|
||||||
|
assert.doesNotMatch(header, />결과<\/th>/);
|
||||||
|
assert.doesNotMatch(homePageSource, /공식 결과/);
|
||||||
|
assert.doesNotMatch(skeleton, /1팀 승리/);
|
||||||
|
assert.match(homePageSource, /colSpan=\{5\}/);
|
||||||
|
});
|
||||||
|
|
||||||
|
function sourceForFunction(name: string): string {
|
||||||
|
const start = homePageSource.indexOf(`function ${name}(`);
|
||||||
|
assert.notEqual(start, -1, `${name} should exist`);
|
||||||
|
|
||||||
|
const nextFunction = homePageSource.indexOf("\nfunction ", start + 1);
|
||||||
|
assert.notEqual(nextFunction, -1, `${name} should have a following function`);
|
||||||
|
return homePageSource.slice(start, nextFunction);
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { readFile } from "node:fs/promises";
|
||||||
|
import test from "node:test";
|
||||||
|
import { SERIES_SCORE_CARD_GEOMETRY } from "../src/components/competition/series-score-card-geometry.ts";
|
||||||
|
|
||||||
|
const component = await readFile(
|
||||||
|
new URL(
|
||||||
|
"../src/components/competition/SeriesScoreCard.tsx",
|
||||||
|
import.meta.url,
|
||||||
|
),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
|
||||||
|
test("keeps bracket entry rows equal by overlaying their divider", () => {
|
||||||
|
assert.equal(
|
||||||
|
SERIES_SCORE_CARD_GEOMETRY.height -
|
||||||
|
SERIES_SCORE_CARD_GEOMETRY.borderWidth * 2 -
|
||||||
|
SERIES_SCORE_CARD_GEOMETRY.headerHeight,
|
||||||
|
SERIES_SCORE_CARD_GEOMETRY.entryHeight * 2,
|
||||||
|
);
|
||||||
|
assert.match(
|
||||||
|
component,
|
||||||
|
/className=\{\s*isBracket\s*\?\s*"relative"\s*:\s*"divide-y divide-base-content\/8"\s*\}/,
|
||||||
|
);
|
||||||
|
assert.match(
|
||||||
|
component,
|
||||||
|
/className="pointer-events-none absolute inset-x-0 border-t border-base-content\/8"/,
|
||||||
|
);
|
||||||
|
assert.match(
|
||||||
|
component,
|
||||||
|
/style=\{\{ top: SERIES_SCORE_CARD_GEOMETRY\.entryHeight \}\}/,
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { readFile } from "node:fs/promises";
|
||||||
|
import test from "node:test";
|
||||||
|
|
||||||
|
const userHistoryPageSource = await readFile(
|
||||||
|
new URL("../src/pages/UserHistoryPage.tsx", import.meta.url),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
|
||||||
|
test("hides the temporary real-time connection status indicator", () => {
|
||||||
|
assert.doesNotMatch(userHistoryPageSource, /실시간 연결됨/);
|
||||||
|
assert.doesNotMatch(userHistoryPageSource, /refreshSocket\.connectionStatus/);
|
||||||
|
});
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
# Implementation Plan: Double-Elimination Connector Routing
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
Replace per-edge winner rail staggering with deterministic, collision-aware winner
|
||||||
|
bundles while retaining the existing target-corridor `H-V-H` path model and the
|
||||||
|
current loser/reset routing behavior.
|
||||||
|
|
||||||
|
## Architecture Decisions
|
||||||
|
|
||||||
|
- Keep routing as a pure layout calculation; the React renderer consumes unchanged
|
||||||
|
`BracketConnectorLayout` paths.
|
||||||
|
- Allocate baseline rails first, then choose one rail for each same-target winner
|
||||||
|
bundle while leaving loser/reset coordinates unchanged.
|
||||||
|
- Score complete candidate paths by parallel-stroke clearance, strict crossings,
|
||||||
|
and distance from the corridor midpoint.
|
||||||
|
- Permit shared `verticalX` only when the participating vertical intervals do not
|
||||||
|
overlap; otherwise search the same corridor for the nearest deterministic pair
|
||||||
|
of separate rails with focused-stroke clearance.
|
||||||
|
|
||||||
|
## Task List
|
||||||
|
|
||||||
|
### Phase 1: Regression Contract
|
||||||
|
|
||||||
|
- [x] Add tests proving quiet winner bundles use the corridor midpoint and all
|
||||||
|
shareable same-target winner paths remain aligned.
|
||||||
|
- [x] Replace target-column rail uniqueness with interval-aware segment assertions.
|
||||||
|
- [x] Cover reversed A/B input where overlapping vertical spans require the
|
||||||
|
deterministic separate-rail fallback.
|
||||||
|
- [x] Confirm the focused test fails with the current allocator.
|
||||||
|
|
||||||
|
### Checkpoint: RED
|
||||||
|
|
||||||
|
- [x] The new behavioral assertion fails for the expected unequal `verticalX`.
|
||||||
|
- [x] Existing tests remain unchanged except where their invariant is obsolete.
|
||||||
|
|
||||||
|
### Phase 2: Bundle-Aware Allocator
|
||||||
|
|
||||||
|
- [x] Represent connector routing inputs with precomputed source/target anchors.
|
||||||
|
- [x] Retain stable independent rails for loser/reset routes.
|
||||||
|
- [x] Group the two winners entering each target and select the nearest safe shared
|
||||||
|
rail without card penetration, forbidden overlap, or avoidable added crossings.
|
||||||
|
- [x] Fall back to the nearest deterministic, stroke-clear separate rails only
|
||||||
|
when the pair's own vertical intervals overlap and cannot safely share a rail.
|
||||||
|
|
||||||
|
### Checkpoint: GREEN
|
||||||
|
|
||||||
|
- [x] Focused layout tests pass for four-team, eight-team, reset-final, and shuffled
|
||||||
|
input fixtures.
|
||||||
|
- [x] Strict crossing, collinear-overlap, and 5px parallel-clearance safeguards pass.
|
||||||
|
|
||||||
|
### Phase 3: Verification and Review
|
||||||
|
|
||||||
|
- [x] Run the full web suite, lint, and production build; document the unrelated
|
||||||
|
pre-existing full-lint failures while verifying changed files separately.
|
||||||
|
- [x] Inspect the diff for correctness, simplicity, security, performance, and
|
||||||
|
adherence to the approved spec.
|
||||||
|
- [x] Perform an independent review and address all required findings.
|
||||||
|
|
||||||
|
### Checkpoint: Complete
|
||||||
|
|
||||||
|
- [x] All success criteria in the spec are verified.
|
||||||
|
- [x] No unrelated files are modified.
|
||||||
|
|
||||||
|
## Risks and Mitigations
|
||||||
|
|
||||||
|
| Risk | Impact | Mitigation |
|
||||||
|
|---|---|---|
|
||||||
|
| Blind midpoint alignment adds crossings in busy upper rounds | High | Score complete candidate paths and move the winner bundle together to the nearest safe rail. |
|
||||||
|
| Shared rails create overlapping vertical segments | High | Check interval overlap before allowing a shared `verticalX`; search deterministic fallback rails with 5px clearance otherwise. |
|
||||||
|
| Visually parallel rails pass exact-coordinate tests but overlap at stroke width | High | Require 5px clearance across overlapping vertical runs and cover it for 4/8-team fixtures. |
|
||||||
|
| Routing changes depend on input array order | Medium | Sort routes and bundles by graph display order and retain shuffled-fixture equality tests. |
|
||||||
|
| A long connector bends through an intermediate card | High | Restrict every candidate to the target corridor and retain card-penetration assertions. |
|
||||||
|
| Reset-final slot carry-over is accidentally treated as a winner pair | Medium | Bundle only connectors whose computed kind is `winner`; keep reset paths independent. |
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
```text
|
||||||
|
Regression contract -> bundle-aware rail allocator -> full verification -> review
|
||||||
|
```
|
||||||
|
|
||||||
|
## Open Questions
|
||||||
|
|
||||||
|
None.
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
# Implementation Plan: Refresh Riot ID by PUUID
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
Deliver the behavior in three backend slices. First add and prove the safe
|
||||||
|
Account-V1-to-user persistence operation. Then invoke it from the existing
|
||||||
|
personal-history refresh worker before completion is broadcast. Finally reuse it
|
||||||
|
from stale-account background refresh with community-aware region resolution and
|
||||||
|
failure isolation. No database or frontend contract change is required.
|
||||||
|
|
||||||
|
## Task List
|
||||||
|
|
||||||
|
### Phase 1: Identity Refresh Boundary
|
||||||
|
|
||||||
|
- [x] Add failing tests for changed, unchanged, incomplete, mismatched, and failed
|
||||||
|
PUUID identity lookups.
|
||||||
|
- Acceptance: tests describe state outcomes and fail because the focused method
|
||||||
|
is not implemented.
|
||||||
|
- Verify:
|
||||||
|
`pnpm --filter api exec jest --runInBand riot-account-enrichment.service.spec.ts`
|
||||||
|
- Files:
|
||||||
|
`apps/api/src/modules/riot/riot-account-enrichment.service.spec.ts`
|
||||||
|
- [x] Implement `refreshRiotIdentity` using `RiotAccountService.getByPuuid`.
|
||||||
|
- Acceptance: valid changed values persist together; invalid results preserve
|
||||||
|
existing values; unchanged values avoid a write.
|
||||||
|
- Verify: the Phase 1 focused test passes.
|
||||||
|
- Files:
|
||||||
|
`apps/api/src/modules/riot/riot-account-enrichment.service.ts`
|
||||||
|
|
||||||
|
### Checkpoint: Phase 1
|
||||||
|
|
||||||
|
- [x] The enrichment service has a typed three-state result and all focused tests
|
||||||
|
pass.
|
||||||
|
- [x] No schema, endpoint, queue payload, or frontend changes exist.
|
||||||
|
|
||||||
|
### Phase 2: Refresh Worker Integration
|
||||||
|
|
||||||
|
- [x] Add a failing worker test proving that a user-history job requests identity
|
||||||
|
refresh with its user ID, PUUID, and region.
|
||||||
|
- Acceptance: the test fails before worker orchestration is updated.
|
||||||
|
- Verify:
|
||||||
|
`pnpm --filter api exec jest --runInBand riot-job-worker.service.spec.ts`
|
||||||
|
- Files: `apps/api/src/modules/riot-job-queue/riot-job-worker.service.spec.ts`
|
||||||
|
- [x] Invoke best-effort identity refresh before job completion.
|
||||||
|
- Acceptance: the worker logs identity failure without aborting successful match
|
||||||
|
refresh work, and broadcasts completion only after identity refresh returns.
|
||||||
|
- Verify: the Phase 2 focused test passes.
|
||||||
|
- Files: `apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts`
|
||||||
|
|
||||||
|
### Checkpoint: Complete
|
||||||
|
|
||||||
|
- [x] Focused API suites pass without skipped tests.
|
||||||
|
- [x] API lint and build pass.
|
||||||
|
- [x] Web lint and production build pass, confirming the existing profile
|
||||||
|
invalidation integration remains compatible.
|
||||||
|
- [x] Final diff contains only the specification, plan, enrichment service, worker,
|
||||||
|
and their tests.
|
||||||
|
|
||||||
|
### Phase 3: Background Refresh Integration
|
||||||
|
|
||||||
|
- [x] Add a failing enrichment-service test proving that an omitted region is
|
||||||
|
resolved from the user's community.
|
||||||
|
- Acceptance: a non-Asia community route reaches Account-V1 without changing the
|
||||||
|
public method signature.
|
||||||
|
- Verify:
|
||||||
|
`pnpm --filter api exec jest --runInBand riot-account-enrichment.service.spec.ts`
|
||||||
|
- Files:
|
||||||
|
`apps/api/src/modules/riot/riot-account-enrichment.service.spec.ts`
|
||||||
|
- [x] Resolve the community Riot region for region-less identity refresh calls.
|
||||||
|
- Acceptance: explicit caller regions remain unchanged; missing community routes
|
||||||
|
use the existing `asia` fallback.
|
||||||
|
- Verify: the focused enrichment-service test passes.
|
||||||
|
- Files:
|
||||||
|
`apps/api/src/modules/riot/riot-account-enrichment.service.ts`
|
||||||
|
- [x] Add failing background scheduler tests for identity refresh ordering and
|
||||||
|
failure isolation.
|
||||||
|
- Acceptance: stale accounts request identity refresh before statistics
|
||||||
|
enrichment, while identity rejection does not increment failure counters.
|
||||||
|
- Verify:
|
||||||
|
`pnpm --filter api exec jest --runInBand background-refresh.scheduler.spec.ts`
|
||||||
|
- Files:
|
||||||
|
`apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.spec.ts`
|
||||||
|
- [x] Invoke best-effort identity refresh from the stale-account loop.
|
||||||
|
- Acceptance: each processed candidate gets one PUUID identity lookup, statistics
|
||||||
|
enrichment still determines processed/failed/backoff state, and no new Redis or
|
||||||
|
database contract is added.
|
||||||
|
- Verify: the focused background scheduler tests pass.
|
||||||
|
- Files:
|
||||||
|
`apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.ts`
|
||||||
|
|
||||||
|
### Checkpoint: Background Refresh Complete
|
||||||
|
|
||||||
|
- [x] Focused identity, manual worker, and background scheduler suites pass.
|
||||||
|
- [x] API lint, full tests, and build pass.
|
||||||
|
- [x] Final diff remains limited to the existing feature documents, identity
|
||||||
|
service/tests, and background scheduler/tests.
|
||||||
|
|
||||||
|
## Risks and Mitigations
|
||||||
|
|
||||||
|
| Risk | Impact | Mitigation |
|
||||||
|
|---|---|---|
|
||||||
|
| Account-V1 returns an incomplete identity | High | Require matching PUUID and two non-empty Riot ID fields before mutation. |
|
||||||
|
| Riot Account-V1 is temporarily unavailable | Medium | Preserve stored identity, log the failure, and retain existing best-effort job semantics. |
|
||||||
|
| Multiple queue groups repeat identity lookup | Low | The personal page requests one queue group; avoid a new dedup mechanism until a measured need exists. |
|
||||||
|
| Background community uses a non-Asia Riot route | High | Resolve omitted regions from the user's community before falling back to `asia`. |
|
||||||
|
| Identity lookup failure triggers background backoff | Medium | Isolate identity exceptions and let existing statistics enrichment alone control failure counters. |
|
||||||
|
| UI keeps the stale profile cached | High | Identity update completes before the existing completion event invalidates the profile query. |
|
||||||
|
| Historical names are unexpectedly rewritten | Medium | Restrict persistence to the embedded Riot account and leave match snapshots untouched. |
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
```text
|
||||||
|
validated Account-V1 lookup
|
||||||
|
-> focused identity persistence method
|
||||||
|
-> manual refresh worker -> existing completion event -> profile invalidation
|
||||||
|
-> background scheduler -> existing statistics enrichment and backoff policy
|
||||||
|
```
|
||||||
|
|
||||||
|
## Open Questions
|
||||||
|
|
||||||
|
None. The user approved the specification and requested implementation.
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
# Spec: Double-Elimination Connector Routing
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
|
||||||
|
Make winner advancement lines in the desktop double-elimination bracket bend at a
|
||||||
|
consistent horizontal position. Two winner lines entering the same match should
|
||||||
|
read as one visual pair when their vertical spans can share a rail: use the center
|
||||||
|
of the 40px inter-column corridor when it is safe, and move the pair together only
|
||||||
|
when another connector would interfere. If an accepted A/B mapping reverses the
|
||||||
|
source order and makes those spans overlap, preserve separate deterministic,
|
||||||
|
stroke-clear rails instead of creating a collinear overlap.
|
||||||
|
|
||||||
|
The primary user is a participant or organizer tracing advancement through a busy
|
||||||
|
eight-team bracket. Success means the solid coral winner paths are visually
|
||||||
|
aligned without degrading the existing dashed loser paths, card placement, or
|
||||||
|
keyboard-driven connector highlighting.
|
||||||
|
|
||||||
|
## Approved Product Decisions
|
||||||
|
|
||||||
|
- Treat the two `winner` connectors entering one Series as a semantic bundle.
|
||||||
|
- Prefer `target.x - columnGap / 2` for a winner bundle.
|
||||||
|
- If the preferred rail causes crossings, collinear overlap, or less than 5px of
|
||||||
|
clearance from an overlapping parallel route, move a shareable bundle to the
|
||||||
|
nearest safe rail. Retain separate rails only when the pair's own vertical spans
|
||||||
|
overlap and therefore cannot safely share any rail; move those rails to the
|
||||||
|
nearest deterministic positions needed to preserve the same 5px clearance.
|
||||||
|
- Preserve the current loser/reset rail ordering unless moving one is required to
|
||||||
|
maintain valid geometry.
|
||||||
|
- Keep every connector as a separate `H-V-H` SVG path so focus highlighting and
|
||||||
|
accessible labels remain independent.
|
||||||
|
- Keep long-distance bends inside the corridor immediately before the target
|
||||||
|
column; do not use the midpoint between source and target cards.
|
||||||
|
|
||||||
|
## Tech Stack
|
||||||
|
|
||||||
|
- React 19, TypeScript 6, Vite 8, Tailwind CSS 4, and daisyUI under `apps/web`
|
||||||
|
- Node's built-in test runner for the pure bracket layout calculation
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
- Focused layout tests: `pnpm --filter web exec node --test --experimental-strip-types test/double-elimination-bracket-layout.test.ts`
|
||||||
|
- Full web tests: `pnpm --filter web test`
|
||||||
|
- Web lint: `pnpm --filter web lint`
|
||||||
|
- Web production build: `pnpm --filter web build:prod`
|
||||||
|
- Development server: `pnpm --filter web start:dev`
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
- `apps/web/src/components/competition/double-elimination-bracket-layout.ts`
|
||||||
|
validates the bracket graph, positions cards, assigns connector rails, and emits
|
||||||
|
SVG path geometry.
|
||||||
|
- `apps/web/src/components/competition/DoubleEliminationBracket.tsx` renders the
|
||||||
|
computed paths and must not need routing-specific changes.
|
||||||
|
- `apps/web/test/double-elimination-bracket-layout.test.ts` contains canonical
|
||||||
|
four-team, eight-team, and reset-final fixtures plus geometry assertions.
|
||||||
|
|
||||||
|
## Code Style
|
||||||
|
|
||||||
|
Keep routing deterministic and express geometry through small named helpers:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const preferredX = target.x - geometry.columnGap / 2;
|
||||||
|
const verticalX = nearestSafeRail(preferredX, bundle, occupiedRoutes);
|
||||||
|
```
|
||||||
|
|
||||||
|
Use existing layout types and semantic connector kinds. Do not add a dependency,
|
||||||
|
DOM measurement, mutable global state, or renderer-specific routing behavior.
|
||||||
|
|
||||||
|
## Testing Strategy
|
||||||
|
|
||||||
|
- Add regression tests before implementation and confirm they fail against the
|
||||||
|
current per-edge rail allocator.
|
||||||
|
- Assert observable geometry: safe winner pairs share a rail, quiet corridors use
|
||||||
|
their exact midpoint, busy corridors keep a pair aligned, and mixed
|
||||||
|
winner/loser entries remain distinguishable.
|
||||||
|
- Cover reversed A/B winner input explicitly: it remains deterministic and uses
|
||||||
|
separate rails without collinear overlap or focused-stroke clearance conflicts
|
||||||
|
because no shared H-V-H rail is safe.
|
||||||
|
- Replace the obsolete "all rails in a target column are unique" assertion with
|
||||||
|
interval-aware overlap and 5px focused-stroke clearance protection.
|
||||||
|
- Preserve deterministic output for shuffled input, finite path coordinates,
|
||||||
|
target-corridor bounds, card avoidance, endpoint alignment, and canonical graph
|
||||||
|
validation.
|
||||||
|
- Verify four-team, eight-team, and reset-final layouts; run the complete web test,
|
||||||
|
lint, and production build commands.
|
||||||
|
|
||||||
|
## Boundaries
|
||||||
|
|
||||||
|
### Always
|
||||||
|
|
||||||
|
- Keep winner, loser, and reset connectors visually distinguishable by the existing
|
||||||
|
solid/dashed patterns and brand tokens.
|
||||||
|
- Keep connector rails strictly inside the target corridor.
|
||||||
|
- Avoid strict segment crossings and collinear overlaps whenever a safe candidate
|
||||||
|
exists.
|
||||||
|
- Keep overlapping parallel winner and loser rails at least 5px apart, matching
|
||||||
|
the widest focused connector underlay.
|
||||||
|
- Produce the same layout regardless of projection input ordering.
|
||||||
|
|
||||||
|
### Ask First
|
||||||
|
|
||||||
|
- Add dependencies or change the public projection contract.
|
||||||
|
- Change bracket card dimensions, round columns, or the 40px column gap.
|
||||||
|
- Redesign mobile bracket presentation or connector interaction behavior.
|
||||||
|
|
||||||
|
### Never
|
||||||
|
|
||||||
|
- Route a connector through a match card.
|
||||||
|
- Infer routing from Series codes; use canonical graph identity and topology.
|
||||||
|
- Merge two logical connectors into one SVG path.
|
||||||
|
- Modify unrelated competition or score-card behavior.
|
||||||
|
|
||||||
|
## Success Criteria
|
||||||
|
|
||||||
|
- The two winner paths into `LB_R3_M1` bend at the corridor midpoint and share the
|
||||||
|
same `verticalX`.
|
||||||
|
- The winner paths into the grand final share the corridor midpoint when safe.
|
||||||
|
- Every same-target winner pair whose vertical spans do not overlap shares one
|
||||||
|
`verticalX`, using the nearest collision-safe rail when the midpoint is busy.
|
||||||
|
- A reversed A/B pair with overlapping vertical spans retains deterministic
|
||||||
|
separate rails, produces no collinear segment overlap, and remains at least 5px
|
||||||
|
from every overlapping vertical route.
|
||||||
|
- Loser/reset paths retain their baseline rails, and winner bundles remain at least
|
||||||
|
5px away where their vertical runs overlap.
|
||||||
|
- All rails remain inside their target corridors without card penetration or
|
||||||
|
collinear overlap.
|
||||||
|
- Canonical four-team, eight-team, reset-final, and shuffled-input tests pass.
|
||||||
|
- Full web tests and production build pass; changed-file lint passes, and any
|
||||||
|
unrelated full-lint baseline failures are documented.
|
||||||
|
|
||||||
|
## Open Questions
|
||||||
|
|
||||||
|
None. The user reviewed the proposed bundle-aware routing behavior and requested
|
||||||
|
implementation.
|
||||||
@@ -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.
|
||||||
Reference in new issue
Block a user